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))
1101 logicore.CoreTranslate(kickMsg, sizeof(kickMsg), "%T", 2, NULL, "Name Reserved", &client);
1102 pPlayer->Kick(kickMsg);
1103 RETURN_META(MRES_IGNORED);
1105 } else if ((id = g_Admins.FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
1106 if (id == pPlayer->GetAdminId())
1108 /* This player is changing their name; force them to drop admin privileges! */
1109 pPlayer->SetAdminId(INVALID_ADMIN_ID, false);
1112 pPlayer->SetName(new_name);
1115 if (m_PassInfoVar.size() > 0)
1117 /* Try for a password change */
1118 const char *old_pass = pPlayer->m_LastPassword.c_str();
1119 const char *new_pass = engine->GetClientConVarValue(client, m_PassInfoVar.c_str());
1120 if (strcmp(old_pass, new_pass) != 0)
1122 pPlayer->m_LastPassword.assign(new_pass);
1123 if (pPlayer->IsInGame() && pPlayer->IsAuthorized())
1125 /* If there is already an admin id assigned, this will just bail out. */
1126 pPlayer->DoBasicAdminChecks();
1130 /* Notify Extensions */
1131 List<IClientListener *>::iterator iter;
1132 IClientListener *pListener = NULL;
1133 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
1135 pListener = (*iter);
1136 if (pListener->GetClientListenerVersion() >= 13)
1138 pListener->OnClientSettingsChanged(client);
1143 int PlayerManager::GetMaxClients()
1145 return m_maxClients;
1148 CPlayer *PlayerManager::GetPlayerByIndex(int client) const
1150 if (client > m_maxClients || client < 1)
1154 return &m_Players[client];
1157 int PlayerManager::GetNumPlayers()
1159 return m_PlayerCount;
1162 int PlayerManager::GetClientOfUserId(int userid)
1164 if (userid < 0 || userid > USHRT_MAX)
1169 int client = m_UserIdLookUp[userid];
1171 /* Verify the userid. The cache can get messed up with older
1172 * Valve engines. :TODO: If this gets fixed, do an old engine
1173 * check before invoking this backwards compat code.
1177 CPlayer *player = GetPlayerByIndex(client);
1178 if (player && player->IsConnected())
1180 int realUserId = engine->GetPlayerUserId(player->GetEdict());
1181 if (realUserId == userid)
1188 /* If we can't verify the userid, we have to do a manual loop */
1190 for (int i = 1; i <= m_maxClients; i++)
1192 player = GetPlayerByIndex(i);
1193 if (!player || !player->IsConnected())
1197 if (engine->GetPlayerUserId(player->GetEdict()) == userid)
1199 m_UserIdLookUp[userid] = i;
1207 void PlayerManager::AddClientListener(IClientListener *listener)
1209 m_hooks.push_back(listener);
1212 void PlayerManager::RemoveClientListener(IClientListener *listener)
1214 m_hooks.remove(listener);
1217 IGamePlayer *PlayerManager::GetGamePlayer(edict_t *pEdict)
1219 int index = IndexOfEdict(pEdict);
1220 return GetGamePlayer(index);
1223 IGamePlayer *PlayerManager::GetGamePlayer(int client)
1225 return GetPlayerByIndex(client);
1228 void PlayerManager::ClearAdminId(AdminId id)
1230 for (int i=1; i<=m_maxClients; i++)
1232 if (m_Players[i].m_Admin == id)
1234 m_Players[i].DumpAdmin(true);
1239 void PlayerManager::ClearAllAdmins()
1241 for (int i=1; i<=m_maxClients; i++)
1243 m_Players[i].DumpAdmin(true);
1247 const char *PlayerManager::GetPassInfoVar()
1249 return m_PassInfoVar.c_str();
1252 void PlayerManager::RecheckAnyAdmins()
1254 for (int i=1; i<=m_maxClients; i++)
1256 if (m_Players[i].IsInGame() && m_Players[i].IsAuthorized())
1258 m_Players[i].DoBasicAdminChecks();
1263 unsigned int PlayerManager::GetReplyTo()
1265 return g_ChatTriggers.GetReplyTo();
1268 unsigned int PlayerManager::SetReplyTo(unsigned int reply)
1270 return g_ChatTriggers.SetReplyTo(reply);
1273 int PlayerManager::FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags)
1275 return InternalFilterCommandTarget((CPlayer *)pAdmin, (CPlayer *)pTarget, flags);
1278 void PlayerManager::RegisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
1280 target_processors.push_back(pHandler);
1283 void PlayerManager::UnregisterCommandTargetProcessor(ICommandTargetProcessor *pHandler)
1285 target_processors.remove(pHandler);
1288 void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
1291 * Remove client from auth queue if necessary
1293 if (!pPlayer->IsAuthorized())
1295 for (unsigned int i=1; i<=m_AuthQueue[0]; i++)
1297 if (m_AuthQueue[i] == (unsigned)pPlayer->m_iIndex)
1299 /* Move everything ahead of us back by one */
1300 for (unsigned int j=i+1; j<=m_AuthQueue[0]; j++)
1302 m_AuthQueue[j-1] = m_AuthQueue[j];
1304 /* Remove us and break */
1311 m_UserIdLookUp[engine->GetPlayerUserId(pPlayer->m_pEdict)] = 0;
1312 pPlayer->Disconnect();
1315 int PlayerManager::InternalFilterCommandTarget(CPlayer *pAdmin, CPlayer *pTarget, int flags)
1317 if ((flags & COMMAND_FILTER_CONNECTED) == COMMAND_FILTER_CONNECTED
1318 && !pTarget->IsConnected())
1320 return COMMAND_TARGET_NONE;
1322 else if ((flags & COMMAND_FILTER_CONNECTED) != COMMAND_FILTER_CONNECTED &&
1323 !pTarget->IsInGame())
1325 return COMMAND_TARGET_NOT_IN_GAME;
1328 if ((flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS
1329 && pTarget->IsFakeClient())
1331 return COMMAND_TARGET_NOT_HUMAN;
1336 if ((flags & COMMAND_FILTER_NO_IMMUNITY) != COMMAND_FILTER_NO_IMMUNITY
1337 && !g_Admins.CanAdminTarget(pAdmin->GetAdminId(), pTarget->GetAdminId()))
1339 return COMMAND_TARGET_IMMUNE;
1343 if ((flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE
1344 && pTarget->GetLifeState() != PLAYER_LIFE_ALIVE)
1346 return COMMAND_TARGET_NOT_ALIVE;
1349 if ((flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD
1350 && pTarget->GetLifeState() != PLAYER_LIFE_DEAD)
1352 return COMMAND_TARGET_NOT_DEAD;
1355 return COMMAND_TARGET_VALID;
1358 void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
1360 CPlayer *pTarget, *pAdmin;
1361 int max_clients, total = 0;
1363 max_clients = GetMaxClients();
1365 if (info->max_targets < 1)
1367 info->reason = COMMAND_TARGET_NONE;
1368 info->num_targets = 0;
1371 if (info->admin == 0)
1377 pAdmin = GetPlayerByIndex(info->admin);
1380 if (info->pattern[0] == '#')
1382 int userid = atoi(&info->pattern[1]);
1383 int client = GetClientOfUserId(userid);
1385 /* See if a valid userid matched */
1388 IGamePlayer *pTarget = GetPlayerByIndex(client);
1389 if (pTarget != NULL)
1391 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags)) == COMMAND_TARGET_VALID)
1393 info->targets[0] = client;
1394 info->num_targets = 1;
1395 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1396 info->target_name_style = COMMAND_TARGETNAME_RAW;
1400 info->num_targets = 0;
1406 /* Do we need to look for a steam id? */
1407 if (strncmp(&info->pattern[1], "STEAM_", 6) == 0)
1410 char new_pattern[256];
1412 strcpy(new_pattern, "STEAM_");
1413 len = strlen(&info->pattern[7]);
1414 for (p = 0; p < len; p++)
1416 new_pattern[6 + p] = info->pattern[7 + p];
1417 if (new_pattern[6 + p] == '_')
1419 new_pattern[6 + p] = ':';
1422 new_pattern[6 + p] = '\0';
1424 for (int i = 1; i <= max_clients; i++)
1426 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1430 if (!pTarget->IsConnected())
1434 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.
1435 if (authstr && strcmp(authstr, new_pattern) == 0)
1437 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
1438 == COMMAND_TARGET_VALID)
1440 info->targets[0] = i;
1441 info->num_targets = 1;
1442 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1443 info->target_name_style = COMMAND_TARGETNAME_RAW;
1447 info->num_targets = 0;
1454 /* See if an exact name matches */
1455 for (int i = 1; i <= max_clients; i++)
1457 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1461 if (!pTarget->IsConnected())
1465 if (strcmp(pTarget->GetName(), &info->pattern[1]) == 0)
1467 if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
1468 == COMMAND_TARGET_VALID)
1470 info->targets[0] = i;
1471 info->num_targets = 1;
1472 strncopy(info->target_name, pTarget->GetName(), info->target_name_maxlength);
1473 info->target_name_style = COMMAND_TARGETNAME_RAW;
1477 info->num_targets = 0;
1484 if (strcmp(info->pattern, "@me") == 0 && info->admin != 0)
1486 info->reason = FilterCommandTarget(pAdmin, pAdmin, info->flags);
1487 if (info->reason == COMMAND_TARGET_VALID)
1489 info->targets[0] = info->admin;
1490 info->num_targets = 1;
1491 strncopy(info->target_name, pAdmin->GetName(), info->target_name_maxlength);
1492 info->target_name_style = COMMAND_TARGETNAME_RAW;
1496 info->num_targets = 0;
1501 if ((info->flags & COMMAND_FILTER_NO_MULTI) != COMMAND_FILTER_NO_MULTI)
1503 bool is_multi = false;
1504 bool bots_only = false;
1505 int skip_client = -1;
1507 if (strcmp(info->pattern, "@all") == 0)
1510 strncopy(info->target_name, "all players", info->target_name_maxlength);
1511 info->target_name_style = COMMAND_TARGETNAME_ML;
1513 else if (strcmp(info->pattern, "@dead") == 0)
1516 if ((info->flags & COMMAND_FILTER_ALIVE) == COMMAND_FILTER_ALIVE)
1518 info->num_targets = 0;
1519 info->reason = COMMAND_TARGET_NOT_ALIVE;
1522 info->flags |= COMMAND_FILTER_DEAD;
1523 strncopy(info->target_name, "all dead players", info->target_name_maxlength);
1524 info->target_name_style = COMMAND_TARGETNAME_ML;
1526 else if (strcmp(info->pattern, "@alive") == 0)
1529 if ((info->flags & COMMAND_FILTER_DEAD) == COMMAND_FILTER_DEAD)
1531 info->num_targets = 0;
1532 info->reason = COMMAND_TARGET_NOT_DEAD;
1535 strncopy(info->target_name, "all alive players", info->target_name_maxlength);
1536 info->target_name_style = COMMAND_TARGETNAME_ML;
1537 info->flags |= COMMAND_FILTER_ALIVE;
1539 else if (strcmp(info->pattern, "@bots") == 0)
1542 if ((info->flags & COMMAND_FILTER_NO_BOTS) == COMMAND_FILTER_NO_BOTS)
1544 info->num_targets = 0;
1545 info->reason = COMMAND_TARGET_NOT_HUMAN;
1548 strncopy(info->target_name, "all bots", info->target_name_maxlength);
1549 info->target_name_style = COMMAND_TARGETNAME_ML;
1552 else if (strcmp(info->pattern, "@humans") == 0)
1555 strncopy(info->target_name, "all humans", info->target_name_maxlength);
1556 info->target_name_style = COMMAND_TARGETNAME_ML;
1557 info->flags |= COMMAND_FILTER_NO_BOTS;
1559 else if (strcmp(info->pattern, "@!me") == 0)
1562 strncopy(info->target_name, "all players", info->target_name_maxlength);
1563 info->target_name_style = COMMAND_TARGETNAME_ML;
1564 skip_client = info->admin;
1569 for (int i = 1; i <= max_clients && total < info->max_targets; i++)
1571 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1575 if (FilterCommandTarget(pAdmin, pTarget, info->flags) > 0)
1577 if ((!bots_only || pTarget->IsFakeClient())
1578 && skip_client != i)
1580 info->targets[total++] = i;
1585 info->num_targets = total;
1586 info->reason = (info->num_targets) ? COMMAND_TARGET_VALID : COMMAND_TARGET_EMPTY_FILTER;
1591 List<ICommandTargetProcessor *>::iterator iter;
1592 for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
1594 ICommandTargetProcessor *pProcessor = (*iter);
1595 if (pProcessor->ProcessCommandTarget(info))
1601 /* Check partial names */
1602 int found_client = 0;
1603 CPlayer *pFoundClient = NULL;
1604 for (int i = 1; i <= max_clients; i++)
1606 if ((pTarget = GetPlayerByIndex(i)) == NULL)
1611 if (logicore.stristr(pTarget->GetName(), info->pattern) != NULL)
1615 info->num_targets = 0;
1616 info->reason = COMMAND_TARGET_AMBIGUOUS;
1622 pFoundClient = pTarget;
1629 if ((info->reason = FilterCommandTarget(pAdmin, pFoundClient, info->flags))
1630 == COMMAND_TARGET_VALID)
1632 info->targets[0] = found_client;
1633 info->num_targets = 1;
1634 strncopy(info->target_name, pFoundClient->GetName(), info->target_name_maxlength);
1635 info->target_name_style = COMMAND_TARGETNAME_RAW;
1639 info->num_targets = 0;
1644 info->num_targets = 0;
1645 info->reason = COMMAND_TARGET_NONE;
1649 void PlayerManager::OnSourceModMaxPlayersChanged( int newvalue )
1651 m_maxClients = newvalue;
1654 void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
1663 newvalue = gpGlobals->maxClients;
1666 if (newvalue == MaxClients())
1671 /* Notify the rest of core */
1672 SMGlobalClass *pBase = SMGlobalClass::head;
1675 pBase->OnSourceModMaxPlayersChanged(newvalue);
1676 pBase = pBase->m_pGlobalClassNext;
1679 /* Notify Extensions */
1680 List<IClientListener *>::iterator iter;
1681 IClientListener *pListener = NULL;
1682 for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
1684 pListener = (*iter);
1685 if (pListener->GetClientListenerVersion() >= 8)
1687 pListener->OnMaxPlayersChanged(newvalue);
1692 int PlayerManager::GetClientFromSerial(unsigned int serial)
1697 int client = s.bits.index;
1699 IGamePlayer *pPlayer = GetGamePlayer(client);
1706 if (serial == pPlayer->GetSerial())
1714 #if SOURCE_ENGINE >= SE_ORANGEBOX
1715 void CmdMaxplayersCallback(const CCommand &command)
1718 void CmdMaxplayersCallback()
1722 g_Players.MaxPlayersChanged();
1726 /*******************
1728 *******************/
1732 m_IsConnected = false;
1734 m_IsAuthorized = false;
1736 m_Admin = INVALID_ADMIN_ID;
1737 m_TempAdmin = false;
1739 m_bAdminCheckSignalled = false;
1741 m_bIsInKickQueue = false;
1742 m_LastPassword.clear();
1743 m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
1744 m_bFakeClient = false;
1745 m_bIsSourceTV = false;
1746 m_bIsReplay = false;
1747 m_Serial.value = -1;
1748 m_SteamAccountID = 0;
1751 void CPlayer::Initialize(const char *name, const char *ip, edict_t *pEntity)
1753 m_IsConnected = true;
1754 m_Name.assign(name);
1757 m_iIndex = IndexOfEdict(pEntity);
1758 m_LangId = translator->GetServerLanguage();
1760 m_Serial.bits.index = m_iIndex;
1761 m_Serial.bits.serial = g_PlayerSerialCount++;
1764 strncopy(ip2, ip, sizeof(ip2));
1765 if ((ptr = strchr(ip2, ':')) != NULL)
1769 m_IpNoPort.assign(ip2);
1772 void CPlayer::Connect()
1781 const char *var = g_Players.GetPassInfoVar();
1782 int client = IndexOfEdict(m_pEdict);
1785 const char *pass = engine->GetClientConVarValue(client, var);
1786 m_LastPassword.assign(pass ? pass : "");
1790 m_LastPassword.assign("");
1794 void CPlayer::SetAuthString(const char *steamid)
1801 m_AuthID.assign(steamid);
1804 // Ensure a valid AuthString is set before calling.
1805 void CPlayer::Authorize()
1807 m_IsAuthorized = true;
1810 void CPlayer::Disconnect()
1813 m_IsConnected = false;
1815 m_IsAuthorized = false;
1821 m_bAdminCheckSignalled = false;
1823 m_bIsInKickQueue = false;
1824 m_bFakeClient = false;
1825 m_bIsSourceTV = false;
1826 m_bIsReplay = false;
1827 m_Serial.value = -1;
1828 m_SteamAccountID = 0;
1831 void CPlayer::SetName(const char *name)
1833 m_Name.assign(name);
1836 const char *CPlayer::GetName()
1838 if (m_Info && m_pEdict->GetUnknown())
1840 return m_Info->GetName();
1843 return m_Name.c_str();
1846 const char *CPlayer::GetIPAddress()
1848 return m_Ip.c_str();
1851 const char *CPlayer::GetAuthString(bool validated)
1853 if (validated && !IsAuthStringValidated())
1858 return m_AuthID.c_str();
1861 unsigned int CPlayer::GetSteamAccountID(bool validated)
1863 if (IsFakeClient() || (validated && !IsAuthStringValidated()))
1868 if (m_SteamAccountID != 0)
1870 return m_SteamAccountID;
1873 #if SOURCE_ENGINE < SE_ORANGEBOX
1874 const char * pAuth = GetAuthString();
1875 /* STEAM_0:1:123123 | STEAM_ID_LAN | STEAM_ID_PENDING */
1876 if (pAuth && (strlen(pAuth) > 10) && pAuth[8] != '_')
1878 m_SteamAccountID = (atoi(&pAuth[8]) | (atoi(&pAuth[10]) << 1));
1881 unsigned long long *steamId = (unsigned long long *)engine->GetClientSteamID(m_pEdict);
1884 m_SteamAccountID = (*steamId & 0xFFFFFFFF);
1887 return m_SteamAccountID;
1890 edict_t *CPlayer::GetEdict()
1895 bool CPlayer::IsInGame()
1897 return m_IsInGame && (m_pEdict->GetUnknown() != NULL);
1900 bool CPlayer::WasCountedAsInGame()
1905 bool CPlayer::IsConnected()
1907 return m_IsConnected;
1910 bool CPlayer::IsAuthorized()
1912 return m_IsAuthorized;
1915 bool CPlayer::IsAuthStringValidated()
1917 #if SOURCE_ENGINE >= SE_ORANGEBOX
1918 if (g_Players.m_bAuthstringValidation && !g_HL2.IsLANServer())
1920 return engine->IsClientFullyAuthenticated(m_pEdict);
1927 IPlayerInfo *CPlayer::GetPlayerInfo()
1929 if (m_pEdict->GetUnknown())
1937 bool CPlayer::IsFakeClient()
1939 return m_bFakeClient;
1942 bool CPlayer::IsSourceTV() const
1944 return m_bIsSourceTV;
1947 bool CPlayer::IsReplay() const
1952 void CPlayer::SetAdminId(AdminId id, bool temporary)
1962 m_TempAdmin = temporary;
1965 AdminId CPlayer::GetAdminId()
1970 void CPlayer::DumpAdmin(bool deleting)
1972 if (m_Admin != INVALID_ADMIN_ID)
1974 if (m_TempAdmin && !deleting)
1976 g_Admins.InvalidateAdmin(m_Admin);
1978 m_Admin = INVALID_ADMIN_ID;
1979 m_TempAdmin = false;
1983 void CPlayer::Kick(const char *str)
1985 MarkAsBeingKicked();
1986 INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(m_iIndex));
1987 if (pNetChan == NULL)
1989 /* What does this even mean? Hell if I know. */
1990 int userid = GetUserId();
1994 UTIL_Format(buffer, sizeof(buffer), "kickid %d %s\n", userid, str);
1995 engine->ServerCommand(buffer);
2000 IClient *pClient = static_cast<IClient *>(pNetChan->GetMsgHandler());
2001 pClient->Disconnect("%s", str);
2005 void CPlayer::Authorize_Post()
2009 DoPostConnectAuthorization();
2013 void CPlayer::DoPostConnectAuthorization()
2017 List<IClientListener *>::iterator iter;
2018 for (iter = g_Players.m_hooks.begin();
2019 iter != g_Players.m_hooks.end();
2022 IClientListener *pListener = (*iter);
2023 #if defined MIN_API_FOR_ADMINCALLS
2024 if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
2029 if (!pListener->OnClientPreAdminCheck(m_iIndex))
2036 PreAdminCheck->PushCell(m_iIndex);
2037 PreAdminCheck->Execute(&result);
2039 /* Defer, for better or worse */
2040 if (delay || (ResultType)result >= Pl_Handled)
2051 /* Otherwise, go ahead and do admin checks */
2052 DoBasicAdminChecks();
2054 /* Send the notification out */
2055 NotifyPostAdminChecks();
2058 bool CPlayer::RunAdminCacheChecks()
2060 AdminId old_id = GetAdminId();
2062 DoBasicAdminChecks();
2064 return (GetAdminId() != old_id);
2067 void CPlayer::NotifyPostAdminChecks()
2069 if (m_bAdminCheckSignalled)
2074 /* Block beforehand so they can't double-call */
2075 m_bAdminCheckSignalled = true;
2077 List<IClientListener *>::iterator iter;
2078 for (iter = g_Players.m_hooks.begin();
2079 iter != g_Players.m_hooks.end();
2082 IClientListener *pListener = (*iter);
2083 #if defined MIN_API_FOR_ADMINCALLS
2084 if (pListener->GetClientListenerVersion() < MIN_API_FOR_ADMINCALLS)
2089 pListener->OnClientPostAdminCheck(m_iIndex);
2092 PostAdminFilter->PushCell(m_iIndex);
2093 PostAdminFilter->Execute(NULL);
2095 PostAdminCheck->PushCell(m_iIndex);
2096 PostAdminCheck->Execute(NULL);
2099 void CPlayer::DoBasicAdminChecks()
2101 if (GetAdminId() != INVALID_ADMIN_ID)
2106 /* First check the name */
2108 int client = IndexOfEdict(m_pEdict);
2110 if ((id = g_Admins.FindAdminByIdentity("name", GetName())) != INVALID_ADMIN_ID)
2112 if (!g_Players.CheckSetAdminName(client, this, id))
2114 int userid = engine->GetPlayerUserId(m_pEdict);
2115 g_Timers.CreateTimer(&s_KickPlayerTimer, 0.1f, (void *)userid, 0);
2121 if ((id = g_Admins.FindAdminByIdentity("ip", m_IpNoPort.c_str())) != INVALID_ADMIN_ID)
2123 if (g_Players.CheckSetAdmin(client, this, id))
2129 /* Check steam id */
2130 if ((id = g_Admins.FindAdminByIdentity("steam", m_AuthID.c_str())) != INVALID_ADMIN_ID)
2132 if (g_Players.CheckSetAdmin(client, this, id))
2139 unsigned int CPlayer::GetLanguageId()
2144 void CPlayer::SetLanguageId(unsigned int id)
2149 int CPlayer::GetUserId()
2153 m_UserId = engine->GetPlayerUserId(GetEdict());
2159 bool CPlayer::IsInKickQueue()
2161 return m_bIsInKickQueue;
2164 void CPlayer::MarkAsBeingKicked()
2166 m_bIsInKickQueue = true;
2169 int CPlayer::GetLifeState()
2171 if (lifestate_offset == -1)
2173 if (!g_pGameConf->GetOffset("m_lifeState", &lifestate_offset))
2175 lifestate_offset = -2;
2179 if (lifestate_offset < 0)
2181 IPlayerInfo *info = GetPlayerInfo();
2184 return PLAYER_LIFE_UNKNOWN;
2186 return info->IsDead() ? PLAYER_LIFE_DEAD : PLAYER_LIFE_ALIVE;
2189 if (m_pEdict == NULL)
2191 return PLAYER_LIFE_UNKNOWN;
2194 CBaseEntity *pEntity;
2195 IServerUnknown *pUnknown = m_pEdict->GetUnknown();
2196 if (pUnknown == NULL || (pEntity = pUnknown->GetBaseEntity()) == NULL)
2198 return PLAYER_LIFE_UNKNOWN;
2201 if (*((uint8_t *)pEntity + lifestate_offset) == LIFE_ALIVE)
2203 return PLAYER_LIFE_ALIVE;
2207 return PLAYER_LIFE_DEAD;
2211 unsigned int CPlayer::GetSerial()
2213 return m_Serial.value;