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