Don't allocate/delete across static CRTs (no bug, irc r=fyren+psychonic).
2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
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"
42 #include "ChatTriggers.h"
43 #include "HalfLife2.h"
44 #include <inetchannel.h>
46 #include <IGameConfigs.h>
47 #include <sourcemod_version.h>
48 #include "ConsoleDetours.h"
49 #include "logic_bridge.h"
51 PlayerManager g_Players;
52 bool g_OnMapStarted = false;
53 IForward *PreAdminCheck = NULL;
54 IForward *PostAdminCheck = NULL;
55 IForward *PostAdminFilter = NULL;
57 const unsigned int *g_NumPlayersToAuth = NULL;
58 int lifestate_offset = -1;
59 List<ICommandTargetProcessor *> target_processors;
61 SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, edict_t *, const char *, const char *, char *, int);
62 SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, const char *);
63 SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *);
64 #if SOURCE_ENGINE >= SE_ORANGEBOX
65 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
67 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
69 SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
70 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
72 #if SOURCE_ENGINE >= SE_ORANGEBOX
73 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
74 #elif SOURCE_ENGINE == SE_DARKMESSIAH
75 SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
77 # if SH_IMPL_VERSION >= 4
78 extern int __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
80 extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
82 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
85 ConCommand *maxplayersCmd = NULL;
87 unsigned int g_PlayerSerialCount = 0;
89 class KickPlayerTimer : public ITimedEvent
92 ResultType OnTimer(ITimer *pTimer, void *pData)
94 int userid = (int)pData;
95 int client = g_Players.GetClientOfUserId(userid);
98 CPlayer *player = g_Players.GetPlayerByIndex(client);
99 player->Kick("Your name is reserved by SourceMod; set your password to use it.");
103 void OnTimerEnd(ITimer *pTimer, void *pData)
108 PlayerManager::PlayerManager()
114 m_SourceTVUserId = -1;
117 m_bAuthstringValidation = true; // use steam auth by default
119 m_UserIdLookUp = new int[USHRT_MAX+1];
120 memset(m_UserIdLookUp, 0, sizeof(int) * (USHRT_MAX+1));
123 PlayerManager::~PlayerManager()
125 g_NumPlayersToAuth = NULL;
127 delete [] m_AuthQueue;
128 delete [] m_UserIdLookUp;
131 void PlayerManager::OnSourceModAllInitialized()
133 SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
134 SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
135 SH_ADD_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
136 SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
137 SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
138 SH_ADD_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
139 SH_ADD_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
140 SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
142 sharesys->AddInterface(NULL, this);
144 ParamType p1[] = {Param_Cell, Param_String, Param_Cell};
145 ParamType p2[] = {Param_Cell};
147 m_clconnect = g_Forwards.CreateForward("OnClientConnect", ET_LowEvent, 3, p1);
148 m_clconnect_post = g_Forwards.CreateForward("OnClientConnected", ET_Ignore, 1, p2);
149 m_clputinserver = g_Forwards.CreateForward("OnClientPutInServer", ET_Ignore, 1, p2);
150 m_cldisconnect = g_Forwards.CreateForward("OnClientDisconnect", ET_Ignore, 1, p2);
151 m_cldisconnect_post = g_Forwards.CreateForward("OnClientDisconnect_Post", ET_Ignore, 1, p2);
152 m_clcommand = g_Forwards.CreateForward("OnClientCommand", ET_Hook, 2, NULL, Param_Cell, Param_Cell);
153 m_clinfochanged = g_Forwards.CreateForward("OnClientSettingsChanged", ET_Ignore, 1, p2);
154 m_clauth = g_Forwards.CreateForward("OnClientAuthorized", ET_Ignore, 2, NULL, Param_Cell, Param_String);
155 m_onActivate = g_Forwards.CreateForward("OnServerLoad", ET_Ignore, 0, NULL);
156 m_onActivate2 = g_Forwards.CreateForward("OnMapStart", ET_Ignore, 0, NULL);
158 PreAdminCheck = g_Forwards.CreateForward("OnClientPreAdminCheck", ET_Event, 1, p1);
159 PostAdminCheck = g_Forwards.CreateForward("OnClientPostAdminCheck", ET_Ignore, 1, p1);
160 PostAdminFilter = g_Forwards.CreateForward("OnClientPostAdminFilter", ET_Ignore, 1, p1);
162 m_bIsListenServer = !engine->IsDedicatedServer();
165 ConCommand *pCmd = FindCommand("maxplayers");
168 SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdMaxplayersCallback), true);
169 maxplayersCmd = pCmd;
173 void PlayerManager::OnSourceModShutdown()
175 SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false);
176 SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true);
177 SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true);
178 SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false);
179 SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
180 SH_REMOVE_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
181 SH_REMOVE_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
182 SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
184 /* Release forwards */
185 g_Forwards.ReleaseForward(m_clconnect);
186 g_Forwards.ReleaseForward(m_clconnect_post);
187 g_Forwards.ReleaseForward(m_clputinserver);
188 g_Forwards.ReleaseForward(m_cldisconnect);
189 g_Forwards.ReleaseForward(m_cldisconnect_post);
190 g_Forwards.ReleaseForward(m_clcommand);
191 g_Forwards.ReleaseForward(m_clinfochanged);
192 g_Forwards.ReleaseForward(m_clauth);
193 g_Forwards.ReleaseForward(m_onActivate);
194 g_Forwards.ReleaseForward(m_onActivate2);
196 g_Forwards.ReleaseForward(PreAdminCheck);
197 g_Forwards.ReleaseForward(PostAdminCheck);
198 g_Forwards.ReleaseForward(PostAdminFilter);
202 if (maxplayersCmd != NULL)
204 SH_REMOVE_HOOK(ConCommand, Dispatch, maxplayersCmd, SH_STATIC(CmdMaxplayersCallback), true);
208 ConfigResult PlayerManager::OnSourceModConfigChanged(const char *key,
214 if (strcmp(key, "PassInfoVar") == 0)
216 if (strcmp(value, "_password") != 0)
218 m_PassInfoVar.assign(value);
220 return ConfigResult_Accept;
221 } else if (strcmp(key, "AllowClLanguageVar") == 0) {
222 if (strcasecmp(value, "on") == 0)
225 } else if (strcasecmp(value, "off") == 0) {
228 UTIL_Format(error, maxlength, "Invalid value: must be \"on\" or \"off\"");
229 return ConfigResult_Reject;
231 return ConfigResult_Accept;
232 } else if (strcmp( key, "SteamAuthstringValidation" ) == 0) {
233 if (strcasecmp(value, "yes") == 0)
235 m_bAuthstringValidation = true;
236 } else if ( strcasecmp(value, "no") == 0) {
237 m_bAuthstringValidation = false;
239 UTIL_Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
240 return ConfigResult_Reject;
242 return ConfigResult_Accept;
244 return ConfigResult_Ignore;
247 void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
249 static ConVar *tv_enable = icvar->FindVar("tv_enable");
250 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
251 static ConVar *replay_enable = icvar->FindVar("replay_enable");
254 // clientMax will not necessarily be correct here (such as on late SourceTV enable)
255 m_maxClients = gpGlobals->maxClients;
257 ICommandLine *commandLine = g_HL2.GetValveCommandLine();
258 m_bIsSourceTVActive = (tv_enable && tv_enable->GetBool() && (!commandLine || commandLine->FindParm("-nohltv") == 0));
259 m_bIsReplayActive = false;
260 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
261 m_bIsReplayActive = (replay_enable && replay_enable->GetBool());
263 m_PlayersSinceActive = 0;
267 /* Initialize all players */
270 m_Players = new CPlayer[ABSOLUTE_PLAYER_LIMIT + 1];
271 m_AuthQueue = new unsigned int[ABSOLUTE_PLAYER_LIMIT + 1];
274 memset(m_AuthQueue, 0, sizeof(unsigned int) * (ABSOLUTE_PLAYER_LIMIT + 1));
276 g_NumPlayersToAuth = &m_AuthQueue[0];
279 scripts->SyncMaxClients(m_maxClients);
281 g_OnMapStarted = true;
283 extsys->CallOnCoreMapStart(pEdictList, edictCount, m_maxClients);
284 m_onActivate->Execute(NULL);
285 m_onActivate2->Execute(NULL);
287 List<IClientListener *>::iterator iter;
288 for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
290 if ((*iter)->GetClientListenerVersion() >= 5)
292 (*iter)->OnServerActivated(m_maxClients);
296 SMGlobalClass *cls = SMGlobalClass::head;
299 cls->OnSourceModLevelActivated();
300 cls = cls->m_pGlobalClassNext;
303 SM_ExecuteAllConfigs();
306 bool PlayerManager::IsServerActivated()
311 bool PlayerManager::CheckSetAdmin(int index, CPlayer *pPlayer, AdminId id)
313 const char *password = g_Admins.GetAdminPassword(id);
314 if (password != NULL)
316 if (m_PassInfoVar.size() < 1)
321 /* Whoa... the user needs a password! */
322 const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
323 if (!given || strcmp(given, password) != 0)
329 pPlayer->SetAdminId(id, false);
334 bool PlayerManager::CheckSetAdminName(int index, CPlayer *pPlayer, AdminId id)
336 const char *password = g_Admins.GetAdminPassword(id);
337 if (password == NULL)
342 if (m_PassInfoVar.size() < 1)
347 /* Whoa... the user needs a password! */
348 const char *given = engine->GetClientConVarValue(index, m_PassInfoVar.c_str());
349 if (!given || strcmp(given, password) != 0)
354 pPlayer->SetAdminId(id, false);
359 void PlayerManager::RunAuthChecks()
363 unsigned int removed = 0;
364 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
366 pPlayer = &m_Players[m_AuthQueue[i]];
367 authstr = engine->GetPlayerNetworkIDString(pPlayer->m_pEdict);
368 pPlayer->SetAuthString(authstr);
370 if (!pPlayer->IsAuthStringValidated())
372 continue; // we're using steam auth, and steam doesn't know about this player yet so we can't do anything about them for now
375 if (authstr && authstr[0] != '\0'
376 && (strcmp(authstr, "STEAM_ID_PENDING") != 0))
378 /* Set authorization */
379 pPlayer->Authorize();
381 /* Mark as removed from queue */
382 unsigned int client = m_AuthQueue[i];
386 /* Send to extensions */
387 List<IClientListener *>::iterator iter;
388 IClientListener *pListener;
389 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
392 pListener->OnClientAuthorized(client, authstr);
393 if (!pPlayer->IsConnected())
399 /* Send to plugins if player is still connected */
400 if (pPlayer->IsConnected() && m_clauth->GetFunctionCount())
402 /* :TODO: handle the case of a player disconnecting in the middle */
403 m_clauth->PushCell(client);
404 m_clauth->PushString(authstr);
405 m_clauth->Execute(NULL);
408 if (pPlayer->IsConnected())
410 pPlayer->Authorize_Post();
415 /* Clean up the queue */
418 /* We don't have to compact the list if it's empty */
419 if (removed != m_AuthQueue[0])
421 unsigned int diff = 0;
422 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
424 /* If this member is removed... */
425 if (m_AuthQueue[i] == 0)
427 /* Increase the differential */
430 /* diff cannot increase faster than i+1 */
432 assert(i - diff >= 1);
433 /* move this index down */
434 m_AuthQueue[i - diff] = m_AuthQueue[i];
437 m_AuthQueue[0] -= removed;
444 bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
446 int client = IndexOfEdict(pEntity);
447 CPlayer *pPlayer = &m_Players[client];
448 ++m_PlayersSinceActive;
450 pPlayer->Initialize(pszName, pszAddress, pEntity);
452 /* Get the client's language */
456 if (!pPlayer->IsFakeClient() && (name=engine->GetClientConVarValue(client, "cl_language")))
459 pPlayer->m_LangId = (translator->GetLanguageByName(name, &langid)) ? langid : translator->GetServerLanguage();
461 pPlayer->m_LangId = translator->GetServerLanguage();
465 List<IClientListener *>::iterator iter;
466 IClientListener *pListener = NULL;
467 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
470 if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
472 RETURN_META_VALUE(MRES_SUPERCEDE, false);
478 m_clconnect->PushCell(client);
479 m_clconnect->PushStringEx(reject, maxrejectlen, SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK);
480 m_clconnect->PushCell(maxrejectlen);
481 m_clconnect->Execute(&res);
485 if (!pPlayer->IsAuthorized())
487 m_AuthQueue[++m_AuthQueue[0]] = client;
490 m_UserIdLookUp[engine->GetPlayerUserId(pEntity)] = client;
494 if (!pPlayer->IsFakeClient())
496 RETURN_META_VALUE(MRES_SUPERCEDE, false);
503 bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
505 int client = IndexOfEdict(pEntity);
506 bool orig_value = META_RESULT_ORIG_RET(bool);
507 CPlayer *pPlayer = &m_Players[client];
511 List<IClientListener *>::iterator iter;
512 IClientListener *pListener = NULL;
513 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
516 pListener->OnClientConnected(client);
517 if (!pPlayer->IsConnected())
523 if (!pPlayer->IsFakeClient()
525 && strncmp(pszAddress, "127.0.0.1", 9) == 0)
527 m_ListenClient = client;
531 m_clconnect_post->PushCell(client);
532 m_clconnect_post->Execute(&res, NULL);
536 InvalidatePlayer(pPlayer);
542 void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername)
545 int client = IndexOfEdict(pEntity);
546 CPlayer *pPlayer = &m_Players[client];
548 /* If they're not connected, they're a bot */
549 if (!pPlayer->IsConnected())
551 /* Run manual connection routines */
553 const char *authid = engine->GetPlayerNetworkIDString(pEntity);
554 pPlayer->SetAuthString(authid);
555 pPlayer->Authorize();
556 pPlayer->m_bFakeClient = true;
559 * While we're already filtered to just bots, we'll do other checks to
560 * make sure that the requisite services are enabled and that the bots
561 * have joined at the expected time.
563 * Checking playerinfo's IsHLTV and IsReplay would be better and less
564 * error-prone but will always show false until later in the frame,
565 * after PutInServer and Activate, and we want it now!
567 * These checks are hairy as hell due to differences between engines and games.
569 * Most engines use "Replay" and "SourceTV" as bot names for these when they're
570 * created. EP2V, CSS and Nuclear Dawn (but not L4D2) differ from this by now using
571 * replay_/tv_name directly when creating the bot(s). To complicate it slightly
572 * further, the cvar can be empty and the engine's fallback to "unnamed" will be used.
573 * We can maybe just rip out the name checks at some point and rely solely on whether
574 * they're enabled and the join order.
577 // This doesn't actually get incremented until OnClientConnect. Fake it to check.
578 int newCount = m_PlayersSinceActive + 1;
580 int userId = engine->GetPlayerUserId(pEntity);
581 #if (SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_LEFT4DEAD2)
582 static ConVar *tv_name = icvar->FindVar("tv_name");
584 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
585 static ConVar *replay_name = icvar->FindVar("replay_name");
587 #if SOURCE_ENGINE == SE_LEFT4DEAD2
588 static bool bIsNuclearDawn = (strcmp(g_SourceMod.GetGameFolderName(), "nucleardawn") == 0);
591 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
592 if (m_bIsReplayActive && newCount == 1
593 && (m_ReplayUserId == userId
594 || (replay_name && strcmp(playername, replay_name->GetString()) == 0) || (replay_name && replay_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
598 pPlayer->m_bIsReplay = true;
599 m_ReplayUserId = userId;
603 if (m_bIsSourceTVActive
604 && ((!m_bIsReplayActive && newCount == 1)
605 || (m_bIsReplayActive && newCount == 2))
606 && (m_SourceTVUserId == userId
607 #if SOURCE_ENGINE == SE_CSGO
608 || strcmp(playername, "GOTV") == 0
609 #elif (SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_LEFT4DEAD2)
610 #if SOURCE_ENGINE == SE_LEFT4DEAD2
611 || (bIsNuclearDawn && ( true
612 #endif // SE_LEFT4DEAD2
613 || (tv_name && strcmp(playername, tv_name->GetString()) == 0) || (tv_name && tv_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
614 #if SOURCE_ENGINE == SE_LEFT4DEAD2
616 || (!bIsNuclearDawn && strcmp(playername, "SourceTV") == 0)
617 #endif // SE_LEFT4DEAD2
619 || strcmp(playername, "SourceTV") == 0
624 pPlayer->m_bIsSourceTV = true;
625 m_SourceTVUserId = userId;
628 if (!OnClientConnect(pEntity, playername, "127.0.0.1", error, sizeof(error)))
630 /* :TODO: kick the bot if it's rejected */
633 List<IClientListener *>::iterator iter;
634 IClientListener *pListener = NULL;
635 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
638 pListener->OnClientConnected(client);
639 /* See if bot was kicked */
640 if (!pPlayer->IsConnected())
647 m_clconnect_post->PushCell(client);
648 m_clconnect_post->Execute(&res, NULL);
650 /* Now do authorization */
651 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
654 pListener->OnClientAuthorized(client, authid);
656 /* Finally, tell plugins */
657 if (m_clauth->GetFunctionCount())
659 m_clauth->PushCell(client);
660 m_clauth->PushString(authid);
661 m_clauth->Execute(NULL);
663 pPlayer->Authorize_Post();
668 pPlayer->m_Info = playerinfo->GetPlayerInfo(pEntity);
674 List<IClientListener *>::iterator iter;
675 IClientListener *pListener = NULL;
676 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
679 pListener->OnClientPutInServer(client);
682 m_clputinserver->PushCell(client);
683 m_clputinserver->Execute(&res, NULL);
685 if (pPlayer->IsAuthorized())
687 pPlayer->DoPostConnectAuthorization();
691 void PlayerManager::OnSourceModLevelEnd()
693 /* Disconnect all bots still in game */
694 for (int i=1; i<=m_maxClients; i++)
696 if (m_Players[i].IsConnected())
698 OnClientDisconnect(m_Players[i].GetEdict());
704 void PlayerManager::OnClientDisconnect(edict_t *pEntity)
707 int client = IndexOfEdict(pEntity);
708 CPlayer *pPlayer = &m_Players[client];
710 if (pPlayer->IsConnected())
712 m_cldisconnect->PushCell(client);
713 m_cldisconnect->Execute(&res, NULL);
717 /* We don't care, prevent a double call */
721 if (pPlayer->WasCountedAsInGame())
726 List<IClientListener *>::iterator iter;
727 IClientListener *pListener = NULL;
728 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
731 pListener->OnClientDisconnecting(client);
734 InvalidatePlayer(pPlayer);
736 if (m_ListenClient == client)
742 void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
745 int client = IndexOfEdict(pEntity);
747 m_cldisconnect_post->PushCell(client);
748 m_cldisconnect_post->Execute(&res, NULL);
750 List<IClientListener *>::iterator iter;
751 IClientListener *pListener = NULL;
752 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
755 pListener->OnClientDisconnected(client);
759 void ClientConsolePrint(edict_t *e, const char *fmt, ...)
765 size_t len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
768 if (len >= sizeof(buffer) - 1)
770 buffer[sizeof(buffer) - 2] = '\n';
771 buffer[sizeof(buffer) - 1] = '\0';
773 buffer[len++] = '\n';
777 engine->ClientPrintf(e, buffer);
780 void ListExtensionsToClient(CPlayer *player, const CCommand &args)
784 unsigned int start = 0;
786 AutoExtensionList extensions(extsys);
787 if (!extensions->size())
789 ClientConsolePrint(player->GetEdict(), "[SM] No extensions found.");
795 start = atoi(args.Arg(2));
799 for (; i < extensions->size(); i++)
801 IExtension *ext = extensions->at(i);
804 if (!ext->IsRunning(error, sizeof(error)))
820 IExtensionInterface *api = ext->GetAPI();
822 const char *name = api->GetExtensionName();
823 const char *version = api->GetExtensionVerString();
824 const char *author = api->GetExtensionAuthor();
825 const char *description = api->GetExtensionDescription();
827 size_t len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", name);
829 if (version != NULL && version[0])
831 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", version);
834 if (author != NULL && author[0])
836 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", author);
839 if (description != NULL && description[0])
841 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, ": %s", description);
845 ClientConsolePrint(player->GetEdict(), "%s", buffer);
848 for (; i < extensions->size(); i++)
851 if (extensions->at(i)->IsRunning(error, sizeof(error)))
857 if (i < extensions->size())
859 ClientConsolePrint(player->GetEdict(), "To see more, type \"sm exts %d\"", id);
863 void ListPluginsToClient(CPlayer *player, const CCommand &args)
867 edict_t *e = player->GetEdict();
868 unsigned int start = 0;
870 AutoPluginList plugins(scripts);
871 if (!plugins->size())
873 ClientConsolePrint(e, "[SM] No plugins found.");
879 start = atoi(args.Arg(2));
882 SourceHook::List<SMPlugin *> m_FailList;
885 for (; i < plugins->size(); i++)
887 SMPlugin *pl = plugins->at(i);
889 if (pl->GetStatus() != Plugin_Running)
894 /* Count valid plugins */
907 const sm_plugininfo_t *info = pl->GetPublicInfo();
908 len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
909 if (IS_STR_FILLED(info->version))
911 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
913 if (IS_STR_FILLED(info->author))
915 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
919 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->GetFilename());
921 ClientConsolePrint(e, "%s", buffer);
924 /* See if we can get more plugins */
925 for (; i < plugins->size(); i++)
927 if (plugins->at(i)->GetStatus() == Plugin_Running)
933 /* Do we actually have more plugins? */
934 if (i < plugins->size())
936 ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id);
940 #if SOURCE_ENGINE >= SE_ORANGEBOX
941 void PlayerManager::OnClientCommand(edict_t *pEntity, const CCommand &args)
944 void PlayerManager::OnClientCommand(edict_t *pEntity)
948 int client = IndexOfEdict(pEntity);
949 cell_t res = Pl_Continue;
950 CPlayer *pPlayer = &m_Players[client];
952 if (!pPlayer->IsConnected())
957 if (strcmp(args.Arg(0), "sm") == 0)
959 if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0)
961 ListPluginsToClient(pPlayer, args);
962 RETURN_META(MRES_SUPERCEDE);
964 else if (args.ArgC() > 1 && strcmp(args.Arg(1), "exts") == 0)
966 ListExtensionsToClient(pPlayer, args);
967 RETURN_META(MRES_SUPERCEDE);
969 else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0)
971 ClientConsolePrint(pEntity,
972 "SourceMod would not be possible without:");
973 ClientConsolePrint(pEntity,
974 " David \"BAILOPAN\" Anderson, Matt \"pRED\" Woodrow");
975 ClientConsolePrint(pEntity,
976 " Scott \"DS\" Ehlert, Fyren");
977 ClientConsolePrint(pEntity,
978 " Nicholas \"psychonic\" Hastings, Asher \"asherkin\" Baker");
979 ClientConsolePrint(pEntity,
980 " Borja \"faluco\" Ferrer, Pavol \"PM OnoTo\" Marko");
981 ClientConsolePrint(pEntity,
982 "SourceMod is open source under the GNU General Public License.");
983 RETURN_META(MRES_SUPERCEDE);
986 ClientConsolePrint(pEntity,
987 "SourceMod %s, by AlliedModders LLC", SM_VERSION_STRING);
988 ClientConsolePrint(pEntity,
989 "To see running plugins, type \"sm plugins\"");
990 ClientConsolePrint(pEntity,
991 "To see credits, type \"sm credits\"");
992 ClientConsolePrint(pEntity,
993 "Visit http://www.sourcemod.net/");
994 RETURN_META(MRES_SUPERCEDE);
997 g_HL2.PushCommandStack(&args);
999 int argcount = args.ArgC() - 1;
1000 const char *cmd = g_HL2.CurrentCommandName();
1002 bool result = g_ValveMenuStyle.OnClientCommand(client, cmd, args);
1007 result = g_RadioMenuStyle.OnClientCommand(client, cmd, args);
1014 if (g_ConsoleDetours.IsEnabled())
1016 cell_t res2 = g_ConsoleDetours.InternalDispatch(client, args);
1017 if (res2 >= Pl_Stop)
1019 g_HL2.PopCommandStack();
1020 RETURN_META(MRES_SUPERCEDE);
1022 else if (res2 > res)
1028 cell_t res2 = Pl_Continue;
1029 if (pPlayer->IsInGame())
1031 m_clcommand->PushCell(client);
1032 m_clcommand->PushCell(argcount);
1033 m_clcommand->Execute(&res2, NULL);
1043 g_HL2.PopCommandStack();
1044 RETURN_META(MRES_SUPERCEDE);
1047 res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res);
1049 g_HL2.PopCommandStack();
1051 if (res >= Pl_Handled)
1053 RETURN_META(MRES_SUPERCEDE);
1057 void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
1060 int client = IndexOfEdict(pEntity);
1061 CPlayer *pPlayer = &m_Players[client];
1063 if (!pPlayer->IsConnected())
1068 m_clinfochanged->PushCell(client);
1069 m_clinfochanged->Execute(&res, NULL);
1071 if (pPlayer->IsFakeClient())
1076 IPlayerInfo *info = pPlayer->GetPlayerInfo();
1077 const char *new_name = info ? info->GetName() : engine->GetClientConVarValue(client, "name");
1078 const char *old_name = pPlayer->m_Name.c_str();
1080 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1081 const char *networkid_force;
1082 if ((networkid_force = engine->GetClientConVarValue(client, "networkid_force")) && networkid_force[0] != '\0')
1084 unsigned int accountId = pPlayer->GetSteamAccountID();
1085 g_Logger.LogMessage("\"%s<%d><STEAM_1:%d:%d><>\" has bad networkid (id \"%s\") (ip \"%s\")",
1086 new_name, pPlayer->GetUserId(), accountId & 1, accountId >> 1, networkid_force, pPlayer->GetIPAddress());
1088 pPlayer->Kick("NetworkID spoofing detected.");
1089 RETURN_META(MRES_IGNORED);
1093 if (strcmp(old_name, new_name) != 0)
1095 AdminId id = g_Admins.FindAdminByIdentity("name", new_name);
1096 if (id != INVALID_ADMIN_ID && pPlayer->GetAdminId() != id)
1098 if (!CheckSetAdminName(client, pPlayer, id))
1100 pPlayer->Kick("Your name is reserved by SourceMod; set your password to use it.");
1101 RETURN_META(MRES_IGNORED);
1103 } else if ((id = g_Admins.FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
1104 if (id == pPlayer->GetAdminId())
1106 /* This player is changing their name; force them to drop admin privileges! */
1107 pPlayer->SetAdminId(INVALID_ADMIN_ID, false);
1110 pPlayer->SetName(new_name);
1113 if (m_PassInfoVar.size() > 0)
1115 /* Try for a password change */
1116 const char *old_pass = pPlayer->m_LastPassword.c_str();
1117 const char *new_pass = engine->GetClientConVarValue(client, m_PassInfoVar.c_str());
1118 if (strcmp(old_pass, new_pass) != 0)
1120 pPlayer->m_LastPassword.assign(new_pass);
1121 if (pPlayer->IsInGame() && pPlayer->IsAuthorized())
1123 /* If there is already an admin id assigned, this will just bail out. */
1124 pPlayer->DoBasicAdminChecks();
1128 /* Notify Extensions */
1129 List<IClientListener *>::iterator iter;
1130 IClientListener *pListener = NULL;
1131 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
1133 pListener = (*iter);
1134 if (pListener->GetClientListenerVersion() >= 13)
1136 pListener->OnClientSettingsChanged(client);
1141 int PlayerManager::GetMaxClients()
1143 return m_maxClients;
1146 CPlayer *PlayerManager::GetPlayerByIndex(int client) const
1148 if (client > m_maxClients || client < 1)
1152 return &m_Players[client];
1155 int PlayerManager::GetNumPlayers()
1157 return m_PlayerCount;
1160 int PlayerManager::GetClientOfUserId(int userid)
1162 if (userid < 0 || userid > USHRT_MAX)
1167 int client = m_UserIdLookUp[userid];
1169 /* Verify the userid. The cache can get messed up with older
1170 * Valve engines. :TODO: If this gets fixed, do an old engine
1171 * check before invoking this backwards compat code.
1175 CPlayer *player = GetPlayerByIndex(client);
1176 if (player && player->IsConnected())
1178 int realUserId = engine->GetPlayerUserId(player->GetEdict());
1179 if (realUserId == userid)
1186 /* If we can't verify the userid, we have to do a manual loop */
1188 for (int i = 1; i <= m_maxClients; i++)
1190 player = GetPlayerByIndex(i);
1191 if (!player || !player->IsConnected())
1195 if (engine->GetPlayerUserId(player->GetEdict()) == userid)
1197 m_UserIdLookUp[userid] = i;
1205 void PlayerManager::AddClientListener(IClientListener *listener)
1207 m_hooks.push_back(listener);
1210 void PlayerManager::RemoveClientListener(IClientListener *listener)
1212 m_hooks.remove(listener);
1215 IGamePlayer *PlayerManager::GetGamePlayer(edict_t *pEdict)
1217 int index = IndexOfEdict(pEdict);
1218 return GetGamePlayer(index);
1221 IGamePlayer *PlayerManager::GetGamePlayer(int client)
1223 return GetPlayerByIndex(client);
1226 void PlayerManager::ClearAdminId(AdminId id)
1228 for (int i=1; i<=m_maxClients; i++)
1230 if (m_Players[i].m_Admin == id)
1232 m_Players[i].DumpAdmin(true);
1237 void PlayerManager::ClearAllAdmins()
1239 for (int i=1; i<=m_maxClients; i++)
1241 m_Players[i].DumpAdmin(true);
1245 const char *PlayerManager::GetPassInfoVar()
1247 return m_PassInfoVar.c_str();
1250 void PlayerManager::RecheckAnyAdmins()
1252 for (int i=1; i<=m_maxClients; i++)
1254 if (m_Players[i].IsInGame() && m_Players[i].IsAuthorized())
1256 m_Players[i].DoBasicAdminChecks();
1261 unsigned int PlayerManager::GetReplyTo()
1263 return g_ChatTriggers.GetReplyTo();
1266 unsigned int PlayerManager::SetReplyTo(unsigned int reply)
1268 return g_ChatTriggers.SetReplyTo(reply);
1271 int PlayerManager::FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags)
1273 return InternalFilterCommandTarget((CPlayer *)pAdmin, (CPlayer *)pTarget, flags);
1276 void PlayerManager::RegisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
1278 target_processors.push_back(pHandler);
1281 void PlayerManager::UnregisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
1283 target_processors.remove(pHandler);
1286 void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
1289 * Remove client from auth queue if necessary
1291 if (!pPlayer->IsAuthorized())
1293 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
1295 if (m_AuthQueue[i] == (unsigned)pPlayer->m_iIndex)
1297 /* Move everything ahead of us back by one */
1298 for (unsigned int j=i+1; j<=m_AuthQueue[0]; j++)
1300 m_AuthQueue[j-1] = m_AuthQueue[j];
1302 /* Remove us and break */
1309 m_UserIdLookUp[engine->GetPlayerUserId(pPlayer->m_pEdict)] = 0;
1310 pPlayer->Disconnect();
1313 int PlayerManager::InternalFilterCommandTarget(CPlayer *pAdmin, CPlayer *pTarget, int flags)
1315 if ((flags & COMMAND_FILTER_CONNECTED) == COMMAND_FILTER_CONNECTED
1316 && !pTarget->IsConnected())
1318 return COMMAND_TARGET_NONE;
1320 else if ((flags & COMMAND_FILTER_CONNECTED) != COMMAND_FILTER_CONNECTED &&
1321 !pTarget->IsInGame())
1323 return COMMAND_TARGET_NOT_IN_GAME;
1326 if ((flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS
1327 && pTarget->IsFakeClient())
1329 return COMMAND_TARGET_NOT_HUMAN;
1334 if ((flags & COMMAND_FILTER_NO_IMMUNITY) != COMMAND_FILTER_NO_IMMUNITY
1335 && !g_Admins.CanAdminTarget(pAdmin->GetAdminId(), pTarget->GetAdminId()))
1337 return COMMAND_TARGET_IMMUNE;
1341 if ((flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE
1342 && pTarget->GetLifeState() != PLAYER_LIFE_ALIVE)
1344 return COMMAND_TARGET_NOT_ALIVE;
1347 if ((flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD
1348 && pTarget->GetLifeState() != PLAYER_LIFE_DEAD)
1350 return COMMAND_TARGET_NOT_DEAD;
1353 return COMMAND_TARGET_VALID;
1356 void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
1358 CPlayer *pTarget, *pAdmin;
1359 int max_clients, total = 0;
1361 max_clients = GetMaxClients();
1363 if (info->max_targets < 1)
1365 info->reason = COMMAND_TARGET_NONE;
1366 info->num_targets = 0;
1369 if (info->admin == 0)
1375 pAdmin = GetPlayerByIndex(info->admin);
1378 if (info->pattern[0] == '#')
1380 int userid = atoi(&info->pattern[1]);
1381 int client = GetClientOfUserId(userid);
1383 /* See if a valid userid matched */
1386 IGamePlayer *pTarget = GetPlayerByIndex(client);
1387 if (pTarget != NULL)
1389 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags)) == COMMAND_TARGET_VALID)
1391 info->targets[0] = client;
1392 info->num_targets = 1;
1393 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1394 info->target_name_style = COMMAND_TARGETNAME_RAW;
1398 info->num_targets = 0;
1404 /* Do we need to look for a steam id? */
1405 if (strncmp(&info->pattern[1], "STEAM_", 6) == 0)
1408 char new_pattern[256];
1410 strcpy(new_pattern, "STEAM_");
1411 len = strlen(&info->pattern[7]);
1412 for (p = 0; p < len; p++)
1414 new_pattern[6 + p] = info->pattern[7 + p];
1415 if (new_pattern[6 + p] == '_')
1417 new_pattern[6 + p] = ':';
1420 new_pattern[6 + p] = '\0';
1422 for (int i = 1; i <= max_clients; i++)
1424 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1428 if (!pTarget->IsConnected())
1432 const char *authstr = pTarget->GetAuthString(false); // We want to make it easy for people to be kicked/banned, so don't require validation for command targets.
1433 if (authstr && strcmp(authstr, new_pattern) == 0)
1435 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
1436 == COMMAND_TARGET_VALID)
1438 info->targets[0] = i;
1439 info->num_targets = 1;
1440 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1441 info->target_name_style = COMMAND_TARGETNAME_RAW;
1445 info->num_targets = 0;
1452 /* See if an exact name matches */
1453 for (int i = 1; i <= max_clients; i++)
1455 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1459 if (!pTarget->IsConnected())
1463 if (strcmp(pTarget->GetName(), &info->pattern[1]) == 0)
1465 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
1466 == COMMAND_TARGET_VALID)
1468 info->targets[0] = i;
1469 info->num_targets = 1;
1470 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1471 info->target_name_style = COMMAND_TARGETNAME_RAW;
1475 info->num_targets = 0;
1482 if (strcmp(info->pattern, "@me") == 0 && info->admin != 0)
1484 info->reason = FilterCommandTarget(pAdmin, pAdmin, info->flags);
1485 if (info->reason == COMMAND_TARGET_VALID)
1487 info->targets[0] = info->admin;
1488 info->num_targets = 1;
1489 strncopy(info->target_name, pAdmin->GetName(), info->target_name_maxlength);
1490 info->target_name_style = COMMAND_TARGETNAME_RAW;
1494 info->num_targets = 0;
1499 if ((info->flags & COMMAND_FILTER_NO_MULTI) != COMMAND_FILTER_NO_MULTI)
1501 bool is_multi = false;
1502 bool bots_only = false;
1503 int skip_client = -1;
1505 if (strcmp(info->pattern, "@all") == 0)
1508 strncopy(info->target_name, "all players", info->target_name_maxlength);
1509 info->target_name_style = COMMAND_TARGETNAME_ML;
1511 else if (strcmp(info->pattern, "@dead") == 0)
1514 if ((info->flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE)
1516 info->num_targets = 0;
1517 info->reason = COMMAND_TARGET_NOT_ALIVE;
1520 info->flags |= COMMAND_FILTER_DEAD;
1521 strncopy(info->target_name, "all dead players", info->target_name_maxlength);
1522 info->target_name_style = COMMAND_TARGETNAME_ML;
1524 else if (strcmp(info->pattern, "@alive") == 0)
1527 if ((info->flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD)
1529 info->num_targets = 0;
1530 info->reason = COMMAND_TARGET_NOT_DEAD;
1533 strncopy(info->target_name, "all alive players", info->target_name_maxlength);
1534 info->target_name_style = COMMAND_TARGETNAME_ML;
1535 info->flags |= COMMAND_FILTER_ALIVE;
1537 else if (strcmp(info->pattern, "@bots") == 0)
1540 if ((info->flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS)
1542 info->num_targets = 0;
1543 info->reason = COMMAND_TARGET_NOT_HUMAN;
1546 strncopy(info->target_name, "all bots", info->target_name_maxlength);
1547 info->target_name_style = COMMAND_TARGETNAME_ML;
1550 else if (strcmp(info->pattern, "@humans") == 0)
1553 strncopy(info->target_name, "all humans", info->target_name_maxlength);
1554 info->target_name_style = COMMAND_TARGETNAME_ML;
1555 info->flags |= COMMAND_FILTER_NO_BOTS;
1557 else if (strcmp(info->pattern, "@!me") == 0)
1560 strncopy(info->target_name, "all players", info->target_name_maxlength);
1561 info->target_name_style = COMMAND_TARGETNAME_ML;
1562 skip_client = info->admin;
1567 for (int i = 1; i <= max_clients && total < info->max_targets; i++)
1569 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1573 if (FilterCommandTarget(pAdmin, pTarget, info->flags) > 0)
1575 if ((!bots_only || pTarget->IsFakeClient())
1576 && skip_client != i)
1578 info->targets[total++] = i;
1583 info->num_targets = total;
1584 info->reason = (info->num_targets) ? COMMAND_TARGET_VALID : COMMAND_TARGET_EMPTY_FILTER;
1589 List<ICommandTargetProcessor *>::iterator iter;
1590 for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
1592 ICommandTargetProcessor *pProcessor = (*iter);
1593 if (pProcessor->ProcessCommandTarget(info))
1599 /* Check partial names */
1600 int found_client = 0;
1601 CPlayer *pFoundClient = NULL;
1602 for (int i = 1; i <= max_clients; i++)
1604 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1609 if (logicore.stristr(pTarget->GetName(), info->pattern) != NULL)
1613 info->num_targets = 0;
1614 info->reason = COMMAND_TARGET_AMBIGUOUS;
1620 pFoundClient = pTarget;
1627 if ((info->reason = FilterCommandTarget(pAdmin, pFoundClient, info->flags))
1628 == COMMAND_TARGET_VALID)
1630 info->targets[0] = found_client;
1631 info->num_targets = 1;
1632 strncopy(info->target_name, pFoundClient->GetName(), info->target_name_maxlength);
1633 info->target_name_style = COMMAND_TARGETNAME_RAW;
1637 info->num_targets = 0;
1642 info->num_targets = 0;
1643 info->reason = COMMAND_TARGET_NONE;
1647 void PlayerManager::OnSourceModMaxPlayersChanged( int newvalue )
1649 m_maxClients = newvalue;
1652 void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
1661 newvalue = gpGlobals->maxClients;
1664 if (newvalue == MaxClients())
1669 /* Notify the rest of core */
1670 SMGlobalClass *pBase = SMGlobalClass::head;
1673 pBase->OnSourceModMaxPlayersChanged(newvalue);
1674 pBase = pBase->m_pGlobalClassNext;
1677 /* Notify Extensions */
1678 List<IClientListener *>::iterator iter;
1679 IClientListener *pListener = NULL;
1680 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
1682 pListener = (*iter);
1683 if (pListener->GetClientListenerVersion() >= 8)
1685 pListener->OnMaxPlayersChanged(newvalue);
1690 int PlayerManager::GetClientFromSerial(unsigned int serial)
1695 int client = s.bits.index;
1697 IGamePlayer *pPlayer = GetGamePlayer(client);
1704 if (serial == pPlayer->GetSerial())
1712 #if SOURCE_ENGINE >= SE_ORANGEBOX
1713 void CmdMaxplayersCallback(const CCommand &command)
1716 void CmdMaxplayersCallback()
1720 g_Players.MaxPlayersChanged();
1724 /*******************
1726 *******************/
1730 m_IsConnected = false;
1732 m_IsAuthorized = false;
1734 m_Admin = INVALID_ADMIN_ID;
1735 m_TempAdmin = false;
1737 m_bAdminCheckSignalled = false;
1739 m_bIsInKickQueue = false;
1740 m_LastPassword.clear();
1741 m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
1742 m_bFakeClient = false;
1743 m_bIsSourceTV = false;
1744 m_bIsReplay = false;
1745 m_Serial.value = -1;
1746 m_SteamAccountID = 0;
1749 void CPlayer::Initialize(const char *name, const char *ip, edict_t *pEntity)
1751 m_IsConnected = true;
1752 m_Name.assign(name);
1755 m_iIndex = IndexOfEdict(pEntity);
1756 m_LangId = translator->GetServerLanguage();
1758 m_Serial.bits.index = m_iIndex;
1759 m_Serial.bits.serial = g_PlayerSerialCount++;
1762 strncopy(ip2, ip, sizeof(ip2));
1763 if ((ptr = strchr(ip2, ':')) != NULL)
1767 m_IpNoPort.assign(ip2);
1770 void CPlayer::Connect()
1779 const char *var = g_Players.GetPassInfoVar();
1780 int client = IndexOfEdict(m_pEdict);
1783 const char *pass = engine->GetClientConVarValue(client, var);
1784 m_LastPassword.assign(pass ? pass : "");
1788 m_LastPassword.assign("");
1792 void CPlayer::SetAuthString(const char *steamid)
1799 m_AuthID.assign(steamid);
1802 // Ensure a valid AuthString is set before calling.
1803 void CPlayer::Authorize()
1805 m_IsAuthorized = true;
1808 void CPlayer::Disconnect()
1811 m_IsConnected = false;
1813 m_IsAuthorized = false;
1819 m_bAdminCheckSignalled = false;
1821 m_bIsInKickQueue = false;
1822 m_bFakeClient = false;
1823 m_bIsSourceTV = false;
1824 m_bIsReplay = false;
1825 m_Serial.value = -1;
1826 m_SteamAccountID = 0;
1829 void CPlayer::SetName(const char *name)
1831 m_Name.assign(name);
1834 const char *CPlayer::GetName()
1836 if (m_Info && m_pEdict->GetUnknown())
1838 return m_Info->GetName();
1841 return m_Name.c_str();
1844 const char *CPlayer::GetIPAddress()
1846 return m_Ip.c_str();
1849 const char *CPlayer::GetAuthString(bool validated)
1851 if (validated && !IsAuthStringValidated())
1856 return m_AuthID.c_str();
1859 unsigned int CPlayer::GetSteamAccountID(bool validated)
1861 if (IsFakeClient() || (validated && !IsAuthStringValidated()))
1866 if (m_SteamAccountID != 0)
1868 return m_SteamAccountID;
1871 #if SOURCE_ENGINE < SE_ORANGEBOX
1872 const char * pAuth = GetAuthString();
1873 /* STEAM_0:1:123123 | STEAM_ID_LAN | STEAM_ID_PENDING */
1874 if (pAuth && (strlen(pAuth) > 10) && pAuth[8] != '_')
1876 m_SteamAccountID = (atoi(&pAuth[8]) | (atoi(&pAuth[10]) << 1));
1879 unsigned long long *steamId = (unsigned long long *)engine->GetClientSteamID(m_pEdict);
1882 m_SteamAccountID = (*steamId & 0xFFFFFFFF);
1885 return m_SteamAccountID;
1888 edict_t *CPlayer::GetEdict()
1893 bool CPlayer::IsInGame()
1895 return m_IsInGame && (m_pEdict->GetUnknown() != NULL);
1898 bool CPlayer::WasCountedAsInGame()
1903 bool CPlayer::IsConnected()
1905 return m_IsConnected;
1908 bool CPlayer::IsAuthorized()
1910 return m_IsAuthorized;
1913 bool CPlayer::IsAuthStringValidated()
1915 #if SOURCE_ENGINE >= SE_ORANGEBOX
1916 if (g_Players.m_bAuthstringValidation && !g_HL2.IsLANServer())
1918 return engine->IsClientFullyAuthenticated(m_pEdict);
1925 IPlayerInfo *CPlayer::GetPlayerInfo()
1927 if (m_pEdict->GetUnknown())
1935 bool CPlayer::IsFakeClient()
1937 return m_bFakeClient;
1940 bool CPlayer::IsSourceTV() const
1942 return m_bIsSourceTV;
1945 bool CPlayer::IsReplay() const
1950 void CPlayer::SetAdminId(AdminId id, bool temporary)
1960 m_TempAdmin = temporary;
1963 AdminId CPlayer::GetAdminId()
1968 void CPlayer::DumpAdmin(bool deleting)
1970 if (m_Admin != INVALID_ADMIN_ID)
1972 if (m_TempAdmin && !deleting)
1974 g_Admins.InvalidateAdmin(m_Admin);
1976 m_Admin = INVALID_ADMIN_ID;
1977 m_TempAdmin = false;
1981 void CPlayer::Kick(const char *str)
1983 MarkAsBeingKicked();
1984 INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
1985 if (pNetChan == NULL)
1987 /* What does this even mean? Hell if I know. */
1988 int userid = GetUserId();
1992 UTIL_Format(buffer, sizeof(buffer), "kickid %d %s\n", userid, str);
1993 engine->ServerCommand(buffer);
1998 IClient *pClient = static_cast<IClient *>(pNetChan->GetMsgHandler());
1999 pClient->Disconnect("%s", str);
2003 void CPlayer::Authorize_Post()
2007 DoPostConnectAuthorization();
2011 void CPlayer::DoPostConnectAuthorization()
2015 List<IClientListener *>::iterator iter;
2016 for (iter = g_Players.m_hooks.begin();
2017 iter != g_Players.m_hooks.end();
2020 IClientListener *pListener = (*iter);
2021 #if defined MIN_API_FOR_ADMINCALLS
2022 if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
2027 if (!pListener->OnClientPreAdminCheck(m_iIndex))
2034 PreAdminCheck->PushCell(m_iIndex);
2035 PreAdminCheck->Execute(&result);
2037 /* Defer, for better or worse */
2038 if (delay || (ResultType)result >= Pl_Handled)
2049 /* Otherwise, go ahead and do admin checks */
2050 DoBasicAdminChecks();
2052 /* Send the notification out */
2053 NotifyPostAdminChecks();
2056 bool CPlayer::RunAdminCacheChecks()
2058 AdminId old_id = GetAdminId();
2060 DoBasicAdminChecks();
2062 return (GetAdminId() != old_id);
2065 void CPlayer::NotifyPostAdminChecks()
2067 if (m_bAdminCheckSignalled)
2072 /* Block beforehand so they can't double-call */
2073 m_bAdminCheckSignalled = true;
2075 List<IClientListener *>::iterator iter;
2076 for (iter = g_Players.m_hooks.begin();
2077 iter != g_Players.m_hooks.end();
2080 IClientListener *pListener = (*iter);
2081 #if defined MIN_API_FOR_ADMINCALLS
2082 if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
2087 pListener->OnClientPostAdminCheck(m_iIndex);
2090 PostAdminFilter->PushCell(m_iIndex);
2091 PostAdminFilter->Execute(NULL);
2093 PostAdminCheck->PushCell(m_iIndex);
2094 PostAdminCheck->Execute(NULL);
2097 void CPlayer::DoBasicAdminChecks()
2099 if (GetAdminId() != INVALID_ADMIN_ID)
2104 /* First check the name */
2106 int client = IndexOfEdict(m_pEdict);
2108 if ((id = g_Admins.FindAdminByIdentity("name", GetName())) != INVALID_ADMIN_ID)
2110 if (!g_Players.CheckSetAdminName(client, this, id))
2112 int userid = engine->GetPlayerUserId(m_pEdict);
2113 g_Timers.CreateTimer(&s_KickPlayerTimer, 0.1f, (void *)userid, 0);
2119 if ((id = g_Admins.FindAdminByIdentity("ip", m_IpNoPort.c_str())) != INVALID_ADMIN_ID)
2121 if (g_Players.CheckSetAdmin(client, this, id))
2127 /* Check steam id */
2128 if ((id = g_Admins.FindAdminByIdentity("steam", m_AuthID.c_str())) != INVALID_ADMIN_ID)
2130 if (g_Players.CheckSetAdmin(client, this, id))
2137 unsigned int CPlayer::GetLanguageId()
2142 void CPlayer::SetLanguageId(unsigned int id)
2147 int CPlayer::GetUserId()
2151 m_UserId = engine->GetPlayerUserId(GetEdict());
2157 bool CPlayer::IsInKickQueue()
2159 return m_bIsInKickQueue;
2162 void CPlayer::MarkAsBeingKicked()
2164 m_bIsInKickQueue = true;
2167 int CPlayer::GetLifeState()
2169 if (lifestate_offset == -1)
2171 if (!g_pGameConf->GetOffset("m_lifeState", &lifestate_offset))
2173 lifestate_offset = -2;
2177 if (lifestate_offset < 0)
2179 IPlayerInfo *info = GetPlayerInfo();
2182 return PLAYER_LIFE_UNKNOWN;
2184 return info->IsDead() ? PLAYER_LIFE_DEAD : PLAYER_LIFE_ALIVE;
2187 if (m_pEdict == NULL)
2189 return PLAYER_LIFE_UNKNOWN;
2192 CBaseEntity *pEntity;
2193 IServerUnknown *pUnknown = m_pEdict->GetUnknown();
2194 if (pUnknown == NULL || (pEntity = pUnknown->GetBaseEntity()) == NULL)
2196 return PLAYER_LIFE_UNKNOWN;
2199 if (*((uint8_t *)pEntity + lifestate_offset) == LIFE_ALIVE)
2201 return PLAYER_LIFE_ALIVE;
2205 return PLAYER_LIFE_DEAD;
2209 unsigned int CPlayer::GetSerial()
2211 return m_Serial.value;