Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
14 KiB

  1. //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. //=============================================================================//
  6. #ifndef BASESERVER_H
  7. #define BASESERVER_H
  8. #ifdef _WIN32
  9. #pragma once
  10. #endif
  11. #include <iserver.h>
  12. #include <netadr.h>
  13. #include <bitbuf.h>
  14. #include <utlvector.h>
  15. #include "baseclient.h"
  16. #include "netmessages.h"
  17. #include "net.h"
  18. #include "event_system.h"
  19. #include <utlmap.h>
  20. class CNetworkStringTableContainer;
  21. class PackedEntity;
  22. class ServerClass;
  23. class INetworkStringTable;
  24. typedef intp SerializedEntityHandle_t;
  25. enum server_state_t
  26. {
  27. ss_dead = 0, // Dead
  28. ss_loading, // Spawning
  29. ss_active, // Running
  30. ss_paused, // Running, but paused
  31. };
  32. // MAX_CHALLENGES is made large to prevent a denial
  33. // of service attack that could cycle all of them
  34. // out before legitimate users connected
  35. #define MAX_CHALLENGES 16384
  36. // time a challenge is valid for, in seconds
  37. #define CHALLENGE_LIFETIME 60*60.0f
  38. // MAX_DELTA_TICKS defines the maximum delta difference allowed
  39. // for delta compression, if clients request on older tick as
  40. // delta baseline, send a full update.
  41. #define MAX_DELTA_TICKS 192 // this is about 3 seconds
  42. typedef struct
  43. {
  44. ns_address adr; // Address where challenge value was sent to.
  45. int challenge; // To connect, adr IP address must respond with this #
  46. float time; // # is valid for only a short duration.
  47. } challenge_t;
  48. class CBaseServer : public IServer
  49. {
  50. friend class CMaster;
  51. public:
  52. CBaseServer();
  53. virtual ~CBaseServer();
  54. bool RestartOnLevelChange() { return m_bRestartOnLevelChange; }
  55. public: // IServer implementation
  56. virtual int GetNumClients( void ) const; // returns current number of clients
  57. virtual int GetNumProxies( void ) const; // returns number of attached HLTV proxies
  58. virtual int GetNumFakeClients() const; // returns number of fake clients/bots
  59. virtual int GetMaxClients( void ) const; // returns current client limit
  60. virtual int GetUDPPort( void ) const { return NET_GetUDPPort( m_Socket ); }
  61. virtual IClient *GetClient( int index ) { return m_Clients[index]; } // returns interface to client
  62. virtual int GetClientCount() const { return m_Clients.Count(); } // for iteration;
  63. virtual float GetTime( void ) const;
  64. virtual int GetTick( void ) const { return m_nTickCount; }
  65. virtual float GetTickInterval( void ) const { return m_flTickInterval; }
  66. virtual float GetTimescale( void ) const { return m_flTimescale; }
  67. virtual const char *GetName( void ) const;
  68. virtual const char *GetMapName( void ) const { return m_szMapname; }
  69. virtual const char *GetBaseMapName( void ) const { return m_szBaseMapname; }
  70. virtual const char *GetMapGroupName( void ) const { return m_szMapGroupName; }
  71. virtual int GetSpawnCount( void ) const { return m_nSpawnCount; }
  72. virtual int GetNumClasses( void ) const { return serverclasses; }
  73. virtual int GetClassBits( void ) const { return serverclassbits; }
  74. virtual void GetNetStats( float &avgIn, float &avgOut );
  75. virtual int GetNumPlayers();
  76. virtual bool GetPlayerInfo( int nClientIndex, player_info_t *pinfo );
  77. virtual float GetCPUUsage( void ) { return m_fCPUPercent; }
  78. virtual bool IsActive( void ) const { return m_State >= ss_active; }
  79. virtual bool IsLoading( void ) const { return m_State == ss_loading; }
  80. virtual bool IsDedicated( void ) const { return m_bIsDedicated; }
  81. FORCEINLINE bool IsDedicatedForXbox( void ) const { return m_bIsDedicatedForXbox; }
  82. FORCEINLINE bool IsDedicatedForPS3( void ) const { return m_bIsDedicatedForPS3; }
  83. virtual bool IsPaused( void ) const { return m_State == ss_paused; }
  84. virtual bool IsMultiplayer( void ) const { return m_nMaxclients > 1; }
  85. virtual bool IsPausable( void ) const { return false; }
  86. virtual bool IsHLTV( void ) const { return false; }
  87. virtual bool IsReplay( void ) const { return false; }
  88. virtual void BroadcastMessage( INetMessage &msg, bool onlyActive = false, bool reliable = false );
  89. virtual void BroadcastMessage( INetMessage &msg, IRecipientFilter &filter );
  90. virtual void BroadcastPrintf ( PRINTF_FORMAT_STRING const char *fmt, ...) FMTFUNCTION( 2, 3 );
  91. virtual const char * GetPassword() const;
  92. virtual void SetMaxClients( int number );
  93. virtual void SetPaused(bool paused);
  94. virtual void SetTimescale( float flTimescale );
  95. virtual void SetPassword(const char *password);
  96. virtual void DisconnectClient(IClient *client, const char *reason );
  97. virtual void WriteDeltaEntities( CBaseClient *client, CClientFrame *to, CClientFrame *from, CSVCMsg_PacketEntities_t &msg );
  98. virtual void WriteTempEntities( CBaseClient *client, CFrameSnapshot *to, CFrameSnapshot *from, CSVCMsg_TempEntities_t &msg, int ev_max );
  99. public: // IConnectionlessPacketHandler implementation
  100. virtual bool ProcessConnectionlessPacket( netpacket_t * packet );
  101. virtual void Init( bool isDedicated );
  102. virtual void Clear( void );
  103. virtual void Shutdown( void );
  104. virtual CBaseClient *CreateFakeClient(const char *name);
  105. virtual void RemoveClientFromGame( CBaseClient *client ) {};
  106. virtual void SendClientMessages ( bool bSendSnapshots );
  107. virtual void FillServerInfo(CSVCMsg_ServerInfo &serverinfo);
  108. virtual void UserInfoChanged( int nClientIndex );
  109. virtual bool GetClassBaseline( ServerClass *pClass, SerializedEntityHandle_t *pHandle);
  110. void RunFrame( void );
  111. void ProcessVoice( void );
  112. void InactivateClients( void );
  113. void ReconnectClients( void );
  114. void CheckTimeouts (void);
  115. void UpdateUserSettings(void);
  116. void SendPendingServerInfo(void);
  117. void OnSteamServerLogonSuccess( uint32 externalIP );
  118. INetworkStringTable *GetInstanceBaselineTable( void );
  119. INetworkStringTable *GetLightStyleTable( void );
  120. INetworkStringTable *GetUserInfoTable( void );
  121. virtual void RejectConnection(const ns_address &adr, PRINTF_FORMAT_STRING const char *fmt, ... ) FMTFUNCTION( 3, 4 );
  122. float GetFinalTickTime( void ) const;
  123. virtual bool CheckIPRestrictions( const ns_address &adr, int nAuthProtocol );
  124. void SetMasterServerRulesDirty();
  125. void SendQueryPortToClient( netadr_t &adr );
  126. void RecalculateTags( void );
  127. void AddTag( const char *pszTag, const char *pszSubTagValue = NULL );
  128. void RemoveTag( const char *pszTag, bool bSubTag = false );
  129. CBaseClient *CreateSplitClient( const CMsg_CVars& vecUserInfo, CBaseClient *pAttachedTo );
  130. CBaseClient *GetBaseUserForSplitClient( CBaseClient *pSplitUser );
  131. void QueueSplitScreenDisconnect( CBaseClient *pSplitHost, CBaseClient *pSplitUser );
  132. void ProcessSplitScreenDisconnects();
  133. void UpdateGameType();
  134. void UpdateGameData();
  135. char const *GetGameType() const;
  136. char const *GetGameData() const;
  137. int GetGameDataVersion() const;
  138. bool IsPlayingSoloAgainstBots() const;
  139. bool ShouldHideServer() const;
  140. bool ShouldHideFromMasterServer() const;
  141. int GetMaxHumanPlayers() const;
  142. int GetNumHumanPlayers() const;
  143. void GetMasterServerPlayerCounts( int &nHumans, int &nMaxHumanSlots, int &nBots );
  144. void OnPasswordChanged();
  145. void ShowTags() const;
  146. uint64 GetMatchId()const { return m_nMatchId; }
  147. protected:
  148. virtual IClient *ConnectClient ( const ns_address &adr, int protocol, int challenge, int authProtocol,
  149. const char *name, const char *password, const char *hashedCDkey, int cdKeyLen,
  150. CUtlVector< CCLCMsg_SplitPlayerConnect_t* > & splitScreenClients, bool isClientLowViolence, CrossPlayPlatform_t clientPlatform,
  151. const byte *pbEncryptionKey, int nEncryptionKeyIndex );
  152. virtual bool GetRedirectAddressForConnectClient( const ns_address &adr, CUtlVector< CCLCMsg_SplitPlayerConnect_t* > & splitScreenClients, ns_address *pNetAdrRedirect ) { return false; }
  153. CBaseClient *GetFreeClient( const ns_address &adr );
  154. virtual CBaseClient *CreateNewClient( int slot ) { return NULL; }; // must be derived
  155. virtual bool FinishCertificateCheck( const ns_address &adr, int nAuthProtocol, const char *szRawCertificate ) { return true; };
  156. virtual int GetChallengeNr ( const ns_address &adr );
  157. virtual int GetChallengeType ( const ns_address &adr );
  158. virtual bool CheckProtocol( const ns_address &adr, int nProtocol );
  159. virtual bool CheckChallengeNr( const ns_address &adr, int nChallengeValue );
  160. virtual bool CheckChallengeType( CBaseClient *client, int nNewUserID, const ns_address &adr, int nAuthProtocol, const char *pchLogonCookie, int cbCookie );
  161. virtual bool CheckPassword( const ns_address &adr, const char *password, const char *name );
  162. virtual void ReplyChallenge( const ns_address &adr, bf_read &msg );
  163. virtual void ReplyServerChallenge( const ns_address &adr);
  164. virtual void ReplyReservationRequest( const ns_address &adr, bf_read &msg );
  165. virtual void ReplyReservationCheckRequest( const ns_address &adr, bf_read &msg );
  166. virtual void CalculateCPUUsage();
  167. // Keep the master server data updated.
  168. virtual bool ShouldUpdateMasterServer();
  169. void CheckMasterServerRequestRestart();
  170. void UpdateMasterServer();
  171. void UpdateMasterServerRules();
  172. virtual void UpdateMasterServerPlayers() {}
  173. void ForwardPacketsFromMasterServerUpdater();
  174. void SetRestartOnLevelChange(bool state) { m_bRestartOnLevelChange = state; }
  175. bool RequireValidChallenge( const ns_address &adr );
  176. bool ValidChallenge( const ns_address &adr, int challengeNr );
  177. bool ValidInfoChallenge( const ns_address &adr, const char *nugget );
  178. void ClearBaselineHandles( void );
  179. // Data
  180. public:
  181. server_state_t m_State; // some actions are only valid during load
  182. int m_Socket; // network socket
  183. int m_nTickCount; // current server tick
  184. char m_szMapname[MAX_PATH]; // map name and path without extension
  185. char m_szBaseMapname[MAX_MAP_NAME]; // map name without path or extension
  186. char m_szMapGroupName[64]; // map group name
  187. char m_szSkyname[64]; // skybox name
  188. char m_Password[32]; // server password
  189. CRC32_t worldmapCRC; // For detecting that client has a hacked local copy of map, the client will be dropped if this occurs.
  190. CRC32_t clientDllCRC; // The dll that this server is expecting clients to be using.
  191. CRC32_t stringTableCRC;
  192. CNetworkStringTableContainer *m_StringTables; // newtork string table container
  193. INetworkStringTable *m_pInstanceBaselineTable;
  194. INetworkStringTable *m_pLightStyleTable;
  195. INetworkStringTable *m_pUserInfoTable;
  196. INetworkStringTable *m_pServerStartupTable;
  197. INetworkStringTable *m_pDownloadableFileTable;
  198. CUtlMap< int, SerializedEntityHandle_t > m_BaselineHandles;
  199. // This will get set to NET_MAX_PAYLOAD if the server is MP.
  200. bf_write m_Signon;
  201. CUtlMemory<byte> m_SignonBuffer;
  202. int serverclasses; // number of unique server classes
  203. int serverclassbits; // log2 of serverclasses
  204. bool IsReserved() const { return m_nReservationCookie != 0; }
  205. void Unreserve(); // clear reservation if there is one
  206. void UpdateReservedState();
  207. uint64 GetReservationCookie() const;
  208. void SetReservationCookie( uint64 uiCookie, PRINTF_FORMAT_STRING char const *pchReasonFormat, ... ) FMTFUNCTION( 3, 4 );
  209. bool ReserveServerForQueuedGame( char const *szReservationPayload );
  210. bool IsExclusiveToLobbyConnections() const;
  211. bool IsSinglePlayerGame() const; // won't allow external connections, no heartbeat to master server, etc.
  212. int GetNumGameSlots() const { return m_numGameSlots; }
  213. enum EReservationStatus_t
  214. {
  215. kEReservationStatusRejected = 0, // Reservation is reject, client should go away
  216. kEReservationStatusSuccess = 1, // Reservation is fully completed, client can connect
  217. kEReservationStatusPending = 2, // Reservation is pending, client should wait and might get success packet later
  218. };
  219. void SendReservationStatus( EReservationStatus_t kEReservationStatus );
  220. void ClearReservationStatus();
  221. void FlagForSteamIDReuseAfterShutdown();
  222. private:
  223. // Gets the next user ID mod SHRT_MAX and unique (not used by any active clients).
  224. int GetNextUserID();
  225. int m_nUserid; // increases by one with every new client
  226. void ClearTagStrings();
  227. void AddTagString( CUtlString &dest, char const *pchString );
  228. protected:
  229. CBaseClient *GetFreeClientInternal( const ns_address &adr );
  230. int m_nMaxclients; // Current max #
  231. int m_nSpawnCount; // Number of servers spawned since start,
  232. // used to check late spawns (e.g., when d/l'ing lots of
  233. // data)
  234. float m_flTickInterval; // time for 1 tick in seconds
  235. float m_flTimescale; // the game time scale (multiplied in conjunction with host_timescale)
  236. CUtlVector<CBaseClient*> m_Clients; // array of up to [maxclients] client slots.
  237. bool m_bIsDedicated;
  238. bool m_bIsDedicatedForXbox;
  239. bool m_bIsDedicatedForPS3;
  240. CUtlVector<challenge_t> m_ServerQueryChallenges; // prevent spoofed IP's from server queries/connecting
  241. float m_fCPUPercent;
  242. float m_fStartTime;
  243. float m_fLastCPUCheckTime;
  244. // This is only used for Steam's master server updater to refer to this server uniquely.
  245. bool m_bRestartOnLevelChange;
  246. double m_flFlagForSteamIDReuseAfterShutdownTime;
  247. bool m_bMasterServerRulesDirty;
  248. double m_flLastMasterServerUpdateTime;
  249. struct SplitDisconnect_t
  250. {
  251. CBaseClient *m_pUser;
  252. CBaseClient *m_pSplit;
  253. };
  254. CUtlVector< SplitDisconnect_t > m_QueuedForDisconnect;
  255. struct QueueMatchPlayer_t
  256. {
  257. uint32 m_uiAccountID;
  258. ns_address m_adr;
  259. uint32 m_uiToken;
  260. uint32 m_uiReservationStage;
  261. };
  262. CUtlVector< QueueMatchPlayer_t > m_arrReservationPlayers; // Reservation players in queue mode
  263. uint64 m_nReservationCookie; // if this server has been reserved, cookie that connecting clients must present
  264. uint64 *m_pnReservationCookieSession; // cookie that represents a server session
  265. float m_flReservationExpiryTime; // time at which reservation expires
  266. float m_flTimeLastClientLeft; // time when last client left server
  267. int m_numGameSlots; // number of game slots allocated
  268. CUtlString m_GameType;
  269. CUtlVector<char> m_GameData;
  270. int m_GameDataVersion;
  271. float m_flTimeReservationGraceStarted; // time when client attempted to connect and was granted a reservation grace period
  272. netadr_t m_adrReservationGraceStarted; // netadr of the client for whom reservation grace has been given
  273. bool CanAcceptChallengesFrom( const ns_address &adrFrom ) const;
  274. struct ReservationStatus_t
  275. {
  276. ReservationStatus_t() : m_bActive( false ), m_bSuccess( false )
  277. {
  278. }
  279. bool m_bActive;
  280. bool m_bSuccess;
  281. ns_address m_Remote;
  282. };
  283. ReservationStatus_t m_ReservationStatus;
  284. uint64 m_nMatchId;
  285. };
  286. extern CThreadFastMutex g_svInstanceBaselineMutex;
  287. const ConVar &GetIndexedConVar( const ConVar &cv, int nIndex );
  288. #endif // BASESERVER_H