core/logic/PluginSys.cpp
author David Anderson <dvander@alliedmods.net>
Fri Mar 29 13:06:12 2013 -0700 (2013-03-29)
changeset 3878 4d0ef1669edf
parent 3872 4c93f74cae51
child 3879 6ce275678a11
permissions -rw-r--r--
Fix build, again.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 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 <stdio.h>
    33 #include <stdarg.h>
    34 #include "PluginSys.h"
    35 #include "ShareSys.h"
    36 #include <ILibrarySys.h>
    37 #include <ISourceMod.h>
    38 #include <IHandleSys.h>
    39 #include <IForwardSys.h>
    40 #include <IPlayerHelpers.h>
    41 #include "ExtensionSys.h"
    42 #include "GameConfigs.h"
    43 #include "common_logic.h"
    44 #include "Translator.h"
    45 
    46 CPluginManager g_PluginSys;
    47 HandleType_t g_PluginType = 0;
    48 IdentityType_t g_PluginIdent = 0;
    49 
    50 CPlugin::CPlugin(const char *file)
    51 {
    52 	static int MySerial = 0;
    53 
    54 	m_type = PluginType_Private;
    55 	m_status = Plugin_Uncompiled;
    56 	m_bSilentlyFailed = false;
    57 	m_serial = ++MySerial;
    58 	m_pRuntime = NULL;
    59 	m_errormsg[sizeof(m_errormsg) - 1] = '\0';
    60 	smcore.Format(m_filename, sizeof(m_filename), "%s", file);
    61 	m_handle = 0;
    62 	m_ident = NULL;
    63 	m_FakeNativesMissing = false;
    64 	m_LibraryMissing = false;
    65 	m_bGotAllLoaded = false;
    66 	m_pPhrases = g_Translator.CreatePhraseCollection();
    67 	m_MaxClientsVar = NULL;
    68 }
    69 
    70 CPlugin::~CPlugin()
    71 {
    72 	if (m_handle)
    73 	{
    74 		HandleSecurity sec;
    75 		sec.pOwner = g_PluginSys.GetIdentity();
    76 		sec.pIdentity = sec.pOwner;
    77 
    78 		handlesys->FreeHandle(m_handle, &sec);
    79 		g_ShareSys.DestroyIdentity(m_ident);
    80 	}
    81 
    82 	if (m_pRuntime != NULL)
    83 	{
    84 		delete m_pRuntime;
    85 		m_pRuntime = NULL;
    86 	}
    87 
    88 	for (size_t i=0; i<m_configs.size(); i++)
    89 	{
    90 		delete m_configs[i];
    91 	}
    92 	m_configs.clear();
    93 	if (m_pPhrases != NULL)
    94 	{
    95 		m_pPhrases->Destroy();
    96 		m_pPhrases = NULL;
    97 	}
    98 }
    99 
   100 void CPlugin::InitIdentity()
   101 {
   102 	if (!m_handle)
   103 	{
   104 		m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
   105 		m_handle = handlesys->CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
   106 		m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
   107 		m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
   108 	}
   109 }
   110 
   111 unsigned int CPlugin::CalcMemUsage()
   112 {
   113 	unsigned int base_size = 
   114 		sizeof(CPlugin) 
   115 		+ sizeof(IdentityToken_t)
   116 		+ (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
   117 		+ m_pProps.mem_usage();
   118 
   119 	for (unsigned int i = 0; i < m_configs.size(); i++)
   120 	{
   121 		base_size += m_configs[i]->autocfg.size();
   122 		base_size += m_configs[i]->folder.size();
   123 	}
   124 
   125 	for (List<String>::iterator i = m_Libraries.begin();
   126 		 i != m_Libraries.end();
   127 		 i++)
   128 	{
   129 		base_size += (*i).size();
   130 	}
   131 
   132 	for (List<String>::iterator i = m_RequiredLibs.begin();
   133 		 i != m_RequiredLibs.end();
   134 		 i++)
   135 	{
   136 		base_size += (*i).size();
   137 	}
   138 
   139 	return base_size;
   140 }
   141 
   142 Handle_t CPlugin::GetMyHandle()
   143 {
   144 	return m_handle;
   145 }
   146 
   147 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
   148 {
   149 	char fullpath[PLATFORM_MAX_PATH];
   150 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
   151 	FILE *fp = fopen(fullpath, "rb");
   152 
   153 	CPlugin *pPlugin = new CPlugin(file);
   154 
   155 	if (!fp)
   156 	{
   157 		if (error)
   158 		{
   159 			smcore.Format(error, maxlength, "Unable to open file");
   160 		}
   161 		pPlugin->m_status = Plugin_BadLoad;
   162 		return pPlugin;
   163 	}
   164 
   165 	fclose(fp);
   166 
   167 	return pPlugin;
   168 }
   169 
   170 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
   171 {
   172 	void **ptrpp = m_pProps.retrieve(prop);
   173 	bool exists = !!ptrpp;
   174 
   175 	if (exists)
   176 	{
   177 		*ptr = *ptrpp;
   178 		if (remove)
   179 			m_pProps.remove(prop);
   180 	}
   181 
   182 	return exists;
   183 }
   184 
   185 bool CPlugin::SetProperty(const char *prop, void *ptr)
   186 {
   187 	 return m_pProps.insert(prop, ptr);
   188 }
   189 
   190 IPluginRuntime *CPlugin::GetRuntime()
   191 {
   192 	return m_pRuntime;
   193 }
   194 
   195 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
   196 {
   197 	PluginStatus old_status = m_status;
   198 	m_status = status;
   199 
   200 	if (old_status == Plugin_Running)
   201 	{
   202 		/* Tell everyone we're now paused */
   203 		g_PluginSys._SetPauseState(this, true);
   204 	}
   205 
   206 	va_list ap;
   207 	va_start(ap, error_fmt);
   208 	smcore.FormatArgs(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
   209 	va_end(ap);
   210 
   211 	if (m_pRuntime != NULL)
   212 	{
   213 		m_pRuntime->SetPauseState(true);
   214 	}
   215 }
   216 
   217 bool CPlugin::UpdateInfo()
   218 {
   219 	/* Now grab the info */
   220 	uint32_t idx;
   221 	IPluginContext *base = GetBaseContext();
   222 	int err = base->FindPubvarByName("myinfo", &idx);
   223 
   224 	memset(&m_info, 0, sizeof(m_info));
   225 
   226 	if (err == SP_ERROR_NONE)
   227 	{
   228 		struct sm_plugininfo_c_t
   229 		{
   230 			cell_t name;
   231 			cell_t description;
   232 			cell_t author;
   233 			cell_t version;
   234 			cell_t url;
   235 		};
   236 		sm_plugininfo_c_t *cinfo;
   237 		cell_t local_addr;
   238 
   239 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
   240 		base->LocalToString(cinfo->name, (char **)&m_info.name);
   241 		base->LocalToString(cinfo->description, (char **)&m_info.description);
   242 		base->LocalToString(cinfo->author, (char **)&m_info.author);
   243 		base->LocalToString(cinfo->url, (char **)&m_info.url);
   244 		base->LocalToString(cinfo->version, (char **)&m_info.version);
   245 	}
   246 
   247 	m_info.author = m_info.author ? m_info.author : "";
   248 	m_info.description = m_info.description ? m_info.description : "";
   249 	m_info.name = m_info.name ? m_info.name : "";
   250 	m_info.url = m_info.url ? m_info.url : "";
   251 	m_info.version = m_info.version ? m_info.version : "";
   252 
   253 	if ((err = base->FindPubvarByName("__version", &idx)) == SP_ERROR_NONE)
   254 	{
   255 		struct __version_info
   256 		{
   257 			cell_t version;
   258 			cell_t filevers;
   259 			cell_t date;
   260 			cell_t time;
   261 		};
   262 		__version_info *info;
   263 		cell_t local_addr;
   264 		const char *pDate, *pTime, *pFileVers;
   265 
   266 		pDate = "";
   267 		pTime = "";
   268 
   269 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&info);
   270 		m_FileVersion = info->version;
   271 		if (m_FileVersion >= 4)
   272 		{
   273 			base->LocalToString(info->date, (char **)&pDate);
   274 			base->LocalToString(info->time, (char **)&pTime);
   275 			smcore.Format(m_DateTime, sizeof(m_DateTime), "%s %s", pDate, pTime);
   276 		}
   277 		if (m_FileVersion > 5)
   278 		{
   279 			base->LocalToString(info->filevers, (char **)&pFileVers);
   280 			SetErrorState(Plugin_Failed, "Newer SourceMod required (%s or higher)", pFileVers);
   281 			return false;
   282 		}
   283 	}
   284 	else
   285 	{
   286 		m_FileVersion = 0;
   287 	}
   288 
   289 	if ((err = base->FindPubvarByName("MaxClients", &idx)) == SP_ERROR_NONE)
   290 	{
   291 		base->GetPubvarByIndex(idx, &m_MaxClientsVar);
   292 	}
   293 
   294 	return true;
   295 }
   296 
   297 void CPlugin::SyncMaxClients(int max_clients)
   298 {
   299 	if (m_MaxClientsVar == NULL)
   300 	{
   301 		return;
   302 	}
   303 
   304 	*m_MaxClientsVar->offs = max_clients;
   305 }
   306 
   307 void CPlugin::Call_OnPluginStart()
   308 {
   309 	if (m_status != Plugin_Loaded)
   310 	{
   311 		return;
   312 	}
   313 
   314 	m_status = Plugin_Running;
   315 
   316 	SyncMaxClients(playerhelpers->GetMaxClients());
   317 
   318 	cell_t result;
   319 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginStart");
   320 	if (!pFunction)
   321 	{
   322 		return;
   323 	}
   324 
   325 	int err;
   326 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   327 	{
   328 		SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
   329 	}
   330 }
   331 
   332 void CPlugin::Call_OnPluginEnd()
   333 {
   334 	if (m_status > Plugin_Paused)
   335 	{
   336 		return;
   337 	}
   338 
   339 	cell_t result;
   340 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginEnd");
   341 	if (!pFunction)
   342 	{
   343 		return;
   344 	}
   345 
   346 	pFunction->Execute(&result);
   347 }
   348 
   349 void CPlugin::Call_OnAllPluginsLoaded()
   350 {
   351 	if (m_status > Plugin_Paused)
   352 	{
   353 		return;
   354 	}
   355 
   356 	if (m_bGotAllLoaded)
   357 	{
   358 		return;
   359 	}
   360 
   361 	m_bGotAllLoaded = true;
   362 
   363 	cell_t result;
   364 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnAllPluginsLoaded");
   365 	if (pFunction != NULL)
   366 	{
   367 		pFunction->Execute(&result);
   368 	}
   369 
   370 	if (smcore.IsMapRunning())
   371 	{
   372 		if ((pFunction = m_pRuntime->GetFunctionByName("OnMapStart")) != NULL)
   373 		{
   374 			pFunction->Execute(NULL);
   375 		}
   376 	}
   377 
   378 	if (smcore.AreConfigsExecuted())
   379 	{
   380 		smcore.ExecuteConfigs(GetBaseContext());
   381 	}
   382 }
   383 
   384 APLRes CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
   385 {
   386 	if (m_status != Plugin_Created)
   387 	{
   388 		return APLRes_Failure;
   389 	}
   390 
   391 	m_status = Plugin_Loaded;
   392 
   393 	int err;
   394 	cell_t result;
   395 	bool haveNewAPL = false;
   396 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad2");
   397 
   398 	if (pFunction) 
   399 	{
   400 		haveNewAPL = true;
   401 	}
   402 	else if (!(pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad")))
   403 	{
   404 		return APLRes_Success;
   405 	}
   406 
   407 	pFunction->PushCell(m_handle);
   408 	pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
   409 	pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
   410 	pFunction->PushCell(maxlength);
   411 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   412 	{
   413 		return APLRes_Failure;
   414 	}
   415 
   416 	if (haveNewAPL) 
   417 	{
   418 		return (APLRes)result;
   419 	}
   420 	else if (result)
   421 	{
   422 		return APLRes_Success;
   423 	}
   424 	else
   425 	{
   426 		return APLRes_Failure;
   427 	}
   428 }
   429 
   430 void *CPlugin::GetPluginStructure()
   431 {
   432 	return NULL;
   433 }
   434 
   435 IPluginContext *CPlugin::GetBaseContext()
   436 {
   437 	if (m_pRuntime == NULL)
   438 	{
   439 		return NULL;
   440 	}
   441 
   442 	return m_pRuntime->GetDefaultContext();
   443 }
   444 
   445 sp_context_t *CPlugin::GetContext()
   446 {
   447 	return NULL;
   448 }
   449 
   450 const char *CPlugin::GetFilename()
   451 {
   452 	return m_filename;
   453 }
   454 
   455 PluginType CPlugin::GetType()
   456 {
   457 	return m_type;
   458 }
   459 
   460 const sm_plugininfo_t *CPlugin::GetPublicInfo()
   461 {
   462 	if (GetStatus() >= Plugin_Created)
   463 	{
   464 		return NULL;
   465 	}
   466 	return &m_info;
   467 }
   468 
   469 unsigned int CPlugin::GetSerial()
   470 {
   471 	return m_serial;
   472 }
   473 
   474 PluginStatus CPlugin::GetStatus()
   475 {
   476 	return m_status;
   477 }
   478 
   479 bool CPlugin::IsSilentlyFailed()
   480 {
   481 	return m_bSilentlyFailed;
   482 }
   483 
   484 bool CPlugin::IsDebugging()
   485 {
   486 	if (m_pRuntime == NULL)
   487 	{
   488 		return false;
   489 	}
   490 
   491 	return true;
   492 }
   493 
   494 void CPlugin::SetSilentlyFailed(bool sf)
   495 {
   496 	m_bSilentlyFailed = sf;
   497 }
   498 
   499 void CPlugin::LibraryActions(LibraryAction action)
   500 {
   501 	List<String>::iterator iter;
   502 	for (iter = m_Libraries.begin();
   503 		iter != m_Libraries.end();
   504 		iter++)
   505 	{
   506 		g_PluginSys.OnLibraryAction((*iter).c_str(), action);
   507 	}
   508 }
   509 
   510 bool CPlugin::SetPauseState(bool paused)
   511 {
   512 	if (paused && GetStatus() != Plugin_Running)
   513 	{
   514 		return false;
   515 	} else if (!paused && GetStatus() != Plugin_Paused) {
   516 		return false;
   517 	}
   518 
   519 	if (paused)
   520 	{
   521 		LibraryActions(LibraryAction_Removed);
   522 	}
   523 
   524 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
   525 	if (pFunction)
   526 	{
   527 		cell_t result;
   528 		pFunction->PushCell(paused ? 1 : 0);
   529 		pFunction->Execute(&result);
   530 	}
   531 
   532 	if (paused)
   533 	{
   534 		m_status = Plugin_Paused;
   535 		m_pRuntime->SetPauseState(true);
   536 	} else {
   537 		m_status = Plugin_Running;
   538 		m_pRuntime->SetPauseState(false);
   539 	}
   540 
   541 	g_PluginSys._SetPauseState(this, paused);
   542 
   543 	if (!paused)
   544 	{
   545 		LibraryActions(LibraryAction_Added);
   546 	}
   547 
   548 	return true;
   549 }
   550 
   551 IdentityToken_t *CPlugin::GetIdentity()
   552 {
   553 	return m_ident;
   554 }
   555 
   556 bool CPlugin::IsRunnable()
   557 {
   558 	return (m_status <= Plugin_Paused) ? true : false;
   559 }
   560 
   561 time_t CPlugin::GetFileTimeStamp()
   562 {
   563 	char path[PLATFORM_MAX_PATH];
   564 	g_pSM->BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
   565 #ifdef PLATFORM_WINDOWS
   566 	struct _stat s;
   567 	if (_stat(path, &s) != 0)
   568 #elif defined PLATFORM_POSIX
   569 	struct stat s;
   570 	if (stat(path, &s) != 0)
   571 #endif
   572 	{
   573 		return 0;
   574 	}
   575 	else
   576 	{
   577 		return s.st_mtime;
   578 	}
   579 }
   580 
   581 time_t CPlugin::GetTimeStamp()
   582 {
   583 	return m_LastAccess;
   584 }
   585 
   586 void CPlugin::SetTimeStamp(time_t t)
   587 {
   588 	m_LastAccess = t;
   589 }
   590 
   591 IPhraseCollection *CPlugin::GetPhrases()
   592 {
   593 	return m_pPhrases;
   594 }
   595 
   596 void CPlugin::DependencyDropped(CPlugin *pOwner)
   597 {
   598 	if (!m_pRuntime)
   599 	{
   600 		return;
   601 	}
   602 
   603 	List<String>::iterator reqlib_iter;
   604 	List<String>::iterator lib_iter;
   605 	for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
   606 	{
   607 		for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
   608 		{
   609 			if ((*reqlib_iter) == (*lib_iter))
   610 			{
   611 				m_LibraryMissing = true;
   612 			}
   613 		}	
   614 	}
   615 
   616 	List<NativeEntry *>::iterator iter;
   617 	NativeEntry *pNative;
   618 	sp_native_t *native;
   619 	uint32_t idx;
   620 	unsigned int unbound = 0;
   621 
   622 	for (iter = pOwner->m_Natives.begin();
   623 		 iter != pOwner->m_Natives.end();
   624 		 iter++)
   625 	{
   626 		pNative = (*iter);
   627 		/* Find this native! */
   628 		if (m_pRuntime->FindNativeByName(pNative->name, &idx) != SP_ERROR_NONE)
   629 		{
   630 			continue;
   631 		}
   632 		/* Unbind it */
   633 		m_pRuntime->GetNativeByIndex(idx, &native);
   634 		native->pfn = NULL;
   635 		native->status = SP_NATIVE_UNBOUND;
   636 		unbound++;
   637 	}
   638 
   639 	if (unbound)
   640 	{
   641 		m_FakeNativesMissing = true;
   642 	}
   643 
   644 	/* :IDEA: in the future, add native trapping? */
   645 	if (m_FakeNativesMissing || m_LibraryMissing)
   646 	{
   647 		SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
   648 	}
   649 }
   650 
   651 unsigned int CPlugin::GetConfigCount()
   652 {
   653 	return (unsigned int)m_configs.size();
   654 }
   655 
   656 AutoConfig *CPlugin::GetConfig(unsigned int i)
   657 {
   658 	if (i >= GetConfigCount())
   659 	{
   660 		return NULL;
   661 	}
   662 
   663 	return m_configs[i];
   664 }
   665 
   666 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
   667 {
   668 	/* Do a check for duplicates to prevent double-execution */
   669 	for (size_t i = 0; i < m_configs.size(); i++)
   670 	{
   671 		if (m_configs[i]->autocfg.compare(cfg) == 0
   672 			&& m_configs[i]->folder.compare(folder) == 0
   673 			&& m_configs[i]->create == autoCreate)
   674 		{
   675 			return;
   676 		}
   677 	}
   678 
   679 	AutoConfig *c = new AutoConfig;
   680 
   681 	c->autocfg = cfg;
   682 	c->folder = folder;
   683 	c->create = autoCreate;
   684 
   685 	m_configs.push_back(c);
   686 }
   687 
   688 void CPlugin::DropEverything()
   689 {
   690 	CPlugin *pOther;
   691 	List<WeakNative>::iterator wk_iter;
   692 
   693 	/* Tell everyone that depends on us that we're about to drop */
   694 	for (List<CPlugin *>::iterator iter = m_Dependents.begin();
   695 		 iter != m_Dependents.end(); 
   696 		 iter++)
   697 	{
   698 		pOther = static_cast<CPlugin *>(*iter);
   699 		pOther->DependencyDropped(this);
   700 	}
   701 
   702 	/* Note: we don't care about things we depend on. 
   703 	 * The reason is that extensions have their own cleanup 
   704 	 * code for plugins.  Although the "right" design would be 
   705 	 * to centralize that here, i'm omitting it for now.  Thus, 
   706 	 * the code below to walk the plugins list will suffice.
   707 	 */
   708 	
   709 	/* Other plugins could be holding weak references that were 
   710 	 * added by us.  We need to clean all of those up now.
   711 	 */
   712 	for (List<CPlugin *>::iterator iter = g_PluginSys.m_plugins.begin();
   713 		 iter != g_PluginSys.m_plugins.end();
   714 		 iter++)
   715 	{
   716 		(*iter)->ToNativeOwner()->DropRefsTo(this);
   717 	}
   718 
   719 	/* Proceed with the rest of the necessities. */
   720 	CNativeOwner::DropEverything();
   721 }
   722 
   723 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
   724 {
   725 	NativeEntry *pEntry;
   726 
   727 	if ((pEntry = g_ShareSys.AddFakeNative(pFunc, name, func)) == NULL)
   728 	{
   729 		return false;
   730 	}
   731 
   732 	m_Natives.push_back(pEntry);
   733 
   734 	return true;
   735 }
   736 
   737 /*******************
   738  * PLUGIN ITERATOR *
   739  *******************/
   740 
   741 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
   742 {
   743 	mylist = _mylist;
   744 	Reset();
   745 }
   746 
   747 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
   748 {
   749 	return (*current);
   750 }
   751 
   752 bool CPluginManager::CPluginIterator::MorePlugins()
   753 {
   754 	return (current != mylist->end());
   755 }
   756 
   757 void CPluginManager::CPluginIterator::NextPlugin()
   758 {
   759 	current++;
   760 }
   761 
   762 void CPluginManager::CPluginIterator::Release()
   763 {
   764 	g_PluginSys.ReleaseIterator(this);
   765 }
   766 
   767 CPluginManager::CPluginIterator::~CPluginIterator()
   768 {
   769 }
   770 
   771 void CPluginManager::CPluginIterator::Reset()
   772 {
   773 	current = mylist->begin();
   774 }
   775 
   776 /******************
   777  * PLUGIN MANAGER *
   778  ******************/
   779 
   780 CPluginManager::CPluginManager()
   781 {
   782 	m_AllPluginsLoaded = false;
   783 	m_MyIdent = NULL;
   784 	m_LoadingLocked = false;
   785 	
   786 	m_bBlockBadPlugins = true;
   787 }
   788 
   789 CPluginManager::~CPluginManager()
   790 {
   791 	CStack<CPluginManager::CPluginIterator *>::iterator iter;
   792 	for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
   793 	{
   794 		delete (*iter);
   795 	}
   796 	m_iters.popall();
   797 }
   798 
   799 void CPluginManager::Shutdown()
   800 {
   801 	List<CPlugin *>::iterator iter;
   802 
   803 	while ((iter = m_plugins.begin()) != m_plugins.end())
   804 	{
   805 		UnloadPlugin(*iter);
   806 	}
   807 }
   808 
   809 void CPluginManager::LoadAll(const char *config_path, const char *plugins_path)
   810 {
   811 	LoadAll_FirstPass(config_path, plugins_path);
   812 	g_Extensions.MarkAllLoaded();
   813 	LoadAll_SecondPass();
   814 	g_Extensions.MarkAllLoaded();
   815 	AllPluginsLoaded();
   816 }
   817 
   818 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
   819 {
   820 	/* First read in the database of plugin settings */
   821 	m_AllPluginsLoaded = false;
   822 	LoadPluginsFromDir(basedir, NULL);
   823 }
   824 
   825 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
   826 {
   827 	char base_path[PLATFORM_MAX_PATH];
   828 
   829 	/* Form the current path to start reading from */
   830 	if (localpath == NULL)
   831 	{
   832 		libsys->PathFormat(base_path, sizeof(base_path), "%s", basedir);
   833 	} else {
   834 		libsys->PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
   835 	}
   836 
   837 	IDirectory *dir = libsys->OpenDirectory(base_path);
   838 
   839 	if (!dir)
   840 	{
   841 		char error[256];
   842 		libsys->GetPlatformError(error, sizeof(error));
   843 		smcore.LogError("[SM] Failure reading from plugins path: %s", localpath);
   844 		smcore.LogError("[SM] Platform returned error: %s", error);
   845 		return;
   846 	}
   847 
   848 	while (dir->MoreFiles())
   849 	{
   850 		if (dir->IsEntryDirectory() 
   851 			&& (strcmp(dir->GetEntryName(), ".") != 0)
   852 			&& (strcmp(dir->GetEntryName(), "..") != 0)
   853 			&& (strcmp(dir->GetEntryName(), "disabled") != 0)
   854 			&& (strcmp(dir->GetEntryName(), "optional") != 0))
   855 		{
   856 			char new_local[PLATFORM_MAX_PATH];
   857 			if (localpath == NULL)
   858 			{
   859 				/* If no path yet, don't add a former slash */
   860 				smcore.Format(new_local, sizeof(new_local), "%s", dir->GetEntryName());
   861 			} else {
   862 				libsys->PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
   863 			}
   864 			LoadPluginsFromDir(basedir, new_local);
   865 		} else if (dir->IsEntryFile()) {
   866 			const char *name = dir->GetEntryName();
   867 			size_t len = strlen(name);
   868 			if (len >= 4
   869 				&& strcmp(&name[len-4], ".smx") == 0)
   870 			{
   871 				/* If the filename matches, load the plugin */
   872 				char plugin[PLATFORM_MAX_PATH];
   873 				if (localpath == NULL)
   874 				{
   875 					smcore.Format(plugin, sizeof(plugin), "%s", name);
   876 				} else {
   877 					libsys->PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
   878 				}
   879 				LoadAutoPlugin(plugin);
   880 			}
   881 		}
   882 		dir->NextEntry();
   883 	}
   884 	libsys->CloseDirectory(dir);
   885 }
   886 
   887 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
   888 {
   889 	if (m_LoadingLocked)
   890 	{
   891 		return LoadRes_NeverLoad;
   892 	}
   893 
   894 	int err;
   895 
   896 	/**
   897 	 * Does this plugin already exist?
   898 	 */
   899 	CPlugin **pluginpp = m_LoadLookup.retrieve(path);
   900 	if (pluginpp && *pluginpp)
   901 	{
   902 		CPlugin *pPlugin = *pluginpp;
   903 		/* Check to see if we should try reloading it */
   904 		if (pPlugin->GetStatus() == Plugin_BadLoad
   905 			|| pPlugin->GetStatus() == Plugin_Error
   906 			|| pPlugin->GetStatus() == Plugin_Failed)
   907 		{
   908 			UnloadPlugin(pPlugin);
   909 		}
   910 		else
   911 		{
   912 			if (_plugin)
   913 			{
   914 				*_plugin = pPlugin;
   915 			}
   916 			return LoadRes_AlreadyLoaded;
   917 		}
   918 	}
   919 
   920 	CPlugin *pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
   921 
   922 	assert(pPlugin != NULL);
   923 
   924 	pPlugin->m_type = PluginType_MapUpdated;
   925 
   926 	ICompilation *co = NULL;
   927 
   928 	if (pPlugin->m_status == Plugin_Uncompiled)
   929 	{
   930 		co = g_pSourcePawn2->StartCompilation();
   931 	}
   932 
   933 	/* Do the actual compiling */
   934 	if (co != NULL)
   935 	{
   936 		char fullpath[PLATFORM_MAX_PATH];
   937 		g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
   938 
   939 		pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
   940 		if (pPlugin->m_pRuntime == NULL)
   941 		{
   942 			if (error)
   943 			{
   944 				smcore.Format(error, 
   945 					maxlength, 
   946 					"Unable to load plugin (error %d: %s)", 
   947 					err, 
   948 					g_pSourcePawn2->GetErrorString(err));
   949 			}
   950 			pPlugin->m_status = Plugin_BadLoad;
   951 		}
   952 		else
   953 		{
   954 			if (pPlugin->UpdateInfo())
   955 			{
   956 				pPlugin->m_status = Plugin_Created;
   957 			}
   958 			else
   959 			{
   960 				if (error)
   961 				{
   962 					smcore.Format(error, maxlength, "%s", pPlugin->m_errormsg);
   963 				}
   964 			}
   965 		}
   966 	}
   967 	
   968 	if (pPlugin->GetStatus() == Plugin_Created)
   969 	{
   970 		unsigned char *pCodeHash = pPlugin->m_pRuntime->GetCodeHash();
   971 		
   972 		char codeHashBuf[40];
   973 		smcore.Format(codeHashBuf, 40, "plugin_");
   974 		for (int i = 0; i < 16; i++)
   975 			smcore.Format(codeHashBuf + 7 + (i * 2), 3, "%02x", pCodeHash[i]);
   976 		
   977 		const char *bulletinUrl = g_pGameConf->GetKeyValue(codeHashBuf);
   978 		if (bulletinUrl != NULL)
   979 		{
   980 			if (m_bBlockBadPlugins)
   981 			{
   982 				if (error)
   983 				{
   984 					if (bulletinUrl[0] != '\0')
   985 					{
   986 						smcore.Format(error, maxlength, "Known malware detected and blocked. See %s for more info", bulletinUrl);
   987 					} else {
   988 						smcore.Format(error, maxlength, "Possible malware or illegal plugin detected and blocked");
   989 					}
   990 				}
   991 				pPlugin->m_status = Plugin_BadLoad;
   992 			} else {
   993 				if (bulletinUrl[0] != '\0')
   994 				{
   995 					smcore.Log("%s: Known malware detected. See %s for more info, blocking disabled in core.cfg", pPlugin->GetFilename(), bulletinUrl);
   996 				} else {
   997 					smcore.Log("%s: Possible malware or illegal plugin detected, blocking disabled in core.cfg", pPlugin->GetFilename());
   998 				}
   999 			}
  1000 		}
  1001 	}
  1002 
  1003 	LoadRes loadFailure = LoadRes_Failure;
  1004 	/* Get the status */
  1005 	if (pPlugin->GetStatus() == Plugin_Created)
  1006 	{
  1007 		/* First native pass - add anything from Core */
  1008 		g_ShareSys.BindNativesToPlugin(pPlugin, true);
  1009 		pPlugin->InitIdentity();
  1010 		APLRes result = pPlugin->Call_AskPluginLoad(error, maxlength);  
  1011 		switch (result)
  1012 		{
  1013 		case APLRes_Success:
  1014 			/* Autoload any modules */
  1015 			LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
  1016 			break;
  1017 		case APLRes_Failure:
  1018 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1019 			loadFailure = LoadRes_Failure;
  1020 			break;
  1021 		case APLRes_SilentFailure:
  1022 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1023 			loadFailure = LoadRes_SilentFailure;
  1024 			pPlugin->SetSilentlyFailed(true);
  1025 			break;
  1026 		default:
  1027 			assert(false);
  1028 		}
  1029 	}
  1030 
  1031 	/* Save the time stamp */
  1032 	time_t t = pPlugin->GetFileTimeStamp();
  1033 	pPlugin->SetTimeStamp(t);
  1034 
  1035 	if (_plugin)
  1036 	{
  1037 		*_plugin = pPlugin;
  1038 	}
  1039 
  1040 	return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : loadFailure;
  1041 }
  1042 
  1043 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
  1044 {
  1045 	CPlugin *pl;
  1046 	LoadRes res;
  1047 
  1048 	*wasloaded = false;
  1049 	if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
  1050 	{
  1051 		delete pl;
  1052 		return NULL;
  1053 	}
  1054 
  1055 	if (res == LoadRes_AlreadyLoaded)
  1056 	{
  1057 		*wasloaded = true;
  1058 		return pl;
  1059 	}
  1060 
  1061 	if (res == LoadRes_NeverLoad)
  1062 	{
  1063 		if (error)
  1064 		{
  1065 			if (m_LoadingLocked)
  1066 			{
  1067 				smcore.Format(error, maxlength, "There is a global plugin loading lock in effect");
  1068 			}
  1069 			else
  1070 			{
  1071 				smcore.Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
  1072 			}
  1073 		}
  1074 		return NULL;
  1075 	}
  1076 
  1077 	AddPlugin(pl);
  1078 
  1079 	/* Run second pass if we need to */
  1080 	if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
  1081 	{
  1082 		if (!RunSecondPass(pl, error, maxlength))
  1083 		{
  1084 			UnloadPlugin(pl);
  1085 			return NULL;
  1086 		}
  1087 		pl->Call_OnAllPluginsLoaded();
  1088 	}
  1089 
  1090 	return pl;
  1091 }
  1092 
  1093 void CPluginManager::LoadAutoPlugin(const char *plugin)
  1094 {
  1095 	CPlugin *pl = NULL;
  1096 	LoadRes res;
  1097 	char error[255] = "Unknown error";
  1098 
  1099 	if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
  1100 	{
  1101 		smcore.LogError("[SM] Failed to load plugin \"%s\": %s.", plugin, error);
  1102 		pl->SetErrorState(
  1103 			pl->GetStatus() <= Plugin_Created ? Plugin_BadLoad : pl->GetStatus(), 
  1104 			"%s",
  1105 			error);
  1106 	}
  1107 
  1108 	if (res == LoadRes_Successful || res == LoadRes_Failure || res == LoadRes_SilentFailure)
  1109 	{
  1110 		AddPlugin(pl);
  1111 	}
  1112 }
  1113 
  1114 void CPluginManager::AddPlugin(CPlugin *pPlugin)
  1115 {
  1116 	List<IPluginsListener *>::iterator iter;
  1117 	IPluginsListener *pListener;
  1118 
  1119 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1120 	{
  1121 		pListener = (*iter);
  1122 		pListener->OnPluginCreated(pPlugin);
  1123 	}
  1124 
  1125 	m_plugins.push_back(pPlugin);
  1126 	m_LoadLookup.insert(pPlugin->m_filename, pPlugin);
  1127 }
  1128 
  1129 void CPluginManager::LoadAll_SecondPass()
  1130 {
  1131 	List<CPlugin *>::iterator iter;
  1132 	CPlugin *pPlugin;
  1133 
  1134 	char error[256];
  1135 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1136 	{
  1137 		pPlugin = (*iter);
  1138 		if (pPlugin->GetStatus() == Plugin_Loaded)
  1139 		{
  1140 			error[0] = '\0';
  1141 			if (!RunSecondPass(pPlugin, error, sizeof(error)))
  1142 			{
  1143 				smcore.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
  1144 				pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1145 			}
  1146 		}
  1147 	}
  1148 
  1149 	m_AllPluginsLoaded = true;
  1150 }
  1151 
  1152 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
  1153 {
  1154 	struct _pl
  1155 	{
  1156 		cell_t name;
  1157 		cell_t file;
  1158 		cell_t required;
  1159 	} *pl;
  1160 
  1161 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1162 	uint32_t num = pBase->GetPubVarsNum();
  1163 	sp_pubvar_t *pubvar;
  1164 	char *name, *file;
  1165 	char pathfile[PLATFORM_MAX_PATH];
  1166 
  1167 	for (uint32_t i=0; i<num; i++)
  1168 	{
  1169 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1170 		{
  1171 			continue;
  1172 		}
  1173 		if (strncmp(pubvar->name, "__pl_", 5) == 0)
  1174 		{
  1175 			pl = (_pl *)pubvar->offs;
  1176 			if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
  1177 			{
  1178 				continue;
  1179 			}
  1180 			if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
  1181 			{
  1182 				continue;
  1183 			}
  1184 			libsys->GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
  1185 			if (strcmp(pathfile, file) == 0)
  1186 			{
  1187 				continue;
  1188 			}
  1189 			if (pl->required == false)
  1190 			{
  1191 				IPluginFunction *pFunc;
  1192 				char buffer[64];
  1193 				smcore.Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
  1194 				if ((pFunc=pBase->GetFunctionByName(buffer)))
  1195 				{
  1196 					cell_t res;
  1197 					pFunc->Execute(&res);
  1198 					if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1199 					{
  1200 						if (error)
  1201 						{
  1202 							smcore.Format(error, maxlength, "Fatal error during initializing plugin load");
  1203 						}
  1204 						return false;
  1205 					}
  1206 				}
  1207 			}
  1208 			else
  1209 			{
  1210 				/* Check that we aren't registering the same library twice */
  1211 				if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
  1212 				{
  1213 					pPlugin->m_RequiredLibs.push_back(name);
  1214 				}
  1215 				else
  1216 				{
  1217 					continue;
  1218 				}
  1219 				List<CPlugin *>::iterator iter;
  1220 				CPlugin *pl;
  1221 				bool found = false;
  1222 				for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1223 				{
  1224 					pl = (*iter);
  1225 					if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
  1226 					{
  1227 						found = true;
  1228 						break;
  1229 					}
  1230 				}
  1231 				if (!found)
  1232 				{
  1233 					if (error)
  1234 					{
  1235 						smcore.Format(error, maxlength, "Could not find required plugin \"%s\"", name);
  1236 					}
  1237 					return false;
  1238 				}
  1239 			}
  1240 		}
  1241 	}
  1242 
  1243 	return true;
  1244 }
  1245 
  1246 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
  1247 {
  1248 	/* Find any extensions this plugin needs */
  1249 	struct _ext
  1250 	{
  1251 		cell_t name;
  1252 		cell_t file;
  1253 		cell_t autoload;
  1254 		cell_t required;
  1255 	} *ext;
  1256 
  1257 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1258 	uint32_t num = pBase->GetPubVarsNum();
  1259 	sp_pubvar_t *pubvar;
  1260 	IExtension *pExt;
  1261 	char path[PLATFORM_MAX_PATH];
  1262 	char *file, *name;
  1263 	for (uint32_t i=0; i<num; i++)
  1264 	{
  1265 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1266 		{
  1267 			continue;
  1268 		}
  1269 		if (strncmp(pubvar->name, "__ext_", 6) == 0)
  1270 		{
  1271 			ext = (_ext *)pubvar->offs;
  1272 			if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
  1273 			{
  1274 				continue;
  1275 			}
  1276 			if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
  1277 			{
  1278 				continue;
  1279 			}
  1280 			if (pass == 1)
  1281 			{
  1282 				/* Attempt to auto-load if necessary */
  1283 				if (ext->autoload)
  1284 				{
  1285 					libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1286 					bool bErrorOnMissing = ext->required ? true : false;
  1287 					g_Extensions.LoadAutoExtension(path);
  1288 				}
  1289 			}
  1290 			else if (pass == 2)
  1291 			{
  1292 				/* Is this required? */
  1293 				if (ext->required)
  1294 				{
  1295 					libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1296 					if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
  1297 					{
  1298 						pExt = g_Extensions.FindExtensionByName(name);
  1299 					}
  1300 					/* :TODO: should we bind to unloaded extensions?
  1301 					 * Currently the extension manager will ignore this.
  1302 					 */
  1303 					if (!pExt || !pExt->IsRunning(NULL, 0))
  1304 					{
  1305 						if (error)
  1306 						{
  1307 							smcore.Format(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
  1308 						}
  1309 						return false;
  1310 					}
  1311 					else
  1312 					{
  1313 						g_Extensions.BindChildPlugin(pExt, pPlugin);
  1314 					}
  1315 				}
  1316 				else
  1317 				{
  1318 					IPluginFunction *pFunc;
  1319 					char buffer[64];
  1320 					smcore.Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
  1321 
  1322 					if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
  1323 					{
  1324 						cell_t res;
  1325 						pFunc->Execute(&res);
  1326 						if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1327 						{
  1328 							if (error)
  1329 							{
  1330 								smcore.Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
  1331 							}
  1332 							return false;
  1333 						}
  1334 					}
  1335 				}
  1336 			}
  1337 		}
  1338 	}
  1339 
  1340 	return true;
  1341 }
  1342 
  1343 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
  1344 {
  1345 	/* Second pass for extension requirements */
  1346 	if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
  1347 	{
  1348 		return false;
  1349 	}
  1350 
  1351 	if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
  1352 	{
  1353 		return false;
  1354 	}
  1355 
  1356 	/* Run another binding pass */
  1357 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1358 
  1359 	/* Find any unbound natives. Right now, these are not allowed. */
  1360 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1361 	uint32_t num = pContext->GetNativesNum();
  1362 	sp_native_t *native;
  1363 	for (unsigned int i=0; i<num; i++)
  1364 	{
  1365 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1366 		{
  1367 			break;
  1368 		}
  1369 		if (native->status == SP_NATIVE_UNBOUND
  1370 			&& native->name[0] != '@'
  1371 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1372 		{
  1373 			if (error)
  1374 			{
  1375 				smcore.Format(error, maxlength, "Native \"%s\" was not found", native->name);
  1376 			}
  1377 			return false;
  1378 		}
  1379 	}
  1380 
  1381 	/* Finish by telling all listeners */
  1382 	List<IPluginsListener *>::iterator iter;
  1383 	IPluginsListener *pListener;
  1384 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1385 	{
  1386 		pListener = (*iter);
  1387 		pListener->OnPluginLoaded(pPlugin);
  1388 	}
  1389 	
  1390 	/* Tell this plugin to finish initializing itself */
  1391 	pPlugin->Call_OnPluginStart();
  1392 
  1393 	/* Now, if we have fake natives, go through all plugins that might need rebinding */
  1394 	if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
  1395 	{
  1396 		List<CPlugin *>::iterator pl_iter;
  1397 		CPlugin *pOther;
  1398 		for (pl_iter = m_plugins.begin();
  1399 			 pl_iter != m_plugins.end();
  1400 			 pl_iter++)
  1401 		{
  1402 			pOther = (*pl_iter);
  1403 			if ((pOther->GetStatus() == Plugin_Error
  1404 				&& (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
  1405 				|| pOther->m_FakeNativesMissing)
  1406 			{
  1407 				TryRefreshDependencies(pOther);
  1408 			}
  1409 			else if ((pOther->GetStatus() == Plugin_Running
  1410 					  || pOther->GetStatus() == Plugin_Paused)
  1411 					 && pOther != pPlugin)
  1412 			{
  1413 				List<NativeEntry *>::iterator nv_iter;
  1414 				for (nv_iter = pPlugin->m_Natives.begin();
  1415 					 nv_iter != pPlugin->m_Natives.end();
  1416 					 nv_iter++)
  1417 				{
  1418 					g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
  1419 				}
  1420 			}
  1421 		}
  1422 	}
  1423 
  1424 	/* Go through our libraries and tell other plugins they're added */
  1425 	List<String>::iterator s_iter;
  1426 	for (s_iter = pPlugin->m_Libraries.begin();
  1427 		s_iter != pPlugin->m_Libraries.end();
  1428 		s_iter++)
  1429 	{
  1430 		OnLibraryAction((*s_iter).c_str(), LibraryAction_Added);
  1431 	}
  1432 
  1433 	/* :TODO: optimize? does this even matter? */
  1434 	pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
  1435 
  1436 	return true;
  1437 }
  1438 
  1439 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
  1440 {
  1441 	assert(pPlugin->GetBaseContext() != NULL);
  1442 
  1443 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1444 
  1445 	List<String>::iterator lib_iter;
  1446 	List<String>::iterator req_iter;
  1447 	List<CPlugin *>::iterator pl_iter;
  1448 	CPlugin *pl;
  1449 	for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
  1450 	{
  1451 		bool found = false;
  1452 		for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
  1453 		{
  1454 			pl = (*pl_iter);
  1455 			for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
  1456 			{
  1457 				if ((*req_iter) == (*lib_iter))
  1458 				{
  1459 					found = true;
  1460 				}
  1461 			}
  1462 		}
  1463 		if (!found)
  1464 		{
  1465 			pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
  1466 			return;
  1467 		}
  1468 	}
  1469 
  1470 	/* Find any unbound natives
  1471 	 * Right now, these are not allowed
  1472 	 */
  1473 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1474 	uint32_t num = pContext->GetNativesNum();
  1475 	sp_native_t *native;
  1476 	for (unsigned int i=0; i<num; i++)
  1477 	{
  1478 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1479 		{
  1480 			break;
  1481 		}
  1482 		if (native->status == SP_NATIVE_UNBOUND
  1483 			&& native->name[0] != '@'
  1484 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1485 		{
  1486 			pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
  1487 			return;
  1488 		}
  1489 	}
  1490 
  1491 	if (pPlugin->GetStatus() == Plugin_Error)
  1492 	{
  1493 		/* If we got here, all natives are okay again! */
  1494 		pPlugin->m_status = Plugin_Running;
  1495 		if (pPlugin->m_pRuntime->IsPaused())
  1496 		{
  1497 			pPlugin->m_pRuntime->SetPauseState(false);
  1498 			_SetPauseState(pPlugin, false);
  1499 		}
  1500 	}
  1501 }
  1502 
  1503 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
  1504 {
  1505 	CPlugin *pPlugin = (CPlugin *)plugin;
  1506 
  1507 	/* This prevents removal during insertion or anything else weird */
  1508 	if (m_plugins.find(pPlugin) == m_plugins.end())
  1509 	{
  1510 		return false;
  1511 	}
  1512 
  1513 	IPluginContext *pContext = plugin->GetBaseContext();
  1514 	if (pContext != NULL && pContext->IsInExec())
  1515 	{
  1516 		char buffer[255];
  1517 		smcore.Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
  1518 		engine->ServerCommand(buffer);
  1519 		return false;
  1520 	}
  1521 
  1522 	/* Remove us from the lookup table and linked list */
  1523 	m_plugins.remove(pPlugin);
  1524 	m_LoadLookup.remove(pPlugin->m_filename);
  1525 
  1526 	/* Go through our libraries and tell other plugins they're gone */
  1527 	List<String>::iterator s_iter;
  1528 	for (s_iter = pPlugin->m_Libraries.begin();
  1529 		 s_iter != pPlugin->m_Libraries.end();
  1530 		 s_iter++)
  1531 	{
  1532 		OnLibraryAction((*s_iter).c_str(), LibraryAction_Removed);
  1533 	}
  1534 
  1535 	List<IPluginsListener *>::iterator iter;
  1536 	IPluginsListener *pListener;
  1537 
  1538 	if (pPlugin->GetStatus() <= Plugin_Error)
  1539 	{
  1540 		/* Notify plugin */
  1541 		pPlugin->Call_OnPluginEnd();
  1542 
  1543 		/* Notify listeners of unloading */
  1544 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1545 		{
  1546 			pListener = (*iter);
  1547 			pListener->OnPluginUnloaded(pPlugin);
  1548 		}
  1549 	}
  1550 
  1551 	pPlugin->DropEverything();
  1552 
  1553 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1554 	{
  1555 		/* Notify listeners of destruction */
  1556 		pListener = (*iter);
  1557 		pListener->OnPluginDestroyed(pPlugin);
  1558 	}
  1559 	
  1560 	/* Tell the plugin to delete itself */
  1561 	delete pPlugin;
  1562 
  1563 	return true;
  1564 }
  1565 
  1566 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
  1567 {
  1568 	IPlugin *pPlugin;
  1569 	IPluginContext *pContext;
  1570 
  1571 	pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
  1572 
  1573 	if (pContext->GetKey(2, (void **)&pPlugin))
  1574 	{
  1575 		return pPlugin;
  1576 	}
  1577 
  1578 	return NULL;
  1579 }
  1580 
  1581 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
  1582 {
  1583 	return (CPlugin *)FindPluginByContext(ctx);
  1584 }
  1585 
  1586 unsigned int CPluginManager::GetPluginCount()
  1587 {
  1588 	return m_plugins.size();
  1589 }
  1590 
  1591 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
  1592 {
  1593 	m_listeners.push_back(listener);
  1594 }
  1595 
  1596 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
  1597 {
  1598 	m_listeners.remove(listener);
  1599 }
  1600 
  1601 IPluginIterator *CPluginManager::GetPluginIterator()
  1602 {
  1603 	if (m_iters.empty())
  1604 	{
  1605 		return new CPluginIterator(&m_plugins);
  1606 	} else {
  1607 		CPluginIterator *iter = m_iters.front();
  1608 		m_iters.pop();
  1609 		iter->Reset();
  1610 		return iter;
  1611 	}
  1612 }
  1613 
  1614 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
  1615 {
  1616 	m_iters.push(iter);
  1617 }
  1618 
  1619 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1620 {
  1621 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1622 	size_t alias_len = 0;
  1623 	size_t local_len = 0;
  1624 
  1625 	const char *ptr = alias;
  1626 	unsigned int alias_explicit_paths = 0;
  1627 	unsigned int alias_path_end = 0;
  1628 	while (*ptr != '\0')
  1629 	{
  1630 		if (*ptr == '\\' || *ptr == '/')
  1631 		{
  1632 			alias_explicit_paths++;
  1633 			alias_path_end = alias_len;
  1634 		}
  1635 		alias_len++;
  1636 		ptr++;
  1637 	}
  1638 
  1639 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1640 	{
  1641 		/* Trailing slash is totally invalid here */
  1642 		return false;
  1643 	}
  1644 
  1645 	ptr = localpath;
  1646 	unsigned int local_explicit_paths = 0;
  1647 	unsigned int local_path_end = 0;
  1648 	while (*ptr != '\0')
  1649 	{
  1650 		if (*ptr == '\\' || *ptr == '/')
  1651 		{
  1652 			local_explicit_paths++;
  1653 			local_path_end = local_len;
  1654 		}
  1655 		local_len++;
  1656 		ptr++;
  1657 	}
  1658 
  1659 	/* If the alias has more explicit paths than the real path,
  1660 	 * no match will be possible.
  1661 	 */
  1662 	if (alias_explicit_paths > local_explicit_paths)
  1663 	{
  1664 		return false;
  1665 	}
  1666 
  1667 	if (alias_explicit_paths)
  1668 	{
  1669 		/* We need to find if the paths match now.  For example, these should all match:
  1670 		 * csdm     csdm
  1671 		 * csdm     optional/csdm
  1672 		 * csdm/ban optional/crab/csdm/ban
  1673 		*/
  1674 		const char *aliasptr = alias;
  1675 		const char *localptr = localpath;
  1676 		bool match = true;
  1677 		do
  1678 		{
  1679 			if (*aliasptr != *localptr)
  1680 			{
  1681 				/* We have to knock one path off */
  1682 				local_explicit_paths--;
  1683 				if (alias_explicit_paths > local_explicit_paths)
  1684 				{
  1685 					/* Skip out if we're gonna have an impossible match */
  1686 					return false;
  1687 				}
  1688 				/* Eat up localptr tokens until we get a result */
  1689 				while (((localptr - localpath) < (int)local_path_end)
  1690 					&& *localptr != '/'
  1691 					&& *localptr != '\\')
  1692 				{
  1693 					localptr++;
  1694 				}
  1695 				/* Check if we hit the end of our searchable area.
  1696 				 * This probably isn't possible because of the path 
  1697 				 * count check, but it's a good idea anyway.
  1698 				 */
  1699 				if ((localptr - localpath) >= (int)local_path_end)
  1700 				{
  1701 					return false;
  1702 				} else {
  1703 					/* Consume the slash token */
  1704 					localptr++;
  1705 				}
  1706 				/* Reset the alias pointer so we can continue consuming */
  1707 				aliasptr = alias;
  1708 				match = false;
  1709 				continue;
  1710 			}
  1711 			/* Note:
  1712 			 * This is safe because if localptr terminates early, aliasptr will too
  1713 			 */
  1714 			do
  1715 			{
  1716 				/* We should never reach the end of the string because of this check. */
  1717 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1718 				bool localend = (localptr - localpath) > (int)local_path_end;
  1719 				if (aliasend || localend)
  1720 				{
  1721 					if (aliasend && localend)
  1722 					{
  1723 						/* we matched, and we can break out now */
  1724 						match = true;
  1725 						break;
  1726 					}
  1727 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1728 					match = false;
  1729 					break;
  1730 				}
  1731 
  1732 				/* If we got here, it's safe to compare the next two tokens */
  1733 				if (*localptr != *aliasptr)
  1734 				{
  1735 					match = false;
  1736 					break;
  1737 				}
  1738 				localptr++;
  1739 				aliasptr++;
  1740 			} while (true);
  1741 		} while (!match);
  1742 	}
  1743 
  1744 	/* If we got here, it's time to compare filenames */
  1745 	const char *aliasptr = alias;
  1746 	const char *localptr = localpath;
  1747 
  1748 	if (alias_explicit_paths)
  1749 	{
  1750 		aliasptr = &alias[alias_path_end + 1];
  1751 	}
  1752 
  1753 	if (local_explicit_paths)
  1754 	{
  1755 		localptr = &localpath[local_path_end + 1];
  1756 	}
  1757 
  1758 	while (true)
  1759 	{
  1760 		if (*aliasptr == '*')
  1761 		{
  1762 			/* First, see if this is the last character */
  1763 			if ((unsigned)(aliasptr - alias) == alias_len - 1)
  1764 			{
  1765 				/* If so, there's no need to match anything else */
  1766 				return true;
  1767 			}
  1768 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1769 			 * Note that we only need to search up to the next asterisk.
  1770 			 */
  1771 			aliasptr++;
  1772 			bool match = true;
  1773 			const char *local_orig = localptr;
  1774 			do
  1775 			{
  1776 				match = true;
  1777 				while (*aliasptr != '\0' && *aliasptr != '*')
  1778 				{
  1779 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1780 					if (*aliasptr != *localptr)
  1781 					{
  1782 						match = false;
  1783 						break;
  1784 					}
  1785 					aliasptr++;
  1786 					localptr++;
  1787 				}
  1788 				if (!match)
  1789 				{
  1790 					/* If we didn't get a match, we need to advance the search stream.
  1791 					 * This will let us skip tokens while still searching for another match.
  1792 					 */
  1793 					localptr = ++local_orig;
  1794 					/* Make sure we don't go out of bounds */
  1795 					if (*localptr == '\0')
  1796 					{
  1797 						break;
  1798 					}
  1799 				}
  1800 			} while (!match);
  1801 
  1802 			if (!match)
  1803 			{
  1804 				return false;
  1805 			} else {
  1806 				/* If we got a match, move on to the next token */
  1807 				continue;
  1808 			}
  1809 		} else if (*aliasptr == '\0') {
  1810 			if (*localptr == '\0'
  1811 				||
  1812 				strcmp(localptr, ".smx") == 0)
  1813 			{
  1814 				return true;
  1815 			} else {
  1816 				return false;
  1817 			}
  1818 		} else if (*aliasptr != *localptr) {
  1819 			return false;
  1820 		}
  1821 		aliasptr++;
  1822 		localptr++;
  1823 	}
  1824 
  1825 	return true;
  1826 }
  1827 
  1828 bool CPluginManager::IsLateLoadTime() const
  1829 {
  1830 	return (m_AllPluginsLoaded || !smcore.IsMapLoading());
  1831 }
  1832 
  1833 void CPluginManager::OnSourceModAllInitialized()
  1834 {
  1835 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1836 
  1837 	HandleAccess sec;
  1838 	handlesys->InitAccessDefaults(NULL, &sec);
  1839 
  1840 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1841 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1842 
  1843 	g_PluginType = handlesys->CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1844 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1845 
  1846 	rootmenu->AddRootConsoleCommand("plugins", "Manage Plugins", this);
  1847 
  1848 	g_ShareSys.AddInterface(NULL, GetOldAPI());
  1849 	
  1850 	m_pOnLibraryAdded = forwardsys->CreateForward("OnLibraryAdded", ET_Ignore, 1, NULL, Param_String);
  1851 	m_pOnLibraryRemoved = forwardsys->CreateForward("OnLibraryRemoved", ET_Ignore, 1, NULL, Param_String);
  1852 }
  1853 
  1854 void CPluginManager::OnSourceModShutdown()
  1855 {
  1856 	rootmenu->RemoveRootConsoleCommand("plugins", this);
  1857 
  1858 	UnloadAll();
  1859 
  1860 	handlesys->RemoveType(g_PluginType, m_MyIdent);
  1861 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1862 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1863 	
  1864 	forwardsys->ReleaseForward(m_pOnLibraryAdded);
  1865 	forwardsys->ReleaseForward(m_pOnLibraryRemoved);
  1866 }
  1867 
  1868 ConfigResult CPluginManager::OnSourceModConfigChanged(const char *key, 
  1869 												 const char *value, 
  1870 												 ConfigSource source, 
  1871 												 char *error, 
  1872 												 size_t maxlength)
  1873 {
  1874 	if (strcmp(key, "BlockBadPlugins") == 0) {
  1875 		if (strcasecmp(value, "yes") == 0)
  1876 		{
  1877 			m_bBlockBadPlugins = true;
  1878 		} else if (strcasecmp(value, "no") == 0) {
  1879 			m_bBlockBadPlugins = false;
  1880 		} else {
  1881 			smcore.Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
  1882 			return ConfigResult_Reject;
  1883 		}
  1884 		return ConfigResult_Accept;
  1885 	}
  1886 	return ConfigResult_Ignore;
  1887 }
  1888 
  1889 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1890 {
  1891 	/* We don't care about the internal object, actually */
  1892 }
  1893 
  1894 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
  1895 {
  1896 	*pSize = ((CPlugin *)object)->CalcMemUsage();
  1897 	return true;
  1898 }
  1899 
  1900 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1901 {
  1902 	IPlugin *pPlugin;
  1903 	HandleError _err;
  1904 
  1905 	HandleSecurity sec;
  1906 
  1907 	sec.pOwner = NULL;
  1908 	sec.pIdentity = m_MyIdent;
  1909 
  1910 	if ((_err=handlesys->ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1911 	{
  1912 		pPlugin = NULL;
  1913 	}
  1914 
  1915 	if (err)
  1916 	{
  1917 		*err = _err;
  1918 	}
  1919 
  1920 	return pPlugin;
  1921 }
  1922 
  1923 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1924 {
  1925 	if (num < 1 || num > (int)GetPluginCount())
  1926 	{
  1927 		return NULL;
  1928 	}
  1929 
  1930 	CPlugin *pl;
  1931 	int id = 1;
  1932 
  1933 	SourceHook::List<CPlugin *>::iterator iter;
  1934 	for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
  1935 
  1936 	pl = *iter;
  1937 
  1938 	return pl;
  1939 }
  1940 
  1941 const char *CPluginManager::GetStatusText(PluginStatus st)
  1942 {
  1943 	switch (st)
  1944 	{
  1945 	case Plugin_Running:
  1946 		return "Running";
  1947 	case Plugin_Paused:
  1948 		return "Paused";
  1949 	case Plugin_Error:
  1950 		return "Error";
  1951 	case Plugin_Uncompiled:
  1952 		return "Uncompiled";
  1953 	case Plugin_BadLoad:
  1954 		return "Bad Load";
  1955 	case Plugin_Failed:
  1956 		return "Failed";
  1957 	default:
  1958 		assert(false);
  1959 		return "-";
  1960 	}
  1961 }
  1962 
  1963 static inline bool IS_STR_FILLED(const char *text)
  1964 {
  1965 	return text[0] != '\0';
  1966 }
  1967 
  1968 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
  1969 {
  1970 	int argcount = smcore.Argc(command);
  1971 	if (argcount >= 3)
  1972 	{
  1973 		const char *cmd = smcore.Arg(command, 2);
  1974 		if (strcmp(cmd, "list") == 0)
  1975 		{
  1976 			char buffer[256];
  1977 			unsigned int id = 1;
  1978 			int plnum = GetPluginCount();
  1979 
  1980 			if (!plnum)
  1981 			{
  1982 				rootmenu->ConsolePrint("[SM] No plugins loaded");
  1983 				return;
  1984 			}
  1985 			else
  1986 			{
  1987 				rootmenu->ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
  1988 			}
  1989 
  1990 			CPlugin *pl;
  1991 			SourceHook::List<CPlugin *>::iterator iter;
  1992 			SourceHook::List<CPlugin *> m_FailList;
  1993 
  1994 			for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  1995 			{
  1996 				pl = (*iter);
  1997 				assert(pl->GetStatus() != Plugin_Created);
  1998 				int len = 0;
  1999 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  2000 				if (pl->GetStatus() != Plugin_Running && !pl->IsSilentlyFailed())
  2001 				{
  2002 					len += smcore.Format(buffer, sizeof(buffer), "  %02d <%s>", id, GetStatusText(pl->GetStatus()));
  2003 
  2004 					if (pl->GetStatus() <= Plugin_Error)
  2005 					{
  2006 						/* Plugin has failed to load. */
  2007 						m_FailList.push_back(pl);
  2008 					}
  2009 				}
  2010 				else
  2011 				{
  2012 					len += smcore.Format(buffer, sizeof(buffer), "  %02d", id);
  2013 				}
  2014 				if (pl->GetStatus() < Plugin_Created)
  2015 				{
  2016 					if (pl->IsSilentlyFailed())
  2017 						len += smcore.Format(&buffer[len], sizeof(buffer)-len, " Disabled:");
  2018 					len += smcore.Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2019 					if (IS_STR_FILLED(info->version))
  2020 					{
  2021 						len += smcore.Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
  2022 					}
  2023 					if (IS_STR_FILLED(info->author))
  2024 					{
  2025 						smcore.Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
  2026 					}
  2027 				}
  2028 				else
  2029 				{
  2030 					smcore.Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
  2031 				}
  2032 				rootmenu->ConsolePrint("%s", buffer);
  2033 			}
  2034 
  2035 			if (!m_FailList.empty())
  2036 			{
  2037 				rootmenu->ConsolePrint("Load Errors:");
  2038 
  2039 				SourceHook::List<CPlugin *>::iterator _iter;
  2040 
  2041 				CPlugin *pl;
  2042 
  2043 				for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
  2044 				{
  2045 					pl = (CPlugin *)*_iter;
  2046 					rootmenu->ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
  2047 				}
  2048 			}
  2049 
  2050 			return;
  2051 		}
  2052 		else if (strcmp(cmd, "load") == 0)
  2053 		{
  2054 			if (argcount < 4)
  2055 			{
  2056 				rootmenu->ConsolePrint("[SM] Usage: sm plugins load <file>");
  2057 				return;
  2058 			}
  2059 
  2060 			char error[128];
  2061 			bool wasloaded;
  2062 			const char *filename = smcore.Arg(command, 3);
  2063 
  2064 			char pluginfile[256];
  2065 			const char *ext = libsys->GetFileExtension(filename) ? "" : ".smx";
  2066 			g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
  2067 
  2068 			IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
  2069 
  2070 			if (wasloaded)
  2071 			{
  2072 				rootmenu->ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
  2073 				return;
  2074 			}
  2075 
  2076 			if (pl)
  2077 			{
  2078 				rootmenu->ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
  2079 			}
  2080 			else
  2081 			{
  2082 				rootmenu->ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
  2083 			}
  2084 
  2085 			return;
  2086 		}
  2087 		else if (strcmp(cmd, "unload") == 0)
  2088 		{
  2089 			if (argcount < 4)
  2090 			{
  2091 				rootmenu->ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
  2092 				return;
  2093 			}
  2094 
  2095 			CPlugin *pl;
  2096 			char *end;
  2097 			const char *arg = smcore.Arg(command, 3);
  2098 			int id = strtol(arg, &end, 10);
  2099 
  2100 			if (*end == '\0')
  2101 			{
  2102 				pl = GetPluginByOrder(id);
  2103 				if (!pl)
  2104 				{
  2105 					rootmenu->ConsolePrint("[SM] Plugin index %d not found.", id);
  2106 					return;
  2107 				}
  2108 			}
  2109 			else
  2110 			{
  2111 				char pluginfile[256];
  2112 				const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2113 				g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2114 
  2115 				CPlugin **pluginpp = m_LoadLookup.retrieve(pluginfile);
  2116 				if (!pluginpp || !*pluginpp)
  2117 				{
  2118 					rootmenu->ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2119 					return;
  2120 				}
  2121 				pl = *pluginpp;
  2122 			}
  2123 
  2124 			char name[PLATFORM_MAX_PATH];
  2125 
  2126 			if (pl->GetStatus() < Plugin_Created)
  2127 			{
  2128 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  2129 				smcore.Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2130 			}
  2131 			else
  2132 			{
  2133 				smcore.Format(name, sizeof(name), "%s", pl->GetFilename());
  2134 			}
  2135 
  2136 			if (UnloadPlugin(pl))
  2137 			{
  2138 				rootmenu->ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
  2139 			}
  2140 			else
  2141 			{
  2142 				rootmenu->ConsolePrint("[SM] Failed to unload plugin %s.", name);
  2143 			}
  2144 
  2145 			return;
  2146 		}
  2147 		else if (strcmp(cmd, "unload_all") == 0)
  2148 		{
  2149 			g_PluginSys.UnloadAll();
  2150 			rootmenu->ConsolePrint("[SM] All plugins have been unloaded.");
  2151 			return;
  2152 		}
  2153 		else if (strcmp(cmd, "load_lock") == 0)
  2154 		{
  2155 			if (m_LoadingLocked)
  2156 			{
  2157 				rootmenu->ConsolePrint("[SM] There is already a loading lock in effect.");
  2158 			}
  2159 			else
  2160 			{
  2161 				m_LoadingLocked = true;
  2162 				rootmenu->ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
  2163 			}
  2164 			return;
  2165 		}
  2166 		else if (strcmp(cmd, "load_unlock") == 0)
  2167 		{
  2168 			if (m_LoadingLocked)
  2169 			{
  2170 				m_LoadingLocked = false;
  2171 				rootmenu->ConsolePrint("[SM] The loading lock is no longer in effect.");
  2172 			}
  2173 			else
  2174 			{
  2175 				rootmenu->ConsolePrint("[SM] There was no loading lock in effect.");
  2176 			}
  2177 			return;
  2178 		}
  2179 		else if (strcmp(cmd, "info") == 0)
  2180 		{
  2181 			if (argcount < 4)
  2182 			{
  2183 				rootmenu->ConsolePrint("[SM] Usage: sm plugins info <#>");
  2184 				return;
  2185 			}
  2186 
  2187 			CPlugin *pl;
  2188 			char *end;
  2189 			const char *arg = smcore.Arg(command, 3);
  2190 			int id = strtol(arg, &end, 10);
  2191 
  2192 			if (*end == '\0')
  2193 			{
  2194 				pl = GetPluginByOrder(id);
  2195 				if (!pl)
  2196 				{
  2197 					rootmenu->ConsolePrint("[SM] Plugin index %d not found.", id);
  2198 					return;
  2199 				}
  2200 			}
  2201 			else
  2202 			{
  2203 				char pluginfile[256];
  2204 				const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2205 				g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2206 
  2207 				CPlugin **pluginpp = m_LoadLookup.retrieve(pluginfile);
  2208 				if (!pluginpp || !*pluginpp)
  2209 				{
  2210 					rootmenu->ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2211 					return;
  2212 				}
  2213 				pl = *pluginpp;
  2214 			}
  2215 
  2216 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2217 
  2218 			rootmenu->ConsolePrint("  Filename: %s", pl->GetFilename());
  2219 			if (pl->GetStatus() <= Plugin_Error)
  2220 			{
  2221 				if (IS_STR_FILLED(info->name))
  2222 				{
  2223 					if (IS_STR_FILLED(info->description))
  2224 					{
  2225 						rootmenu->ConsolePrint("  Title: %s (%s)", info->name, info->description);
  2226 					} else {
  2227 						rootmenu->ConsolePrint("  Title: %s", info->name);
  2228 					}
  2229 				}
  2230 				if (IS_STR_FILLED(info->author))
  2231 				{
  2232 					rootmenu->ConsolePrint("  Author: %s", info->author);
  2233 				}
  2234 				if (IS_STR_FILLED(info->version))
  2235 				{
  2236 					rootmenu->ConsolePrint("  Version: %s", info->version);
  2237 				}
  2238 				if (IS_STR_FILLED(info->url))
  2239 				{
  2240 					rootmenu->ConsolePrint("  URL: %s", info->url);
  2241 				}
  2242 				if (pl->GetStatus() == Plugin_Error)
  2243 				{
  2244 					rootmenu->ConsolePrint("  Error: %s", pl->m_errormsg);
  2245 				}
  2246 				else
  2247 				{
  2248 					if (pl->GetStatus() == Plugin_Running)
  2249 					{
  2250 						rootmenu->ConsolePrint("  Status: running");
  2251 					}
  2252 					else
  2253 					{
  2254 						rootmenu->ConsolePrint("  Status: not running");
  2255 					}
  2256 
  2257 					const char *typestr = "";
  2258 					switch (pl->GetType())
  2259 					{
  2260 					case PluginType_MapUpdated:
  2261 						typestr = "Map Change if Updated";
  2262 						break;
  2263 					case PluginType_MapOnly:
  2264 						typestr = "Map Change";
  2265 						break;
  2266 					case PluginType_Private:
  2267 					case PluginType_Global:
  2268 						typestr = "Never";
  2269 						break;
  2270 					}
  2271 
  2272 					rootmenu->ConsolePrint("  Reloads: %s", typestr);
  2273 				}
  2274 				if (pl->m_FileVersion >= 3)
  2275 				{
  2276 					rootmenu->ConsolePrint("  Timestamp: %s", pl->m_DateTime);
  2277 				}
  2278 				
  2279 				unsigned char *pCodeHash = pl->m_pRuntime->GetCodeHash();
  2280 				unsigned char *pDataHash = pl->m_pRuntime->GetDataHash();
  2281 				
  2282 				char combinedHash[33];
  2283 				for (int i = 0; i < 16; i++)
  2284 					smcore.Format(combinedHash + (i * 2), 3, "%02x", pCodeHash[i] ^ pDataHash[i]);
  2285 				
  2286 				rootmenu->ConsolePrint("  Hash: %s", combinedHash);
  2287 			}
  2288 			else
  2289 			{
  2290 				rootmenu->ConsolePrint("  Load error: %s", pl->m_errormsg);
  2291 				if (pl->GetStatus() < Plugin_Created)
  2292 				{
  2293 					rootmenu->ConsolePrint("  File info: (title \"%s\") (version \"%s\")", 
  2294 											info->name ? info->name : "<none>",
  2295 											info->version ? info->version : "<none>");
  2296 					if (IS_STR_FILLED(info->url))
  2297 					{
  2298 						rootmenu->ConsolePrint("  File URL: %s", info->url);
  2299 					}
  2300 				}
  2301 			}
  2302 
  2303 			return;
  2304 		}
  2305 		else if (strcmp(cmd, "refresh") == 0)
  2306 		{
  2307 			smcore.DoGlobalPluginLoads();
  2308 			rootmenu->ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
  2309 			return;
  2310 		}
  2311 		else if (strcmp(cmd, "reload") == 0)
  2312 		{
  2313 			if (argcount < 4)
  2314 			{
  2315 				rootmenu->ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
  2316 				return;
  2317 			}
  2318 
  2319 			CPlugin *pl;
  2320 			char *end;
  2321 			const char *arg = smcore.Arg(command, 3);
  2322 			int id = strtol(arg, &end, 10);
  2323 
  2324 			if (*end == '\0')
  2325 			{
  2326 				pl = GetPluginByOrder(id);
  2327 				if (!pl)
  2328 				{
  2329 					rootmenu->ConsolePrint("[SM] Plugin index %d not found.", id);
  2330 					return;
  2331 				}
  2332 			}
  2333 			else
  2334 			{
  2335 				char pluginfile[256];
  2336 				const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2337 				g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2338 
  2339 				CPlugin **pluginpp = m_LoadLookup.retrieve(pluginfile);
  2340 				if (!pluginpp || !*pluginpp)
  2341 				{
  2342 					rootmenu->ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2343 					return;
  2344 				}
  2345 				pl = *pluginpp;
  2346 			}
  2347 
  2348 			char name[PLATFORM_MAX_PATH];
  2349 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2350 			if (pl->GetStatus() <= Plugin_Paused) 
  2351 				strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2352 			else
  2353 				strcpy(name, pl->GetFilename());
  2354 
  2355 			if (ReloadPlugin(pl))
  2356 			{
  2357 				rootmenu->ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
  2358 			}
  2359 			else
  2360 			{
  2361 				rootmenu->ConsolePrint("[SM] Failed to reload plugin %s.", name);
  2362 			}
  2363 
  2364 			return;
  2365 		}
  2366 	}
  2367 
  2368 	/* Draw the main menu */
  2369 	rootmenu->ConsolePrint("SourceMod Plugins Menu:");
  2370 	rootmenu->DrawGenericOption("info", "Information about a plugin");
  2371 	rootmenu->DrawGenericOption("list", "Show loaded plugins");
  2372 	rootmenu->DrawGenericOption("load", "Load a plugin");
  2373 	rootmenu->DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
  2374 	rootmenu->DrawGenericOption("load_unlock", "Re-enables plugin loading");
  2375 	rootmenu->DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
  2376 	rootmenu->DrawGenericOption("reload", "Reloads a plugin");
  2377 	rootmenu->DrawGenericOption("unload", "Unload a plugin");
  2378 	rootmenu->DrawGenericOption("unload_all", "Unloads all plugins");
  2379 }
  2380 
  2381 bool CPluginManager::ReloadPlugin(CPlugin *pl)
  2382 {
  2383 	List<CPlugin *>::iterator iter;
  2384 	char filename[PLATFORM_MAX_PATH];
  2385 	bool wasloaded;
  2386 	PluginType ptype;
  2387 	IPlugin *newpl;
  2388 	int id = 1;
  2389 
  2390 	strcpy(filename, pl->m_filename);
  2391 	ptype = pl->GetType();
  2392 
  2393 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
  2394 	{
  2395 		if ((*iter) == pl)
  2396 		{
  2397 			break;
  2398 		}
  2399 	}
  2400 
  2401 	if (!UnloadPlugin(pl))
  2402 	{
  2403 		return false;
  2404 	}
  2405 	if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
  2406 	{
  2407 		return false;
  2408 	}
  2409 
  2410 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2411 	{
  2412 		if ((*iter) == (CPlugin *)newpl)
  2413 		{
  2414 			m_plugins.erase(iter);
  2415 			break;
  2416 		}
  2417 	}
  2418 
  2419 	int i;
  2420 	for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
  2421 	{
  2422 	}
  2423 	m_plugins.insert(iter, (CPlugin *)newpl);
  2424 
  2425 	return true;
  2426 }
  2427 
  2428 void CPluginManager::RefreshAll()
  2429 {
  2430 	/* If we're in a load lock, just skip this whole bit. */
  2431 	if (m_LoadingLocked)
  2432 	{
  2433 		return;
  2434 	}
  2435 
  2436 	List<CPlugin *>::iterator iter;
  2437 	List<CPlugin *> tmp_list = m_plugins;
  2438 	CPlugin *pl;
  2439 	time_t t;
  2440 
  2441 	for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
  2442 	{
  2443 		pl = (*iter);
  2444 		if (pl->GetType() ==  PluginType_MapOnly)
  2445 		{
  2446 			UnloadPlugin((IPlugin *)pl);
  2447 		}
  2448 		else if (pl->GetType() == PluginType_MapUpdated)
  2449 		{
  2450 			t = pl->GetFileTimeStamp();
  2451 			if (!t || t > pl->GetTimeStamp())
  2452 			{
  2453 				pl->SetTimeStamp(t);
  2454 				UnloadPlugin((IPlugin *)pl);
  2455 			}
  2456 		}
  2457 	}
  2458 }
  2459 
  2460 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
  2461 {
  2462 	List<IPluginsListener *>::iterator iter;
  2463 	IPluginsListener *pListener;
  2464 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  2465 	{
  2466 		pListener = (*iter);
  2467 		pListener->OnPluginPauseChange(pl, paused);
  2468 	}	
  2469 }
  2470 
  2471 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
  2472 {
  2473 	List<CPlugin *>::iterator iter;
  2474 	CPlugin *pPlugin;
  2475 	IPluginFunction *pFunction;
  2476 
  2477 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2478 	{
  2479 		pPlugin = (*iter);
  2480 
  2481 		if (pPlugin->GetStatus() <= Plugin_Paused)
  2482 		{
  2483 			pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
  2484 
  2485 			if (pFunction)
  2486 			{
  2487 				pForward->AddFunction(pFunction);
  2488 			}
  2489 		}
  2490 	}
  2491 }
  2492 
  2493 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
  2494 {
  2495 	if (pToken->type != g_PluginIdent)
  2496 	{
  2497 		return NULL;
  2498 	}
  2499 
  2500 	return (CPlugin *)(pToken->ptr);
  2501 }
  2502 
  2503 void CPluginManager::OnLibraryAction(const char *lib, LibraryAction action)
  2504 {
  2505 	switch (action)
  2506 	{
  2507 	case LibraryAction_Removed:
  2508 		m_pOnLibraryRemoved->PushString(lib);
  2509 		m_pOnLibraryRemoved->Execute(NULL);
  2510 		break;
  2511 	case LibraryAction_Added:
  2512 		m_pOnLibraryAdded->PushString(lib);
  2513 		m_pOnLibraryAdded->Execute(NULL);
  2514 		break;
  2515 	}
  2516 }
  2517 
  2518 bool CPluginManager::LibraryExists(const char *lib)
  2519 {
  2520 	List<CPlugin *>::iterator iter;
  2521 
  2522 	for (iter=m_plugins.begin();
  2523 		 iter!=m_plugins.end();
  2524 		 iter++)
  2525 	{
  2526 		CPlugin *pl = (*iter);
  2527 		if (pl->GetStatus() != Plugin_Running)
  2528 		{
  2529 			continue;
  2530 		}
  2531 		List<String>::iterator s_iter;
  2532 		for (s_iter = pl->m_Libraries.begin();
  2533 			 s_iter != pl->m_Libraries.end();
  2534 			 s_iter++)
  2535 		{
  2536 			if ((*s_iter).compare(lib) == 0)
  2537 			{
  2538 				return true;
  2539 			}
  2540 		}
  2541 	}
  2542 
  2543 	return false;
  2544 }
  2545 
  2546 void CPluginManager::AllPluginsLoaded()
  2547 {
  2548 	List<CPlugin *>::iterator iter;
  2549 	CPlugin *pl;
  2550 
  2551 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2552 	{
  2553 		pl = (*iter);
  2554 		pl->Call_OnAllPluginsLoaded();
  2555 	}
  2556 }
  2557 
  2558 void CPluginManager::UnloadAll()
  2559 {
  2560 	List<CPlugin *>::iterator iter;
  2561 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  2562 	{
  2563 		UnloadPlugin((*iter));
  2564 	}
  2565 }
  2566 
  2567 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
  2568 {
  2569 	int id = 1;
  2570 	List<CPlugin *>::iterator iter;
  2571 
  2572 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  2573 	{
  2574 		if ((*iter) == pl)
  2575 		{
  2576 			return id;
  2577 		}
  2578 	}
  2579 
  2580 	return -1;
  2581 }
  2582 
  2583 SMPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
  2584 {
  2585 	int id;
  2586 	char *end;
  2587 	CPlugin *pl;
  2588 	
  2589 	id = strtol(arg, &end, 10);
  2590 
  2591 	if (*end == '\0')
  2592 	{
  2593 		pl = GetPluginByOrder(id);
  2594 		if (!pl)
  2595 		{
  2596 			return NULL;
  2597 		}
  2598 	}
  2599 	else
  2600 	{
  2601 		char pluginfile[256];
  2602 		const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2603 		smcore.Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2604 
  2605 		CPlugin **pluginpp = m_LoadLookup.retrieve(pluginfile);
  2606 		if (!pluginpp || !*pluginpp)
  2607 		{
  2608 			return NULL;
  2609 		}
  2610 	}
  2611 
  2612 	return pl;
  2613 }
  2614 
  2615 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
  2616 {
  2617 	SyncMaxClients(newvalue);
  2618 }
  2619 
  2620 void CPluginManager::SyncMaxClients(int max_clients)
  2621 {
  2622 	List<CPlugin *>::iterator iter;
  2623 
  2624 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2625 	{
  2626 		(*iter)->SyncMaxClients(max_clients);
  2627 	}
  2628 }
  2629 
  2630 void CPluginManager::ListPlugins(CVector<SMPlugin *> *list)
  2631 {
  2632 	List<CPlugin *>::iterator iter;
  2633 
  2634 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2635 	{
  2636 		list->push_back((*iter));
  2637 	}
  2638 }
  2639 
  2640 class OldPluginAPI : public IPluginManager
  2641 {
  2642 public:
  2643 	IPlugin *LoadPlugin(const char *path, 
  2644 						bool debug,
  2645 						PluginType type,
  2646 						char error[],
  2647 						size_t maxlength,
  2648 						bool *wasloaded)
  2649 	{
  2650 		return g_PluginSys.LoadPlugin(path, debug, type, error, maxlength, wasloaded);
  2651 	}
  2652 
  2653 	bool UnloadPlugin(IPlugin *plugin)
  2654 	{
  2655 		return g_PluginSys.UnloadPlugin(plugin);
  2656 	}
  2657 
  2658 	IPlugin *FindPluginByContext(const sp_context_t *ctx)
  2659 	{
  2660 		return g_PluginSys.FindPluginByContext(ctx);
  2661 	}
  2662 
  2663 	unsigned int GetPluginCount()
  2664 	{
  2665 		return g_PluginSys.GetPluginCount();
  2666 	}
  2667 
  2668 	IPluginIterator *GetPluginIterator()
  2669 	{
  2670 		return g_PluginSys.GetPluginIterator();
  2671 	}
  2672 
  2673 	void AddPluginsListener(IPluginsListener *listener)
  2674 	{
  2675 		g_PluginSys.AddPluginsListener(listener);
  2676 	}
  2677 
  2678 	void RemovePluginsListener(IPluginsListener *listener)
  2679 	{
  2680 		g_PluginSys.RemovePluginsListener(listener);
  2681 	}
  2682 
  2683 	IPlugin *PluginFromHandle(Handle_t handle, HandleError *err)
  2684 	{
  2685 		return g_PluginSys.PluginFromHandle(handle, err);
  2686 	}
  2687 };
  2688 
  2689 static OldPluginAPI sOldPluginAPI;
  2690 
  2691 IPluginManager *CPluginManager::GetOldAPI()
  2692 {
  2693 	return &sOldPluginAPI;
  2694 }