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 #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);
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 &);
74 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
76 SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
79 #if SOURCE_ENGINE == SE_DOTA
80 SH_DECL_HOOK0_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0);
82 SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
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);
92 # if SH_IMPL_VERSION >= 4
93 extern int __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
95 extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
97 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
100 ConCommand *maxplayersCmd = NULL;
102 unsigned int g_PlayerSerialCount = 0;
104 class KickPlayerTimer : public ITimedEvent
107 ResultType OnTimer(ITimer *pTimer, void *pData)
109 int userid = (int)pData;
110 int client = g_Players.GetClientOfUserId(userid);
113 CPlayer *player = g_Players.GetPlayerByIndex(client);
114 player->Kick("Your name is reserved by SourceMod; set your password to use it.");
118 void OnTimerEnd(ITimer *pTimer, void *pData)
123 PlayerManager::PlayerManager()
129 m_SourceTVUserId = -1;
132 m_bAuthstringValidation = true; // use steam auth by default
134 m_UserIdLookUp = new int[USHRT_MAX+1];
135 memset(m_UserIdLookUp, 0, sizeof(int) * (USHRT_MAX+1));
138 PlayerManager::~PlayerManager()
140 g_NumPlayersToAuth = NULL;
142 delete [] m_AuthQueue;
143 delete [] m_UserIdLookUp;
146 void PlayerManager::OnSourceModAllInitialized()
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);
157 sharesys->AddInterface(NULL, this);
159 ParamType p1[] = {Param_Cell, Param_String, Param_Cell};
160 ParamType p2[] = {Param_Cell};
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);
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);
177 m_bIsListenServer = !engine->IsDedicatedServer();
180 ConCommand *pCmd = FindCommand("maxplayers");
183 SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdMaxplayersCallback), true);
184 maxplayersCmd = pCmd;
188 void PlayerManager::OnSourceModShutdown()
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);
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);
211 g_Forwards.ReleaseForward(PreAdminCheck);
212 g_Forwards.ReleaseForward(PostAdminCheck);
213 g_Forwards.ReleaseForward(PostAdminFilter);
217 if (maxplayersCmd != NULL)
219 SH_REMOVE_HOOK(ConCommand, Dispatch, maxplayersCmd, SH_STATIC(CmdMaxplayersCallback), true);
223 ConfigResult PlayerManager::OnSourceModConfigChanged(const char *key,
229 if (strcmp(key, "PassInfoVar") == 0)
231 if (strcmp(value, "_password") != 0)
233 m_PassInfoVar.assign(value);
235 return ConfigResult_Accept;
236 } else if (strcmp(key, "AllowClLanguageVar") == 0) {
237 if (strcasecmp(value, "on") == 0)
240 } else if (strcasecmp(value, "off") == 0) {
243 UTIL_Format(error, maxlength, "Invalid value: must be \"on\" or \"off\"");
244 return ConfigResult_Reject;
246 return ConfigResult_Accept;
247 } else if (strcmp( key, "SteamAuthstringValidation" ) == 0) {
248 if (strcasecmp(value, "yes") == 0)
250 m_bAuthstringValidation = true;
251 } else if ( strcasecmp(value, "no") == 0) {
252 m_bAuthstringValidation = false;
254 UTIL_Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
255 return ConfigResult_Reject;
257 return ConfigResult_Accept;
259 return ConfigResult_Ignore;
262 #if SOURCE_ENGINE == SE_DOTA
263 void PlayerManager::OnServerActivate()
265 void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
268 static ConVar *tv_enable = icvar->FindVar("tv_enable");
269 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
270 static ConVar *replay_enable = icvar->FindVar("replay_enable");
273 // clientMax will not necessarily be correct here (such as on late SourceTV enable)
274 m_maxClients = gpGlobals->maxClients;
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_ORANGEBOXVALVE
280 m_bIsReplayActive = (replay_enable && replay_enable->GetBool());
282 m_PlayersSinceActive = 0;
286 /* Initialize all players */
289 m_Players = new CPlayer[ABSOLUTE_PLAYER_LIMIT + 1];
290 m_AuthQueue = new unsigned int[ABSOLUTE_PLAYER_LIMIT + 1];
293 memset(m_AuthQueue, 0, sizeof(unsigned int) * (ABSOLUTE_PLAYER_LIMIT + 1));
295 g_NumPlayersToAuth = &m_AuthQueue[0];
298 scripts->SyncMaxClients(m_maxClients);
300 g_OnMapStarted = true;
302 #if SOURCE_ENGINE == SE_DOTA
303 extsys->CallOnCoreMapStart(gpGlobals->pEdicts, gpGlobals->maxEntities, gpGlobals->maxClients);
305 extsys->CallOnCoreMapStart(pEdictList, edictCount, m_maxClients);
308 m_onActivate->Execute(NULL);
309 m_onActivate2->Execute(NULL);
311 List<IClientListener *>::iterator iter;
312 for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
314 if ((*iter)->GetClientListenerVersion() >= 5)
316 (*iter)->OnServerActivated(m_maxClients);
320 SMGlobalClass *cls = SMGlobalClass::head;
323 cls->OnSourceModLevelActivated();
324 cls = cls->m_pGlobalClassNext;
327 SM_ExecuteAllConfigs();
330 bool PlayerManager::IsServerActivated()
335 bool PlayerManager::CheckSetAdmin(int index, CPlayer *pPlayer, AdminId id)
337 const char *password = g_Admins.GetAdminPassword(id);
338 if (password != NULL)
340 if (m_PassInfoVar.size() < 1)
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)
353 pPlayer->SetAdminId(id, false);
358 bool PlayerManager::CheckSetAdminName(int index, CPlayer *pPlayer, AdminId id)
360 const char *password = g_Admins.GetAdminPassword(id);
361 if (password == NULL)
366 if (m_PassInfoVar.size() < 1)
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)
378 pPlayer->SetAdminId(id, false);
383 void PlayerManager::RunAuthChecks()
387 unsigned int removed = 0;
388 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
390 pPlayer = &m_Players[m_AuthQueue[i]];
391 #if SOURCE_ENGINE == SE_DOTA
392 authstr = engine->GetPlayerNetworkIDString(pPlayer->m_iIndex - 1);
394 authstr = engine->GetPlayerNetworkIDString(pPlayer->m_pEdict);
396 pPlayer->SetAuthString(authstr);
398 if (!pPlayer->IsAuthStringValidated())
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
403 if (authstr && authstr[0] != '\0'
404 && (strcmp(authstr, "STEAM_ID_PENDING") != 0))
406 /* Set authorization */
407 pPlayer->Authorize();
409 /* Mark as removed from queue */
410 unsigned int client = m_AuthQueue[i];
414 /* Send to extensions */
415 List<IClientListener *>::iterator iter;
416 IClientListener *pListener;
417 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
420 pListener->OnClientAuthorized(client, authstr);
421 if (!pPlayer->IsConnected())
427 /* Send to plugins if player is still connected */
428 if (pPlayer->IsConnected() && m_clauth->GetFunctionCount())
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);
436 if (pPlayer->IsConnected())
438 pPlayer->Authorize_Post();
443 /* Clean up the queue */
446 /* We don't have to compact the list if it's empty */
447 if (removed != m_AuthQueue[0])
449 unsigned int diff = 0;
450 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
452 /* If this member is removed... */
453 if (m_AuthQueue[i] == 0)
455 /* Increase the differential */
458 /* diff cannot increase faster than i+1 */
460 assert(i - diff >= 1);
461 /* move this index down */
462 m_AuthQueue[i - diff] = m_AuthQueue[i];
465 m_AuthQueue[0] -= removed;
472 #if SOURCE_ENGINE == SE_DOTA
473 bool PlayerManager::OnClientConnect(CEntityIndex index, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
475 int client = index.Get();
476 edict_t *pEntity = PEntityOfEntIndex(client);
478 bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
480 int client = IndexOfEdict(pEntity);
482 CPlayer *pPlayer = &m_Players[client];
483 ++m_PlayersSinceActive;
485 pPlayer->Initialize(pszName, pszAddress, pEntity);
487 /* Get the client's language */
491 if (!pPlayer->IsFakeClient() && (name=engine->GetClientConVarValue(client, "cl_language")))
494 pPlayer->m_LangId = (translator->GetLanguageByName(name, &langid)) ? langid : translator->GetServerLanguage();
496 pPlayer->m_LangId = translator->GetServerLanguage();
500 List<IClientListener *>::iterator iter;
501 IClientListener *pListener = NULL;
502 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
505 if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
507 RETURN_META_VALUE(MRES_SUPERCEDE, false);
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);
520 if (!pPlayer->IsAuthorized())
522 m_AuthQueue[++m_AuthQueue[0]] = client;
525 m_UserIdLookUp[GetPlayerUserId(pEntity)] = client;
529 if (!pPlayer->IsFakeClient())
531 RETURN_META_VALUE(MRES_SUPERCEDE, false);
538 #if SOURCE_ENGINE == SE_DOTA
539 bool PlayerManager::OnClientConnect_Post(CEntityIndex index, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
541 int client = index.Get();
542 edict_t *pEntity = PEntityOfEntIndex(client);
544 bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
546 int client = IndexOfEdict(pEntity);
549 bool orig_value = META_RESULT_ORIG_RET(bool);
550 CPlayer *pPlayer = &m_Players[client];
554 List<IClientListener *>::iterator iter;
555 IClientListener *pListener = NULL;
556 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
559 pListener->OnClientConnected(client);
560 if (!pPlayer->IsConnected())
566 if (!pPlayer->IsFakeClient()
568 && strncmp(pszAddress, "127.0.0.1", 9) == 0)
570 m_ListenClient = client;
574 m_clconnect_post->PushCell(client);
575 m_clconnect_post->Execute(&res, NULL);
579 InvalidatePlayer(pPlayer);
585 #if SOURCE_ENGINE == SE_DOTA
586 void PlayerManager::OnClientPutInServer(CEntityIndex index, const char *playername)
588 int client = index.Get();
589 edict_t *pEntity = PEntityOfEntIndex(client);
591 void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername)
593 int client = IndexOfEdict(pEntity);
597 CPlayer *pPlayer = &m_Players[client];
599 /* If they're not connected, they're a bot */
600 if (!pPlayer->IsConnected())
602 /* Run manual connection routines */
605 #if SOURCE_ENGINE == SE_DOTA
606 authid = engine->GetPlayerNetworkIDString(client - 1);
608 authid = engine->GetPlayerNetworkIDString(pEntity);
610 pPlayer->SetAuthString(authid);
611 pPlayer->Authorize();
612 pPlayer->m_bFakeClient = true;
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.
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!
623 * These checks are hairy as hell due to differences between engines and games.
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.
633 // This doesn't actually get incremented until OnClientConnect. Fake it to check.
634 int newCount = m_PlayersSinceActive + 1;
636 int userId = GetPlayerUserId(pEntity);
637 #if (SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_LEFT4DEAD2)
638 static ConVar *tv_name = icvar->FindVar("tv_name");
640 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
641 static ConVar *replay_name = icvar->FindVar("replay_name");
643 #if SOURCE_ENGINE == SE_LEFT4DEAD2
644 static bool bIsNuclearDawn = (strcmp(g_SourceMod.GetGameFolderName(), "nucleardawn") == 0);
647 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE
648 if (m_bIsReplayActive && newCount == 1
649 && (m_ReplayUserId == userId
650 || (replay_name && strcmp(playername, replay_name->GetString()) == 0) || (replay_name && replay_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
654 pPlayer->m_bIsReplay = true;
655 m_ReplayUserId = userId;
659 if (m_bIsSourceTVActive
660 && ((!m_bIsReplayActive && newCount == 1)
661 || (m_bIsReplayActive && newCount == 2))
662 && (m_SourceTVUserId == userId
663 #if SOURCE_ENGINE == SE_CSGO
664 || strcmp(playername, "GOTV") == 0
665 #elif (SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_LEFT4DEAD2)
666 #if SOURCE_ENGINE == SE_LEFT4DEAD2
667 || (bIsNuclearDawn && ( true
668 #endif // SE_LEFT4DEAD2
669 || (tv_name && strcmp(playername, tv_name->GetString()) == 0) || (tv_name && tv_name->GetString()[0] == 0 && strcmp(playername, "unnamed") == 0)
670 #if SOURCE_ENGINE == SE_LEFT4DEAD2
672 || (!bIsNuclearDawn && strcmp(playername, "SourceTV") == 0)
673 #endif // SE_LEFT4DEAD2
675 || strcmp(playername, "SourceTV") == 0
680 pPlayer->m_bIsSourceTV = true;
681 m_SourceTVUserId = userId;
684 #if SOURCE_ENGINE == SE_DOTA
685 if (!OnClientConnect(client, playername, "127.0.0.1", error, sizeof(error)))
687 if (!OnClientConnect(pEntity, playername, "127.0.0.1", error, sizeof(error)))
690 /* :TODO: kick the bot if it's rejected */
693 List<IClientListener *>::iterator iter;
694 IClientListener *pListener = NULL;
695 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
698 pListener->OnClientConnected(client);
699 /* See if bot was kicked */
700 if (!pPlayer->IsConnected())
707 m_clconnect_post->PushCell(client);
708 m_clconnect_post->Execute(&res, NULL);
710 /* Now do authorization */
711 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
714 pListener->OnClientAuthorized(client, authid);
716 /* Finally, tell plugins */
717 if (m_clauth->GetFunctionCount())
719 m_clauth->PushCell(client);
720 m_clauth->PushString(authid);
721 m_clauth->Execute(NULL);
723 pPlayer->Authorize_Post();
728 pPlayer->m_Info = playerinfo->GetPlayerInfo(pEntity);
734 List<IClientListener *>::iterator iter;
735 IClientListener *pListener = NULL;
736 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
739 pListener->OnClientPutInServer(client);
742 m_clputinserver->PushCell(client);
743 m_clputinserver->Execute(&res, NULL);
745 if (pPlayer->IsAuthorized())
747 pPlayer->DoPostConnectAuthorization();
751 void PlayerManager::OnSourceModLevelEnd()
753 /* Disconnect all bots still in game */
754 for (int i=1; i<=m_maxClients; i++)
756 if (m_Players[i].IsConnected())
758 #if SOURCE_ENGINE == SE_DOTA
759 OnClientDisconnect(m_Players[i].GetIndex());
761 OnClientDisconnect(m_Players[i].GetEdict());
768 #if SOURCE_ENGINE == SE_DOTA
769 void PlayerManager::OnClientDisconnect(CEntityIndex index)
771 int client = index.Get();
772 edict_t *pEntity = PEntityOfEntIndex(client);
774 void PlayerManager::OnClientDisconnect(edict_t *pEntity)
776 int client = IndexOfEdict(pEntity);
780 CPlayer *pPlayer = &m_Players[client];
782 if (pPlayer->IsConnected())
784 m_cldisconnect->PushCell(client);
785 m_cldisconnect->Execute(&res, NULL);
789 /* We don't care, prevent a double call */
793 if (pPlayer->WasCountedAsInGame())
798 List<IClientListener *>::iterator iter;
799 IClientListener *pListener = NULL;
800 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
803 pListener->OnClientDisconnecting(client);
806 InvalidatePlayer(pPlayer);
808 if (m_ListenClient == client)
814 #if SOURCE_ENGINE == SE_DOTA
815 void PlayerManager::OnClientDisconnect_Post(CEntityIndex index)
817 int client = index.Get();
818 edict_t *pEntity = PEntityOfEntIndex(client);
820 void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
822 int client = IndexOfEdict(pEntity);
827 m_cldisconnect_post->PushCell(client);
828 m_cldisconnect_post->Execute(&res, NULL);
830 List<IClientListener *>::iterator iter;
831 IClientListener *pListener = NULL;
832 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
835 pListener->OnClientDisconnected(client);
839 void ClientConsolePrint(edict_t *e, const char *fmt, ...)
845 size_t len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
848 if (len >= sizeof(buffer) - 1)
850 buffer[sizeof(buffer) - 2] = '\n';
851 buffer[sizeof(buffer) - 1] = '\0';
853 buffer[len++] = '\n';
857 #if SOURCE_ENGINE == SE_DOTA
858 engine->ClientPrintf(CEntityIndex(IndexOfEdict(e)), buffer);
860 engine->ClientPrintf(e, buffer);
864 void ListExtensionsToClient(CPlayer *player, const CCommand &args)
868 unsigned int start = 0;
870 AutoExtensionList extensions(extsys);
871 if (!extensions->size())
873 ClientConsolePrint(player->GetEdict(), "[SM] No extensions found.");
879 start = atoi(args.Arg(2));
883 for (; i < extensions->size(); i++)
885 IExtension *ext = extensions->at(i);
888 if (!ext->IsRunning(error, sizeof(error)))
904 IExtensionInterface *api = ext->GetAPI();
906 const char *name = api->GetExtensionName();
907 const char *version = api->GetExtensionVerString();
908 const char *author = api->GetExtensionAuthor();
909 const char *description = api->GetExtensionDescription();
911 size_t len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", name);
913 if (version != NULL && version[0])
915 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", version);
918 if (author != NULL && author[0])
920 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", author);
923 if (description != NULL && description[0])
925 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, ": %s", description);
929 ClientConsolePrint(player->GetEdict(), "%s", buffer);
932 for (; i < extensions->size(); i++)
935 if (extensions->at(i)->IsRunning(error, sizeof(error)))
941 if (i < extensions->size())
943 ClientConsolePrint(player->GetEdict(), "To see more, type \"sm exts %d\"", id);
947 void ListPluginsToClient(CPlayer *player, const CCommand &args)
951 edict_t *e = player->GetEdict();
952 unsigned int start = 0;
954 AutoPluginList plugins(scripts);
955 if (!plugins->size())
957 ClientConsolePrint(e, "[SM] No plugins found.");
963 start = atoi(args.Arg(2));
966 SourceHook::List<SMPlugin *> m_FailList;
969 for (; i < plugins->size(); i++)
971 SMPlugin *pl = plugins->at(i);
973 if (pl->GetStatus() != Plugin_Running)
978 /* Count valid plugins */
991 const sm_plugininfo_t *info = pl->GetPublicInfo();
992 len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
993 if (IS_STR_FILLED(info->version))
995 len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
997 if (IS_STR_FILLED(info->author))
999 UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
1003 UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->GetFilename());
1005 ClientConsolePrint(e, "%s", buffer);
1008 /* See if we can get more plugins */
1009 for (; i < plugins->size(); i++)
1011 if (plugins->at(i)->GetStatus() == Plugin_Running)
1017 /* Do we actually have more plugins? */
1018 if (i < plugins->size())
1020 ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id);
1024 #if SOURCE_ENGINE == SE_DOTA
1025 void PlayerManager::OnClientCommand(CEntityIndex index, const CCommand &args)
1027 int client = index.Get();
1028 edict_t *pEntity = PEntityOfEntIndex(client);
1029 #elif SOURCE_ENGINE >= SE_ORANGEBOX
1030 void PlayerManager::OnClientCommand(edict_t *pEntity, const CCommand &args)
1032 int client = IndexOfEdict(pEntity);
1034 void PlayerManager::OnClientCommand(edict_t *pEntity)
1038 int client = IndexOfEdict(pEntity);
1041 cell_t res = Pl_Continue;
1042 CPlayer *pPlayer = &m_Players[client];
1044 if (!pPlayer->IsConnected())
1049 if (strcmp(args.Arg(0), "sm") == 0)
1051 if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0)
1053 ListPluginsToClient(pPlayer, args);
1054 RETURN_META(MRES_SUPERCEDE);
1056 else if (args.ArgC() > 1 && strcmp(args.Arg(1), "exts") == 0)
1058 ListExtensionsToClient(pPlayer, args);
1059 RETURN_META(MRES_SUPERCEDE);
1061 else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0)
1063 ClientConsolePrint(pEntity,
1064 "SourceMod would not be possible without:");
1065 ClientConsolePrint(pEntity,
1066 " David \"BAILOPAN\" Anderson, Matt \"pRED\" Woodrow");
1067 ClientConsolePrint(pEntity,
1068 " Scott \"DS\" Ehlert, Fyren");
1069 ClientConsolePrint(pEntity,
1070 " Nicholas \"psychonic\" Hastings, Asher \"asherkin\" Baker");
1071 ClientConsolePrint(pEntity,
1072 " Borja \"faluco\" Ferrer, Pavol \"PM OnoTo\" Marko");
1073 ClientConsolePrint(pEntity,
1074 "SourceMod is open source under the GNU General Public License.");
1075 RETURN_META(MRES_SUPERCEDE);
1078 ClientConsolePrint(pEntity,
1079 "SourceMod %s, by AlliedModders LLC", SM_VERSION_STRING);
1080 ClientConsolePrint(pEntity,
1081 "To see running plugins, type \"sm plugins\"");
1082 ClientConsolePrint(pEntity,
1083 "To see credits, type \"sm credits\"");
1084 ClientConsolePrint(pEntity,
1085 "Visit http://www.sourcemod.net/");
1086 RETURN_META(MRES_SUPERCEDE);
1089 g_HL2.PushCommandStack(&args);
1091 int argcount = args.ArgC() - 1;
1092 const char *cmd = g_HL2.CurrentCommandName();
1094 bool result = g_ValveMenuStyle.OnClientCommand(client, cmd, args);
1099 result = g_RadioMenuStyle.OnClientCommand(client, cmd, args);
1106 if (g_ConsoleDetours.IsEnabled())
1108 cell_t res2 = g_ConsoleDetours.InternalDispatch(client, args);
1109 if (res2 >= Pl_Stop)
1111 g_HL2.PopCommandStack();
1112 RETURN_META(MRES_SUPERCEDE);
1114 else if (res2 > res)
1120 cell_t res2 = Pl_Continue;
1121 if (pPlayer->IsInGame())
1123 m_clcommand->PushCell(client);
1124 m_clcommand->PushCell(argcount);
1125 m_clcommand->Execute(&res2, NULL);
1135 g_HL2.PopCommandStack();
1136 RETURN_META(MRES_SUPERCEDE);
1139 res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res);
1141 g_HL2.PopCommandStack();
1143 if (res >= Pl_Handled)
1145 RETURN_META(MRES_SUPERCEDE);
1149 #if SOURCE_ENGINE == SE_DOTA
1150 void PlayerManager::OnClientSettingsChanged(CEntityIndex index)
1152 int client = index.Get();
1153 edict_t *pEntity = PEntityOfEntIndex(client);
1155 void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
1157 int client = IndexOfEdict(pEntity);
1161 CPlayer *pPlayer = &m_Players[client];
1163 if (!pPlayer->IsConnected())
1168 m_clinfochanged->PushCell(client);
1169 m_clinfochanged->Execute(&res, NULL);
1171 if (pPlayer->IsFakeClient())
1176 IPlayerInfo *info = pPlayer->GetPlayerInfo();
1177 const char *new_name = info ? info->GetName() : engine->GetClientConVarValue(client, "name");
1178 const char *old_name = pPlayer->m_Name.c_str();
1180 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1181 const char *networkid_force;
1182 if ((networkid_force = engine->GetClientConVarValue(client, "networkid_force")) && networkid_force[0] != '\0')
1184 unsigned int accountId = pPlayer->GetSteamAccountID();
1185 g_Logger.LogMessage("\"%s<%d><STEAM_1:%d:%d><>\" has bad networkid (id \"%s\") (ip \"%s\")",
1186 new_name, pPlayer->GetUserId(), accountId & 1, accountId >> 1, networkid_force, pPlayer->GetIPAddress());
1188 pPlayer->Kick("NetworkID spoofing detected.");
1189 RETURN_META(MRES_IGNORED);
1193 if (strcmp(old_name, new_name) != 0)
1195 AdminId id = g_Admins.FindAdminByIdentity("name", new_name);
1196 if (id != INVALID_ADMIN_ID && pPlayer->GetAdminId() != id)
1198 if (!CheckSetAdminName(client, pPlayer, id))
1201 logicore.CoreTranslate(kickMsg, sizeof(kickMsg), "%T", 2, NULL, "Name Reserved", &client);
1202 pPlayer->Kick(kickMsg);
1203 RETURN_META(MRES_IGNORED);
1205 } else if ((id = g_Admins.FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
1206 if (id == pPlayer->GetAdminId())
1208 /* This player is changing their name; force them to drop admin privileges! */
1209 pPlayer->SetAdminId(INVALID_ADMIN_ID, false);
1212 pPlayer->SetName(new_name);
1215 if (m_PassInfoVar.size() > 0)
1217 /* Try for a password change */
1218 const char *old_pass = pPlayer->m_LastPassword.c_str();
1219 const char *new_pass = engine->GetClientConVarValue(client, m_PassInfoVar.c_str());
1220 if (strcmp(old_pass, new_pass) != 0)
1222 pPlayer->m_LastPassword.assign(new_pass);
1223 if (pPlayer->IsInGame() && pPlayer->IsAuthorized())
1225 /* If there is already an admin id assigned, this will just bail out. */
1226 pPlayer->DoBasicAdminChecks();
1230 /* Notify Extensions */
1231 List<IClientListener *>::iterator iter;
1232 IClientListener *pListener = NULL;
1233 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
1235 pListener = (*iter);
1236 if (pListener->GetClientListenerVersion() >= 13)
1238 pListener->OnClientSettingsChanged(client);
1243 int PlayerManager::GetMaxClients()
1245 return m_maxClients;
1248 CPlayer *PlayerManager::GetPlayerByIndex(int client) const
1250 if (client > m_maxClients || client < 1)
1254 return &m_Players[client];
1257 int PlayerManager::GetNumPlayers()
1259 return m_PlayerCount;
1262 int PlayerManager::GetClientOfUserId(int userid)
1264 if (userid < 0 || userid > USHRT_MAX)
1269 int client = m_UserIdLookUp[userid];
1271 /* Verify the userid. The cache can get messed up with older
1272 * Valve engines. :TODO: If this gets fixed, do an old engine
1273 * check before invoking this backwards compat code.
1277 CPlayer *player = GetPlayerByIndex(client);
1278 if (player && player->IsConnected())
1280 int realUserId = GetPlayerUserId(player->GetEdict());
1281 if (realUserId == userid)
1288 /* If we can't verify the userid, we have to do a manual loop */
1290 for (int i = 1; i <= m_maxClients; i++)
1292 player = GetPlayerByIndex(i);
1293 if (!player || !player->IsConnected())
1297 if (GetPlayerUserId(player->GetEdict()) == userid)
1299 m_UserIdLookUp[userid] = i;
1307 void PlayerManager::AddClientListener(IClientListener *listener)
1309 m_hooks.push_back(listener);
1312 void PlayerManager::RemoveClientListener(IClientListener *listener)
1314 m_hooks.remove(listener);
1317 IGamePlayer *PlayerManager::GetGamePlayer(edict_t *pEdict)
1319 int index = IndexOfEdict(pEdict);
1320 return GetGamePlayer(index);
1323 IGamePlayer *PlayerManager::GetGamePlayer(int client)
1325 return GetPlayerByIndex(client);
1328 void PlayerManager::ClearAdminId(AdminId id)
1330 for (int i=1; i<=m_maxClients; i++)
1332 if (m_Players[i].m_Admin == id)
1334 m_Players[i].DumpAdmin(true);
1339 void PlayerManager::ClearAllAdmins()
1341 for (int i=1; i<=m_maxClients; i++)
1343 m_Players[i].DumpAdmin(true);
1347 const char *PlayerManager::GetPassInfoVar()
1349 return m_PassInfoVar.c_str();
1352 void PlayerManager::RecheckAnyAdmins()
1354 for (int i=1; i<=m_maxClients; i++)
1356 if (m_Players[i].IsInGame() && m_Players[i].IsAuthorized())
1358 m_Players[i].DoBasicAdminChecks();
1363 unsigned int PlayerManager::GetReplyTo()
1365 return g_ChatTriggers.GetReplyTo();
1368 unsigned int PlayerManager::SetReplyTo(unsigned int reply)
1370 return g_ChatTriggers.SetReplyTo(reply);
1373 int PlayerManager::FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags)
1375 return InternalFilterCommandTarget((CPlayer *)pAdmin, (CPlayer *)pTarget, flags);
1378 void PlayerManager::RegisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
1380 target_processors.push_back(pHandler);
1383 void PlayerManager::UnregisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
1385 target_processors.remove(pHandler);
1388 void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
1391 * Remove client from auth queue if necessary
1393 if (!pPlayer->IsAuthorized())
1395 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
1397 if (m_AuthQueue[i] == (unsigned)pPlayer->m_iIndex)
1399 /* Move everything ahead of us back by one */
1400 for (unsigned int j=i+1; j<=m_AuthQueue[0]; j++)
1402 m_AuthQueue[j-1] = m_AuthQueue[j];
1404 /* Remove us and break */
1411 m_UserIdLookUp[GetPlayerUserId(pPlayer->m_pEdict)] = 0;
1412 pPlayer->Disconnect();
1415 int PlayerManager::InternalFilterCommandTarget(CPlayer *pAdmin, CPlayer *pTarget, int flags)
1417 if ((flags & COMMAND_FILTER_CONNECTED) == COMMAND_FILTER_CONNECTED
1418 && !pTarget->IsConnected())
1420 return COMMAND_TARGET_NONE;
1422 else if ((flags & COMMAND_FILTER_CONNECTED) != COMMAND_FILTER_CONNECTED &&
1423 !pTarget->IsInGame())
1425 return COMMAND_TARGET_NOT_IN_GAME;
1428 if ((flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS
1429 && pTarget->IsFakeClient())
1431 return COMMAND_TARGET_NOT_HUMAN;
1436 if ((flags & COMMAND_FILTER_NO_IMMUNITY) != COMMAND_FILTER_NO_IMMUNITY
1437 && !g_Admins.CanAdminTarget(pAdmin->GetAdminId(), pTarget->GetAdminId()))
1439 return COMMAND_TARGET_IMMUNE;
1443 if ((flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE
1444 && pTarget->GetLifeState() != PLAYER_LIFE_ALIVE)
1446 return COMMAND_TARGET_NOT_ALIVE;
1449 if ((flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD
1450 && pTarget->GetLifeState() != PLAYER_LIFE_DEAD)
1452 return COMMAND_TARGET_NOT_DEAD;
1455 return COMMAND_TARGET_VALID;
1458 void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
1460 CPlayer *pTarget, *pAdmin;
1461 int max_clients, total = 0;
1463 max_clients = GetMaxClients();
1465 if (info->max_targets < 1)
1467 info->reason = COMMAND_TARGET_NONE;
1468 info->num_targets = 0;
1471 if (info->admin == 0)
1477 pAdmin = GetPlayerByIndex(info->admin);
1480 if (info->pattern[0] == '#')
1482 int userid = atoi(&info->pattern[1]);
1483 int client = GetClientOfUserId(userid);
1485 /* See if a valid userid matched */
1488 IGamePlayer *pTarget = GetPlayerByIndex(client);
1489 if (pTarget != NULL)
1491 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags)) == COMMAND_TARGET_VALID)
1493 info->targets[0] = client;
1494 info->num_targets = 1;
1495 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1496 info->target_name_style = COMMAND_TARGETNAME_RAW;
1500 info->num_targets = 0;
1506 /* Do we need to look for a steam id? */
1507 if (strncmp(&info->pattern[1], "STEAM_", 6) == 0)
1510 char new_pattern[256];
1512 strcpy(new_pattern, "STEAM_");
1513 len = strlen(&info->pattern[7]);
1514 for (p = 0; p < len; p++)
1516 new_pattern[6 + p] = info->pattern[7 + p];
1517 if (new_pattern[6 + p] == '_')
1519 new_pattern[6 + p] = ':';
1522 new_pattern[6 + p] = '\0';
1524 for (int i = 1; i <= max_clients; i++)
1526 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1530 if (!pTarget->IsConnected())
1534 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.
1535 if (authstr && strcmp(authstr, new_pattern) == 0)
1537 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
1538 == COMMAND_TARGET_VALID)
1540 info->targets[0] = i;
1541 info->num_targets = 1;
1542 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1543 info->target_name_style = COMMAND_TARGETNAME_RAW;
1547 info->num_targets = 0;
1554 /* See if an exact name matches */
1555 for (int i = 1; i <= max_clients; i++)
1557 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1561 if (!pTarget->IsConnected())
1565 if (strcmp(pTarget->GetName(), &info->pattern[1]) == 0)
1567 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
1568 == COMMAND_TARGET_VALID)
1570 info->targets[0] = i;
1571 info->num_targets = 1;
1572 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1573 info->target_name_style = COMMAND_TARGETNAME_RAW;
1577 info->num_targets = 0;
1584 if (strcmp(info->pattern, "@me") == 0 && info->admin != 0)
1586 info->reason = FilterCommandTarget(pAdmin, pAdmin, info->flags);
1587 if (info->reason == COMMAND_TARGET_VALID)
1589 info->targets[0] = info->admin;
1590 info->num_targets = 1;
1591 strncopy(info->target_name, pAdmin->GetName(), info->target_name_maxlength);
1592 info->target_name_style = COMMAND_TARGETNAME_RAW;
1596 info->num_targets = 0;
1601 if ((info->flags & COMMAND_FILTER_NO_MULTI) != COMMAND_FILTER_NO_MULTI)
1603 bool is_multi = false;
1604 bool bots_only = false;
1605 int skip_client = -1;
1607 if (strcmp(info->pattern, "@all") == 0)
1610 strncopy(info->target_name, "all players", info->target_name_maxlength);
1611 info->target_name_style = COMMAND_TARGETNAME_ML;
1613 else if (strcmp(info->pattern, "@dead") == 0)
1616 if ((info->flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE)
1618 info->num_targets = 0;
1619 info->reason = COMMAND_TARGET_NOT_ALIVE;
1622 info->flags |= COMMAND_FILTER_DEAD;
1623 strncopy(info->target_name, "all dead players", info->target_name_maxlength);
1624 info->target_name_style = COMMAND_TARGETNAME_ML;
1626 else if (strcmp(info->pattern, "@alive") == 0)
1629 if ((info->flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD)
1631 info->num_targets = 0;
1632 info->reason = COMMAND_TARGET_NOT_DEAD;
1635 strncopy(info->target_name, "all alive players", info->target_name_maxlength);
1636 info->target_name_style = COMMAND_TARGETNAME_ML;
1637 info->flags |= COMMAND_FILTER_ALIVE;
1639 else if (strcmp(info->pattern, "@bots") == 0)
1642 if ((info->flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS)
1644 info->num_targets = 0;
1645 info->reason = COMMAND_TARGET_NOT_HUMAN;
1648 strncopy(info->target_name, "all bots", info->target_name_maxlength);
1649 info->target_name_style = COMMAND_TARGETNAME_ML;
1652 else if (strcmp(info->pattern, "@humans") == 0)
1655 strncopy(info->target_name, "all humans", info->target_name_maxlength);
1656 info->target_name_style = COMMAND_TARGETNAME_ML;
1657 info->flags |= COMMAND_FILTER_NO_BOTS;
1659 else if (strcmp(info->pattern, "@!me") == 0)
1662 strncopy(info->target_name, "all players", info->target_name_maxlength);
1663 info->target_name_style = COMMAND_TARGETNAME_ML;
1664 skip_client = info->admin;
1669 for (int i = 1; i <= max_clients && total < info->max_targets; i++)
1671 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1675 if (FilterCommandTarget(pAdmin, pTarget, info->flags) > 0)
1677 if ((!bots_only || pTarget->IsFakeClient())
1678 && skip_client != i)
1680 info->targets[total++] = i;
1685 info->num_targets = total;
1686 info->reason = (info->num_targets) ? COMMAND_TARGET_VALID : COMMAND_TARGET_EMPTY_FILTER;
1691 List<ICommandTargetProcessor *>::iterator iter;
1692 for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
1694 ICommandTargetProcessor *pProcessor = (*iter);
1695 if (pProcessor->ProcessCommandTarget(info))
1701 /* Check partial names */
1702 int found_client = 0;
1703 CPlayer *pFoundClient = NULL;
1704 for (int i = 1; i <= max_clients; i++)
1706 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1711 if (logicore.stristr(pTarget->GetName(), info->pattern) != NULL)
1715 info->num_targets = 0;
1716 info->reason = COMMAND_TARGET_AMBIGUOUS;
1722 pFoundClient = pTarget;
1729 if ((info->reason = FilterCommandTarget(pAdmin, pFoundClient, info->flags))
1730 == COMMAND_TARGET_VALID)
1732 info->targets[0] = found_client;
1733 info->num_targets = 1;
1734 strncopy(info->target_name, pFoundClient->GetName(), info->target_name_maxlength);
1735 info->target_name_style = COMMAND_TARGETNAME_RAW;
1739 info->num_targets = 0;
1744 info->num_targets = 0;
1745 info->reason = COMMAND_TARGET_NONE;
1749 void PlayerManager::OnSourceModMaxPlayersChanged( int newvalue )
1751 m_maxClients = newvalue;
1754 void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
1763 newvalue = gpGlobals->maxClients;
1766 if (newvalue == MaxClients())
1771 /* Notify the rest of core */
1772 SMGlobalClass *pBase = SMGlobalClass::head;
1775 pBase->OnSourceModMaxPlayersChanged(newvalue);
1776 pBase = pBase->m_pGlobalClassNext;
1779 /* Notify Extensions */
1780 List<IClientListener *>::iterator iter;
1781 IClientListener *pListener = NULL;
1782 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
1784 pListener = (*iter);
1785 if (pListener->GetClientListenerVersion() >= 8)
1787 pListener->OnMaxPlayersChanged(newvalue);
1792 int PlayerManager::GetClientFromSerial(unsigned int serial)
1797 int client = s.bits.index;
1799 IGamePlayer *pPlayer = GetGamePlayer(client);
1806 if (serial == pPlayer->GetSerial())
1814 #if SOURCE_ENGINE == SE_DOTA
1815 void CmdMaxplayersCallback(const CCommandContext &context, const CCommand &command)
1817 #elif SOURCE_ENGINE >= SE_ORANGEBOX
1818 void CmdMaxplayersCallback(const CCommand &command)
1821 void CmdMaxplayersCallback()
1825 g_Players.MaxPlayersChanged();
1829 /*******************
1831 *******************/
1835 m_IsConnected = false;
1837 m_IsAuthorized = false;
1839 m_Admin = INVALID_ADMIN_ID;
1840 m_TempAdmin = false;
1842 m_bAdminCheckSignalled = false;
1844 m_bIsInKickQueue = false;
1845 m_LastPassword.clear();
1846 m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
1847 m_bFakeClient = false;
1848 m_bIsSourceTV = false;
1849 m_bIsReplay = false;
1850 m_Serial.value = -1;
1851 m_SteamAccountID = 0;
1854 void CPlayer::Initialize(const char *name, const char *ip, edict_t *pEntity)
1856 m_IsConnected = true;
1857 m_Name.assign(name);
1860 m_iIndex = IndexOfEdict(pEntity);
1861 m_LangId = translator->GetServerLanguage();
1863 m_Serial.bits.index = m_iIndex;
1864 m_Serial.bits.serial = g_PlayerSerialCount++;
1867 strncopy(ip2, ip, sizeof(ip2));
1868 if ((ptr = strchr(ip2, ':')) != NULL)
1872 m_IpNoPort.assign(ip2);
1875 void CPlayer::Connect()
1884 const char *var = g_Players.GetPassInfoVar();
1885 int client = IndexOfEdict(m_pEdict);
1888 const char *pass = engine->GetClientConVarValue(client, var);
1889 m_LastPassword.assign(pass ? pass : "");
1893 m_LastPassword.assign("");
1897 void CPlayer::SetAuthString(const char *steamid)
1904 m_AuthID.assign(steamid);
1907 // Ensure a valid AuthString is set before calling.
1908 void CPlayer::Authorize()
1910 m_IsAuthorized = true;
1913 void CPlayer::Disconnect()
1916 m_IsConnected = false;
1918 m_IsAuthorized = false;
1924 m_bAdminCheckSignalled = false;
1926 m_bIsInKickQueue = false;
1927 m_bFakeClient = false;
1928 m_bIsSourceTV = false;
1929 m_bIsReplay = false;
1930 m_Serial.value = -1;
1931 m_SteamAccountID = 0;
1934 void CPlayer::SetName(const char *name)
1936 m_Name.assign(name);
1939 const char *CPlayer::GetName()
1941 if (m_Info && m_pEdict->GetUnknown())
1943 return m_Info->GetName();
1946 return m_Name.c_str();
1949 const char *CPlayer::GetIPAddress()
1951 return m_Ip.c_str();
1954 const char *CPlayer::GetAuthString(bool validated)
1956 if (validated && !IsAuthStringValidated())
1961 return m_AuthID.c_str();
1964 unsigned int CPlayer::GetSteamAccountID(bool validated)
1966 if (IsFakeClient() || (validated && !IsAuthStringValidated()))
1971 if (m_SteamAccountID != 0)
1973 return m_SteamAccountID;
1976 #if SOURCE_ENGINE < SE_ORANGEBOX
1977 const char * pAuth = GetAuthString();
1978 /* STEAM_0:1:123123 | STEAM_ID_LAN | STEAM_ID_PENDING */
1979 if (pAuth && (strlen(pAuth) > 10) && pAuth[8] != '_')
1981 m_SteamAccountID = (atoi(&pAuth[8]) | (atoi(&pAuth[10]) << 1));
1984 unsigned long long *steamId;
1985 #if SOURCE_ENGINE == SE_DOTA
1986 steamId = (unsigned long long *)engine->GetClientSteamID(m_iIndex);
1988 steamId = (unsigned long long *)engine->GetClientSteamID(m_pEdict);
1993 m_SteamAccountID = (*steamId & 0xFFFFFFFF);
1996 return m_SteamAccountID;
1999 edict_t *CPlayer::GetEdict()
2004 int CPlayer::GetIndex() const
2009 bool CPlayer::IsInGame()
2011 return m_IsInGame && (m_pEdict->GetUnknown() != NULL);
2014 bool CPlayer::WasCountedAsInGame()
2019 bool CPlayer::IsConnected()
2021 return m_IsConnected;
2024 bool CPlayer::IsAuthorized()
2026 return m_IsAuthorized;
2029 bool CPlayer::IsAuthStringValidated()
2031 #if SOURCE_ENGINE >= SE_ORANGEBOX
2032 if (g_Players.m_bAuthstringValidation && !g_HL2.IsLANServer())
2034 #if SOURCE_ENGINE == SE_DOTA
2035 return engine->IsClientFullyAuthenticated(m_iIndex);
2037 return engine->IsClientFullyAuthenticated(m_pEdict);
2045 IPlayerInfo *CPlayer::GetPlayerInfo()
2047 if (m_pEdict->GetUnknown())
2055 bool CPlayer::IsFakeClient()
2057 return m_bFakeClient;
2060 bool CPlayer::IsSourceTV() const
2062 return m_bIsSourceTV;
2065 bool CPlayer::IsReplay() const
2070 void CPlayer::SetAdminId(AdminId id, bool temporary)
2080 m_TempAdmin = temporary;
2083 AdminId CPlayer::GetAdminId()
2088 void CPlayer::DumpAdmin(bool deleting)
2090 if (m_Admin != INVALID_ADMIN_ID)
2092 if (m_TempAdmin && !deleting)
2094 g_Admins.InvalidateAdmin(m_Admin);
2096 m_Admin = INVALID_ADMIN_ID;
2097 m_TempAdmin = false;
2101 void CPlayer::Kick(const char *str)
2103 MarkAsBeingKicked();
2104 INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
2105 if (pNetChan == NULL)
2107 /* What does this even mean? Hell if I know. */
2108 int userid = GetUserId();
2112 UTIL_Format(buffer, sizeof(buffer), "kickid %d %s\n", userid, str);
2113 engine->ServerCommand(buffer);
2118 IClient *pClient = static_cast<IClient *>(pNetChan->GetMsgHandler());
2119 #if SOURCE_ENGINE == SE_DOTA
2120 pClient->Disconnect(str);
2122 pClient->Disconnect("%s", str);
2127 void CPlayer::Authorize_Post()
2131 DoPostConnectAuthorization();
2135 void CPlayer::DoPostConnectAuthorization()
2139 List<IClientListener *>::iterator iter;
2140 for (iter = g_Players.m_hooks.begin();
2141 iter != g_Players.m_hooks.end();
2144 IClientListener *pListener = (*iter);
2145 #if defined MIN_API_FOR_ADMINCALLS
2146 if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
2151 if (!pListener->OnClientPreAdminCheck(m_iIndex))
2158 PreAdminCheck->PushCell(m_iIndex);
2159 PreAdminCheck->Execute(&result);
2161 /* Defer, for better or worse */
2162 if (delay || (ResultType)result >= Pl_Handled)
2173 /* Otherwise, go ahead and do admin checks */
2174 DoBasicAdminChecks();
2176 /* Send the notification out */
2177 NotifyPostAdminChecks();
2180 bool CPlayer::RunAdminCacheChecks()
2182 AdminId old_id = GetAdminId();
2184 DoBasicAdminChecks();
2186 return (GetAdminId() != old_id);
2189 void CPlayer::NotifyPostAdminChecks()
2191 if (m_bAdminCheckSignalled)
2196 /* Block beforehand so they can't double-call */
2197 m_bAdminCheckSignalled = true;
2199 List<IClientListener *>::iterator iter;
2200 for (iter = g_Players.m_hooks.begin();
2201 iter != g_Players.m_hooks.end();
2204 IClientListener *pListener = (*iter);
2205 #if defined MIN_API_FOR_ADMINCALLS
2206 if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
2211 pListener->OnClientPostAdminCheck(m_iIndex);
2214 PostAdminFilter->PushCell(m_iIndex);
2215 PostAdminFilter->Execute(NULL);
2217 PostAdminCheck->PushCell(m_iIndex);
2218 PostAdminCheck->Execute(NULL);
2221 void CPlayer::DoBasicAdminChecks()
2223 if (GetAdminId() != INVALID_ADMIN_ID)
2228 /* First check the name */
2230 int client = IndexOfEdict(m_pEdict);
2232 if ((id = g_Admins.FindAdminByIdentity("name", GetName())) != INVALID_ADMIN_ID)
2234 if (!g_Players.CheckSetAdminName(client, this, id))
2236 int userid = GetPlayerUserId(m_pEdict);
2237 g_Timers.CreateTimer(&s_KickPlayerTimer, 0.1f, (void *)userid, 0);
2243 if ((id = g_Admins.FindAdminByIdentity("ip", m_IpNoPort.c_str())) != INVALID_ADMIN_ID)
2245 if (g_Players.CheckSetAdmin(client, this, id))
2251 /* Check steam id */
2252 if ((id = g_Admins.FindAdminByIdentity("steam", m_AuthID.c_str())) != INVALID_ADMIN_ID)
2254 if (g_Players.CheckSetAdmin(client, this, id))
2261 unsigned int CPlayer::GetLanguageId()
2266 void CPlayer::SetLanguageId(unsigned int id)
2271 int CPlayer::GetUserId()
2275 m_UserId = GetPlayerUserId(GetEdict());
2281 bool CPlayer::IsInKickQueue()
2283 return m_bIsInKickQueue;
2286 void CPlayer::MarkAsBeingKicked()
2288 m_bIsInKickQueue = true;
2291 int CPlayer::GetLifeState()
2293 if (lifestate_offset == -1)
2295 if (!g_pGameConf->GetOffset("m_lifeState", &lifestate_offset))
2297 lifestate_offset = -2;
2301 if (lifestate_offset < 0)
2303 IPlayerInfo *info = GetPlayerInfo();
2306 return PLAYER_LIFE_UNKNOWN;
2308 return info->IsDead() ? PLAYER_LIFE_DEAD : PLAYER_LIFE_ALIVE;
2311 if (m_pEdict == NULL)
2313 return PLAYER_LIFE_UNKNOWN;
2316 CBaseEntity *pEntity;
2317 IServerUnknown *pUnknown = m_pEdict->GetUnknown();
2318 if (pUnknown == NULL || (pEntity = pUnknown->GetBaseEntity()) == NULL)
2320 return PLAYER_LIFE_UNKNOWN;
2323 if (*((uint8_t *)pEntity + lifestate_offset) == LIFE_ALIVE)
2325 return PLAYER_LIFE_ALIVE;
2329 return PLAYER_LIFE_DEAD;
2333 unsigned int CPlayer::GetSerial()
2335 return m_Serial.value;