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