core/PlayerManager.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Sun Jun 06 17:53:38 2010 -0400 (2010-06-06)
changeset 3032 ee7a5629ff68
parent 3010 8ea042c00c80
child 3177 c31089f82da4
permissions -rw-r--r--
Fixed OnClientConnected forward not firing for bots (bug 4443, r=fyren)
     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 "PlayerManager.h"
    33 #include "ForwardSys.h"
    34 #include "ShareSys.h"
    35 #include "AdminCache.h"
    36 #include "ConCmdManager.h"
    37 #include "MenuStyle_Valve.h"
    38 #include "MenuStyle_Radio.h"
    39 #include "sm_stringutil.h"
    40 #include "CoreConfig.h"
    41 #include "TimerSys.h"
    42 #include "Logger.h"
    43 #include "ChatTriggers.h"
    44 #include "HalfLife2.h"
    45 #include <inetchannel.h>
    46 #include <iclient.h>
    47 #include <IGameConfigs.h>
    48 #include "ExtensionSys.h"
    49 #include <sourcemod_version.h>
    50 #include "ConsoleDetours.h"
    51 #include "logic_bridge.h"
    52 
    53 PlayerManager g_Players;
    54 bool g_OnMapStarted = false;
    55 IForward *PreAdminCheck = NULL;
    56 IForward *PostAdminCheck = NULL;
    57 IForward *PostAdminFilter = NULL;
    58 IForward *OnClientConnected = NULL;
    59 const unsigned int *g_NumPlayersToAuth = NULL;
    60 int lifestate_offset = -1;
    61 List<ICommandTargetProcessor *> target_processors;
    62 
    63 SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, edict_t *, const char *, const char *, char *, int);
    64 SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, const char *);
    65 SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *);
    66 #if SOURCE_ENGINE >= SE_ORANGEBOX
    67 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    68 #else
    69 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    70 #endif
    71 SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
    72 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
    73 
    74 #if SOURCE_ENGINE >= SE_ORANGEBOX
    75 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
    76 #elif SOURCE_ENGINE == SE_DARKMESSIAH
    77 SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
    78 #else
    79 # if SH_IMPL_VERSION >= 4
    80  extern int __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    81 # else
    82  extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    83 # endif
    84 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    85 #endif
    86 
    87 ConCommand *maxplayersCmd = NULL;
    88 
    89 unsigned int g_PlayerSerialCount = 0;
    90 
    91 class KickPlayerTimer : public ITimedEvent
    92 {
    93 public:
    94 	ResultType OnTimer(ITimer *pTimer, void *pData)
    95 	{
    96 		int userid = (int)pData;
    97 		int client = g_Players.GetClientOfUserId(userid);
    98 		if (client)
    99 		{
   100 			CPlayer *player = g_Players.GetPlayerByIndex(client);
   101 			player->Kick("Your name is reserved by SourceMod; set your password to use it.");
   102 		}
   103 		return Pl_Stop;
   104 	}
   105 	void OnTimerEnd(ITimer *pTimer, void *pData)
   106 	{
   107 	}
   108 } s_KickPlayerTimer;
   109 
   110 PlayerManager::PlayerManager()
   111 {
   112 	m_AuthQueue = NULL;
   113 	m_FirstPass = false;
   114 	m_maxClients = 0;
   115 
   116 	m_UserIdLookUp = new int[USHRT_MAX+1];
   117 	memset(m_UserIdLookUp, 0, sizeof(int) * (USHRT_MAX+1));
   118 }
   119 
   120 PlayerManager::~PlayerManager()
   121 {
   122 	g_NumPlayersToAuth = NULL;
   123 
   124 	delete [] m_AuthQueue;
   125 	delete [] m_UserIdLookUp;
   126 }
   127 
   128 void PlayerManager::OnSourceModAllInitialized()
   129 {
   130 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientConnect, serverClients, this, &PlayerManager::OnClientConnect, false);
   131 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientConnect, serverClients, this, &PlayerManager::OnClientConnect_Post, true);
   132 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientPutInServer, serverClients, this, &PlayerManager::OnClientPutInServer, true);
   133 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientDisconnect, serverClients, this, &PlayerManager::OnClientDisconnect, false);
   134 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientDisconnect, serverClients, this, &PlayerManager::OnClientDisconnect_Post, true);
   135 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientCommand, serverClients, this, &PlayerManager::OnClientCommand, false);
   136 	SH_ADD_HOOK_MEMFUNC(IServerGameClients, ClientSettingsChanged, serverClients, this, &PlayerManager::OnClientSettingsChanged, true);
   137 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, ServerActivate, gamedll, this, &PlayerManager::OnServerActivate, true);
   138 
   139 	g_ShareSys.AddInterface(NULL, this);
   140 
   141 	ParamType p1[] = {Param_Cell, Param_String, Param_Cell};
   142 	ParamType p2[] = {Param_Cell};
   143 
   144 	m_clconnect = g_Forwards.CreateForward("OnClientConnect", ET_LowEvent, 3, p1);
   145 	m_clputinserver = g_Forwards.CreateForward("OnClientPutInServer", ET_Ignore, 1, p2);
   146 	m_cldisconnect = g_Forwards.CreateForward("OnClientDisconnect", ET_Ignore, 1, p2);
   147 	m_cldisconnect_post = g_Forwards.CreateForward("OnClientDisconnect_Post", ET_Ignore, 1, p2);
   148 	m_clcommand = g_Forwards.CreateForward("OnClientCommand", ET_Hook, 2, NULL, Param_Cell, Param_Cell);
   149 	m_clinfochanged = g_Forwards.CreateForward("OnClientSettingsChanged", ET_Ignore, 1, p2);
   150 	m_clauth = g_Forwards.CreateForward("OnClientAuthorized", ET_Ignore, 2, NULL, Param_Cell, Param_String);
   151 	m_onActivate = g_Forwards.CreateForward("OnServerLoad", ET_Ignore, 0, NULL);
   152 	m_onActivate2 = g_Forwards.CreateForward("OnMapStart", ET_Ignore, 0, NULL);
   153 	OnClientConnected = g_Forwards.CreateForward("OnClientConnected", ET_Ignore, 1, p2);
   154 
   155 	PreAdminCheck = g_Forwards.CreateForward("OnClientPreAdminCheck", ET_Event, 1, p1);
   156 	PostAdminCheck = g_Forwards.CreateForward("OnClientPostAdminCheck", ET_Ignore, 1, p1);
   157 	PostAdminFilter = g_Forwards.CreateForward("OnClientPostAdminFilter", ET_Ignore, 1, p1);
   158 
   159 	m_bIsListenServer = !engine->IsDedicatedServer();
   160 	m_ListenClient = 0;
   161 
   162 	g_ConVarManager.AddConVarChangeListener("tv_enable", this);
   163 
   164 	ConCommand *pCmd = FindCommand("maxplayers");
   165 	if (pCmd != NULL)
   166 	{
   167 		SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, pCmd, CmdMaxplayersCallback, true);
   168 		maxplayersCmd = pCmd;
   169 	}
   170 }
   171 
   172 void PlayerManager::OnSourceModShutdown()
   173 {
   174 	SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientConnect, serverClients, this, &PlayerManager::OnClientConnect, false);
   175 	SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientPutInServer, serverClients, this, &PlayerManager::OnClientPutInServer, true);
   176 	SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientDisconnect, serverClients, this, &PlayerManager::OnClientDisconnect, false);
   177 	SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientDisconnect, serverClients, this, &PlayerManager::OnClientDisconnect_Post, true);
   178 	SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientCommand, serverClients, this, &PlayerManager::OnClientCommand, false);
   179 	SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, ClientSettingsChanged, serverClients, this, &PlayerManager::OnClientSettingsChanged, true);
   180 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, ServerActivate, gamedll, this, &PlayerManager::OnServerActivate, true);
   181 
   182 	/* Release forwards */
   183 	g_Forwards.ReleaseForward(m_clconnect);
   184 	g_Forwards.ReleaseForward(m_clputinserver);
   185 	g_Forwards.ReleaseForward(m_cldisconnect);
   186 	g_Forwards.ReleaseForward(m_cldisconnect_post);
   187 	g_Forwards.ReleaseForward(m_clcommand);
   188 	g_Forwards.ReleaseForward(m_clinfochanged);
   189 	g_Forwards.ReleaseForward(m_clauth);
   190 	g_Forwards.ReleaseForward(m_onActivate);
   191 	g_Forwards.ReleaseForward(m_onActivate2);
   192 	g_Forwards.ReleaseForward(OnClientConnected);
   193 
   194 	g_Forwards.ReleaseForward(PreAdminCheck);
   195 	g_Forwards.ReleaseForward(PostAdminCheck);
   196 	g_Forwards.ReleaseForward(PostAdminFilter);
   197 
   198 	delete [] m_Players;
   199 
   200 	g_ConVarManager.RemoveConVarChangeListener("tv_enable", this);
   201 
   202 	if (maxplayersCmd != NULL)
   203 	{
   204 		SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, maxplayersCmd, CmdMaxplayersCallback, true);
   205 	}
   206 }
   207 
   208 ConfigResult PlayerManager::OnSourceModConfigChanged(const char *key, 
   209 												 const char *value, 
   210 												 ConfigSource source, 
   211 												 char *error, 
   212 												 size_t maxlength)
   213 {
   214 	if (strcmp(key, "PassInfoVar") == 0)
   215 	{
   216 		if (strcmp(value, "_password") != 0)
   217 		{
   218 			m_PassInfoVar.assign(value);
   219 		}
   220 		return ConfigResult_Accept;
   221 	} else if (strcmp(key, "AllowClLanguageVar") == 0) {
   222 		if (strcasecmp(value, "on") == 0)
   223 		{
   224 			m_QueryLang = true;
   225 		} else if (strcasecmp(value, "off") == 0) {
   226 			m_QueryLang = false;
   227 		} else {
   228 			UTIL_Format(error, maxlength, "Invalid value: must be \"on\" or \"off\"");
   229 			return ConfigResult_Reject;
   230 		}
   231 		return ConfigResult_Accept;
   232 	}
   233 	return ConfigResult_Ignore;
   234 }
   235 
   236 void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
   237 {
   238 	if (!m_FirstPass)
   239 	{
   240 		/* Initialize all players */
   241 		m_maxClients = clientMax;
   242 		m_PlayerCount = 0;
   243 		m_Players = new CPlayer[ABSOLUTE_PLAYER_LIMIT + 1];
   244 		m_AuthQueue = new unsigned int[ABSOLUTE_PLAYER_LIMIT + 1];
   245 		m_FirstPass = true;
   246 
   247 		memset(m_AuthQueue, 0, sizeof(unsigned int) * (ABSOLUTE_PLAYER_LIMIT + 1));
   248 
   249 		g_NumPlayersToAuth = &m_AuthQueue[0];
   250 
   251 		g_PluginSys.SyncMaxClients(clientMax);
   252 	}
   253 	g_Extensions.CallOnCoreMapStart(pEdictList, edictCount, clientMax);
   254 	m_onActivate->Execute(NULL);
   255 	m_onActivate2->Execute(NULL);
   256 
   257 	List<IClientListener *>::iterator iter;
   258 	for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
   259 	{
   260 		if ((*iter)->GetClientListenerVersion() >= 5)
   261 		{
   262 			(*iter)->OnServerActivated(clientMax);
   263 		}
   264 	}
   265 
   266 	g_OnMapStarted = true;
   267 
   268 	SMGlobalClass *cls = SMGlobalClass::head;
   269 	while (cls)
   270 	{
   271 		cls->OnSourceModLevelActivated();
   272 		cls = cls->m_pGlobalClassNext;
   273 	}
   274 
   275 	SM_ExecuteAllConfigs();
   276 }
   277 
   278 bool PlayerManager::IsServerActivated()
   279 {
   280 	return m_FirstPass;
   281 }
   282 
   283 bool PlayerManager::CheckSetAdmin(int index, CPlayer *pPlayer, AdminId id)
   284 {
   285 	const char *password = g_Admins.GetAdminPassword(id);
   286 	if (password != NULL)
   287 	{
   288 		if (m_PassInfoVar.size() < 1)
   289 		{
   290 			return false;
   291 		}
   292 
   293 		/* Whoa... the user needs a password! */
   294 		const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
   295 		if (!given || strcmp(given, password) != 0)
   296 		{
   297 			return false;
   298 		}
   299 	}
   300 
   301 	pPlayer->SetAdminId(id, false);
   302 
   303 	return true;
   304 }
   305 
   306 bool PlayerManager::CheckSetAdminName(int index, CPlayer *pPlayer, AdminId id)
   307 {
   308 	const char *password = g_Admins.GetAdminPassword(id);
   309 	if (password == NULL)
   310 	{
   311 		return false;
   312 	}
   313 
   314 	if (m_PassInfoVar.size() < 1)
   315 	{
   316 		return false;
   317 	}
   318 
   319 	/* Whoa... the user needs a password! */
   320 	const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
   321 	if (!given || strcmp(given, password) != 0)
   322 	{
   323 		return false;
   324 	}
   325 
   326 	pPlayer->SetAdminId(id, false);
   327 
   328 	return true;
   329 }
   330 
   331 void PlayerManager::RunAuthChecks()
   332 {
   333 	CPlayer *pPlayer;
   334 	const char *authstr;
   335 	unsigned int removed = 0;
   336 	for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   337 	{
   338 		pPlayer = &m_Players[m_AuthQueue[i]];
   339 		authstr = engine->GetPlayerNetworkIDString(pPlayer->m_pEdict);
   340 		if (authstr && authstr[0] != '\0'
   341 			&& (strcmp(authstr, "STEAM_ID_PENDING") != 0))
   342 		{
   343 			/* Set authorization */
   344 			pPlayer->Authorize(authstr);
   345 
   346 			/* Mark as removed from queue */
   347 			unsigned int client = m_AuthQueue[i];
   348 			m_AuthQueue[i] = 0;
   349 			removed++;
   350 
   351 			/* Send to extensions */
   352 			List<IClientListener *>::iterator iter;
   353 			IClientListener *pListener;
   354 			for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   355 			{
   356 				pListener = (*iter);
   357 				pListener->OnClientAuthorized(client, authstr);
   358 				if (!pPlayer->IsConnected())
   359 				{
   360 					break;
   361 				}
   362 			}
   363 
   364 			/* Send to plugins if player is still connected */
   365 			if (pPlayer->IsConnected() && m_clauth->GetFunctionCount())
   366 			{
   367 				/* :TODO: handle the case of a player disconnecting in the middle */
   368 				m_clauth->PushCell(client);
   369 				m_clauth->PushString(authstr);
   370 				m_clauth->Execute(NULL);
   371 			}
   372 
   373 			if (pPlayer->IsConnected())
   374 			{
   375 				pPlayer->Authorize_Post();
   376 			}
   377 		}
   378 	}
   379 
   380 	/* Clean up the queue */
   381 	if (removed)
   382 	{
   383 		/* We don't have to compact the list if it's empty */
   384 		if (removed != m_AuthQueue[0])
   385 		{
   386 			unsigned int diff = 0;
   387 			for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   388 			{
   389 				/* If this member is removed... */
   390 				if (m_AuthQueue[i] == 0)
   391 				{
   392 					/* Increase the differential */
   393 					diff++;
   394 				} else {
   395 					/* diff cannot increase faster than i+1 */
   396 					assert(i > diff);
   397 					assert(i - diff >= 1);
   398 					/* move this index down */
   399 					m_AuthQueue[i - diff] = m_AuthQueue[i];
   400 				}
   401 			}
   402 			m_AuthQueue[0] -= removed;
   403 		} else {
   404 			m_AuthQueue[0] = 0;
   405 		}
   406 	}
   407 }
   408 
   409 bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   410 {
   411 	int client = IndexOfEdict(pEntity);
   412 	CPlayer *pPlayer = &m_Players[client];
   413 
   414 	List<IClientListener *>::iterator iter;
   415 	IClientListener *pListener = NULL;
   416 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   417 	{
   418 		pListener = (*iter);
   419 		if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
   420 		{
   421 			return false;
   422 		}
   423 	}
   424 
   425 	cell_t res = 1;
   426 
   427 	pPlayer->Initialize(pszName, pszAddress, pEntity);
   428 	m_clconnect->PushCell(client);
   429 	m_clconnect->PushStringEx(reject, maxrejectlen, SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK);
   430 	m_clconnect->PushCell(maxrejectlen);
   431 	m_clconnect->Execute(&res);
   432 
   433 	if (res)
   434 	{
   435 		if (!pPlayer->IsAuthorized())
   436 		{
   437 			m_AuthQueue[++m_AuthQueue[0]] = client;
   438 		}
   439 
   440 		m_UserIdLookUp[engine->GetPlayerUserId(pEntity)] = client;
   441 	}
   442 	else
   443 	{
   444 		if (!pPlayer->IsFakeClient())
   445 		{
   446 			RETURN_META_VALUE(MRES_SUPERCEDE, false);
   447 		}
   448 	}
   449 
   450 	return true;
   451 }
   452 
   453 bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   454 {
   455 	int client = IndexOfEdict(pEntity);
   456 	bool orig_value = META_RESULT_ORIG_RET(bool);
   457 	CPlayer *pPlayer = &m_Players[client];
   458 
   459 	if (orig_value)
   460 	{
   461 		List<IClientListener *>::iterator iter;
   462 		IClientListener *pListener = NULL;
   463 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   464 		{
   465 			pListener = (*iter);
   466 			pListener->OnClientConnected(client);
   467 			if (!pPlayer->IsConnected())
   468 			{
   469 				return true;
   470 			}
   471 		}
   472 
   473 		if (!pPlayer->IsFakeClient() 
   474 			&& m_bIsListenServer
   475 			&& strncmp(pszAddress, "127.0.0.1", 9) == 0)
   476 		{
   477 			m_ListenClient = client;
   478 		}
   479 
   480 		cell_t res;
   481 		OnClientConnected->PushCell(client);
   482 		OnClientConnected->Execute(&res, NULL);
   483 	}
   484 	else
   485 	{
   486 		InvalidatePlayer(pPlayer);
   487 	}
   488 
   489 	return true;
   490 }
   491 
   492 void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername)
   493 {
   494 	cell_t res;
   495 	int client = IndexOfEdict(pEntity);
   496 	CPlayer *pPlayer = &m_Players[client];
   497 
   498 	/* If they're not connected, they're a bot */
   499 	if (!pPlayer->IsConnected())
   500 	{
   501 		/* Run manual connection routines */
   502 		char error[255];
   503 		const char *authid = engine->GetPlayerNetworkIDString(pEntity);
   504 		pPlayer->Authorize(authid);
   505 		pPlayer->m_bFakeClient = true;
   506 		if (!OnClientConnect(pEntity, playername, "127.0.0.1", error, sizeof(error)))
   507 		{
   508 			/* :TODO: kick the bot if it's rejected */
   509 			return;
   510 		}
   511 		List<IClientListener *>::iterator iter;
   512 		IClientListener *pListener = NULL;
   513 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   514 		{
   515 			pListener = (*iter);
   516 			pListener->OnClientConnected(client);
   517 			/* See if bot was kicked */
   518 			if (!pPlayer->IsConnected())
   519 			{
   520 				return;
   521 			}
   522 		}
   523 
   524 		cell_t res;
   525 		OnClientConnected->PushCell(client);
   526 		OnClientConnected->Execute(&res, NULL);
   527 
   528 		/* Now do authorization */
   529 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   530 		{
   531 			pListener = (*iter);
   532 			pListener->OnClientAuthorized(client, authid);
   533 		}
   534 		/* Finally, tell plugins */
   535 		if (m_clauth->GetFunctionCount())
   536 		{
   537 			m_clauth->PushCell(client);
   538 			m_clauth->PushString(authid);
   539 			m_clauth->Execute(NULL);
   540 		}
   541 		pPlayer->Authorize_Post();
   542 	}
   543 
   544 	if (playerinfo)
   545 	{
   546 		pPlayer->m_Info = playerinfo->GetPlayerInfo(pEntity);
   547 	}
   548 
   549 	/* Get the client's language */
   550 	if (m_QueryLang)
   551 	{
   552 		const char *name;
   553 		if (!pPlayer->IsFakeClient() && (name=engine->GetClientConVarValue(client, "cl_language")))
   554 		{
   555 			unsigned int langid;
   556 			pPlayer->m_LangId = (translator->GetLanguageByName(name, &langid)) ? langid : translator->GetServerLanguage();
   557 		} else {
   558 			pPlayer->m_LangId = translator->GetServerLanguage();
   559 		}
   560 	}
   561 
   562 	pPlayer->Connect();
   563 	m_PlayerCount++;
   564 
   565 	List<IClientListener *>::iterator iter;
   566 	IClientListener *pListener = NULL;
   567 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   568 	{
   569 		pListener = (*iter);
   570 		pListener->OnClientPutInServer(client);
   571 	}
   572 
   573 	m_clputinserver->PushCell(client);
   574 	m_clputinserver->Execute(&res, NULL);
   575 
   576 	if (pPlayer->IsAuthorized())
   577 	{
   578 		pPlayer->DoPostConnectAuthorization();
   579 	}
   580 }
   581 
   582 void PlayerManager::OnSourceModLevelEnd()
   583 {
   584 	/* Disconnect all bots still in game */
   585 	for (int i=1; i<=m_maxClients; i++)
   586 	{
   587 		if (m_Players[i].IsConnected())
   588 		{
   589 			OnClientDisconnect(m_Players[i].GetEdict());
   590 		}
   591 	}
   592 	m_PlayerCount = 0;
   593 }
   594 
   595 void PlayerManager::OnClientDisconnect(edict_t *pEntity)
   596 {
   597 	cell_t res;
   598 	int client = IndexOfEdict(pEntity);
   599 	CPlayer *pPlayer = &m_Players[client];
   600 
   601 	if (pPlayer->IsConnected())
   602 	{
   603 		m_cldisconnect->PushCell(client);
   604 		m_cldisconnect->Execute(&res, NULL);
   605 	}
   606 	else
   607 	{
   608 		/* We don't care, prevent a double call */
   609 		return;
   610 	}
   611 
   612 	if (pPlayer->WasCountedAsInGame())
   613 	{
   614 		m_PlayerCount--;
   615 	}
   616 
   617 	List<IClientListener *>::iterator iter;
   618 	IClientListener *pListener = NULL;
   619 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   620 	{
   621 		pListener = (*iter);
   622 		pListener->OnClientDisconnecting(client);
   623 	}
   624 
   625 	InvalidatePlayer(pPlayer);
   626 
   627 	if (m_ListenClient == client)
   628 	{
   629 		m_ListenClient = 0;
   630 	}
   631 }
   632 
   633 void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
   634 {
   635 	cell_t res;
   636 	int client = IndexOfEdict(pEntity);
   637 
   638 	m_cldisconnect_post->PushCell(client);
   639 	m_cldisconnect_post->Execute(&res, NULL);
   640 
   641 	List<IClientListener *>::iterator iter;
   642 	IClientListener *pListener = NULL;
   643 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   644 	{
   645 		pListener = (*iter);
   646 		pListener->OnClientDisconnected(client);
   647 	}
   648 }
   649 
   650 void ClientConsolePrint(edict_t *e, const char *fmt, ...)
   651 {
   652 	char buffer[512];
   653 
   654 	va_list ap;
   655 	va_start(ap, fmt);
   656 	size_t len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
   657 	va_end(ap);
   658 
   659 	if (len >= sizeof(buffer) - 1)
   660 	{
   661 		buffer[sizeof(buffer) - 2] = '\n';
   662 		buffer[sizeof(buffer) - 1] = '\0';
   663 	} else {
   664 		buffer[len++] = '\n';
   665 		buffer[len] = '\0';
   666 	}
   667 
   668 	engine->ClientPrintf(e, buffer);
   669 }
   670 
   671 #if SOURCE_ENGINE >= SE_ORANGEBOX
   672 void PlayerManager::OnClientCommand(edict_t *pEntity, const CCommand &args)
   673 {
   674 #else
   675 void PlayerManager::OnClientCommand(edict_t *pEntity)
   676 {
   677 	CCommand args;
   678 #endif
   679 	int client = IndexOfEdict(pEntity);
   680 	cell_t res = Pl_Continue;
   681 	CPlayer *pPlayer = &m_Players[client];
   682 
   683 	if (!pPlayer->IsConnected())
   684 	{
   685 		return;
   686 	}
   687 
   688 	if (strcmp(args.Arg(0), "sm") == 0)
   689 	{
   690 		if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0)
   691 		{
   692 			g_PluginSys.ListPluginsToClient(pPlayer, args);
   693 			RETURN_META(MRES_SUPERCEDE);
   694 		}
   695 		else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0)
   696 		{
   697 			ClientConsolePrint(pEntity,
   698 				"SourceMod would not be possible without:");
   699 			ClientConsolePrint(pEntity,
   700 				" David \"BAILOPAN\" Anderson, Borja \"faluco\" Ferrer");
   701 			ClientConsolePrint(pEntity,
   702 				" Scott \"DS\" Ehlert, Matt \"pRED\" Woodrow");
   703 			ClientConsolePrint(pEntity,
   704 				" Michael \"ferret\" McKoy, Pavol \"PM OnoTo\" Marko");
   705 			ClientConsolePrint(pEntity,
   706 				"SourceMod is open source under the GNU General Public License.");
   707 			RETURN_META(MRES_SUPERCEDE);
   708 		}
   709 
   710 		ClientConsolePrint(pEntity,
   711 			"SourceMod %s, by AlliedModders LLC", SM_FULL_VERSION);
   712 		ClientConsolePrint(pEntity,
   713 			"To see running plugins, type \"sm plugins\"");
   714 		ClientConsolePrint(pEntity,
   715 			"To see credits, type \"sm credits\"");
   716 		ClientConsolePrint(pEntity,
   717 			"Visit http://www.sourcemod.net/");
   718 		RETURN_META(MRES_SUPERCEDE);
   719 	}
   720 
   721 	g_HL2.PushCommandStack(&args);
   722 
   723 	int argcount = args.ArgC() - 1;
   724 	const char *cmd = g_HL2.CurrentCommandName();
   725 
   726 	bool result = g_ValveMenuStyle.OnClientCommand(client, cmd, args);
   727 	if (result)
   728 	{
   729 		res = Pl_Handled;
   730 	} else {
   731 		result = g_RadioMenuStyle.OnClientCommand(client, cmd, args);
   732 		if (result)
   733 		{
   734 			res = Pl_Handled;
   735 		}
   736 	}
   737 
   738 	if (g_ConsoleDetours.IsEnabled())
   739 	{
   740 		cell_t res2 = g_ConsoleDetours.InternalDispatch(client, args);
   741 		if (res2 >= Pl_Stop)
   742 		{
   743 			g_HL2.PopCommandStack();
   744 			RETURN_META(MRES_SUPERCEDE);
   745 		}
   746 		else if (res2 > res)
   747 		{
   748 			res = res2;
   749 		}
   750 	}
   751 
   752 	cell_t res2 = Pl_Continue;
   753 	if (pPlayer->IsInGame())
   754 	{
   755 		m_clcommand->PushCell(client);
   756 		m_clcommand->PushCell(argcount);
   757 		m_clcommand->Execute(&res2, NULL);
   758 	}
   759 
   760 	if (res2 > res)
   761 	{
   762 		res = res2;
   763 	}
   764 
   765 	if (res >= Pl_Stop)
   766 	{
   767 		g_HL2.PopCommandStack();
   768 		RETURN_META(MRES_SUPERCEDE);
   769 	}
   770 
   771 	res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res);
   772 
   773 	g_HL2.PopCommandStack();
   774 
   775 	if (res >= Pl_Handled)
   776 	{
   777 		RETURN_META(MRES_SUPERCEDE);
   778 	}
   779 }
   780 
   781 void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
   782 {
   783 	cell_t res;
   784 	int client = IndexOfEdict(pEntity);
   785 	CPlayer *pPlayer = &m_Players[client];
   786 
   787 	if (!pPlayer->IsConnected())
   788 	{
   789 		return;
   790 	}
   791 
   792 	m_clinfochanged->PushCell(client);
   793 	m_clinfochanged->Execute(&res, NULL);
   794 
   795 	if (pPlayer->IsFakeClient())
   796 	{
   797 		return;
   798 	}
   799 
   800 	IPlayerInfo *info = pPlayer->GetPlayerInfo();
   801 	const char *new_name = info ? info->GetName() : engine->GetClientConVarValue(client, "name");
   802 	const char *old_name = pPlayer->m_Name.c_str();
   803 
   804 	if (strcmp(old_name, new_name) != 0)
   805 	{
   806 		AdminId id = g_Admins.FindAdminByIdentity("name", new_name);
   807 		if (id != INVALID_ADMIN_ID && pPlayer->GetAdminId() != id)
   808 		{
   809 			if (!CheckSetAdminName(client, pPlayer, id))
   810 			{
   811 				pPlayer->Kick("Your name is reserved by SourceMod; set your password to use it.");
   812 				RETURN_META(MRES_IGNORED);
   813 			}
   814 		} else if ((id = g_Admins.FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
   815 			if (id == pPlayer->GetAdminId())
   816 			{
   817 				/* This player is changing their name; force them to drop admin privileges! */
   818 				pPlayer->SetAdminId(INVALID_ADMIN_ID, false);
   819 			}
   820 		}
   821 		pPlayer->SetName(new_name);
   822 	}
   823 	
   824 	if (m_PassInfoVar.size() > 0)
   825 	{
   826 		/* Try for a password change */
   827 		const char *old_pass = pPlayer->m_LastPassword.c_str();
   828 		const char *new_pass = engine->GetClientConVarValue(client, m_PassInfoVar.c_str());
   829 		if (strcmp(old_pass, new_pass) != 0)
   830 		{
   831 			pPlayer->m_LastPassword.assign(new_pass);
   832 			if (pPlayer->IsInGame() && pPlayer->IsAuthorized())
   833 			{
   834 				/* If there is already an admin id assigned, this will just bail out. */
   835 				pPlayer->DoBasicAdminChecks();
   836 			}
   837 		}
   838 	}
   839 }
   840 
   841 int PlayerManager::GetMaxClients()
   842 {
   843 	return m_maxClients;
   844 }
   845 
   846 CPlayer *PlayerManager::GetPlayerByIndex(int client) const
   847 {
   848 	if (client > m_maxClients || client < 1)
   849 	{
   850 		return NULL;
   851 	}
   852 	return &m_Players[client];
   853 }
   854 
   855 int PlayerManager::GetNumPlayers()
   856 {
   857 	return m_PlayerCount;
   858 }
   859 
   860 int PlayerManager::GetClientOfUserId(int userid)
   861 {
   862 	if (userid < 0 || userid > USHRT_MAX)
   863 	{
   864 		return 0;
   865 	}
   866 	
   867 	int client = m_UserIdLookUp[userid];
   868 
   869 	/* Verify the userid.  The cache can get messed up with older
   870 	 * Valve engines.  :TODO: If this gets fixed, do an old engine 
   871 	 * check before invoking this backwards compat code.
   872 	 */
   873 	if (client)
   874 	{
   875 		CPlayer *player = GetPlayerByIndex(client);
   876 		if (player && player->IsConnected())
   877 		{
   878 			int realUserId = engine->GetPlayerUserId(player->GetEdict());
   879 			if (realUserId == userid)
   880 			{
   881 				return client;
   882 			}
   883 		}
   884 	}
   885 
   886 	/* If we can't verify the userid, we have to do a manual loop */
   887 	CPlayer *player;
   888 	for (int i = 1; i <= m_maxClients; i++)
   889 	{
   890 		player = GetPlayerByIndex(i);
   891 		if (!player || !player->IsConnected())
   892 		{
   893 			continue;
   894 		}
   895 		if (engine->GetPlayerUserId(player->GetEdict()) == userid)
   896 		{
   897 			m_UserIdLookUp[userid] = i;
   898 			return i;
   899 		}
   900 	}
   901 
   902 	return 0;
   903 }
   904 
   905 void PlayerManager::AddClientListener(IClientListener *listener)
   906 {
   907 	m_hooks.push_back(listener);
   908 }
   909 
   910 void PlayerManager::RemoveClientListener(IClientListener *listener)
   911 {
   912 	m_hooks.remove(listener);
   913 }
   914 
   915 IGamePlayer *PlayerManager::GetGamePlayer(edict_t *pEdict)
   916 {
   917 	int index = IndexOfEdict(pEdict);
   918 	return GetGamePlayer(index);
   919 }
   920 
   921 IGamePlayer *PlayerManager::GetGamePlayer(int client)
   922 {
   923 	return GetPlayerByIndex(client);
   924 }
   925 
   926 void PlayerManager::ClearAdminId(AdminId id)
   927 {
   928 	for (int i=1; i<=m_maxClients; i++)
   929 	{
   930 		if (m_Players[i].m_Admin == id)
   931 		{
   932 			m_Players[i].DumpAdmin(true);
   933 		}
   934 	}
   935 }
   936 
   937 void PlayerManager::ClearAllAdmins()
   938 {
   939 	for (int i=1; i<=m_maxClients; i++)
   940 	{
   941 		m_Players[i].DumpAdmin(true);
   942 	}
   943 }
   944 
   945 const char *PlayerManager::GetPassInfoVar()
   946 {
   947 	return m_PassInfoVar.c_str();
   948 }
   949 
   950 void PlayerManager::RecheckAnyAdmins()
   951 {
   952 	for (int i=1; i<=m_maxClients; i++)
   953 	{
   954 		if (m_Players[i].IsInGame() && m_Players[i].IsAuthorized())
   955 		{
   956 			m_Players[i].DoBasicAdminChecks();
   957 		}
   958 	}
   959 }
   960 
   961 unsigned int PlayerManager::GetReplyTo()
   962 {
   963 	return g_ChatTriggers.GetReplyTo();
   964 }
   965 
   966 unsigned int PlayerManager::SetReplyTo(unsigned int reply)
   967 {
   968 	return g_ChatTriggers.SetReplyTo(reply);
   969 }
   970 
   971 int PlayerManager::FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags)
   972 {
   973 	return InternalFilterCommandTarget((CPlayer *)pAdmin, (CPlayer *)pTarget, flags);
   974 }
   975 
   976 void PlayerManager::RegisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
   977 {
   978 	target_processors.push_back(pHandler);
   979 }
   980 
   981 void PlayerManager::UnregisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
   982 {
   983 	target_processors.remove(pHandler);
   984 }
   985 
   986 void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
   987 {
   988 	/**
   989 	* Remove client from auth queue if necessary
   990 	*/
   991 	if (!pPlayer->IsAuthorized())
   992 	{
   993 		for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   994 		{
   995 			if (m_AuthQueue[i] == (unsigned)pPlayer->m_iIndex)
   996 			{
   997 				/* Move everything ahead of us back by one */
   998 				for (unsigned int j=i+1; j<=m_AuthQueue[0]; j++)
   999 				{
  1000 					m_AuthQueue[j-1] = m_AuthQueue[j];
  1001 				}
  1002 				/* Remove us and break */
  1003 				m_AuthQueue[0]--;
  1004 				break;
  1005 			}
  1006 		}
  1007 	}
  1008 	
  1009 	m_UserIdLookUp[engine->GetPlayerUserId(pPlayer->m_pEdict)] = 0;
  1010 	pPlayer->Disconnect();
  1011 }
  1012 
  1013 int PlayerManager::InternalFilterCommandTarget(CPlayer *pAdmin, CPlayer *pTarget, int flags)
  1014 {
  1015 	if ((flags & COMMAND_FILTER_CONNECTED) == COMMAND_FILTER_CONNECTED
  1016 		&& !pTarget->IsConnected())
  1017 	{
  1018 		return COMMAND_TARGET_NONE;
  1019 	}
  1020 	else if ((flags & COMMAND_FILTER_CONNECTED) != COMMAND_FILTER_CONNECTED && 
  1021 		!pTarget->IsInGame())
  1022 	{
  1023 		return COMMAND_TARGET_NOT_IN_GAME;
  1024 	}
  1025 
  1026 	if ((flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS
  1027 		&& pTarget->IsFakeClient())
  1028 	{
  1029 		return COMMAND_TARGET_NOT_HUMAN;
  1030 	}
  1031 
  1032 	if (pAdmin != NULL)
  1033 	{
  1034 		if ((flags & COMMAND_FILTER_NO_IMMUNITY) != COMMAND_FILTER_NO_IMMUNITY
  1035 			&& !g_Admins.CanAdminTarget(pAdmin->GetAdminId(), pTarget->GetAdminId()))
  1036 		{
  1037 			return COMMAND_TARGET_IMMUNE;
  1038 		}
  1039 	}
  1040 
  1041 	if ((flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE 
  1042 		&& pTarget->GetLifeState() != PLAYER_LIFE_ALIVE)
  1043 	{
  1044 		return COMMAND_TARGET_NOT_ALIVE;
  1045 	}
  1046 
  1047 	if ((flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD
  1048 		&& pTarget->GetLifeState() != PLAYER_LIFE_DEAD)
  1049 	{
  1050 		return COMMAND_TARGET_NOT_DEAD;
  1051 	}
  1052 
  1053 	return COMMAND_TARGET_VALID;
  1054 }
  1055 
  1056 void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
  1057 {
  1058 	CPlayer *pTarget, *pAdmin;
  1059 	int max_clients, total = 0;
  1060 
  1061 	max_clients = GetMaxClients();
  1062 
  1063 	if (info->max_targets < 1)
  1064 	{
  1065 		info->reason = COMMAND_TARGET_NONE;
  1066 		info->num_targets = 0;
  1067 	}
  1068 
  1069 	if (info->admin == 0)
  1070 	{
  1071 		pAdmin = NULL;
  1072 	}
  1073 	else
  1074 	{
  1075 		pAdmin = GetPlayerByIndex(info->admin);
  1076 	}
  1077 
  1078 	if (info->pattern[0] == '#')
  1079 	{
  1080 		int userid = atoi(&info->pattern[1]);
  1081 		int client = GetClientOfUserId(userid);
  1082 
  1083 		/* See if a valid userid matched */
  1084 		if (client > 0)
  1085 		{
  1086 			IGamePlayer *pTarget = GetPlayerByIndex(client);
  1087 			if (pTarget != NULL)
  1088 			{
  1089 				if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags)) == COMMAND_TARGET_VALID)
  1090 				{
  1091 					info->targets[0] = client;
  1092 					info->num_targets = 1;
  1093 					strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1094 					info->target_name_style = COMMAND_TARGETNAME_RAW;
  1095 				}
  1096 				else
  1097 				{
  1098 					info->num_targets = 0;
  1099 				}
  1100 				return;
  1101 			}
  1102 		}
  1103 
  1104 		/* Do we need to look for a steam id? */
  1105 		if (strncmp(&info->pattern[1], "STEAM_", 6) == 0)
  1106 		{
  1107 			size_t p, len;
  1108 			char new_pattern[256];
  1109 
  1110 			strcpy(new_pattern, "STEAM_");
  1111 			len = strlen(&info->pattern[7]);
  1112 			for (p = 0; p < len; p++)
  1113 			{
  1114 				new_pattern[6 + p] = info->pattern[7 + p];
  1115 				if (new_pattern[6 + p] == '_')
  1116 				{
  1117 					new_pattern[6 + p] = ':';
  1118 				}
  1119 			}
  1120 			new_pattern[6 + p] = '\0';
  1121 
  1122 			for (int i = 1; i <= max_clients; i++)
  1123 			{
  1124 				if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1125 				{
  1126 					continue;
  1127 				}
  1128 				if (!pTarget->IsConnected() || !pTarget->IsAuthorized())
  1129 				{
  1130 					continue;
  1131 				}
  1132 				if (strcmp(pTarget->GetAuthString(), new_pattern) == 0)
  1133 				{
  1134 					if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
  1135 						== COMMAND_TARGET_VALID)
  1136 					{
  1137 						info->targets[0] = i;
  1138 						info->num_targets = 1;
  1139 						strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1140 						info->target_name_style = COMMAND_TARGETNAME_RAW;
  1141 					}
  1142 					else
  1143 					{
  1144 						info->num_targets = 0;
  1145 					}
  1146 					return;
  1147 				}
  1148 			}
  1149 		}
  1150 
  1151 		/* See if an exact name matches */
  1152 		for (int i = 1; i <= max_clients; i++)
  1153 		{
  1154 			if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1155 			{
  1156 				continue;
  1157 			}
  1158 			if  (!pTarget->IsConnected())
  1159 			{
  1160 				continue;
  1161 			}
  1162 			if (strcmp(pTarget->GetName(), &info->pattern[1]) == 0)
  1163 			{
  1164 				if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
  1165 					== COMMAND_TARGET_VALID)
  1166 				{
  1167 					info->targets[0] = i;
  1168 					info->num_targets = 1;
  1169 					strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1170 					info->target_name_style = COMMAND_TARGETNAME_RAW;
  1171 				}
  1172 				else
  1173 				{
  1174 					info->num_targets = 0;
  1175 				}
  1176 				return;
  1177 			}
  1178 		}
  1179 	}
  1180 
  1181 	if (strcmp(info->pattern, "@me") == 0 && info->admin != 0)
  1182 	{
  1183 		info->reason = FilterCommandTarget(pAdmin, pAdmin, info->flags);
  1184 		if (info->reason == COMMAND_TARGET_VALID)
  1185 		{
  1186 			info->targets[0] = info->admin;
  1187 			info->num_targets = 1;
  1188 			strncopy(info->target_name, pAdmin->GetName(), info->target_name_maxlength);
  1189 			info->target_name_style = COMMAND_TARGETNAME_RAW;
  1190 		}
  1191 		else
  1192 		{
  1193 			info->num_targets = 0;
  1194 		}
  1195 		return;
  1196 	}
  1197 
  1198 	if ((info->flags & COMMAND_FILTER_NO_MULTI) != COMMAND_FILTER_NO_MULTI)
  1199 	{
  1200 		bool is_multi = false;
  1201 		bool bots_only = false;
  1202 		int skip_client = -1;
  1203 
  1204 		if (strcmp(info->pattern, "@all") == 0)
  1205 		{
  1206 			is_multi = true;
  1207 			strncopy(info->target_name, "all players", info->target_name_maxlength);
  1208 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1209 		}
  1210 		else if (strcmp(info->pattern, "@dead") == 0)
  1211 		{
  1212 			is_multi = true;
  1213 			if ((info->flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE)
  1214 			{
  1215 				info->num_targets = 0;
  1216 				info->reason = COMMAND_TARGET_NOT_ALIVE;
  1217 				return;
  1218 			}
  1219 			info->flags |= COMMAND_FILTER_DEAD;
  1220 			strncopy(info->target_name, "all dead players", info->target_name_maxlength);
  1221 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1222 		}
  1223 		else if (strcmp(info->pattern, "@alive") == 0)
  1224 		{
  1225 			is_multi = true;
  1226 			if ((info->flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD)
  1227 			{
  1228 				info->num_targets = 0;
  1229 				info->reason = COMMAND_TARGET_NOT_DEAD;
  1230 				return;
  1231 			}
  1232 			strncopy(info->target_name, "all alive players", info->target_name_maxlength);
  1233 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1234 			info->flags |= COMMAND_FILTER_ALIVE;
  1235 		}
  1236 		else if (strcmp(info->pattern, "@bots") == 0)
  1237 		{
  1238 			is_multi = true;
  1239 			if ((info->flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS)
  1240 			{
  1241 				info->num_targets = 0;
  1242 				info->reason = COMMAND_FILTER_NO_BOTS;
  1243 				return;
  1244 			}
  1245 			strncopy(info->target_name, "all bots", info->target_name_maxlength);
  1246 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1247 			bots_only = true;
  1248 		}
  1249 		else if (strcmp(info->pattern, "@humans") == 0)
  1250 		{
  1251 			is_multi = true;
  1252 			strncopy(info->target_name, "all humans", info->target_name_maxlength);
  1253 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1254 			info->flags |= COMMAND_FILTER_NO_BOTS;
  1255 		}
  1256 		else if (strcmp(info->pattern, "@!me") == 0)
  1257 		{
  1258 			is_multi = true;
  1259 			strncopy(info->target_name, "all players", info->target_name_maxlength);
  1260 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1261 			skip_client = info->admin;
  1262 		}
  1263 
  1264 		if (is_multi)
  1265 		{
  1266 			for (int i = 1; i <= max_clients && total < info->max_targets; i++)
  1267 			{
  1268 				if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1269 				{
  1270 					continue;
  1271 				}
  1272 				if (FilterCommandTarget(pAdmin, pTarget, info->flags) > 0)
  1273 				{
  1274 					if ((!bots_only || pTarget->IsFakeClient())
  1275 						&& skip_client != i)
  1276 					{
  1277 						info->targets[total++] = i;
  1278 					}
  1279 				}
  1280 			}
  1281 
  1282 			info->num_targets = total;
  1283 			info->reason = (info->num_targets) ? COMMAND_TARGET_VALID : COMMAND_TARGET_EMPTY_FILTER;
  1284 			return;
  1285 		}
  1286 	}
  1287 
  1288 	List<ICommandTargetProcessor *>::iterator iter;
  1289 	for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
  1290 	{
  1291 		ICommandTargetProcessor *pProcessor = (*iter);
  1292 		if (pProcessor->ProcessCommandTarget(info))
  1293 		{
  1294 			return;
  1295 		}
  1296 	}
  1297 
  1298 	/* Check partial names */
  1299 	int found_client = 0;
  1300 	CPlayer *pFoundClient = NULL;
  1301 	for (int i = 1; i <= max_clients; i++)
  1302 	{
  1303 		if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1304 		{
  1305 			continue;
  1306 		}
  1307 
  1308 		if (logicore.stristr(pTarget->GetName(), info->pattern) != NULL)
  1309 		{
  1310 			if (found_client)
  1311 			{
  1312 				info->num_targets = 0;
  1313 				info->reason = COMMAND_TARGET_AMBIGUOUS;
  1314 				return;
  1315 			}
  1316 			else
  1317 			{
  1318 				found_client = i;
  1319 				pFoundClient = pTarget;
  1320 			}
  1321 		}
  1322 	}
  1323 
  1324 	if (found_client)
  1325 	{
  1326 		if ((info->reason = FilterCommandTarget(pAdmin, pFoundClient, info->flags)) 
  1327 			== COMMAND_TARGET_VALID)
  1328 		{
  1329 			info->targets[0] = found_client;
  1330 			info->num_targets = 1;
  1331 			strncopy(info->target_name, pFoundClient->GetName(), info->target_name_maxlength);
  1332 			info->target_name_style = COMMAND_TARGETNAME_RAW;
  1333 		}
  1334 		else
  1335 		{
  1336 			info->num_targets = 0;
  1337 		}
  1338 	}
  1339 	else
  1340 	{
  1341 		info->num_targets = 0;
  1342 		info->reason = COMMAND_TARGET_NONE;
  1343 	}
  1344 }
  1345 
  1346 void PlayerManager::OnConVarChanged( ConVar *pConVar, const char *oldValue, float flOldValue )
  1347 {
  1348 	if (pConVar->GetBool() && !atoi(oldValue))
  1349 	{
  1350 		MaxPlayersChanged(gpGlobals->maxClients + 1);
  1351 	}
  1352 	else
  1353 	{
  1354 		MaxPlayersChanged();
  1355 	}
  1356 }
  1357 
  1358 void PlayerManager::OnSourceModMaxPlayersChanged( int newvalue )
  1359 {
  1360 	m_maxClients = newvalue;
  1361 }
  1362 
  1363 void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
  1364 {
  1365 	if (!m_FirstPass)
  1366 	{
  1367 		return;
  1368 	}
  1369 
  1370 	if (newvalue == -1)
  1371 	{
  1372 		newvalue = gpGlobals->maxClients;
  1373 	}
  1374 
  1375 	if (newvalue == MaxClients())
  1376 	{
  1377 		return;
  1378 	}
  1379 
  1380 	/* Notify the rest of core */
  1381 	SMGlobalClass *pBase = SMGlobalClass::head;
  1382 	while (pBase)
  1383 	{
  1384 		pBase->OnSourceModMaxPlayersChanged(newvalue);
  1385 		pBase = pBase->m_pGlobalClassNext;
  1386 	}
  1387 
  1388 	/* Notify Extensions */
  1389 	List<IClientListener *>::iterator iter;
  1390 	IClientListener *pListener = NULL;
  1391 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1392 	{
  1393 		pListener = (*iter);
  1394 		if (pListener->GetClientListenerVersion() >= 8)
  1395 		{
  1396 			pListener->OnMaxPlayersChanged(newvalue);
  1397 		}
  1398 	}
  1399 }
  1400 
  1401 int PlayerManager::GetClientFromSerial(unsigned int serial)
  1402 {
  1403 	serial_t s;
  1404 	s.value = serial;
  1405 
  1406 	int client = s.bits.index;
  1407 
  1408 	IGamePlayer *pPlayer = GetGamePlayer(client);
  1409 
  1410 	if (!pPlayer)
  1411 	{
  1412 		return 0;
  1413 	}
  1414 
  1415 	if (serial == pPlayer->GetSerial())
  1416 	{
  1417 		return client;
  1418 	}
  1419 
  1420 	return 0;
  1421 }
  1422 
  1423 #if SOURCE_ENGINE >= SE_ORANGEBOX
  1424 void CmdMaxplayersCallback(const CCommand &command)
  1425 {
  1426 #else
  1427 void CmdMaxplayersCallback()
  1428 {
  1429 #endif
  1430 
  1431 	g_Players.MaxPlayersChanged();
  1432 }
  1433 
  1434 
  1435 /*******************
  1436  *** PLAYER CODE ***
  1437  *******************/
  1438 
  1439 CPlayer::CPlayer()
  1440 {
  1441 	m_IsConnected = false;
  1442 	m_IsInGame = false;
  1443 	m_IsAuthorized = false;
  1444 	m_pEdict = NULL;
  1445 	m_Admin = INVALID_ADMIN_ID;
  1446 	m_TempAdmin = false;
  1447 	m_Info = NULL;
  1448 	m_bAdminCheckSignalled = false;
  1449 	m_UserId = -1;
  1450 	m_bIsInKickQueue = false;
  1451 	m_LastPassword.clear();
  1452 	m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
  1453 	m_bFakeClient = false;
  1454 }
  1455 
  1456 void CPlayer::Initialize(const char *name, const char *ip, edict_t *pEntity)
  1457 {
  1458 	m_IsConnected = true;
  1459 	m_Name.assign(name);
  1460 	m_Ip.assign(ip);
  1461 	m_pEdict = pEntity;
  1462 	m_iIndex = IndexOfEdict(pEntity);
  1463 	m_LangId = translator->GetServerLanguage();
  1464 
  1465 	m_Serial.bits.index = m_iIndex;
  1466 	m_Serial.bits.serial = g_PlayerSerialCount++;
  1467 
  1468 	char ip2[24], *ptr;
  1469 	strncopy(ip2, ip, sizeof(ip2));
  1470 	if ((ptr = strchr(ip2, ':')) != NULL)
  1471 	{
  1472 		*ptr = '\0';
  1473 	}
  1474 	m_IpNoPort.assign(ip2);
  1475 }
  1476 
  1477 void CPlayer::Connect()
  1478 {
  1479 	if (m_IsInGame)
  1480 	{
  1481 		return;
  1482 	}
  1483 
  1484 	m_IsInGame = true;
  1485 
  1486 	const char *var = g_Players.GetPassInfoVar();
  1487 	int client = IndexOfEdict(m_pEdict);
  1488 	if (var[0] != '\0')
  1489 	{
  1490 		const char *pass = engine->GetClientConVarValue(client, var);
  1491 		m_LastPassword.assign(pass ? pass : "");
  1492 	}
  1493 	else
  1494 	{
  1495 		m_LastPassword.assign("");
  1496 	}
  1497 }
  1498 
  1499 void CPlayer::Authorize(const char *steamid)
  1500 {
  1501 	if (m_IsAuthorized)
  1502 	{
  1503 		return;
  1504 	}
  1505 
  1506 	m_IsAuthorized = true;
  1507 	m_AuthID.assign(steamid);
  1508 }
  1509 
  1510 void CPlayer::Disconnect()
  1511 {
  1512 	DumpAdmin(false);
  1513 	m_IsConnected = false;
  1514 	m_IsInGame = false;
  1515 	m_IsAuthorized = false;
  1516 	m_Name.clear();
  1517 	m_Ip.clear();
  1518 	m_AuthID.clear();
  1519 	m_pEdict = NULL;
  1520 	m_Info = NULL;
  1521 	m_bAdminCheckSignalled = false;
  1522 	m_UserId = -1;
  1523 	m_bIsInKickQueue = false;
  1524 	m_bFakeClient = false;
  1525 }
  1526 
  1527 void CPlayer::SetName(const char *name)
  1528 {
  1529 	m_Name.assign(name);
  1530 }
  1531 
  1532 const char *CPlayer::GetName()
  1533 {
  1534 	if (m_Info && m_pEdict->GetUnknown())
  1535 	{
  1536 		return m_Info->GetName();
  1537 	}
  1538 	
  1539 	return m_Name.c_str();
  1540 }
  1541 
  1542 const char *CPlayer::GetIPAddress()
  1543 {
  1544 	return m_Ip.c_str();
  1545 }
  1546 
  1547 const char *CPlayer::GetAuthString()
  1548 {
  1549 	return m_AuthID.c_str();
  1550 }
  1551 
  1552 edict_t *CPlayer::GetEdict()
  1553 {
  1554 	return m_pEdict;
  1555 }
  1556 
  1557 bool CPlayer::IsInGame()
  1558 {
  1559 	return m_IsInGame && (m_pEdict->GetUnknown() != NULL);
  1560 }
  1561 
  1562 bool CPlayer::WasCountedAsInGame()
  1563 {
  1564 	return m_IsInGame;
  1565 }
  1566 
  1567 bool CPlayer::IsConnected()
  1568 {
  1569 	return m_IsConnected;
  1570 }
  1571 
  1572 bool CPlayer::IsAuthorized()
  1573 {
  1574 	return m_IsAuthorized;
  1575 }
  1576 
  1577 IPlayerInfo *CPlayer::GetPlayerInfo()
  1578 {
  1579 	if (m_pEdict->GetUnknown())
  1580 	{
  1581 		return m_Info;
  1582 	}
  1583 
  1584 	return NULL;
  1585 }
  1586 
  1587 bool CPlayer::IsFakeClient()
  1588 {
  1589 	return m_bFakeClient;
  1590 }
  1591 
  1592 void CPlayer::SetAdminId(AdminId id, bool temporary)
  1593 {
  1594 	if (!m_IsConnected)
  1595 	{
  1596 		return;
  1597 	}
  1598 
  1599 	DumpAdmin(false);
  1600 
  1601 	m_Admin = id;
  1602 	m_TempAdmin = temporary;
  1603 }
  1604 
  1605 AdminId CPlayer::GetAdminId()
  1606 {
  1607 	return m_Admin;
  1608 }
  1609 
  1610 void CPlayer::DumpAdmin(bool deleting)
  1611 {
  1612 	if (m_Admin != INVALID_ADMIN_ID)
  1613 	{
  1614 		if (m_TempAdmin && !deleting)
  1615 		{
  1616 			g_Admins.InvalidateAdmin(m_Admin);
  1617 		}
  1618 		m_Admin = INVALID_ADMIN_ID;
  1619 		m_TempAdmin = false;
  1620 	}
  1621 }
  1622 
  1623 void CPlayer::Kick(const char *str)
  1624 {
  1625 	MarkAsBeingKicked();
  1626 	INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
  1627 	if (pNetChan == NULL)
  1628 	{
  1629 		/* What does this even mean? Hell if I know. */
  1630 		int userid = GetUserId();
  1631 		if (userid > 0)
  1632 		{
  1633 			char buffer[255];
  1634 			UTIL_Format(buffer, sizeof(buffer), "kickid %d %s\n", userid, str);
  1635 			engine->ServerCommand(buffer);
  1636 		}
  1637 	}
  1638 	else
  1639 	{
  1640 		IClient *pClient = static_cast<IClient *>(pNetChan->GetMsgHandler());
  1641 		pClient->Disconnect("%s", str);
  1642 	}
  1643 }
  1644 
  1645 void CPlayer::Authorize_Post()
  1646 {
  1647 	if (m_IsInGame)
  1648 	{
  1649 		DoPostConnectAuthorization();
  1650 	}
  1651 }
  1652 
  1653 void CPlayer::DoPostConnectAuthorization()
  1654 {
  1655 	bool delay = false;
  1656 
  1657 	List<IClientListener *>::iterator iter;
  1658 	for (iter = g_Players.m_hooks.begin();
  1659 		 iter != g_Players.m_hooks.end();
  1660 		 iter++)
  1661 	{
  1662 		IClientListener *pListener = (*iter);
  1663 #if defined MIN_API_FOR_ADMINCALLS
  1664 		if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
  1665 		{
  1666 			continue;
  1667 		}
  1668 #endif
  1669 		if (!pListener->OnClientPreAdminCheck(m_iIndex))
  1670 		{
  1671 			delay = true;
  1672 		}
  1673 	}
  1674 	
  1675 	cell_t result = 0;
  1676 	PreAdminCheck->PushCell(m_iIndex);
  1677 	PreAdminCheck->Execute(&result);
  1678 
  1679 	/* Defer, for better or worse */
  1680 	if (delay || (ResultType)result >= Pl_Handled)
  1681 	{
  1682 		return;
  1683 	}
  1684 
  1685 	/* Sanity check */
  1686 	if (!IsConnected())
  1687 	{
  1688 		return;
  1689 	}
  1690 
  1691 	/* Otherwise, go ahead and do admin checks */
  1692 	DoBasicAdminChecks();
  1693 
  1694 	/* Send the notification out */
  1695 	NotifyPostAdminChecks();
  1696 }
  1697 
  1698 bool CPlayer::RunAdminCacheChecks()
  1699 {
  1700 	AdminId old_id = GetAdminId();
  1701 
  1702 	DoBasicAdminChecks();
  1703 
  1704 	return (GetAdminId() != old_id);
  1705 }
  1706 
  1707 void CPlayer::NotifyPostAdminChecks()
  1708 {
  1709 	if (m_bAdminCheckSignalled)
  1710 	{
  1711 		return;
  1712 	}
  1713 
  1714 	/* Block beforehand so they can't double-call */
  1715 	m_bAdminCheckSignalled = true;
  1716 
  1717 	List<IClientListener *>::iterator iter;
  1718 	for (iter = g_Players.m_hooks.begin();
  1719 		iter != g_Players.m_hooks.end();
  1720 		iter++)
  1721 	{
  1722 		IClientListener *pListener = (*iter);
  1723 #if defined MIN_API_FOR_ADMINCALLS
  1724 		if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
  1725 		{
  1726 			continue;
  1727 		}
  1728 #endif
  1729 		pListener->OnClientPostAdminCheck(m_iIndex);
  1730 	}
  1731 
  1732 	PostAdminFilter->PushCell(m_iIndex);
  1733 	PostAdminFilter->Execute(NULL);
  1734 
  1735 	PostAdminCheck->PushCell(m_iIndex);
  1736 	PostAdminCheck->Execute(NULL);
  1737 }
  1738 
  1739 void CPlayer::DoBasicAdminChecks()
  1740 {
  1741 	if (GetAdminId() != INVALID_ADMIN_ID)
  1742 	{
  1743 		return;
  1744 	}
  1745 
  1746 	/* First check the name */
  1747 	AdminId id;
  1748 	int client = IndexOfEdict(m_pEdict);
  1749 
  1750 	if ((id = g_Admins.FindAdminByIdentity("name", GetName())) != INVALID_ADMIN_ID)
  1751 	{
  1752 		if (!g_Players.CheckSetAdminName(client, this, id))
  1753 		{
  1754 			int userid = engine->GetPlayerUserId(m_pEdict);
  1755 			g_Timers.CreateTimer(&s_KickPlayerTimer, 0.1f, (void *)userid, 0);
  1756 		}
  1757 		return;
  1758 	}
  1759 	
  1760 	/* Check IP */
  1761 	if ((id = g_Admins.FindAdminByIdentity("ip", m_IpNoPort.c_str())) != INVALID_ADMIN_ID)
  1762 	{
  1763 		if (g_Players.CheckSetAdmin(client, this, id))
  1764 		{
  1765 			return;
  1766 		}
  1767 	}
  1768 
  1769 	/* Check steam id */
  1770 	if ((id = g_Admins.FindAdminByIdentity("steam", m_AuthID.c_str())) != INVALID_ADMIN_ID)
  1771 	{
  1772 		if (g_Players.CheckSetAdmin(client, this, id))
  1773 		{
  1774 			return;
  1775 		}
  1776 	}
  1777 }
  1778 
  1779 unsigned int CPlayer::GetLanguageId()
  1780 {
  1781 	return m_LangId;
  1782 }
  1783 
  1784 int CPlayer::GetUserId()
  1785 {
  1786 	if (m_UserId == -1)
  1787 	{
  1788 		m_UserId = engine->GetPlayerUserId(GetEdict());
  1789 	}
  1790 
  1791 	return m_UserId;
  1792 }
  1793 
  1794 bool CPlayer::IsInKickQueue()
  1795 {
  1796 	return m_bIsInKickQueue;
  1797 }
  1798 
  1799 void CPlayer::MarkAsBeingKicked()
  1800 {
  1801 	m_bIsInKickQueue = true;
  1802 }
  1803 
  1804 int CPlayer::GetLifeState()
  1805 {
  1806 	if (lifestate_offset == -1)
  1807 	{
  1808 		if (!g_pGameConf->GetOffset("m_lifeState", &lifestate_offset))
  1809 		{
  1810 			lifestate_offset = -2;
  1811 		}
  1812 	}
  1813 
  1814 	if (lifestate_offset < 0)
  1815 	{
  1816 		IPlayerInfo *info = GetPlayerInfo();
  1817 		if (info == NULL)
  1818 		{
  1819 			return PLAYER_LIFE_UNKNOWN;
  1820 		}
  1821 		return info->IsDead() ? PLAYER_LIFE_DEAD : PLAYER_LIFE_ALIVE;
  1822 	}
  1823 
  1824 	if (m_pEdict == NULL)
  1825 	{
  1826 		return PLAYER_LIFE_UNKNOWN;
  1827 	}
  1828 
  1829 	CBaseEntity *pEntity;
  1830 	IServerUnknown *pUnknown = m_pEdict->GetUnknown();
  1831 	if (pUnknown == NULL || (pEntity = pUnknown->GetBaseEntity()) == NULL)
  1832 	{
  1833 		return PLAYER_LIFE_UNKNOWN;
  1834 	}
  1835 
  1836 	if (*((uint8_t *)pEntity + lifestate_offset) == LIFE_ALIVE)
  1837 	{
  1838 		return PLAYER_LIFE_ALIVE;
  1839 	}
  1840 	else
  1841 	{
  1842 		return PLAYER_LIFE_DEAD;
  1843 	}
  1844 }
  1845 
  1846 unsigned int CPlayer::GetSerial()
  1847 {
  1848 	return m_Serial.value;
  1849 }