core/PlayerManager.cpp
author David Anderson <dvander@alliedmods.net>
Sun Mar 31 13:30:22 2013 -0700 (2013-03-31)
changeset 3881 7ec742e7d629
parent 3872 4c93f74cae51
child 3886 7b84bcba1fca
permissions -rw-r--r--
Don't allocate/delete across static CRTs (no bug, irc r=fyren+psychonic).
     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 "AdminCache.h"
    35 #include "ConCmdManager.h"
    36 #include "MenuStyle_Valve.h"
    37 #include "MenuStyle_Radio.h"
    38 #include "sm_stringutil.h"
    39 #include "CoreConfig.h"
    40 #include "TimerSys.h"
    41 #include "Logger.h"
    42 #include "ChatTriggers.h"
    43 #include "HalfLife2.h"
    44 #include <inetchannel.h>
    45 #include <iclient.h>
    46 #include <IGameConfigs.h>
    47 #include <sourcemod_version.h>
    48 #include "ConsoleDetours.h"
    49 #include "logic_bridge.h"
    50 
    51 PlayerManager g_Players;
    52 bool g_OnMapStarted = false;
    53 IForward *PreAdminCheck = NULL;
    54 IForward *PostAdminCheck = NULL;
    55 IForward *PostAdminFilter = NULL;
    56 
    57 const unsigned int *g_NumPlayersToAuth = NULL;
    58 int lifestate_offset = -1;
    59 List<ICommandTargetProcessor *> target_processors;
    60 
    61 SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, edict_t *, const char *, const char *, char *, int);
    62 SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, const char *);
    63 SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *);
    64 #if SOURCE_ENGINE >= SE_ORANGEBOX
    65 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    66 #else
    67 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    68 #endif
    69 SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
    70 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
    71 
    72 #if SOURCE_ENGINE >= SE_ORANGEBOX
    73 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
    74 #elif SOURCE_ENGINE == SE_DARKMESSIAH
    75 SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
    76 #else
    77 # if SH_IMPL_VERSION >= 4
    78  extern int __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    79 # else
    80  extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    81 # endif
    82 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    83 #endif
    84 
    85 ConCommand *maxplayersCmd = NULL;
    86 
    87 unsigned int g_PlayerSerialCount = 0;
    88 
    89 class KickPlayerTimer : public ITimedEvent
    90 {
    91 public:
    92 	ResultType OnTimer(ITimer *pTimer, void *pData)
    93 	{
    94 		int userid = (int)pData;
    95 		int client = g_Players.GetClientOfUserId(userid);
    96 		if (client)
    97 		{
    98 			CPlayer *player = g_Players.GetPlayerByIndex(client);
    99 			player->Kick("Your name is reserved by SourceMod; set your password to use it.");
   100 		}
   101 		return Pl_Stop;
   102 	}
   103 	void OnTimerEnd(ITimer *pTimer, void *pData)
   104 	{
   105 	}
   106 } s_KickPlayerTimer;
   107 
   108 PlayerManager::PlayerManager()
   109 {
   110 	m_AuthQueue = NULL;
   111 	m_FirstPass = false;
   112 	m_maxClients = 0;
   113 
   114 	m_SourceTVUserId = -1;
   115 	m_ReplayUserId = -1;
   116 
   117 	m_bAuthstringValidation = true; // use steam auth by default
   118 
   119 	m_UserIdLookUp = new int[USHRT_MAX+1];
   120 	memset(m_UserIdLookUp, 0, sizeof(int) * (USHRT_MAX+1));
   121 }
   122 
   123 PlayerManager::~PlayerManager()
   124 {
   125 	g_NumPlayersToAuth = NULL;
   126 
   127 	delete [] m_AuthQueue;
   128 	delete [] m_UserIdLookUp;
   129 }
   130 
   131 void PlayerManager::OnSourceModAllInitialized()
   132 {
   133 	SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
   134 	SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
   135 	SH_ADD_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
   136 	SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
   137 	SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
   138 	SH_ADD_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
   139 	SH_ADD_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
   140 	SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
   141 
   142 	sharesys->AddInterface(NULL, this);
   143 
   144 	ParamType p1[] = {Param_Cell, Param_String, Param_Cell};
   145 	ParamType p2[] = {Param_Cell};
   146 
   147 	m_clconnect = g_Forwards.CreateForward("OnClientConnect", ET_LowEvent, 3, p1);
   148 	m_clconnect_post = g_Forwards.CreateForward("OnClientConnected", ET_Ignore, 1, p2);
   149 	m_clputinserver = g_Forwards.CreateForward("OnClientPutInServer", ET_Ignore, 1, p2);
   150 	m_cldisconnect = g_Forwards.CreateForward("OnClientDisconnect", ET_Ignore, 1, p2);
   151 	m_cldisconnect_post = g_Forwards.CreateForward("OnClientDisconnect_Post", ET_Ignore, 1, p2);
   152 	m_clcommand = g_Forwards.CreateForward("OnClientCommand", ET_Hook, 2, NULL, Param_Cell, Param_Cell);
   153 	m_clinfochanged = g_Forwards.CreateForward("OnClientSettingsChanged", ET_Ignore, 1, p2);
   154 	m_clauth = g_Forwards.CreateForward("OnClientAuthorized", ET_Ignore, 2, NULL, Param_Cell, Param_String);
   155 	m_onActivate = g_Forwards.CreateForward("OnServerLoad", ET_Ignore, 0, NULL);
   156 	m_onActivate2 = g_Forwards.CreateForward("OnMapStart", ET_Ignore, 0, NULL);
   157 
   158 	PreAdminCheck = g_Forwards.CreateForward("OnClientPreAdminCheck", ET_Event, 1, p1);
   159 	PostAdminCheck = g_Forwards.CreateForward("OnClientPostAdminCheck", ET_Ignore, 1, p1);
   160 	PostAdminFilter = g_Forwards.CreateForward("OnClientPostAdminFilter", ET_Ignore, 1, p1);
   161 
   162 	m_bIsListenServer = !engine->IsDedicatedServer();
   163 	m_ListenClient = 0;
   164 
   165 	ConCommand *pCmd = FindCommand("maxplayers");
   166 	if (pCmd != NULL)
   167 	{
   168 		SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdMaxplayersCallback), true);
   169 		maxplayersCmd = pCmd;
   170 	}
   171 }
   172 
   173 void PlayerManager::OnSourceModShutdown()
   174 {
   175 	SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
   176 	SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
   177 	SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
   178 	SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
   179 	SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
   180 	SH_REMOVE_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
   181 	SH_REMOVE_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
   182 	SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
   183 
   184 	/* Release forwards */
   185 	g_Forwards.ReleaseForward(m_clconnect);
   186 	g_Forwards.ReleaseForward(m_clconnect_post);
   187 	g_Forwards.ReleaseForward(m_clputinserver);
   188 	g_Forwards.ReleaseForward(m_cldisconnect);
   189 	g_Forwards.ReleaseForward(m_cldisconnect_post);
   190 	g_Forwards.ReleaseForward(m_clcommand);
   191 	g_Forwards.ReleaseForward(m_clinfochanged);
   192 	g_Forwards.ReleaseForward(m_clauth);
   193 	g_Forwards.ReleaseForward(m_onActivate);
   194 	g_Forwards.ReleaseForward(m_onActivate2);
   195 
   196 	g_Forwards.ReleaseForward(PreAdminCheck);
   197 	g_Forwards.ReleaseForward(PostAdminCheck);
   198 	g_Forwards.ReleaseForward(PostAdminFilter);
   199 
   200 	delete [] m_Players;
   201 
   202 	if (maxplayersCmd != NULL)
   203 	{
   204 		SH_REMOVE_HOOK(ConCommand, Dispatch, maxplayersCmd, SH_STATIC(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 	} else if (strcmp( key, "SteamAuthstringValidation" ) == 0) {
   233 		if (strcasecmp(value, "yes") == 0)
   234 		{
   235 			m_bAuthstringValidation = true;
   236 		} else if ( strcasecmp(value, "no") == 0) {
   237 			m_bAuthstringValidation = false;
   238 		} else {
   239 			UTIL_Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
   240 			return ConfigResult_Reject;
   241 		}
   242 		return ConfigResult_Accept;
   243 	}
   244 	return ConfigResult_Ignore;
   245 }
   246 
   247 void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
   248 {
   249 	static ConVar *tv_enable = icvar->FindVar("tv_enable");
   250 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
   251 	static ConVar *replay_enable = icvar->FindVar("replay_enable");
   252 #endif
   253 
   254 	// clientMax will not necessarily be correct here (such as on late SourceTV enable)
   255 	m_maxClients = gpGlobals->maxClients;
   256 
   257 	ICommandLine *commandLine = g_HL2.GetValveCommandLine();
   258 	m_bIsSourceTVActive = (tv_enable && tv_enable->GetBool() && (!commandLine || commandLine->FindParm("-nohltv") == 0));
   259 	m_bIsReplayActive = false;
   260 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
   261 	m_bIsReplayActive = (replay_enable && replay_enable->GetBool());
   262 #endif
   263 	m_PlayersSinceActive = 0;
   264 	
   265 	if (!m_FirstPass)
   266 	{
   267 		/* Initialize all players */
   268 
   269 		m_PlayerCount = 0;
   270 		m_Players = new CPlayer[ABSOLUTE_PLAYER_LIMIT + 1];
   271 		m_AuthQueue = new unsigned int[ABSOLUTE_PLAYER_LIMIT + 1];
   272 		m_FirstPass = true;
   273 
   274 		memset(m_AuthQueue, 0, sizeof(unsigned int) * (ABSOLUTE_PLAYER_LIMIT + 1));
   275 
   276 		g_NumPlayersToAuth = &m_AuthQueue[0];
   277 	}
   278 
   279 	scripts->SyncMaxClients(m_maxClients);
   280 
   281 	g_OnMapStarted = true;
   282 
   283 	extsys->CallOnCoreMapStart(pEdictList, edictCount, m_maxClients);
   284 	m_onActivate->Execute(NULL);
   285 	m_onActivate2->Execute(NULL);
   286 
   287 	List<IClientListener *>::iterator iter;
   288 	for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
   289 	{
   290 		if ((*iter)->GetClientListenerVersion() >= 5)
   291 		{
   292 			(*iter)->OnServerActivated(m_maxClients);
   293 		}
   294 	}
   295 
   296 	SMGlobalClass *cls = SMGlobalClass::head;
   297 	while (cls)
   298 	{
   299 		cls->OnSourceModLevelActivated();
   300 		cls = cls->m_pGlobalClassNext;
   301 	}
   302 
   303 	SM_ExecuteAllConfigs();
   304 }
   305 
   306 bool PlayerManager::IsServerActivated()
   307 {
   308 	return m_FirstPass;
   309 }
   310 
   311 bool PlayerManager::CheckSetAdmin(int index, CPlayer *pPlayer, AdminId id)
   312 {
   313 	const char *password = g_Admins.GetAdminPassword(id);
   314 	if (password != NULL)
   315 	{
   316 		if (m_PassInfoVar.size() < 1)
   317 		{
   318 			return false;
   319 		}
   320 
   321 		/* Whoa... the user needs a password! */
   322 		const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
   323 		if (!given || strcmp(given, password) != 0)
   324 		{
   325 			return false;
   326 		}
   327 	}
   328 
   329 	pPlayer->SetAdminId(id, false);
   330 
   331 	return true;
   332 }
   333 
   334 bool PlayerManager::CheckSetAdminName(int index, CPlayer *pPlayer, AdminId id)
   335 {
   336 	const char *password = g_Admins.GetAdminPassword(id);
   337 	if (password == NULL)
   338 	{
   339 		return false;
   340 	}
   341 
   342 	if (m_PassInfoVar.size() < 1)
   343 	{
   344 		return false;
   345 	}
   346 
   347 	/* Whoa... the user needs a password! */
   348 	const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
   349 	if (!given || strcmp(given, password) != 0)
   350 	{
   351 		return false;
   352 	}
   353 
   354 	pPlayer->SetAdminId(id, false);
   355 
   356 	return true;
   357 }
   358 
   359 void PlayerManager::RunAuthChecks()
   360 {
   361 	CPlayer *pPlayer;
   362 	const char *authstr;
   363 	unsigned int removed = 0;
   364 	for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   365 	{
   366 		pPlayer = &m_Players[m_AuthQueue[i]];
   367 		authstr = engine->GetPlayerNetworkIDString(pPlayer->m_pEdict);
   368 		pPlayer->SetAuthString(authstr);
   369 
   370 		if (!pPlayer->IsAuthStringValidated())
   371 		{
   372 			continue; // we're using steam auth, and steam doesn't know about this player yet so we can't do anything about them for now
   373 		}
   374 
   375 		if (authstr && authstr[0] != '\0'
   376 			&& (strcmp(authstr, "STEAM_ID_PENDING") != 0))
   377 		{
   378 			/* Set authorization */
   379 			pPlayer->Authorize();
   380 
   381 			/* Mark as removed from queue */
   382 			unsigned int client = m_AuthQueue[i];
   383 			m_AuthQueue[i] = 0;
   384 			removed++;
   385 
   386 			/* Send to extensions */
   387 			List<IClientListener *>::iterator iter;
   388 			IClientListener *pListener;
   389 			for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   390 			{
   391 				pListener = (*iter);
   392 				pListener->OnClientAuthorized(client, authstr);
   393 				if (!pPlayer->IsConnected())
   394 				{
   395 					break;
   396 				}
   397 			}
   398 
   399 			/* Send to plugins if player is still connected */
   400 			if (pPlayer->IsConnected() && m_clauth->GetFunctionCount())
   401 			{
   402 				/* :TODO: handle the case of a player disconnecting in the middle */
   403 				m_clauth->PushCell(client);
   404 				m_clauth->PushString(authstr);
   405 				m_clauth->Execute(NULL);
   406 			}
   407 
   408 			if (pPlayer->IsConnected())
   409 			{
   410 				pPlayer->Authorize_Post();
   411 			}
   412 		}
   413 	}
   414 
   415 	/* Clean up the queue */
   416 	if (removed)
   417 	{
   418 		/* We don't have to compact the list if it's empty */
   419 		if (removed != m_AuthQueue[0])
   420 		{
   421 			unsigned int diff = 0;
   422 			for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
   423 			{
   424 				/* If this member is removed... */
   425 				if (m_AuthQueue[i] == 0)
   426 				{
   427 					/* Increase the differential */
   428 					diff++;
   429 				} else {
   430 					/* diff cannot increase faster than i+1 */
   431 					assert(i > diff);
   432 					assert(i - diff >= 1);
   433 					/* move this index down */
   434 					m_AuthQueue[i - diff] = m_AuthQueue[i];
   435 				}
   436 			}
   437 			m_AuthQueue[0] -= removed;
   438 		} else {
   439 			m_AuthQueue[0] = 0;
   440 		}
   441 	}
   442 }
   443 
   444 bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   445 {
   446 	int client = IndexOfEdict(pEntity);
   447 	CPlayer *pPlayer = &m_Players[client];
   448 	++m_PlayersSinceActive;
   449 
   450 	pPlayer->Initialize(pszName, pszAddress, pEntity);
   451 	
   452 	/* Get the client's language */
   453 	if (m_QueryLang)
   454 	{
   455 		const char *name;
   456 		if (!pPlayer->IsFakeClient() && (name=engine->GetClientConVarValue(client, "cl_language")))
   457 		{
   458 			unsigned int langid;
   459 			pPlayer->m_LangId = (translator->GetLanguageByName(name, &langid)) ? langid : translator->GetServerLanguage();
   460 		} else {
   461 			pPlayer->m_LangId = translator->GetServerLanguage();
   462 		}
   463 	}
   464 	
   465 	List<IClientListener *>::iterator iter;
   466 	IClientListener *pListener = NULL;
   467 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   468 	{
   469 		pListener = (*iter);
   470 		if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
   471 		{
   472 			RETURN_META_VALUE(MRES_SUPERCEDE, false);
   473 		}
   474 	}
   475 
   476 	cell_t res = 1;
   477 
   478 	m_clconnect->PushCell(client);
   479 	m_clconnect->PushStringEx(reject, maxrejectlen, SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK);
   480 	m_clconnect->PushCell(maxrejectlen);
   481 	m_clconnect->Execute(&res);
   482 
   483 	if (res)
   484 	{
   485 		if (!pPlayer->IsAuthorized())
   486 		{
   487 			m_AuthQueue[++m_AuthQueue[0]] = client;
   488 		}
   489 
   490 		m_UserIdLookUp[engine->GetPlayerUserId(pEntity)] = client;
   491 	}
   492 	else
   493 	{
   494 		if (!pPlayer->IsFakeClient())
   495 		{
   496 			RETURN_META_VALUE(MRES_SUPERCEDE, false);
   497 		}
   498 	}
   499 
   500 	return true;
   501 }
   502 
   503 bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
   504 {
   505 	int client = IndexOfEdict(pEntity);
   506 	bool orig_value = META_RESULT_ORIG_RET(bool);
   507 	CPlayer *pPlayer = &m_Players[client];
   508 
   509 	if (orig_value)
   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 			if (!pPlayer->IsConnected())
   518 			{
   519 				return true;
   520 			}
   521 		}
   522 
   523 		if (!pPlayer->IsFakeClient() 
   524 			&& m_bIsListenServer
   525 			&& strncmp(pszAddress, "127.0.0.1", 9) == 0)
   526 		{
   527 			m_ListenClient = client;
   528 		}
   529 
   530 		cell_t res;
   531 		m_clconnect_post->PushCell(client);
   532 		m_clconnect_post->Execute(&res, NULL);
   533 	}
   534 	else
   535 	{
   536 		InvalidatePlayer(pPlayer);
   537 	}
   538 
   539 	return true;
   540 }
   541 
   542 void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername)
   543 {
   544 	cell_t res;
   545 	int client = IndexOfEdict(pEntity);
   546 	CPlayer *pPlayer = &m_Players[client];
   547 
   548 	/* If they're not connected, they're a bot */
   549 	if (!pPlayer->IsConnected())
   550 	{
   551 		/* Run manual connection routines */
   552 		char error[255];
   553 		const char *authid = engine->GetPlayerNetworkIDString(pEntity);
   554 		pPlayer->SetAuthString(authid);
   555 		pPlayer->Authorize();
   556 		pPlayer->m_bFakeClient = true;
   557 
   558 		/*
   559 		 * While we're already filtered to just bots, we'll do other checks to
   560 		 * make sure that the requisite services are enabled and that the bots
   561 		 * have joined at the expected time.
   562 		 *
   563 		 * Checking playerinfo's IsHLTV and IsReplay would be better and less
   564 		 * error-prone but will always show false until later in the frame,
   565 		 * after PutInServer and Activate, and we want it now!
   566 		 *
   567 		 * These checks are hairy as hell due to differences between engines and games.
   568 		 * 
   569 		 * Most engines use "Replay" and "SourceTV" as bot names for these when they're
   570 		 * created. EP2V, CSS and Nuclear Dawn (but not L4D2) differ from this by now using
   571 		 * replay_/tv_name directly when creating the bot(s). To complicate it slightly
   572 		 * further, the cvar can be empty and the engine's fallback to "unnamed" will be used.
   573 		 * We can maybe just rip out the name checks at some point and rely solely on whether
   574 		 * they're enabled and the join order.
   575 		 */
   576 		
   577 		// This doesn't actually get incremented until OnClientConnect. Fake it to check.
   578 		int newCount = m_PlayersSinceActive + 1;
   579 
   580 		int userId = engine->GetPlayerUserId(pEntity);
   581 #if (SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_LEFT4DEAD2)
   582 		static ConVar *tv_name = icvar->FindVar("tv_name");
   583 #endif
   584 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
   585 		static ConVar *replay_name = icvar->FindVar("replay_name");
   586 #endif
   587 #if SOURCE_ENGINE == SE_LEFT4DEAD2
   588 		static bool bIsNuclearDawn = (strcmp(g_SourceMod.GetGameFolderName(), "nucleardawn") == 0);
   589 #endif
   590 
   591 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
   592 		if (m_bIsReplayActive && newCount == 1
   593 			&& (m_ReplayUserId == userId
   594 				|| (replay_name && strcmp(playername, replay_name->GetString()) == 0) || (replay_name && replay_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
   595 				)
   596 			)
   597 		{
   598 			pPlayer->m_bIsReplay = true;
   599 			m_ReplayUserId = userId;
   600 		}
   601 #endif
   602 
   603 		if (m_bIsSourceTVActive
   604 			&& ((!m_bIsReplayActive && newCount == 1)
   605 				|| (m_bIsReplayActive && newCount == 2))
   606 			&& (m_SourceTVUserId == userId
   607 #if SOURCE_ENGINE == SE_CSGO
   608 				|| strcmp(playername, "GOTV") == 0
   609 #elif (SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_LEFT4DEAD2)
   610 #if SOURCE_ENGINE == SE_LEFT4DEAD2
   611 				|| (bIsNuclearDawn && ( true
   612 #endif // SE_LEFT4DEAD2
   613 				|| (tv_name && strcmp(playername, tv_name->GetString()) == 0) || (tv_name && tv_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
   614 #if SOURCE_ENGINE == SE_LEFT4DEAD2
   615 					))
   616 				|| (!bIsNuclearDawn && strcmp(playername, "SourceTV") == 0)
   617 #endif // SE_LEFT4DEAD2
   618 #else
   619 				|| strcmp(playername, "SourceTV") == 0
   620 #endif
   621 				)
   622 			)
   623 		{
   624 			pPlayer->m_bIsSourceTV = true;
   625 			m_SourceTVUserId = userId;
   626 		}
   627 
   628 		if (!OnClientConnect(pEntity, playername, "127.0.0.1", error, sizeof(error)))
   629 		{
   630 			/* :TODO: kick the bot if it's rejected */
   631 			return;
   632 		}
   633 		List<IClientListener *>::iterator iter;
   634 		IClientListener *pListener = NULL;
   635 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   636 		{
   637 			pListener = (*iter);
   638 			pListener->OnClientConnected(client);
   639 			/* See if bot was kicked */
   640 			if (!pPlayer->IsConnected())
   641 			{
   642 				return;
   643 			}
   644 		}
   645 
   646 		cell_t res;
   647 		m_clconnect_post->PushCell(client);
   648 		m_clconnect_post->Execute(&res, NULL);
   649 
   650 		/* Now do authorization */
   651 		for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   652 		{
   653 			pListener = (*iter);
   654 			pListener->OnClientAuthorized(client, authid);
   655 		}
   656 		/* Finally, tell plugins */
   657 		if (m_clauth->GetFunctionCount())
   658 		{
   659 			m_clauth->PushCell(client);
   660 			m_clauth->PushString(authid);
   661 			m_clauth->Execute(NULL);
   662 		}
   663 		pPlayer->Authorize_Post();
   664 	}
   665 
   666 	if (playerinfo)
   667 	{
   668 		pPlayer->m_Info = playerinfo->GetPlayerInfo(pEntity);
   669 	}
   670 
   671 	pPlayer->Connect();
   672 	m_PlayerCount++;
   673 
   674 	List<IClientListener *>::iterator iter;
   675 	IClientListener *pListener = NULL;
   676 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   677 	{
   678 		pListener = (*iter);
   679 		pListener->OnClientPutInServer(client);
   680 	}
   681 
   682 	m_clputinserver->PushCell(client);
   683 	m_clputinserver->Execute(&res, NULL);
   684 
   685 	if (pPlayer->IsAuthorized())
   686 	{
   687 		pPlayer->DoPostConnectAuthorization();
   688 	}
   689 }
   690 
   691 void PlayerManager::OnSourceModLevelEnd()
   692 {
   693 	/* Disconnect all bots still in game */
   694 	for (int i=1; i<=m_maxClients; i++)
   695 	{
   696 		if (m_Players[i].IsConnected())
   697 		{
   698 			OnClientDisconnect(m_Players[i].GetEdict());
   699 		}
   700 	}
   701 	m_PlayerCount = 0;
   702 }
   703 
   704 void PlayerManager::OnClientDisconnect(edict_t *pEntity)
   705 {
   706 	cell_t res;
   707 	int client = IndexOfEdict(pEntity);
   708 	CPlayer *pPlayer = &m_Players[client];
   709 
   710 	if (pPlayer->IsConnected())
   711 	{
   712 		m_cldisconnect->PushCell(client);
   713 		m_cldisconnect->Execute(&res, NULL);
   714 	}
   715 	else
   716 	{
   717 		/* We don't care, prevent a double call */
   718 		return;
   719 	}
   720 
   721 	if (pPlayer->WasCountedAsInGame())
   722 	{
   723 		m_PlayerCount--;
   724 	}
   725 
   726 	List<IClientListener *>::iterator iter;
   727 	IClientListener *pListener = NULL;
   728 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   729 	{
   730 		pListener = (*iter);
   731 		pListener->OnClientDisconnecting(client);
   732 	}
   733 
   734 	InvalidatePlayer(pPlayer);
   735 
   736 	if (m_ListenClient == client)
   737 	{
   738 		m_ListenClient = 0;
   739 	}
   740 }
   741 
   742 void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
   743 {
   744 	cell_t res;
   745 	int client = IndexOfEdict(pEntity);
   746 
   747 	m_cldisconnect_post->PushCell(client);
   748 	m_cldisconnect_post->Execute(&res, NULL);
   749 
   750 	List<IClientListener *>::iterator iter;
   751 	IClientListener *pListener = NULL;
   752 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
   753 	{
   754 		pListener = (*iter);
   755 		pListener->OnClientDisconnected(client);
   756 	}
   757 }
   758 
   759 void ClientConsolePrint(edict_t *e, const char *fmt, ...)
   760 {
   761 	char buffer[512];
   762 
   763 	va_list ap;
   764 	va_start(ap, fmt);
   765 	size_t len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
   766 	va_end(ap);
   767 
   768 	if (len >= sizeof(buffer) - 1)
   769 	{
   770 		buffer[sizeof(buffer) - 2] = '\n';
   771 		buffer[sizeof(buffer) - 1] = '\0';
   772 	} else {
   773 		buffer[len++] = '\n';
   774 		buffer[len] = '\0';
   775 	}
   776 
   777 	engine->ClientPrintf(e, buffer);
   778 }
   779 
   780 void ListExtensionsToClient(CPlayer *player, const CCommand &args)
   781 {
   782 	char buffer[256];
   783 	unsigned int id = 0;
   784 	unsigned int start = 0;
   785 
   786 	AutoExtensionList extensions(extsys);
   787 	if (!extensions->size())
   788 	{
   789 		ClientConsolePrint(player->GetEdict(), "[SM] No extensions found.");
   790 		return;
   791 	}
   792 
   793 	if (args.ArgC() > 2)
   794 	{
   795 		start = atoi(args.Arg(2));
   796 	}
   797 
   798 	size_t i = 0;
   799 	for (; i < extensions->size(); i++)
   800 	{
   801 		IExtension *ext = extensions->at(i);
   802 
   803 		char error[255];
   804 		if (!ext->IsRunning(error, sizeof(error)))
   805 		{
   806 			continue;
   807 		}
   808 
   809 		id++;
   810 		if (id < start)
   811 		{
   812 			continue;
   813 		}
   814 
   815 		if (id - start > 10)
   816 		{
   817 			break;
   818 		}
   819 
   820 		IExtensionInterface *api = ext->GetAPI();
   821 
   822 		const char *name = api->GetExtensionName();
   823 		const char *version = api->GetExtensionVerString();
   824 		const char *author = api->GetExtensionAuthor();
   825 		const char *description = api->GetExtensionDescription();
   826 
   827 		size_t len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", name);
   828 
   829 		if (version != NULL && version[0])
   830 		{
   831 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", version);
   832 		}
   833 
   834 		if (author != NULL && author[0])
   835 		{
   836 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", author);
   837 		}
   838 
   839 		if (description != NULL && description[0])
   840 		{
   841 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, ": %s", description);
   842 		}
   843 
   844 
   845 		ClientConsolePrint(player->GetEdict(), "%s", buffer);
   846 	}
   847 
   848 	for (; i < extensions->size(); i++)
   849 	{
   850 		char error[255];
   851 		if (extensions->at(i)->IsRunning(error, sizeof(error)))
   852 		{
   853 			break;
   854 		}
   855 	}
   856 
   857 	if (i < extensions->size())
   858 	{
   859 		ClientConsolePrint(player->GetEdict(), "To see more, type \"sm exts %d\"", id);
   860 	}
   861 }
   862 
   863 void ListPluginsToClient(CPlayer *player, const CCommand &args)
   864 {
   865 	char buffer[256];
   866 	unsigned int id = 0;
   867 	edict_t *e = player->GetEdict();
   868 	unsigned int start = 0;
   869 
   870 	AutoPluginList plugins(scripts);
   871 	if (!plugins->size())
   872 	{
   873 		ClientConsolePrint(e, "[SM] No plugins found.");
   874 		return;
   875 	}
   876 
   877 	if (args.ArgC() > 2)
   878 	{
   879 		start = atoi(args.Arg(2));
   880 	}
   881 
   882 	SourceHook::List<SMPlugin *> m_FailList;
   883 
   884 	size_t i = 0;
   885 	for (; i < plugins->size(); i++)
   886 	{
   887 		SMPlugin *pl = plugins->at(i);
   888 
   889 		if (pl->GetStatus() != Plugin_Running)
   890 		{
   891 			continue;
   892 		}
   893 
   894 		/* Count valid plugins */
   895 		id++;
   896 		if (id < start)
   897 		{
   898 			continue;
   899 		}
   900 
   901 		if (id - start > 10)
   902 		{
   903 			break;
   904 		}
   905 
   906 		size_t len;
   907 		const sm_plugininfo_t *info = pl->GetPublicInfo();
   908 		len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
   909 		if (IS_STR_FILLED(info->version))
   910 		{
   911 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
   912 		}
   913 		if (IS_STR_FILLED(info->author))
   914 		{
   915 			UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
   916 		}
   917 		else
   918 		{
   919 			UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->GetFilename());
   920 		}
   921 		ClientConsolePrint(e, "%s", buffer);
   922 	}
   923 
   924 	/* See if we can get more plugins */
   925 	for (; i < plugins->size(); i++)
   926 	{
   927 		if (plugins->at(i)->GetStatus() == Plugin_Running)
   928 		{
   929 			break;
   930 		}
   931 	}
   932 
   933 	/* Do we actually have more plugins? */
   934 	if (i < plugins->size())
   935 	{
   936 		ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id);
   937 	}
   938 }
   939 
   940 #if SOURCE_ENGINE >= SE_ORANGEBOX
   941 void PlayerManager::OnClientCommand(edict_t *pEntity, const CCommand &args)
   942 {
   943 #else
   944 void PlayerManager::OnClientCommand(edict_t *pEntity)
   945 {
   946 	CCommand args;
   947 #endif
   948 	int client = IndexOfEdict(pEntity);
   949 	cell_t res = Pl_Continue;
   950 	CPlayer *pPlayer = &m_Players[client];
   951 
   952 	if (!pPlayer->IsConnected())
   953 	{
   954 		return;
   955 	}
   956 
   957 	if (strcmp(args.Arg(0), "sm") == 0)
   958 	{
   959 		if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0)
   960 		{
   961 			ListPluginsToClient(pPlayer, args);
   962 			RETURN_META(MRES_SUPERCEDE);
   963 		}
   964 		else if (args.ArgC() > 1 && strcmp(args.Arg(1), "exts") == 0)
   965 		{
   966 			ListExtensionsToClient(pPlayer, args);
   967 			RETURN_META(MRES_SUPERCEDE);
   968 		}
   969 		else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0)
   970 		{
   971  			ClientConsolePrint(pEntity,
   972  				"SourceMod would not be possible without:");
   973  			ClientConsolePrint(pEntity,
   974 				" David \"BAILOPAN\" Anderson, Matt \"pRED\" Woodrow");
   975  			ClientConsolePrint(pEntity,
   976 				" Scott \"DS\" Ehlert, Fyren");
   977  			ClientConsolePrint(pEntity,
   978 				" Nicholas \"psychonic\" Hastings, Asher \"asherkin\" Baker");
   979 			ClientConsolePrint(pEntity,
   980 				" Borja \"faluco\" Ferrer, Pavol \"PM OnoTo\" Marko");
   981 			ClientConsolePrint(pEntity,
   982 				"SourceMod is open source under the GNU General Public License.");
   983 			RETURN_META(MRES_SUPERCEDE);
   984 		}
   985 
   986 		ClientConsolePrint(pEntity,
   987 			"SourceMod %s, by AlliedModders LLC", SM_VERSION_STRING);
   988 		ClientConsolePrint(pEntity,
   989 			"To see running plugins, type \"sm plugins\"");
   990 		ClientConsolePrint(pEntity,
   991 			"To see credits, type \"sm credits\"");
   992 		ClientConsolePrint(pEntity,
   993 			"Visit http://www.sourcemod.net/");
   994 		RETURN_META(MRES_SUPERCEDE);
   995 	}
   996 
   997 	g_HL2.PushCommandStack(&args);
   998 
   999 	int argcount = args.ArgC() - 1;
  1000 	const char *cmd = g_HL2.CurrentCommandName();
  1001 
  1002 	bool result = g_ValveMenuStyle.OnClientCommand(client, cmd, args);
  1003 	if (result)
  1004 	{
  1005 		res = Pl_Handled;
  1006 	} else {
  1007 		result = g_RadioMenuStyle.OnClientCommand(client, cmd, args);
  1008 		if (result)
  1009 		{
  1010 			res = Pl_Handled;
  1011 		}
  1012 	}
  1013 
  1014 	if (g_ConsoleDetours.IsEnabled())
  1015 	{
  1016 		cell_t res2 = g_ConsoleDetours.InternalDispatch(client, args);
  1017 		if (res2 >= Pl_Stop)
  1018 		{
  1019 			g_HL2.PopCommandStack();
  1020 			RETURN_META(MRES_SUPERCEDE);
  1021 		}
  1022 		else if (res2 > res)
  1023 		{
  1024 			res = res2;
  1025 		}
  1026 	}
  1027 
  1028 	cell_t res2 = Pl_Continue;
  1029 	if (pPlayer->IsInGame())
  1030 	{
  1031 		m_clcommand->PushCell(client);
  1032 		m_clcommand->PushCell(argcount);
  1033 		m_clcommand->Execute(&res2, NULL);
  1034 	}
  1035 
  1036 	if (res2 > res)
  1037 	{
  1038 		res = res2;
  1039 	}
  1040 
  1041 	if (res >= Pl_Stop)
  1042 	{
  1043 		g_HL2.PopCommandStack();
  1044 		RETURN_META(MRES_SUPERCEDE);
  1045 	}
  1046 
  1047 	res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res);
  1048 
  1049 	g_HL2.PopCommandStack();
  1050 
  1051 	if (res >= Pl_Handled)
  1052 	{
  1053 		RETURN_META(MRES_SUPERCEDE);
  1054 	}
  1055 }
  1056 
  1057 void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
  1058 {
  1059 	cell_t res;
  1060 	int client = IndexOfEdict(pEntity);
  1061 	CPlayer *pPlayer = &m_Players[client];
  1062 
  1063 	if (!pPlayer->IsConnected())
  1064 	{
  1065 		return;
  1066 	}
  1067 
  1068 	m_clinfochanged->PushCell(client);
  1069 	m_clinfochanged->Execute(&res, NULL);
  1070 
  1071 	if (pPlayer->IsFakeClient())
  1072 	{
  1073 		return;
  1074 	}
  1075 
  1076 	IPlayerInfo *info = pPlayer->GetPlayerInfo();
  1077 	const char *new_name = info ? info->GetName() : engine->GetClientConVarValue(client, "name");
  1078 	const char *old_name = pPlayer->m_Name.c_str();
  1079 
  1080 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1081 	const char *networkid_force;
  1082 	if ((networkid_force = engine->GetClientConVarValue(client, "networkid_force")) && networkid_force[0] != '\0')
  1083 	{
  1084 		unsigned int accountId = pPlayer->GetSteamAccountID();
  1085 		g_Logger.LogMessage("\"%s<%d><STEAM_1:%d:%d><>\" has bad networkid (id \"%s\") (ip \"%s\")",
  1086 			new_name, pPlayer->GetUserId(), accountId & 1, accountId >> 1, networkid_force, pPlayer->GetIPAddress());
  1087 
  1088 		pPlayer->Kick("NetworkID spoofing detected.");
  1089 		RETURN_META(MRES_IGNORED);
  1090 	}
  1091 #endif
  1092 
  1093 	if (strcmp(old_name, new_name) != 0)
  1094 	{
  1095 		AdminId id = g_Admins.FindAdminByIdentity("name", new_name);
  1096 		if (id != INVALID_ADMIN_ID && pPlayer->GetAdminId() != id)
  1097 		{
  1098 			if (!CheckSetAdminName(client, pPlayer, id))
  1099 			{
  1100 				pPlayer->Kick("Your name is reserved by SourceMod; set your password to use it.");
  1101 				RETURN_META(MRES_IGNORED);
  1102 			}
  1103 		} else if ((id = g_Admins.FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
  1104 			if (id == pPlayer->GetAdminId())
  1105 			{
  1106 				/* This player is changing their name; force them to drop admin privileges! */
  1107 				pPlayer->SetAdminId(INVALID_ADMIN_ID, false);
  1108 			}
  1109 		}
  1110 		pPlayer->SetName(new_name);
  1111 	}
  1112 	
  1113 	if (m_PassInfoVar.size() > 0)
  1114 	{
  1115 		/* Try for a password change */
  1116 		const char *old_pass = pPlayer->m_LastPassword.c_str();
  1117 		const char *new_pass = engine->GetClientConVarValue(client, m_PassInfoVar.c_str());
  1118 		if (strcmp(old_pass, new_pass) != 0)
  1119 		{
  1120 			pPlayer->m_LastPassword.assign(new_pass);
  1121 			if (pPlayer->IsInGame() && pPlayer->IsAuthorized())
  1122 			{
  1123 				/* If there is already an admin id assigned, this will just bail out. */
  1124 				pPlayer->DoBasicAdminChecks();
  1125 			}
  1126 		}
  1127 	}
  1128 	/* Notify Extensions */
  1129 	List<IClientListener *>::iterator iter;
  1130 	IClientListener *pListener = NULL;
  1131 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1132 	{
  1133 		pListener = (*iter);
  1134 		if (pListener->GetClientListenerVersion() >= 13)
  1135 		{
  1136 			pListener->OnClientSettingsChanged(client);
  1137 		}
  1138 	}
  1139 }
  1140 
  1141 int PlayerManager::GetMaxClients()
  1142 {
  1143 	return m_maxClients;
  1144 }
  1145 
  1146 CPlayer *PlayerManager::GetPlayerByIndex(int client) const
  1147 {
  1148 	if (client > m_maxClients || client < 1)
  1149 	{
  1150 		return NULL;
  1151 	}
  1152 	return &m_Players[client];
  1153 }
  1154 
  1155 int PlayerManager::GetNumPlayers()
  1156 {
  1157 	return m_PlayerCount;
  1158 }
  1159 
  1160 int PlayerManager::GetClientOfUserId(int userid)
  1161 {
  1162 	if (userid < 0 || userid > USHRT_MAX)
  1163 	{
  1164 		return 0;
  1165 	}
  1166 	
  1167 	int client = m_UserIdLookUp[userid];
  1168 
  1169 	/* Verify the userid.  The cache can get messed up with older
  1170 	 * Valve engines.  :TODO: If this gets fixed, do an old engine 
  1171 	 * check before invoking this backwards compat code.
  1172 	 */
  1173 	if (client)
  1174 	{
  1175 		CPlayer *player = GetPlayerByIndex(client);
  1176 		if (player && player->IsConnected())
  1177 		{
  1178 			int realUserId = engine->GetPlayerUserId(player->GetEdict());
  1179 			if (realUserId == userid)
  1180 			{
  1181 				return client;
  1182 			}
  1183 		}
  1184 	}
  1185 
  1186 	/* If we can't verify the userid, we have to do a manual loop */
  1187 	CPlayer *player;
  1188 	for (int i = 1; i <= m_maxClients; i++)
  1189 	{
  1190 		player = GetPlayerByIndex(i);
  1191 		if (!player || !player->IsConnected())
  1192 		{
  1193 			continue;
  1194 		}
  1195 		if (engine->GetPlayerUserId(player->GetEdict()) == userid)
  1196 		{
  1197 			m_UserIdLookUp[userid] = i;
  1198 			return i;
  1199 		}
  1200 	}
  1201 
  1202 	return 0;
  1203 }
  1204 
  1205 void PlayerManager::AddClientListener(IClientListener *listener)
  1206 {
  1207 	m_hooks.push_back(listener);
  1208 }
  1209 
  1210 void PlayerManager::RemoveClientListener(IClientListener *listener)
  1211 {
  1212 	m_hooks.remove(listener);
  1213 }
  1214 
  1215 IGamePlayer *PlayerManager::GetGamePlayer(edict_t *pEdict)
  1216 {
  1217 	int index = IndexOfEdict(pEdict);
  1218 	return GetGamePlayer(index);
  1219 }
  1220 
  1221 IGamePlayer *PlayerManager::GetGamePlayer(int client)
  1222 {
  1223 	return GetPlayerByIndex(client);
  1224 }
  1225 
  1226 void PlayerManager::ClearAdminId(AdminId id)
  1227 {
  1228 	for (int i=1; i<=m_maxClients; i++)
  1229 	{
  1230 		if (m_Players[i].m_Admin == id)
  1231 		{
  1232 			m_Players[i].DumpAdmin(true);
  1233 		}
  1234 	}
  1235 }
  1236 
  1237 void PlayerManager::ClearAllAdmins()
  1238 {
  1239 	for (int i=1; i<=m_maxClients; i++)
  1240 	{
  1241 		m_Players[i].DumpAdmin(true);
  1242 	}
  1243 }
  1244 
  1245 const char *PlayerManager::GetPassInfoVar()
  1246 {
  1247 	return m_PassInfoVar.c_str();
  1248 }
  1249 
  1250 void PlayerManager::RecheckAnyAdmins()
  1251 {
  1252 	for (int i=1; i<=m_maxClients; i++)
  1253 	{
  1254 		if (m_Players[i].IsInGame() && m_Players[i].IsAuthorized())
  1255 		{
  1256 			m_Players[i].DoBasicAdminChecks();
  1257 		}
  1258 	}
  1259 }
  1260 
  1261 unsigned int PlayerManager::GetReplyTo()
  1262 {
  1263 	return g_ChatTriggers.GetReplyTo();
  1264 }
  1265 
  1266 unsigned int PlayerManager::SetReplyTo(unsigned int reply)
  1267 {
  1268 	return g_ChatTriggers.SetReplyTo(reply);
  1269 }
  1270 
  1271 int PlayerManager::FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags)
  1272 {
  1273 	return InternalFilterCommandTarget((CPlayer *)pAdmin, (CPlayer *)pTarget, flags);
  1274 }
  1275 
  1276 void PlayerManager::RegisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
  1277 {
  1278 	target_processors.push_back(pHandler);
  1279 }
  1280 
  1281 void PlayerManager::UnregisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
  1282 {
  1283 	target_processors.remove(pHandler);
  1284 }
  1285 
  1286 void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
  1287 {
  1288 	/**
  1289 	* Remove client from auth queue if necessary
  1290 	*/
  1291 	if (!pPlayer->IsAuthorized())
  1292 	{
  1293 		for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
  1294 		{
  1295 			if (m_AuthQueue[i] == (unsigned)pPlayer->m_iIndex)
  1296 			{
  1297 				/* Move everything ahead of us back by one */
  1298 				for (unsigned int j=i+1; j<=m_AuthQueue[0]; j++)
  1299 				{
  1300 					m_AuthQueue[j-1] = m_AuthQueue[j];
  1301 				}
  1302 				/* Remove us and break */
  1303 				m_AuthQueue[0]--;
  1304 				break;
  1305 			}
  1306 		}
  1307 	}
  1308 	
  1309 	m_UserIdLookUp[engine->GetPlayerUserId(pPlayer->m_pEdict)] = 0;
  1310 	pPlayer->Disconnect();
  1311 }
  1312 
  1313 int PlayerManager::InternalFilterCommandTarget(CPlayer *pAdmin, CPlayer *pTarget, int flags)
  1314 {
  1315 	if ((flags & COMMAND_FILTER_CONNECTED) == COMMAND_FILTER_CONNECTED
  1316 		&& !pTarget->IsConnected())
  1317 	{
  1318 		return COMMAND_TARGET_NONE;
  1319 	}
  1320 	else if ((flags & COMMAND_FILTER_CONNECTED) != COMMAND_FILTER_CONNECTED && 
  1321 		!pTarget->IsInGame())
  1322 	{
  1323 		return COMMAND_TARGET_NOT_IN_GAME;
  1324 	}
  1325 
  1326 	if ((flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS
  1327 		&& pTarget->IsFakeClient())
  1328 	{
  1329 		return COMMAND_TARGET_NOT_HUMAN;
  1330 	}
  1331 
  1332 	if (pAdmin != NULL)
  1333 	{
  1334 		if ((flags & COMMAND_FILTER_NO_IMMUNITY) != COMMAND_FILTER_NO_IMMUNITY
  1335 			&& !g_Admins.CanAdminTarget(pAdmin->GetAdminId(), pTarget->GetAdminId()))
  1336 		{
  1337 			return COMMAND_TARGET_IMMUNE;
  1338 		}
  1339 	}
  1340 
  1341 	if ((flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE 
  1342 		&& pTarget->GetLifeState() != PLAYER_LIFE_ALIVE)
  1343 	{
  1344 		return COMMAND_TARGET_NOT_ALIVE;
  1345 	}
  1346 
  1347 	if ((flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD
  1348 		&& pTarget->GetLifeState() != PLAYER_LIFE_DEAD)
  1349 	{
  1350 		return COMMAND_TARGET_NOT_DEAD;
  1351 	}
  1352 
  1353 	return COMMAND_TARGET_VALID;
  1354 }
  1355 
  1356 void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
  1357 {
  1358 	CPlayer *pTarget, *pAdmin;
  1359 	int max_clients, total = 0;
  1360 
  1361 	max_clients = GetMaxClients();
  1362 
  1363 	if (info->max_targets < 1)
  1364 	{
  1365 		info->reason = COMMAND_TARGET_NONE;
  1366 		info->num_targets = 0;
  1367 	}
  1368 
  1369 	if (info->admin == 0)
  1370 	{
  1371 		pAdmin = NULL;
  1372 	}
  1373 	else
  1374 	{
  1375 		pAdmin = GetPlayerByIndex(info->admin);
  1376 	}
  1377 
  1378 	if (info->pattern[0] == '#')
  1379 	{
  1380 		int userid = atoi(&info->pattern[1]);
  1381 		int client = GetClientOfUserId(userid);
  1382 
  1383 		/* See if a valid userid matched */
  1384 		if (client > 0)
  1385 		{
  1386 			IGamePlayer *pTarget = GetPlayerByIndex(client);
  1387 			if (pTarget != NULL)
  1388 			{
  1389 				if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags)) == COMMAND_TARGET_VALID)
  1390 				{
  1391 					info->targets[0] = client;
  1392 					info->num_targets = 1;
  1393 					strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1394 					info->target_name_style = COMMAND_TARGETNAME_RAW;
  1395 				}
  1396 				else
  1397 				{
  1398 					info->num_targets = 0;
  1399 				}
  1400 				return;
  1401 			}
  1402 		}
  1403 
  1404 		/* Do we need to look for a steam id? */
  1405 		if (strncmp(&info->pattern[1], "STEAM_", 6) == 0)
  1406 		{
  1407 			size_t p, len;
  1408 			char new_pattern[256];
  1409 
  1410 			strcpy(new_pattern, "STEAM_");
  1411 			len = strlen(&info->pattern[7]);
  1412 			for (p = 0; p < len; p++)
  1413 			{
  1414 				new_pattern[6 + p] = info->pattern[7 + p];
  1415 				if (new_pattern[6 + p] == '_')
  1416 				{
  1417 					new_pattern[6 + p] = ':';
  1418 				}
  1419 			}
  1420 			new_pattern[6 + p] = '\0';
  1421 
  1422 			for (int i = 1; i <= max_clients; i++)
  1423 			{
  1424 				if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1425 				{
  1426 					continue;
  1427 				}
  1428 				if (!pTarget->IsConnected())
  1429 				{
  1430 					continue;
  1431 				}
  1432 				const char *authstr = pTarget->GetAuthString(false); // We want to make it easy for people to be kicked/banned, so don't require validation for command targets.
  1433 				if (authstr && strcmp(authstr, new_pattern) == 0)
  1434 				{
  1435 					if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
  1436 						== COMMAND_TARGET_VALID)
  1437 					{
  1438 						info->targets[0] = i;
  1439 						info->num_targets = 1;
  1440 						strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1441 						info->target_name_style = COMMAND_TARGETNAME_RAW;
  1442 					}
  1443 					else
  1444 					{
  1445 						info->num_targets = 0;
  1446 					}
  1447 					return;
  1448 				}
  1449 			}
  1450 		}
  1451 
  1452 		/* See if an exact name matches */
  1453 		for (int i = 1; i <= max_clients; i++)
  1454 		{
  1455 			if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1456 			{
  1457 				continue;
  1458 			}
  1459 			if  (!pTarget->IsConnected())
  1460 			{
  1461 				continue;
  1462 			}
  1463 			if (strcmp(pTarget->GetName(), &info->pattern[1]) == 0)
  1464 			{
  1465 				if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
  1466 					== COMMAND_TARGET_VALID)
  1467 				{
  1468 					info->targets[0] = i;
  1469 					info->num_targets = 1;
  1470 					strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
  1471 					info->target_name_style = COMMAND_TARGETNAME_RAW;
  1472 				}
  1473 				else
  1474 				{
  1475 					info->num_targets = 0;
  1476 				}
  1477 				return;
  1478 			}
  1479 		}
  1480 	}
  1481 
  1482 	if (strcmp(info->pattern, "@me") == 0 && info->admin != 0)
  1483 	{
  1484 		info->reason = FilterCommandTarget(pAdmin, pAdmin, info->flags);
  1485 		if (info->reason == COMMAND_TARGET_VALID)
  1486 		{
  1487 			info->targets[0] = info->admin;
  1488 			info->num_targets = 1;
  1489 			strncopy(info->target_name, pAdmin->GetName(), info->target_name_maxlength);
  1490 			info->target_name_style = COMMAND_TARGETNAME_RAW;
  1491 		}
  1492 		else
  1493 		{
  1494 			info->num_targets = 0;
  1495 		}
  1496 		return;
  1497 	}
  1498 
  1499 	if ((info->flags & COMMAND_FILTER_NO_MULTI) != COMMAND_FILTER_NO_MULTI)
  1500 	{
  1501 		bool is_multi = false;
  1502 		bool bots_only = false;
  1503 		int skip_client = -1;
  1504 
  1505 		if (strcmp(info->pattern, "@all") == 0)
  1506 		{
  1507 			is_multi = true;
  1508 			strncopy(info->target_name, "all players", info->target_name_maxlength);
  1509 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1510 		}
  1511 		else if (strcmp(info->pattern, "@dead") == 0)
  1512 		{
  1513 			is_multi = true;
  1514 			if ((info->flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE)
  1515 			{
  1516 				info->num_targets = 0;
  1517 				info->reason = COMMAND_TARGET_NOT_ALIVE;
  1518 				return;
  1519 			}
  1520 			info->flags |= COMMAND_FILTER_DEAD;
  1521 			strncopy(info->target_name, "all dead players", info->target_name_maxlength);
  1522 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1523 		}
  1524 		else if (strcmp(info->pattern, "@alive") == 0)
  1525 		{
  1526 			is_multi = true;
  1527 			if ((info->flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD)
  1528 			{
  1529 				info->num_targets = 0;
  1530 				info->reason = COMMAND_TARGET_NOT_DEAD;
  1531 				return;
  1532 			}
  1533 			strncopy(info->target_name, "all alive players", info->target_name_maxlength);
  1534 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1535 			info->flags |= COMMAND_FILTER_ALIVE;
  1536 		}
  1537 		else if (strcmp(info->pattern, "@bots") == 0)
  1538 		{
  1539 			is_multi = true;
  1540 			if ((info->flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS)
  1541 			{
  1542 				info->num_targets = 0;
  1543 				info->reason = COMMAND_TARGET_NOT_HUMAN;
  1544 				return;
  1545 			}
  1546 			strncopy(info->target_name, "all bots", info->target_name_maxlength);
  1547 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1548 			bots_only = true;
  1549 		}
  1550 		else if (strcmp(info->pattern, "@humans") == 0)
  1551 		{
  1552 			is_multi = true;
  1553 			strncopy(info->target_name, "all humans", info->target_name_maxlength);
  1554 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1555 			info->flags |= COMMAND_FILTER_NO_BOTS;
  1556 		}
  1557 		else if (strcmp(info->pattern, "@!me") == 0)
  1558 		{
  1559 			is_multi = true;
  1560 			strncopy(info->target_name, "all players", info->target_name_maxlength);
  1561 			info->target_name_style = COMMAND_TARGETNAME_ML;
  1562 			skip_client = info->admin;
  1563 		}
  1564 
  1565 		if (is_multi)
  1566 		{
  1567 			for (int i = 1; i <= max_clients && total < info->max_targets; i++)
  1568 			{
  1569 				if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1570 				{
  1571 					continue;
  1572 				}
  1573 				if (FilterCommandTarget(pAdmin, pTarget, info->flags) > 0)
  1574 				{
  1575 					if ((!bots_only || pTarget->IsFakeClient())
  1576 						&& skip_client != i)
  1577 					{
  1578 						info->targets[total++] = i;
  1579 					}
  1580 				}
  1581 			}
  1582 
  1583 			info->num_targets = total;
  1584 			info->reason = (info->num_targets) ? COMMAND_TARGET_VALID : COMMAND_TARGET_EMPTY_FILTER;
  1585 			return;
  1586 		}
  1587 	}
  1588 
  1589 	List<ICommandTargetProcessor *>::iterator iter;
  1590 	for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
  1591 	{
  1592 		ICommandTargetProcessor *pProcessor = (*iter);
  1593 		if (pProcessor->ProcessCommandTarget(info))
  1594 		{
  1595 			return;
  1596 		}
  1597 	}
  1598 
  1599 	/* Check partial names */
  1600 	int found_client = 0;
  1601 	CPlayer *pFoundClient = NULL;
  1602 	for (int i = 1; i <= max_clients; i++)
  1603 	{
  1604 		if ((pTarget = GetPlayerByIndex(i)) == NULL)
  1605 		{
  1606 			continue;
  1607 		}
  1608 
  1609 		if (logicore.stristr(pTarget->GetName(), info->pattern) != NULL)
  1610 		{
  1611 			if (found_client)
  1612 			{
  1613 				info->num_targets = 0;
  1614 				info->reason = COMMAND_TARGET_AMBIGUOUS;
  1615 				return;
  1616 			}
  1617 			else
  1618 			{
  1619 				found_client = i;
  1620 				pFoundClient = pTarget;
  1621 			}
  1622 		}
  1623 	}
  1624 
  1625 	if (found_client)
  1626 	{
  1627 		if ((info->reason = FilterCommandTarget(pAdmin, pFoundClient, info->flags)) 
  1628 			== COMMAND_TARGET_VALID)
  1629 		{
  1630 			info->targets[0] = found_client;
  1631 			info->num_targets = 1;
  1632 			strncopy(info->target_name, pFoundClient->GetName(), info->target_name_maxlength);
  1633 			info->target_name_style = COMMAND_TARGETNAME_RAW;
  1634 		}
  1635 		else
  1636 		{
  1637 			info->num_targets = 0;
  1638 		}
  1639 	}
  1640 	else
  1641 	{
  1642 		info->num_targets = 0;
  1643 		info->reason = COMMAND_TARGET_NONE;
  1644 	}
  1645 }
  1646 
  1647 void PlayerManager::OnSourceModMaxPlayersChanged( int newvalue )
  1648 {
  1649 	m_maxClients = newvalue;
  1650 }
  1651 
  1652 void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
  1653 {
  1654 	if (!m_FirstPass)
  1655 	{
  1656 		return;
  1657 	}
  1658 
  1659 	if (newvalue == -1)
  1660 	{
  1661 		newvalue = gpGlobals->maxClients;
  1662 	}
  1663 
  1664 	if (newvalue == MaxClients())
  1665 	{
  1666 		return;
  1667 	}
  1668 
  1669 	/* Notify the rest of core */
  1670 	SMGlobalClass *pBase = SMGlobalClass::head;
  1671 	while (pBase)
  1672 	{
  1673 		pBase->OnSourceModMaxPlayersChanged(newvalue);
  1674 		pBase = pBase->m_pGlobalClassNext;
  1675 	}
  1676 
  1677 	/* Notify Extensions */
  1678 	List<IClientListener *>::iterator iter;
  1679 	IClientListener *pListener = NULL;
  1680 	for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
  1681 	{
  1682 		pListener = (*iter);
  1683 		if (pListener->GetClientListenerVersion() >= 8)
  1684 		{
  1685 			pListener->OnMaxPlayersChanged(newvalue);
  1686 		}
  1687 	}
  1688 }
  1689 
  1690 int PlayerManager::GetClientFromSerial(unsigned int serial)
  1691 {
  1692 	serial_t s;
  1693 	s.value = serial;
  1694 
  1695 	int client = s.bits.index;
  1696 
  1697 	IGamePlayer *pPlayer = GetGamePlayer(client);
  1698 
  1699 	if (!pPlayer)
  1700 	{
  1701 		return 0;
  1702 	}
  1703 
  1704 	if (serial == pPlayer->GetSerial())
  1705 	{
  1706 		return client;
  1707 	}
  1708 
  1709 	return 0;
  1710 }
  1711 
  1712 #if SOURCE_ENGINE >= SE_ORANGEBOX
  1713 void CmdMaxplayersCallback(const CCommand &command)
  1714 {
  1715 #else
  1716 void CmdMaxplayersCallback()
  1717 {
  1718 #endif
  1719 
  1720 	g_Players.MaxPlayersChanged();
  1721 }
  1722 
  1723 
  1724 /*******************
  1725  *** PLAYER CODE ***
  1726  *******************/
  1727 
  1728 CPlayer::CPlayer()
  1729 {
  1730 	m_IsConnected = false;
  1731 	m_IsInGame = false;
  1732 	m_IsAuthorized = false;
  1733 	m_pEdict = NULL;
  1734 	m_Admin = INVALID_ADMIN_ID;
  1735 	m_TempAdmin = false;
  1736 	m_Info = NULL;
  1737 	m_bAdminCheckSignalled = false;
  1738 	m_UserId = -1;
  1739 	m_bIsInKickQueue = false;
  1740 	m_LastPassword.clear();
  1741 	m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
  1742 	m_bFakeClient = false;
  1743 	m_bIsSourceTV = false;
  1744 	m_bIsReplay = false;
  1745 	m_Serial.value = -1;
  1746 	m_SteamAccountID = 0;
  1747 }
  1748 
  1749 void CPlayer::Initialize(const char *name, const char *ip, edict_t *pEntity)
  1750 {
  1751 	m_IsConnected = true;
  1752 	m_Name.assign(name);
  1753 	m_Ip.assign(ip);
  1754 	m_pEdict = pEntity;
  1755 	m_iIndex = IndexOfEdict(pEntity);
  1756 	m_LangId = translator->GetServerLanguage();
  1757 
  1758 	m_Serial.bits.index = m_iIndex;
  1759 	m_Serial.bits.serial = g_PlayerSerialCount++;
  1760 
  1761 	char ip2[24], *ptr;
  1762 	strncopy(ip2, ip, sizeof(ip2));
  1763 	if ((ptr = strchr(ip2, ':')) != NULL)
  1764 	{
  1765 		*ptr = '\0';
  1766 	}
  1767 	m_IpNoPort.assign(ip2);
  1768 }
  1769 
  1770 void CPlayer::Connect()
  1771 {
  1772 	if (m_IsInGame)
  1773 	{
  1774 		return;
  1775 	}
  1776 
  1777 	m_IsInGame = true;
  1778 
  1779 	const char *var = g_Players.GetPassInfoVar();
  1780 	int client = IndexOfEdict(m_pEdict);
  1781 	if (var[0] != '\0')
  1782 	{
  1783 		const char *pass = engine->GetClientConVarValue(client, var);
  1784 		m_LastPassword.assign(pass ? pass : "");
  1785 	}
  1786 	else
  1787 	{
  1788 		m_LastPassword.assign("");
  1789 	}
  1790 }
  1791 
  1792 void CPlayer::SetAuthString(const char *steamid)
  1793 {
  1794 	if (m_IsAuthorized)
  1795 	{
  1796 		return;
  1797 	}
  1798 
  1799 	m_AuthID.assign(steamid);
  1800 }
  1801 
  1802 // Ensure a valid AuthString is set before calling.
  1803 void CPlayer::Authorize()
  1804 {
  1805 	m_IsAuthorized = true;
  1806 }
  1807 
  1808 void CPlayer::Disconnect()
  1809 {
  1810 	DumpAdmin(false);
  1811 	m_IsConnected = false;
  1812 	m_IsInGame = false;
  1813 	m_IsAuthorized = false;
  1814 	m_Name.clear();
  1815 	m_Ip.clear();
  1816 	m_AuthID.clear();
  1817 	m_pEdict = NULL;
  1818 	m_Info = NULL;
  1819 	m_bAdminCheckSignalled = false;
  1820 	m_UserId = -1;
  1821 	m_bIsInKickQueue = false;
  1822 	m_bFakeClient = false;
  1823 	m_bIsSourceTV = false;
  1824 	m_bIsReplay = false;
  1825 	m_Serial.value = -1;
  1826 	m_SteamAccountID = 0;
  1827 }
  1828 
  1829 void CPlayer::SetName(const char *name)
  1830 {
  1831 	m_Name.assign(name);
  1832 }
  1833 
  1834 const char *CPlayer::GetName()
  1835 {
  1836 	if (m_Info && m_pEdict->GetUnknown())
  1837 	{
  1838 		return m_Info->GetName();
  1839 	}
  1840 	
  1841 	return m_Name.c_str();
  1842 }
  1843 
  1844 const char *CPlayer::GetIPAddress()
  1845 {
  1846 	return m_Ip.c_str();
  1847 }
  1848 
  1849 const char *CPlayer::GetAuthString(bool validated)
  1850 {
  1851 	if (validated && !IsAuthStringValidated())
  1852 	{
  1853 		return NULL;
  1854 	}
  1855 
  1856 	return m_AuthID.c_str();
  1857 }
  1858 
  1859 unsigned int CPlayer::GetSteamAccountID(bool validated)
  1860 {
  1861 	if (IsFakeClient() || (validated && !IsAuthStringValidated()))
  1862 	{
  1863 		return 0;
  1864 	}
  1865 
  1866 	if (m_SteamAccountID != 0)
  1867 	{
  1868 		return m_SteamAccountID;
  1869 	}
  1870 
  1871 #if SOURCE_ENGINE < SE_ORANGEBOX
  1872 	const char * pAuth = GetAuthString();
  1873 	/* STEAM_0:1:123123 | STEAM_ID_LAN | STEAM_ID_PENDING */
  1874 	if (pAuth && (strlen(pAuth) > 10) && pAuth[8] != '_')
  1875 	{
  1876 		m_SteamAccountID = (atoi(&pAuth[8]) | (atoi(&pAuth[10]) << 1));
  1877 	}
  1878 #else
  1879 	unsigned long long *steamId = (unsigned long long *)engine->GetClientSteamID(m_pEdict);
  1880 	if (steamId)
  1881 	{
  1882 		m_SteamAccountID = (*steamId & 0xFFFFFFFF);
  1883 	}
  1884 #endif
  1885 	return m_SteamAccountID;
  1886 }
  1887 
  1888 edict_t *CPlayer::GetEdict()
  1889 {
  1890 	return m_pEdict;
  1891 }
  1892 
  1893 bool CPlayer::IsInGame()
  1894 {
  1895 	return m_IsInGame && (m_pEdict->GetUnknown() != NULL);
  1896 }
  1897 
  1898 bool CPlayer::WasCountedAsInGame()
  1899 {
  1900 	return m_IsInGame;
  1901 }
  1902 
  1903 bool CPlayer::IsConnected()
  1904 {
  1905 	return m_IsConnected;
  1906 }
  1907 
  1908 bool CPlayer::IsAuthorized()
  1909 {
  1910 	return m_IsAuthorized;
  1911 }
  1912 
  1913 bool CPlayer::IsAuthStringValidated()
  1914 {     
  1915 #if SOURCE_ENGINE >= SE_ORANGEBOX
  1916 	if (g_Players.m_bAuthstringValidation && !g_HL2.IsLANServer())
  1917 	{
  1918 		return engine->IsClientFullyAuthenticated(m_pEdict);
  1919 	}
  1920 #endif
  1921 
  1922 	return true;
  1923 }
  1924 
  1925 IPlayerInfo *CPlayer::GetPlayerInfo()
  1926 {
  1927 	if (m_pEdict->GetUnknown())
  1928 	{
  1929 		return m_Info;
  1930 	}
  1931 
  1932 	return NULL;
  1933 }
  1934 
  1935 bool CPlayer::IsFakeClient()
  1936 {
  1937 	return m_bFakeClient;
  1938 }
  1939 
  1940 bool CPlayer::IsSourceTV() const
  1941 {
  1942 	return m_bIsSourceTV;
  1943 }
  1944 
  1945 bool CPlayer::IsReplay() const
  1946 {
  1947 	return m_bIsReplay;
  1948 }
  1949 
  1950 void CPlayer::SetAdminId(AdminId id, bool temporary)
  1951 {
  1952 	if (!m_IsConnected)
  1953 	{
  1954 		return;
  1955 	}
  1956 
  1957 	DumpAdmin(false);
  1958 
  1959 	m_Admin = id;
  1960 	m_TempAdmin = temporary;
  1961 }
  1962 
  1963 AdminId CPlayer::GetAdminId()
  1964 {
  1965 	return m_Admin;
  1966 }
  1967 
  1968 void CPlayer::DumpAdmin(bool deleting)
  1969 {
  1970 	if (m_Admin != INVALID_ADMIN_ID)
  1971 	{
  1972 		if (m_TempAdmin && !deleting)
  1973 		{
  1974 			g_Admins.InvalidateAdmin(m_Admin);
  1975 		}
  1976 		m_Admin = INVALID_ADMIN_ID;
  1977 		m_TempAdmin = false;
  1978 	}
  1979 }
  1980 
  1981 void CPlayer::Kick(const char *str)
  1982 {
  1983 	MarkAsBeingKicked();
  1984 	INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
  1985 	if (pNetChan == NULL)
  1986 	{
  1987 		/* What does this even mean? Hell if I know. */
  1988 		int userid = GetUserId();
  1989 		if (userid > 0)
  1990 		{
  1991 			char buffer[255];
  1992 			UTIL_Format(buffer, sizeof(buffer), "kickid %d %s\n", userid, str);
  1993 			engine->ServerCommand(buffer);
  1994 		}
  1995 	}
  1996 	else
  1997 	{
  1998 		IClient *pClient = static_cast<IClient *>(pNetChan->GetMsgHandler());
  1999 		pClient->Disconnect("%s", str);
  2000 	}
  2001 }
  2002 
  2003 void CPlayer::Authorize_Post()
  2004 {
  2005 	if (m_IsInGame)
  2006 	{
  2007 		DoPostConnectAuthorization();
  2008 	}
  2009 }
  2010 
  2011 void CPlayer::DoPostConnectAuthorization()
  2012 {
  2013 	bool delay = false;
  2014 
  2015 	List<IClientListener *>::iterator iter;
  2016 	for (iter = g_Players.m_hooks.begin();
  2017 		 iter != g_Players.m_hooks.end();
  2018 		 iter++)
  2019 	{
  2020 		IClientListener *pListener = (*iter);
  2021 #if defined MIN_API_FOR_ADMINCALLS
  2022 		if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
  2023 		{
  2024 			continue;
  2025 		}
  2026 #endif
  2027 		if (!pListener->OnClientPreAdminCheck(m_iIndex))
  2028 		{
  2029 			delay = true;
  2030 		}
  2031 	}
  2032 	
  2033 	cell_t result = 0;
  2034 	PreAdminCheck->PushCell(m_iIndex);
  2035 	PreAdminCheck->Execute(&result);
  2036 
  2037 	/* Defer, for better or worse */
  2038 	if (delay || (ResultType)result >= Pl_Handled)
  2039 	{
  2040 		return;
  2041 	}
  2042 
  2043 	/* Sanity check */
  2044 	if (!IsConnected())
  2045 	{
  2046 		return;
  2047 	}
  2048 
  2049 	/* Otherwise, go ahead and do admin checks */
  2050 	DoBasicAdminChecks();
  2051 
  2052 	/* Send the notification out */
  2053 	NotifyPostAdminChecks();
  2054 }
  2055 
  2056 bool CPlayer::RunAdminCacheChecks()
  2057 {
  2058 	AdminId old_id = GetAdminId();
  2059 
  2060 	DoBasicAdminChecks();
  2061 
  2062 	return (GetAdminId() != old_id);
  2063 }
  2064 
  2065 void CPlayer::NotifyPostAdminChecks()
  2066 {
  2067 	if (m_bAdminCheckSignalled)
  2068 	{
  2069 		return;
  2070 	}
  2071 
  2072 	/* Block beforehand so they can't double-call */
  2073 	m_bAdminCheckSignalled = true;
  2074 
  2075 	List<IClientListener *>::iterator iter;
  2076 	for (iter = g_Players.m_hooks.begin();
  2077 		iter != g_Players.m_hooks.end();
  2078 		iter++)
  2079 	{
  2080 		IClientListener *pListener = (*iter);
  2081 #if defined MIN_API_FOR_ADMINCALLS
  2082 		if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
  2083 		{
  2084 			continue;
  2085 		}
  2086 #endif
  2087 		pListener->OnClientPostAdminCheck(m_iIndex);
  2088 	}
  2089 
  2090 	PostAdminFilter->PushCell(m_iIndex);
  2091 	PostAdminFilter->Execute(NULL);
  2092 
  2093 	PostAdminCheck->PushCell(m_iIndex);
  2094 	PostAdminCheck->Execute(NULL);
  2095 }
  2096 
  2097 void CPlayer::DoBasicAdminChecks()
  2098 {
  2099 	if (GetAdminId() != INVALID_ADMIN_ID)
  2100 	{
  2101 		return;
  2102 	}
  2103 
  2104 	/* First check the name */
  2105 	AdminId id;
  2106 	int client = IndexOfEdict(m_pEdict);
  2107 
  2108 	if ((id = g_Admins.FindAdminByIdentity("name", GetName())) != INVALID_ADMIN_ID)
  2109 	{
  2110 		if (!g_Players.CheckSetAdminName(client, this, id))
  2111 		{
  2112 			int userid = engine->GetPlayerUserId(m_pEdict);
  2113 			g_Timers.CreateTimer(&s_KickPlayerTimer, 0.1f, (void *)userid, 0);
  2114 		}
  2115 		return;
  2116 	}
  2117 	
  2118 	/* Check IP */
  2119 	if ((id = g_Admins.FindAdminByIdentity("ip", m_IpNoPort.c_str())) != INVALID_ADMIN_ID)
  2120 	{
  2121 		if (g_Players.CheckSetAdmin(client, this, id))
  2122 		{
  2123 			return;
  2124 		}
  2125 	}
  2126 
  2127 	/* Check steam id */
  2128 	if ((id = g_Admins.FindAdminByIdentity("steam", m_AuthID.c_str())) != INVALID_ADMIN_ID)
  2129 	{
  2130 		if (g_Players.CheckSetAdmin(client, this, id))
  2131 		{
  2132 			return;
  2133 		}
  2134 	}
  2135 }
  2136 
  2137 unsigned int CPlayer::GetLanguageId()
  2138 {
  2139 	return m_LangId;
  2140 }
  2141 
  2142 void CPlayer::SetLanguageId(unsigned int id)
  2143 {
  2144 	m_LangId = id;
  2145 }
  2146 
  2147 int CPlayer::GetUserId()
  2148 {
  2149 	if (m_UserId == -1)
  2150 	{
  2151 		m_UserId = engine->GetPlayerUserId(GetEdict());
  2152 	}
  2153 
  2154 	return m_UserId;
  2155 }
  2156 
  2157 bool CPlayer::IsInKickQueue()
  2158 {
  2159 	return m_bIsInKickQueue;
  2160 }
  2161 
  2162 void CPlayer::MarkAsBeingKicked()
  2163 {
  2164 	m_bIsInKickQueue = true;
  2165 }
  2166 
  2167 int CPlayer::GetLifeState()
  2168 {
  2169 	if (lifestate_offset == -1)
  2170 	{
  2171 		if (!g_pGameConf->GetOffset("m_lifeState", &lifestate_offset))
  2172 		{
  2173 			lifestate_offset = -2;
  2174 		}
  2175 	}
  2176 
  2177 	if (lifestate_offset < 0)
  2178 	{
  2179 		IPlayerInfo *info = GetPlayerInfo();
  2180 		if (info == NULL)
  2181 		{
  2182 			return PLAYER_LIFE_UNKNOWN;
  2183 		}
  2184 		return info->IsDead() ? PLAYER_LIFE_DEAD : PLAYER_LIFE_ALIVE;
  2185 	}
  2186 
  2187 	if (m_pEdict == NULL)
  2188 	{
  2189 		return PLAYER_LIFE_UNKNOWN;
  2190 	}
  2191 
  2192 	CBaseEntity *pEntity;
  2193 	IServerUnknown *pUnknown = m_pEdict->GetUnknown();
  2194 	if (pUnknown == NULL || (pEntity = pUnknown->GetBaseEntity()) == NULL)
  2195 	{
  2196 		return PLAYER_LIFE_UNKNOWN;
  2197 	}
  2198 
  2199 	if (*((uint8_t *)pEntity + lifestate_offset) == LIFE_ALIVE)
  2200 	{
  2201 		return PLAYER_LIFE_ALIVE;
  2202 	}
  2203 	else
  2204 	{
  2205 		return PLAYER_LIFE_DEAD;
  2206 	}
  2207 }
  2208 
  2209 unsigned int CPlayer::GetSerial()
  2210 {
  2211 	return m_Serial.value;
  2212 }