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