core/ExtensionSys.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Tue Nov 30 13:09:30 2010 -0500 (2010-11-30)
changeset 3162 d8f90b56529f
parent 3108 9fc8e7ac629a
child 3180 61db674548aa
permissions -rw-r--r--
Fixed BanClient always banning by IP address (bug 4626, r=fyren).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     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 #include <stdlib.h>
    33 #include "ExtensionSys.h"
    34 #include "LibrarySys.h"
    35 #include "ShareSys.h"
    36 #include "Logger.h"
    37 #include "sourcemm_api.h"
    38 #include "sm_srvcmds.h"
    39 #include "sm_stringutil.h"
    40 
    41 CExtensionManager g_Extensions;
    42 IdentityType_t g_ExtType;
    43 
    44 void CExtension::Initialize(const char *filename, const char *path)
    45 {
    46 	m_pAPI = NULL;
    47 	m_pIdentToken = NULL;
    48 	unload_code = 0;
    49 	m_bFullyLoaded = false;
    50 	m_File.assign(filename);
    51 	m_Path.assign(path);
    52 	char real_name[PLATFORM_MAX_PATH];
    53 	g_LibSys.GetFileFromPath(real_name, sizeof(real_name), m_Path.c_str());
    54 	m_RealFile.assign(real_name);
    55 }
    56 
    57 CRemoteExtension::CRemoteExtension(IExtensionInterface *pAPI, const char *filename, const char *path)
    58 {
    59 	Initialize(filename, path);
    60 	m_pAPI = pAPI;
    61 }
    62 
    63 #if defined METAMOD_PLAPI_VERSION
    64 #if SOURCE_ENGINE == SE_LEFT4DEAD
    65 #define GAMEFIX "2.l4d"
    66 #elif SOURCE_ENGINE == SE_LEFT4DEAD2
    67 #define GAMEFIX "2.l4d2"
    68 #elif SOURCE_ENGINE == SE_ALIENSWARM
    69 #define GAMEFIX "2.swarm"
    70 #elif SOURCE_ENGINE == SE_ORANGEBOX
    71 #define GAMEFIX "2.ep2"
    72 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
    73 #define GAMEFIX "2.ep2v"
    74 #elif SOURCE_ENGINE == SE_DARKMESSIAH
    75 #define GAMEFIX "2.darkm"
    76 #else
    77 #define GAMEFIX "2.ep1"
    78 #endif //(SOURCE_ENGINE == SE_LEFT4DEAD) || (SOURCE_ENGINE == SE_LEFT4DEAD2)
    79 #else  //METAMOD_PLAPI_VERSION
    80 #define GAMEFIX "1.ep1"
    81 #endif //METAMOD_PLAPI_VERSION
    82 
    83 CLocalExtension::CLocalExtension(const char *filename)
    84 {
    85 	m_PlId = 0;
    86 	m_pLib = NULL;
    87 
    88 	char path[PLATFORM_MAX_PATH];
    89 
    90 	/* Special case for new bintools binary */
    91 	if (strcmp(filename, "bintools.ext") == 0)
    92 	{
    93 		goto normal;
    94 	}
    95 
    96 	/* Zeroth, see if there is an engine specific build in the new place. */
    97 	g_SourceMod.BuildPath(Path_SM,
    98 		path,
    99 		PLATFORM_MAX_PATH,
   100 		"extensions/%s." GAMEFIX "." PLATFORM_LIB_EXT,
   101 		filename);
   102 
   103 	if (g_LibSys.IsPathFile(path))
   104 	{
   105 		goto found;
   106 	}
   107 
   108 	/* First see if there is an engine specific build! */
   109 	g_SourceMod.BuildPath(Path_SM, 
   110 		path, 
   111 		PLATFORM_MAX_PATH,
   112 		"extensions/auto." GAMEFIX "/%s." PLATFORM_LIB_EXT,
   113 		filename);
   114 
   115 normal:
   116 	/* Try the "normal" version */
   117 	if (!g_LibSys.IsPathFile(path))
   118 	{
   119 		g_SourceMod.BuildPath(Path_SM,
   120 			path,
   121 			PLATFORM_MAX_PATH,
   122 			"extensions/%s." PLATFORM_LIB_EXT,
   123 			filename);
   124 	}
   125 
   126 found:
   127 	Initialize(filename, path);
   128 }
   129 
   130 bool CRemoteExtension::Load(char *error, size_t maxlength)
   131 {
   132 	if (!PerformAPICheck(error, maxlength))
   133 	{
   134 		m_pAPI = NULL;
   135 		return false;
   136 	}
   137 
   138 	if (!CExtension::Load(error, maxlength))
   139 	{
   140 		m_pAPI = NULL;
   141 		return false;
   142 	}
   143 
   144 	return true;
   145 }
   146 
   147 bool CLocalExtension::Load(char *error, size_t maxlength)
   148 {
   149 	m_pLib = g_LibSys.OpenLibrary(m_Path.c_str(), error, maxlength);
   150 
   151 	if (m_pLib == NULL)
   152 	{
   153 		return false;
   154 	}
   155 
   156 	typedef IExtensionInterface *(*GETAPI)();
   157 	GETAPI pfnGetAPI = NULL;
   158 
   159 	if ((pfnGetAPI=(GETAPI)m_pLib->GetSymbolAddress("GetSMExtAPI")) == NULL)
   160 	{
   161 		m_pLib->CloseLibrary();
   162 		m_pLib = NULL;
   163 		snprintf(error, maxlength, "Unable to find extension entry point");
   164 		return false;
   165 	}
   166 
   167 	m_pAPI = pfnGetAPI();
   168 
   169 	/* Check pointer and version */
   170 	if (!PerformAPICheck(error, maxlength))
   171 	{
   172 		m_pLib->CloseLibrary();
   173 		m_pLib = NULL;
   174 		m_pAPI = NULL;
   175 		return false;
   176 	}
   177 
   178 	/* Load as MM:S */
   179 	if (m_pAPI->IsMetamodExtension())
   180 	{
   181 		bool already;
   182 		m_PlId = g_pMMPlugins->Load(m_Path.c_str(), g_PLID, already, error, maxlength);
   183 	}
   184 
   185 	if (!CExtension::Load(error, maxlength))
   186 	{
   187 		if (m_pAPI->IsMetamodExtension())
   188 		{
   189 			if (m_PlId)
   190 			{
   191 				char dummy[255];
   192 				g_pMMPlugins->Unload(m_PlId, true, dummy, sizeof(dummy));
   193 				m_PlId = 0;
   194 			}
   195 		}
   196 		m_pLib->CloseLibrary();
   197 		m_pLib = NULL;
   198 		m_pAPI = NULL;
   199 		return false;
   200 	}
   201 
   202 	return true;
   203 }
   204 
   205 void CRemoteExtension::Unload()
   206 {
   207 }
   208 
   209 void CLocalExtension::Unload()
   210 {
   211 	if (m_pAPI != NULL && m_PlId)
   212 	{
   213 		char temp_buffer[255];
   214 		g_pMMPlugins->Unload(m_PlId, true, temp_buffer, sizeof(temp_buffer));
   215 		m_PlId = 0;
   216 	}
   217 
   218 	if (m_pLib != NULL)
   219 	{
   220 		m_pLib->CloseLibrary();
   221 		m_pLib = NULL;
   222 	}
   223 }
   224 
   225 bool CRemoteExtension::Reload(char *error, size_t maxlength)
   226 {
   227 	snprintf(error, maxlength, "Remote extensions do not support reloading");
   228 	return false;
   229 }
   230 
   231 bool CLocalExtension::Reload(char *error, size_t maxlength)
   232 {
   233 	if (m_pLib == NULL) // FIXME: just load it instead?
   234 		return false;
   235 	
   236 	m_pAPI->OnExtensionUnload();
   237 	Unload();
   238 	
   239 	return Load(error, maxlength);
   240 }
   241 
   242 bool CRemoteExtension::IsExternal()
   243 {
   244 	return true;
   245 }
   246 
   247 bool CLocalExtension::IsExternal()
   248 {
   249 	return false;
   250 }
   251 
   252 CExtension::~CExtension()
   253 {
   254 	DestroyIdentity();
   255 }
   256 
   257 bool CExtension::PerformAPICheck(char *error, size_t maxlength)
   258 {
   259 	if (!m_pAPI)
   260 	{
   261 		snprintf(error, maxlength, "No IExtensionInterface instance provided");
   262 		return false;
   263 	}
   264 	
   265 	if (m_pAPI->GetExtensionVersion() > SMINTERFACE_EXTENSIONAPI_VERSION)
   266 	{
   267 		snprintf(error, maxlength, "Extension version is too new to load (%d, max is %d)", m_pAPI->GetExtensionVersion(), SMINTERFACE_EXTENSIONAPI_VERSION);
   268 		return false;
   269 	}
   270 
   271 	return true;
   272 }
   273 
   274 bool CExtension::Load(char *error, size_t maxlength)
   275 {
   276 	CreateIdentity();
   277 	if (!m_pAPI->OnExtensionLoad(this, &g_ShareSys, error, maxlength, !g_SourceMod.IsMapLoading()))
   278 	{
   279 		DestroyIdentity();
   280 		return false;
   281 	}
   282 	else
   283 	{
   284 		/* Check if we're past load time */
   285 		if (!g_SourceMod.IsMapLoading())
   286 		{
   287 			m_pAPI->OnExtensionsAllLoaded();
   288 		}
   289 	}
   290 
   291 	return true;
   292 }
   293 
   294 void CExtension::CreateIdentity()
   295 {
   296 	if (m_pIdentToken != NULL)
   297 	{
   298 		return;
   299 	}
   300 
   301 	m_pIdentToken = g_ShareSys.CreateIdentity(g_ExtType, this);
   302 }
   303 
   304 void CExtension::DestroyIdentity()
   305 {
   306 	if (m_pIdentToken == NULL)
   307 	{
   308 		return;
   309 	}
   310 
   311 	g_ShareSys.DestroyIdentity(m_pIdentToken);
   312 	m_pIdentToken = NULL;
   313 }
   314 
   315 void CExtension::MarkAllLoaded()
   316 {
   317 	assert(m_bFullyLoaded == false);
   318 	if (!m_bFullyLoaded)
   319 	{
   320 		m_bFullyLoaded = true;
   321 		m_pAPI->OnExtensionsAllLoaded();
   322 	}
   323 }
   324 
   325 void CExtension::AddPlugin(CPlugin *pPlugin)
   326 {
   327 	/* Unfortunately we have to do this :( */
   328 	if (m_Dependents.find(pPlugin) != m_Dependents.end())
   329 	{
   330 		m_Dependents.push_back(pPlugin);
   331 	}
   332 }
   333 
   334 void CExtension::SetError(const char *error)
   335 {
   336 	m_Error.assign(error);
   337 }
   338 
   339 IExtensionInterface *CExtension::GetAPI()
   340 {
   341 	return m_pAPI;
   342 }
   343 
   344 const char *CExtension::GetFilename()
   345 {
   346 	return m_RealFile.c_str();
   347 }
   348 
   349 IdentityToken_t *CExtension::GetIdentity()
   350 {
   351 	return m_pIdentToken;
   352 }
   353 
   354 bool CRemoteExtension::IsLoaded()
   355 {
   356 	return (m_pAPI != NULL);
   357 }
   358 
   359 bool CLocalExtension::IsLoaded()
   360 {
   361 	return (m_pLib != NULL);
   362 }
   363 
   364 void CExtension::AddDependency(const IfaceInfo *pInfo)
   365 {
   366 	if (m_Deps.find(*pInfo) == m_Deps.end())
   367 	{
   368 		m_Deps.push_back(*pInfo);
   369 	}
   370 }
   371 
   372 bool operator ==(const IfaceInfo &i1, const IfaceInfo &i2)
   373 {
   374 	return (i1.iface == i2.iface) && (i1.owner == i2.owner);
   375 }
   376 
   377 void CExtension::AddChildDependent(CExtension *pOther, SMInterface *iface)
   378 {
   379 	IfaceInfo info;
   380 	info.iface = iface;
   381 	info.owner = pOther;
   382 
   383 	List<IfaceInfo>::iterator iter;
   384 	for (iter = m_ChildDeps.begin();
   385 		 iter != m_ChildDeps.end();
   386 		 iter++)
   387 	{
   388 		IfaceInfo &other = (*iter);
   389 		if (other == info)
   390 		{
   391 			return;
   392 		}
   393 	}
   394 
   395 	m_ChildDeps.push_back(info);
   396 }
   397 
   398 ITERATOR *CExtension::FindFirstDependency(IExtension **pOwner, SMInterface **pInterface)
   399 {
   400 	List<IfaceInfo>::iterator iter = m_Deps.begin();
   401 
   402 	if (iter == m_Deps.end())
   403 	{
   404 		return NULL;
   405 	}
   406 
   407 	if (pOwner)
   408 	{
   409 		*pOwner = (*iter).owner;
   410 	}
   411 	if (pInterface)
   412 	{
   413 		*pInterface = (*iter).iface;
   414 	}
   415 
   416 	List<IfaceInfo>::iterator *pIter = new List<IfaceInfo>::iterator(iter);
   417 
   418 	return (ITERATOR *)pIter;
   419 }
   420 
   421 bool CExtension::FindNextDependency(ITERATOR *iter, IExtension **pOwner, SMInterface **pInterface)
   422 {
   423 	List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
   424 	List<IfaceInfo>::iterator _iter;
   425 
   426 	if (_iter == m_Deps.end())
   427 	{
   428 		return false;
   429 	}
   430 
   431 	_iter++;
   432 
   433 	if (pOwner)
   434 	{
   435 		*pOwner = (*_iter).owner;
   436 	}
   437 	if (pInterface)
   438 	{
   439 		*pInterface = (*_iter).iface;
   440 	}
   441 
   442 	*pIter = _iter;
   443 
   444 	if (_iter == m_Deps.end())
   445 	{
   446 		return false;
   447 	}
   448 
   449 	return true;
   450 }
   451 
   452 void CExtension::FreeDependencyIterator(ITERATOR *iter)
   453 {
   454 	List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
   455 
   456 	delete pIter;
   457 }
   458 
   459 void CExtension::AddInterface(SMInterface *pInterface)
   460 {
   461 	m_Interfaces.push_back(pInterface);
   462 }
   463 
   464 bool CExtension::IsRunning(char *error, size_t maxlength)
   465 {
   466 	if (!IsLoaded())
   467 	{
   468 		if (error)
   469 		{
   470 			snprintf(error, maxlength, "%s", m_Error.c_str());
   471 		}
   472 		return false;
   473 	}
   474 
   475 	return m_pAPI->QueryRunning(error, maxlength);
   476 }
   477 
   478 void CExtension::AddLibrary(const char *library)
   479 {
   480 	m_Libraries.push_back(library);
   481 }
   482 
   483 /*********************
   484  * EXTENSION MANAGER *
   485  *********************/
   486 
   487 void CExtensionManager::OnSourceModAllInitialized()
   488 {
   489 	g_ExtType = g_ShareSys.CreateIdentType("EXTENSION");
   490 	g_PluginSys.AddPluginsListener(this);
   491 	g_RootMenu.AddRootConsoleCommand("exts", "Manage extensions", this);
   492 	g_ShareSys.AddInterface(NULL, this);
   493 }
   494 
   495 void CExtensionManager::OnSourceModShutdown()
   496 {
   497 	g_RootMenu.RemoveRootConsoleCommand("exts", this);
   498 	g_ShareSys.DestroyIdentType(g_ExtType);
   499 }
   500 
   501 void CExtensionManager::Shutdown()
   502 {
   503 	List<CExtension *>::iterator iter;
   504 
   505 	while ((iter = m_Libs.begin()) != m_Libs.end())
   506 	{
   507 		UnloadExtension((*iter));
   508 	}
   509 }
   510 
   511 void CExtensionManager::TryAutoload()
   512 {
   513 	char path[PLATFORM_MAX_PATH];
   514 
   515 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "extensions");
   516 
   517 	IDirectory *pDir = g_LibSys.OpenDirectory(path);
   518 	if (!pDir)
   519 	{
   520 		return;
   521 	}
   522 
   523 	const char *lfile;
   524 	size_t len;
   525 	while (pDir->MoreFiles())
   526 	{
   527 		if (pDir->IsEntryDirectory())
   528 		{
   529 			pDir->NextEntry();
   530 			continue;
   531 		}
   532 
   533 		lfile = pDir->GetEntryName();
   534 		len = strlen(lfile);
   535 		if (len <= 9) /* size of ".autoload" */
   536 		{
   537 			pDir->NextEntry();
   538 			continue;
   539 		}
   540 
   541 		if (strcmp(&lfile[len - 9], ".autoload") != 0)
   542 		{
   543 			pDir->NextEntry();
   544 			continue;
   545 		}
   546 
   547 		char file[PLATFORM_MAX_PATH];
   548 		len = UTIL_Format(file, sizeof(file), "%s", lfile);
   549 		strcpy(&file[len - 9], ".ext");
   550 
   551 		LoadAutoExtension(file);
   552 		
   553 		pDir->NextEntry();
   554 	}
   555 }
   556 
   557 IExtension *CExtensionManager::LoadAutoExtension(const char *path)
   558 {
   559 	/* Remove platform extension if it's there. Compat hack. */
   560 	const char *ext = g_LibSys.GetFileExtension(path);
   561 	if (strcmp(ext, PLATFORM_LIB_EXT) == 0)
   562 	{
   563 		char path2[PLATFORM_MAX_PATH];
   564 		UTIL_Format(path2, sizeof(path2), "%s", path);
   565 		path2[strlen(path) - strlen(PLATFORM_LIB_EXT) - 1] = '\0';
   566 		return LoadAutoExtension(path2);
   567 	}
   568 
   569 	IExtension *pAlready;
   570 	if ((pAlready=FindExtensionByFile(path)) != NULL)
   571 	{
   572 		return pAlready;
   573 	}
   574 
   575 	char error[256];
   576 	CExtension *p = new CLocalExtension(path);
   577 
   578 	/* We put us in the list beforehand so extensions that check for each other
   579 	 * won't recursively load each other.
   580 	 */
   581 	m_Libs.push_back(p);
   582 
   583 	if (!p->Load(error, sizeof(error)) || !p->IsLoaded())
   584 	{
   585 		g_Logger.LogError("[SM] Unable to load extension \"%s\": %s", path, error);
   586 		p->SetError(error);
   587 	}
   588 
   589 	return p;
   590 }
   591 
   592 IExtension *CExtensionManager::FindExtensionByFile(const char *file)
   593 {
   594 	List<CExtension *>::iterator iter;
   595 	CExtension *pExt;
   596 
   597 	/* Chomp off the path */
   598 	char lookup[PLATFORM_MAX_PATH];
   599 	g_LibSys.GetFileFromPath(lookup, sizeof(lookup), file);
   600 
   601 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   602 	{
   603 		pExt = (*iter);
   604 		if (pExt->IsSameFile(lookup))
   605 		{
   606 			return pExt;
   607 		}
   608 	}
   609 
   610 	return NULL;
   611 }
   612 
   613 IExtension *CExtensionManager::FindExtensionByName(const char *ext)
   614 {
   615 	List<CExtension *>::iterator iter;
   616 	CExtension *pExt;
   617 	IExtensionInterface *pAPI;
   618 	const char *name;
   619 
   620 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   621 	{
   622 		pExt = (*iter);
   623 		if (!pExt->IsLoaded())
   624 		{
   625 			continue;
   626 		}
   627 		if ((pAPI = pExt->GetAPI()) == NULL)
   628 		{
   629 			continue;
   630 		}
   631 		name = pAPI->GetExtensionName();
   632 		if (!name)
   633 		{
   634 			continue;
   635 		}
   636 		if (strcmp(name, ext) == 0)
   637 		{
   638 			return pExt;
   639 		}
   640 	}
   641 
   642 	return NULL;
   643 }
   644 
   645 IExtension *CExtensionManager::LoadExtension(const char *file, char *error, size_t maxlength)
   646 {
   647 	/* Remove platform extension if it's there. Compat hack. */
   648 	const char *ext = g_LibSys.GetFileExtension(file);
   649 	if (strcmp(ext, PLATFORM_LIB_EXT) == 0)
   650 	{
   651 		char path2[PLATFORM_MAX_PATH];
   652 		UTIL_Format(path2, sizeof(path2), "%s", file);
   653 		path2[strlen(file) - strlen(PLATFORM_LIB_EXT) - 1] = '\0';
   654 		return LoadExtension(path2, error, maxlength);
   655 	}
   656 
   657 	IExtension *pAlready;
   658 	if ((pAlready=FindExtensionByFile(file)) != NULL)
   659 	{
   660 		return pAlready;
   661 	}
   662 
   663 	CExtension *pExt = new CLocalExtension(file);
   664 
   665 	if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
   666 	{
   667 		pExt->Unload();
   668 		delete pExt;
   669 		return NULL;
   670 	}
   671 
   672 	/* :TODO: do QueryRunning check if the map is loaded */
   673 
   674 	m_Libs.push_back(pExt);
   675 
   676 	return pExt;
   677 }
   678 
   679 void CExtensionManager::BindDependency(IExtension *pRequester, IfaceInfo *pInfo)
   680 {
   681 	CExtension *pExt = (CExtension *)pRequester;
   682 	CExtension *pOwner = (CExtension *)pInfo->owner;
   683 
   684 	pExt->AddDependency(pInfo);
   685 
   686 	IExtensionInterface *pAPI = pExt->GetAPI();
   687 	if (pAPI && !pAPI->QueryInterfaceDrop(pInfo->iface))
   688 	{
   689 		pOwner->AddChildDependent(pExt, pInfo->iface);
   690 	}
   691 }
   692 
   693 void CExtensionManager::AddRawDependency(IExtension *ext, IdentityToken_t *other, void *iface)
   694 {
   695 	CExtension *pExt = (CExtension *)ext;
   696 	CExtension *pOwner = GetExtensionFromIdent(other);
   697 
   698 	IfaceInfo info;
   699 
   700 	info.iface = (SMInterface *)iface;
   701 	info.owner = pOwner;
   702 
   703 	pExt->AddDependency(&info);
   704 	pOwner->AddChildDependent(pExt, (SMInterface *)iface);
   705 }
   706 
   707 void CExtensionManager::AddInterface(IExtension *pOwner, SMInterface *pInterface)
   708 {
   709 	CExtension *pExt = (CExtension *)pOwner;
   710 
   711 	pExt->AddInterface(pInterface);
   712 }
   713 
   714 void CExtensionManager::BindChildPlugin( IExtension *pParent, CPlugin *pPlugin )
   715 {
   716 	CExtension *pExt = (CExtension *)pParent;
   717 
   718 	pExt->AddPlugin(pPlugin);
   719 }
   720 
   721 void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
   722 {
   723 	List<CExtension *>::iterator iter;
   724 
   725 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   726 	{
   727 		(*iter)->DropRefsTo((CPlugin *)plugin);
   728 	}
   729 }
   730 
   731 CExtension *CExtensionManager::FindByOrder(unsigned int num)
   732 {
   733 	if (num < 1 || num > m_Libs.size())
   734 	{
   735 		return NULL;
   736 	}
   737 
   738 	List<CExtension *>::iterator iter = m_Libs.begin();
   739 
   740 	while (iter != m_Libs.end())
   741 	{
   742 		if (--num == 0)
   743 		{
   744 			return (*iter);
   745 		}
   746 		iter++;
   747 	}
   748 
   749 	return NULL;
   750 }
   751 
   752 bool CExtensionManager::UnloadExtension(IExtension *_pExt)
   753 {
   754 	if (!_pExt)
   755 	{
   756 		return false;
   757 	}
   758 
   759 	CExtension *pExt = (CExtension *)_pExt;
   760 
   761 	if (m_Libs.find(pExt) == m_Libs.end())
   762 	{
   763 		return false;
   764 	}
   765 
   766 	/* First remove us from internal lists */
   767 	g_ShareSys.RemoveInterfaces(_pExt);
   768 	m_Libs.remove(pExt);
   769 
   770 	List<CExtension *> UnloadQueue;
   771 
   772 	/* Handle dependencies */
   773 	if (pExt->IsLoaded())
   774 	{
   775 		/* Unload any dependent plugins */
   776 		List<CPlugin *>::iterator p_iter = pExt->m_Dependents.begin();
   777 		while (p_iter != pExt->m_Dependents.end())
   778 		{
   779 			/* We have to manually unlink ourselves here, since we're no longer being managed */
   780 			g_PluginSys.UnloadPlugin((*p_iter));
   781 			p_iter = pExt->m_Dependents.erase(p_iter);
   782 		}
   783 
   784 		List<String>::iterator s_iter;
   785 		for (s_iter = pExt->m_Libraries.begin();
   786 			 s_iter != pExt->m_Libraries.end();
   787 			 s_iter++)
   788 		{
   789 			g_PluginSys.OnLibraryAction((*s_iter).c_str(), false, true);
   790 		}
   791 
   792 		/* Notify and/or unload all dependencies */
   793 		List<CExtension *>::iterator c_iter;
   794 		CExtension *pDep;
   795 		IExtensionInterface *pAPI;
   796 		for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
   797 		{
   798 			pDep = (*c_iter);
   799 			if ((pAPI=pDep->GetAPI()) == NULL)
   800 			{
   801 				continue;
   802 			}
   803 			if (pDep == pExt)
   804 			{
   805 				continue;
   806 			}
   807 			/* Now, get its dependency list */
   808 			bool dropped = false;
   809 			List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin();
   810 			while (i_iter != pDep->m_Deps.end())
   811 			{
   812 				if ((*i_iter).owner == _pExt)
   813 				{
   814 					if (!pAPI->QueryInterfaceDrop((*i_iter).iface))
   815 					{
   816 						if (!dropped)
   817 						{
   818 							dropped = true;
   819 							UnloadQueue.push_back(pDep);
   820 						}
   821 					}
   822 					pAPI->NotifyInterfaceDrop((*i_iter).iface);
   823 					i_iter = pDep->m_Deps.erase(i_iter);
   824 				}
   825 				else
   826 				{
   827 					i_iter++;
   828 				}
   829 			}
   830 			/* Flush out any back references to this plugin */
   831 			i_iter = pDep->m_ChildDeps.begin();
   832 			while (i_iter != pDep->m_ChildDeps.end())
   833 			{
   834 				if ((*i_iter).owner == pExt)
   835 				{
   836 					i_iter = pDep->m_ChildDeps.erase(i_iter);
   837 				}
   838 				else
   839 				{
   840 					i_iter++;
   841 				}
   842 			}
   843 		}
   844 
   845 		/* Unbind our natives from Core */
   846 		pExt->DropEverything();
   847 	}
   848 
   849 	IdentityToken_t *pIdentity;
   850 	if ((pIdentity = pExt->GetIdentity()) != NULL)
   851 	{
   852 		SMGlobalClass *glob = SMGlobalClass::head;
   853 		while (glob)
   854 		{
   855 			glob->OnSourceModIdentityDropped(pIdentity);
   856 			glob = glob->m_pGlobalClassNext;
   857 		}
   858 	}
   859 
   860 	/* Tell it to unload */
   861 	if (pExt->IsLoaded())
   862 	{
   863 		IExtensionInterface *pAPI = pExt->GetAPI();
   864 		pAPI->OnExtensionUnload();
   865 	}
   866 
   867 	pExt->Unload();
   868 	delete pExt;
   869 
   870 	List<CExtension *>::iterator iter;
   871 	for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
   872 	{
   873 		/* NOTE: This is safe because the unload function backs out of anything not present */
   874 		UnloadExtension((*iter));
   875 	}
   876 
   877 	return true;
   878 }
   879 
   880 void CExtensionManager::MarkAllLoaded()
   881 {
   882 	List<CExtension *>::iterator iter;
   883 	CExtension *pExt;
   884 
   885 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   886 	{
   887 		pExt = (*iter);
   888 		if (!pExt->IsLoaded())
   889 		{
   890 			continue;
   891 		}
   892 		if (pExt->m_bFullyLoaded)
   893 		{
   894 			continue;
   895 		}
   896 		pExt->MarkAllLoaded();
   897 	}
   898 }
   899 
   900 void CExtensionManager::AddDependency(IExtension *pSource, const char *file, bool required, bool autoload)
   901 {
   902 	/* This function doesn't really need to do anything now.  We make sure the 
   903 	 * other extension is loaded, but handling of dependencies is really done 
   904 	 * by the interface fetcher.
   905 	 */
   906 	if (required || autoload)
   907 	{
   908 		LoadAutoExtension(file);
   909 	}
   910 }
   911 
   912 void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
   913 {
   914 	int argcount = command.ArgC();
   915 	if (argcount >= 3)
   916 	{
   917 		const char *cmd = command.Arg(2);
   918 		if (strcmp(cmd, "list") == 0)
   919 		{
   920 			List<CExtension *>::iterator iter;
   921 			CExtension *pExt;
   922 			unsigned int num = 1;
   923 			switch (m_Libs.size())
   924 			{
   925 			case 1:
   926 				{
   927 					g_RootMenu.ConsolePrint("[SM] Displaying 1 extension:");
   928 					break;
   929 				}
   930 			case 0:
   931 				{
   932 					g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
   933 					break;
   934 				}
   935 			default:
   936 				{
   937 					g_RootMenu.ConsolePrint("[SM] Displaying %d extensions:", m_Libs.size());
   938 					break;
   939 				}
   940 			}
   941 			for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++,num++)
   942 			{
   943 				pExt = (*iter);
   944 				if (pExt->IsLoaded())
   945 				{
   946 					char error[255];
   947 					if (!pExt->IsRunning(error, sizeof(error)))
   948 					{
   949 						g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), error);
   950 					}
   951 					else
   952 					{
   953 						IExtensionInterface *pAPI = pExt->GetAPI();
   954 						const char *name = pAPI->GetExtensionName();
   955 						const char *version = pAPI->GetExtensionVerString();
   956 						const char *descr = pAPI->GetExtensionDescription();
   957 						g_RootMenu.ConsolePrint("[%02d] %s (%s): %s", num, name, version, descr);
   958 					}
   959 				} else {
   960 					g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), pExt->m_Error.c_str());
   961 				}
   962 			}
   963 			return;
   964 		}
   965 		else if (strcmp(cmd, "load") == 0)
   966 		{
   967 			if (argcount < 4)
   968 			{
   969 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts load <file>");
   970 				return;
   971 			}
   972 
   973 			const char *filename = command.Arg(3);
   974 			char path[PLATFORM_MAX_PATH];
   975 			char error[256];
   976 
   977 			UTIL_Format(path, sizeof(path), "%s%s%s", filename, !strstr(filename, ".ext") ? ".ext" : "",
   978 				!strstr(filename, "." PLATFORM_LIB_EXT) ? "." PLATFORM_LIB_EXT : "");
   979 			
   980 			if (FindExtensionByFile(path) != NULL)
   981 			{
   982 				g_RootMenu.ConsolePrint("[SM] Extension %s is already loaded.", path);
   983 				return;
   984 			}
   985 			
   986 			if (LoadExtension(path, error, sizeof(error)))
   987 			{
   988 				g_RootMenu.ConsolePrint("[SM] Loaded extension %s successfully.", path);
   989 			} else
   990 			{
   991 				g_RootMenu.ConsolePrint("[SM] Extension %s failed to load: %s", path, error);
   992 			}
   993 			
   994 			return;
   995 		}
   996 		else if (strcmp(cmd, "info") == 0)
   997 		{
   998 			if (argcount < 4)
   999 			{
  1000 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts info <#>");
  1001 				return;
  1002 			}
  1003 
  1004 			const char *sId = command.Arg(3);
  1005 			unsigned int id = atoi(sId);
  1006 			if (id <= 0)
  1007 			{
  1008 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts info <#>");
  1009 				return;
  1010 			}
  1011 
  1012 			if (m_Libs.size() == 0)
  1013 			{
  1014 				g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
  1015 				return;
  1016 			}
  1017 
  1018 			if (id > m_Libs.size())
  1019 			{
  1020 				g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
  1021 				return;
  1022 			}
  1023 
  1024 			List<CExtension *>::iterator iter = m_Libs.begin();
  1025 			CExtension *pExt = NULL;
  1026 			while (iter != m_Libs.end())
  1027 			{
  1028 				if (--id == 0)
  1029 				{
  1030 					pExt = (*iter);
  1031 					break;
  1032 				}
  1033 				iter++;
  1034 			}
  1035 			/* This should never happen */
  1036 			if (!pExt)
  1037 			{
  1038 				g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
  1039 				return;
  1040 			}
  1041 
  1042 			if (!pExt->IsLoaded())
  1043 			{
  1044 				g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
  1045 				g_RootMenu.ConsolePrint(" Loaded: No (%s)", pExt->m_Error.c_str());
  1046 			}
  1047 			else
  1048 			{
  1049 				char error[255];
  1050 				if (!pExt->IsRunning(error, sizeof(error)))
  1051 				{
  1052 					g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
  1053 					g_RootMenu.ConsolePrint(" Loaded: Yes");
  1054 					g_RootMenu.ConsolePrint(" Running: No (%s)", error);
  1055 				}
  1056 				else
  1057 				{
  1058 					IExtensionInterface *pAPI = pExt->GetAPI();
  1059 					g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
  1060 					g_RootMenu.ConsolePrint(" Loaded: Yes (version %s)", pAPI->GetExtensionVerString());
  1061 					g_RootMenu.ConsolePrint(" Name: %s (%s)", pAPI->GetExtensionName(), pAPI->GetExtensionDescription());
  1062 					g_RootMenu.ConsolePrint(" Author: %s (%s)", pAPI->GetExtensionAuthor(), pAPI->GetExtensionURL());
  1063 					g_RootMenu.ConsolePrint(" Binary info: API version %d (compiled %s)", pAPI->GetExtensionVersion(), pAPI->GetExtensionDateString());
  1064 
  1065 					if (pExt->IsExternal())
  1066 					{
  1067 						g_RootMenu.ConsolePrint(" Method: Loaded by Metamod:Source, attached to SourceMod");
  1068 					}
  1069 					else if (pAPI->IsMetamodExtension())
  1070 					{
  1071 						g_RootMenu.ConsolePrint(" Method: Loaded by SourceMod, attached to Metamod:Source");
  1072 					}
  1073 					else
  1074 					{
  1075 						g_RootMenu.ConsolePrint(" Method: Loaded by SourceMod");
  1076 					}
  1077 				}
  1078 			}
  1079 			return;
  1080 		}
  1081 		else if (strcmp(cmd, "unload") == 0)
  1082 		{
  1083 			if (argcount < 4)
  1084 			{
  1085 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts unload <#> [code]");
  1086 				return;
  1087 			}
  1088 
  1089 			const char *arg = command.Arg(3);
  1090 			unsigned int num = atoi(arg);
  1091 			CExtension *pExt = FindByOrder(num);
  1092 
  1093 			if (!pExt)
  1094 			{
  1095 				g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
  1096 				return;
  1097 			}
  1098 
  1099 			if (argcount > 4 && pExt->unload_code)
  1100 			{
  1101 				const char *unload = command.Arg(4);
  1102 				if (pExt->unload_code == (unsigned)atoi(unload))
  1103 				{
  1104 					char filename[PLATFORM_MAX_PATH];
  1105 					snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
  1106 					UnloadExtension(pExt);
  1107 					g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
  1108 				}
  1109 				else
  1110 				{
  1111 					g_RootMenu.ConsolePrint("[SM] Please try again, the correct unload code is \"%d\"", pExt->unload_code);
  1112 				}
  1113 				return;
  1114 			}
  1115 
  1116 			if (!pExt->IsLoaded() 
  1117 				|| (!pExt->m_ChildDeps.size() && !pExt->m_Dependents.size()))
  1118 			{
  1119 				char filename[PLATFORM_MAX_PATH];
  1120 				snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
  1121 				UnloadExtension(pExt);
  1122 				g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
  1123 				return;
  1124 			}
  1125 			else
  1126 			{
  1127 				List<CPlugin *> plugins;
  1128 				if (pExt->m_ChildDeps.size())
  1129 				{
  1130 					g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
  1131 					List<CExtension *>::iterator iter;
  1132 					CExtension *pOther;
  1133 					/* Get list of all extensions */
  1134 					for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
  1135 					{
  1136 						List<IfaceInfo>::iterator i_iter;
  1137 						pOther = (*iter);
  1138 						if (!pOther->IsLoaded() || pOther == pExt)
  1139 						{
  1140 							continue;
  1141 						}
  1142 						/* Get their dependencies */
  1143 						for (i_iter=pOther->m_Deps.begin();
  1144 							 i_iter!=pOther->m_Deps.end();
  1145 							 i_iter++)
  1146 						{
  1147 							/* Is this dependency to us? */
  1148 							if ((*i_iter).owner != pExt)
  1149 							{
  1150 								continue;
  1151 							}
  1152 							/* Will our dependent care? */
  1153 							if (!pExt->GetAPI()->QueryInterfaceDrop((*i_iter).iface))
  1154 							{
  1155 								g_RootMenu.ConsolePrint(" -> %s", pExt->GetFilename());
  1156 								/* Add to plugin unload list */
  1157 								List<CPlugin *>::iterator p_iter;
  1158 								for (p_iter=pOther->m_Dependents.begin();
  1159 									 p_iter!=pOther->m_Dependents.end();
  1160 									 p_iter++)
  1161 								{
  1162 									if (plugins.find((*p_iter)) == plugins.end())
  1163 									{
  1164 										plugins.push_back((*p_iter));
  1165 									}
  1166 								}
  1167 							}
  1168 						}
  1169 					}
  1170 				}
  1171 				if (pExt->m_Dependents.size())
  1172 				{
  1173 					g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
  1174 					List<CPlugin *>::iterator iter;
  1175 					CPlugin *pPlugin;
  1176 					for (iter = pExt->m_Dependents.begin(); iter != pExt->m_Dependents.end(); iter++)
  1177 					{
  1178 						pPlugin = (*iter);
  1179 						if (plugins.find(pPlugin) == plugins.end())
  1180 						{
  1181 							plugins.push_back(pPlugin);
  1182 						}
  1183 					}
  1184 					for (iter = plugins.begin(); iter != plugins.end(); iter++)
  1185 					{
  1186 						pPlugin = (*iter);
  1187 						g_RootMenu.ConsolePrint(" -> %s", pPlugin->GetFilename());
  1188 					}
  1189 				}
  1190 				srand(static_cast<int>(time(NULL)));
  1191 				pExt->unload_code = (rand() % 877) + 123;	//123 to 999
  1192 				g_RootMenu.ConsolePrint("[SM] To verify unloading %s, please use the following: ", pExt->GetFilename());
  1193 				g_RootMenu.ConsolePrint("[SM] sm exts unload %d %d", num, pExt->unload_code);
  1194 
  1195 				return;
  1196 			}
  1197 		}
  1198 		else if (strcmp(cmd, "reload") == 0)
  1199 		{
  1200 			if (argcount < 4)
  1201 			{
  1202 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts reload <#>");
  1203 				return;
  1204 			}
  1205 			
  1206 			const char *arg = command.Arg(3);
  1207 			unsigned int num = atoi(arg);
  1208 			CExtension *pExt = FindByOrder(num);
  1209 
  1210 			if (!pExt)
  1211 			{
  1212 				g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
  1213 				return;
  1214 			}
  1215 			
  1216 			if (pExt->IsLoaded())
  1217 			{
  1218 				char filename[PLATFORM_MAX_PATH];
  1219 				char error[255];
  1220 				
  1221 				snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
  1222 				
  1223 				if (pExt->Reload(error, sizeof(error)))
  1224 				{
  1225 					g_RootMenu.ConsolePrint("[SM] Extension %s is now reloaded.", filename);
  1226 				}
  1227 				else
  1228 				{
  1229 					g_RootMenu.ConsolePrint("[SM] Extension %s failed to reload: %s", filename, error);
  1230 				}
  1231 					
  1232 				return;
  1233 			} 
  1234 			else
  1235 			{
  1236 				g_RootMenu.ConsolePrint("[SM] Extension %s is not loaded.", pExt->GetFilename());
  1237 				
  1238 				return;
  1239 			}
  1240 			
  1241 		}
  1242 	}
  1243 
  1244 	g_RootMenu.ConsolePrint("SourceMod Extensions Menu:");
  1245 	g_RootMenu.DrawGenericOption("info", "Extra extension information");
  1246 	g_RootMenu.DrawGenericOption("list", "List extensions");
  1247 	g_RootMenu.DrawGenericOption("load", "Load an extension");
  1248 	g_RootMenu.DrawGenericOption("reload", "Reload an extension");
  1249 	g_RootMenu.DrawGenericOption("unload", "Unload an extension");
  1250 }
  1251 
  1252 CExtension *CExtensionManager::GetExtensionFromIdent(IdentityToken_t *ptr)
  1253 {
  1254 	if (ptr->type == g_ExtType)
  1255 	{
  1256 		return (CExtension *)(ptr->ptr);
  1257 	}
  1258 
  1259 	return NULL;
  1260 }
  1261 
  1262 CExtensionManager::CExtensionManager()
  1263 {
  1264 }
  1265 
  1266 CExtensionManager::~CExtensionManager()
  1267 {
  1268 }
  1269 
  1270 void CExtensionManager::AddLibrary(IExtension *pSource, const char *library)
  1271 {
  1272 	CExtension *pExt = (CExtension *)pSource;
  1273 	pExt->AddLibrary(library);
  1274 	g_PluginSys.OnLibraryAction(library, false, false);
  1275 }
  1276 
  1277 bool CExtensionManager::LibraryExists(const char *library)
  1278 {
  1279 	CExtension *pExt;
  1280 
  1281 	for (List<CExtension *>::iterator iter = m_Libs.begin();
  1282 		 iter != m_Libs.end();
  1283 		 iter++)
  1284 	{
  1285 		pExt = (*iter);
  1286 		for (List<String>::iterator s_iter = pExt->m_Libraries.begin();
  1287 			 s_iter != pExt->m_Libraries.end();
  1288 			 s_iter++)
  1289 		{
  1290 			if ((*s_iter).compare(library) == 0)
  1291 			{
  1292 				return true;
  1293 			}
  1294 		}
  1295 	}
  1296 
  1297 	return false;
  1298 }
  1299 
  1300 IExtension *CExtensionManager::LoadExternal(IExtensionInterface *pInterface,
  1301 											const char *filepath,
  1302 											const char *filename,
  1303 											char *error,
  1304 											size_t maxlength)
  1305 {
  1306 	IExtension *pAlready;
  1307 	if ((pAlready=FindExtensionByFile(filename)) != NULL)
  1308 	{
  1309 		return pAlready;
  1310 	}
  1311 
  1312 	CExtension *pExt = new CRemoteExtension(pInterface, filename, filepath);
  1313 
  1314 	if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
  1315 	{
  1316 		pExt->Unload();
  1317 		delete pExt;
  1318 		return NULL;
  1319 	}
  1320 
  1321 	m_Libs.push_back(pExt);
  1322 
  1323 	return pExt;
  1324 }
  1325 
  1326 void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax)
  1327 {
  1328 	IExtensionInterface *pAPI;
  1329 	List<CExtension *>::iterator iter;
  1330 
  1331 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
  1332 	{
  1333 		if ((pAPI = (*iter)->GetAPI()) == NULL)
  1334 		{
  1335 			continue;
  1336 		}
  1337 		if (pAPI->GetExtensionVersion() > 3)
  1338 		{
  1339 			pAPI->OnCoreMapStart(pEdictList, edictCount, clientMax);
  1340 		}
  1341 	}
  1342 }
  1343 
  1344 bool CLocalExtension::IsSameFile(const char *file)
  1345 {
  1346 	/* Only care about the shortened name. */
  1347 	return strcmp(file, m_File.c_str()) == 0;
  1348 }
  1349 
  1350 bool CRemoteExtension::IsSameFile(const char *file)
  1351 {
  1352 	/* :TODO: this could be better, but no one uses this API anyway. */
  1353 	return strcmp(file, m_Path.c_str()) == 0;
  1354 }
  1355