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.

420 lines
15 KiB

  1. //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: net_chan.h
  4. //
  5. //=============================================================================//
  6. #ifndef NET_CHAN_H
  7. #define NET_CHAN_H
  8. #ifdef _WIN32
  9. #pragma once
  10. #endif
  11. #include "net.h"
  12. #include "netadr.h"
  13. #include "qlimits.h"
  14. #include "bitbuf.h"
  15. #include <inetmessage.h>
  16. #include <filesystem.h>
  17. #include "utlvector.h"
  18. #include "utlbuffer.h"
  19. #include "const.h"
  20. #include "inetchannel.h"
  21. #include "netmessages.h"
  22. // How fast to converge flow estimates
  23. #define FLOW_AVG ( 3.0 / 4.0 )
  24. // Don't compute more often than this
  25. #define FLOW_INTERVAL 0.25
  26. #define NET_FRAMES_BACKUP 128 // must be power of 2
  27. #define NET_FRAMES_MASK (NET_FRAMES_BACKUP-1)
  28. #define MAX_SUBCHANNELS 8 // we have 8 alternative send&wait bits
  29. #define SUBCHANNEL_FREE 0 // subchannel is free to use
  30. #define SUBCHANNEL_TOSEND 1 // subchannel has data, but not send yet
  31. #define SUBCHANNEL_WAITING 2 // sbuchannel sent data, waiting for ACK
  32. #define SUBCHANNEL_DIRTY 3 // subchannel is marked as dirty during changelevel
  33. class CNETMsg_SplitScreenUser;
  34. class CNetChan : public INetChannel
  35. {
  36. private: // netchan structurs
  37. typedef struct dataFragments_s
  38. {
  39. FileHandle_t file; // open file handle
  40. char filename[MAX_OSPATH]; // filename
  41. char* buffer; // if NULL it's a file
  42. unsigned int bytes; // size in bytes
  43. unsigned int bits; // size in bits
  44. unsigned int transferID; // only for files
  45. bool isCompressed; // true if data is bzip compressed
  46. unsigned int nUncompressedSize; // full size in bytes
  47. bool asTCP; // send as TCP stream
  48. bool isReplayDemo; // if it's a file, is it a replay .dem file?
  49. int numFragments; // number of total fragments
  50. int ackedFragments; // number of fragments send & acknowledged
  51. int pendingFragments; // number of fragments send, but not acknowledged yet
  52. } dataFragments_t;
  53. struct subChannel_s
  54. {
  55. int startFraggment[MAX_STREAMS];
  56. int numFragments[MAX_STREAMS];
  57. int sendSeqNr;
  58. int state; // 0 = free, 1 = scheduled to send, 2 = send & waiting, 3 = dirty
  59. int index; // index in m_SubChannels[]
  60. void Free()
  61. {
  62. state = SUBCHANNEL_FREE;
  63. sendSeqNr = -1;
  64. for ( int i = 0; i < MAX_STREAMS; i++ )
  65. {
  66. numFragments[i] = 0;
  67. startFraggment[i] = -1;
  68. }
  69. }
  70. };
  71. // Client's now store the command they sent to the server and the entire results set of
  72. // that command.
  73. typedef struct netframe_header_s
  74. {
  75. // Data received from server
  76. float time; // net_time received/send
  77. int size; // total size in bytes
  78. short choked; // number of previously chocked packets
  79. bool valid; // false if dropped, lost, flushed
  80. float latency; // raw ping for this packet, not cleaned. set when acknowledged otherwise -1.
  81. } netframe_header_t;
  82. typedef struct netframe_s
  83. {
  84. // Data received from server
  85. int dropped;
  86. float avg_latency; // averaged ping for this packet
  87. float m_flInterpolationAmount;
  88. unsigned short msggroups[INetChannelInfo::TOTAL]; // received bytes for each message group
  89. } netframe_t;
  90. typedef struct
  91. {
  92. float nextcompute; // Time when we should recompute k/sec data
  93. float avgbytespersec; // average bytes/sec
  94. float avgpacketspersec;// average packets/sec
  95. float avgloss; // average packet loss [0..1]
  96. float avgchoke; // average packet choke [0..1]
  97. float avglatency; // average ping, not cleaned
  98. float latency; // current ping, more accurate also more jittering
  99. int totalpackets; // total processed packets
  100. int totalbytes; // total processed bytes
  101. int currentindex; // current frame index
  102. netframe_header_t frame_headers[ NET_FRAMES_BACKUP ]; // frame history
  103. netframe_t frames[ NET_FRAMES_BACKUP ]; // frame history
  104. netframe_t *currentframe; // current frame
  105. } netflow_t;
  106. public:
  107. CNetChan();
  108. ~CNetChan();
  109. public: // INetChannelInfo interface
  110. const char *GetName( void ) const;
  111. const char *GetAddress( void ) const;
  112. float GetTime( void ) const;
  113. float GetTimeConnected( void ) const;
  114. float GetTimeSinceLastReceived( void ) const;
  115. int GetDataRate( void ) const;
  116. int GetBufferSize( void ) const;
  117. bool IsLoopback( void ) const;
  118. bool IsNull() const; // .dem file playback channel is of type NA_NULL!!!
  119. bool IsTimingOut( void ) const;
  120. bool IsPlayback( void ) const;
  121. float GetLatency( int flow ) const;
  122. float GetAvgLatency( int flow ) const;
  123. float GetAvgLoss( int flow ) const;
  124. float GetAvgData( int flow ) const;
  125. float GetAvgChoke( int flow ) const;
  126. float GetAvgPackets( int flow ) const;
  127. int GetTotalData( int flow ) const;
  128. int GetTotalPackets( int flow ) const;
  129. int GetSequenceNr( int flow ) const;
  130. bool IsValidPacket( int flow, int frame_number ) const ;
  131. float GetPacketTime( int flow, int frame_number ) const ;
  132. int GetPacketBytes( int flow, int frame_number, int group ) const ;
  133. bool GetStreamProgress( int flow, int *received, int *total ) const;
  134. float GetCommandInterpolationAmount( int flow, int frame_number ) const;
  135. void GetPacketResponseLatency( int flow, int frame_number, int *pnLatencyMsecs, int *pnChoke ) const;
  136. void GetRemoteFramerate( float *pflFrameTime, float *pflFrameTimeStdDeviation, float *pflFrameStartTimeStdDeviation ) const;
  137. float GetTimeoutSeconds() const;
  138. public: // INetChannel interface
  139. void SetDataRate(float rate);
  140. INetMessageBinder* FindMessageBinder( int type, int index );
  141. bool RegisterMessage(INetMessageBinder *msg);
  142. bool UnregisterMessage(INetMessageBinder *msg);
  143. bool StartStreaming( unsigned int challengeNr );
  144. void ResetStreaming( void );
  145. void SetTimeout(float seconds, bool bForceExact = false);
  146. void SetDemoRecorder(IDemoRecorder *recorder);
  147. void SetChallengeNr(unsigned int chnr);
  148. void Reset( void );
  149. void Clear( void );
  150. void Shutdown(const char * reason);
  151. void ProcessPlayback( void );
  152. bool ProcessStream( void );
  153. void ProcessPacket( netpacket_t * packet, bool bHasHeader );
  154. void SetCompressionMode( bool bUseCompression );
  155. void SetFileTransmissionMode(bool bBackgroundMode);
  156. bool SendNetMsg( INetMessage &msg, bool bForceReliable = false, bool bVoice = false ); // send a net message
  157. bool SendData(bf_write &msg, bool bReliable = true); // send a chunk of data
  158. bool SendFile(const char *filename, unsigned int transferID, bool isReplayDemo); // transmit a local file
  159. void SetChoked( void ); // choke a packet
  160. int SendDatagram(bf_write *data); // build and send datagram packet
  161. unsigned int RequestFile(const char *filename, bool isReplayDemoFile); // request remote file to upload, returns request ID
  162. void RequestFile_OLD(const char *filename, unsigned int transferID); // request remote file to upload, returns request ID
  163. void DenyFile(const char *filename, unsigned int transferID, bool isReplayDemoFile); // deny a file request
  164. bool Transmit(bool onlyReliable = false); // send data from buffers
  165. const ns_address &GetRemoteAddress( void ) const;
  166. INetChannelHandler *GetMsgHandler( void ) const;
  167. int GetDropNumber( void ) const;
  168. int GetSocket( void ) const;
  169. unsigned int GetChallengeNr( void ) const;
  170. void GetSequenceData( int &nOutSequenceNr, int &nInSequenceNr, int &nOutSequenceNrAck );
  171. void SetSequenceData( int nOutSequenceNr, int nInSequenceNr, int nOutSequenceNrAck );
  172. void UpdateMessageStats( int msggroup, int bits);
  173. bool CanPacket( void ) const;
  174. bool IsOverflowed( void ) const;
  175. bool IsTimedOut( void ) const;
  176. bool HasPendingReliableData( void );
  177. void SetMaxBufferSize(bool bReliable, int nBytes, bool bVoice = false );
  178. virtual int GetNumBitsWritten( bool bReliable );
  179. virtual void SetInterpolationAmount( float flInterpolationAmount );
  180. virtual void SetRemoteFramerate( float flFrameTime, float flFrameTimeStdDeviation, float flFrameStartTimeStdDeviation );
  181. // Max # of payload bytes before we must split/fragment the packet
  182. virtual void SetMaxRoutablePayloadSize( int nSplitSize );
  183. virtual int GetMaxRoutablePayloadSize();
  184. virtual bool SetActiveChannel( INetChannel *pNewChannel );
  185. virtual void AttachSplitPlayer( int nSplitPlayerSlot, INetChannel *pChannel );
  186. virtual void DetachSplitPlayer( int nSplitPlayerSlot );
  187. int IncrementSplitPacketSequence();
  188. virtual bool WasLastMessageReliable() const OVERRIDE; // True if the last (or currently processing) message was sent via the reliable channel
  189. virtual const unsigned char * GetChannelEncryptionKey() const OVERRIDE;
  190. virtual bool EnqueueVeryLargeAsyncTransfer( INetMessage &msg ) OVERRIDE; // Enqueues a message for a large async transfer
  191. // For Steam sockets, returns true if the low level socket is gone (remote disconnected, etc.)
  192. bool IsRemoteDisconnected() const;
  193. public:
  194. static bool IsValidFileForTransfer( const char *pFilename );
  195. void Setup( int sock, const ns_address &adr, const char * name, INetChannelHandler * handler, const byte *pbEncryptionKey );
  196. // Send queue management
  197. void IncrementQueuedPackets();
  198. void DecrementQueuedPackets();
  199. bool HasQueuedPackets() const;
  200. enum EBufType
  201. {
  202. BUF_RELIABLE = 0,
  203. BUF_UNRELIABLE,
  204. BUF_VOICE
  205. };
  206. bf_write &GetBuffer( EBufType eBufType );
  207. private:
  208. struct SplitPlayer_t
  209. {
  210. SplitPlayer_t() : m_nSlot( -1 ), m_pChannel( NULL ) {}
  211. int m_nSlot;
  212. INetChannel *m_pChannel;
  213. static bool Less( const SplitPlayer_t &lhs, const SplitPlayer_t &rhs )
  214. {
  215. return lhs.m_nSlot < rhs.m_nSlot;
  216. }
  217. };
  218. void FlowReset( void );
  219. void FlowUpdate( int flow, int addbytes );
  220. void FlowNewPacket(int flow, int seqnr, int acknr, int nChoked, int nDropped, int nSize );
  221. bool ProcessMessages( bf_read &buf, bool wasReliable );
  222. bool _ProcessMessages( bf_read &buf, bool wasReliable );
  223. bool SendReliableViaStream( dataFragments_t *data);
  224. bool SendReliableAcknowledge( int seqnr );
  225. int ProcessPacketHeader( netpacket_t *packet );
  226. void AcknowledgeSubChannel(int seqnr, int list );
  227. bool CreateFragmentsFromBuffer( bf_write *buffer, int stream );
  228. bool CreateFragmentsFromFile( const char *filename, int stream, unsigned int transferID, bool isReplayDemoFile );
  229. void CompressFragments();
  230. void UncompressFragments( dataFragments_t *data );
  231. bool SendSubChannelData( bf_write &buf );
  232. bool ReadSubChannelData( bf_read &buf, int stream );
  233. void AcknowledgeSeqNr( int seqnr );
  234. void CheckWaitingList(int nList);
  235. bool CheckReceivingList(int nList);
  236. void RemoveHeadInWaitingList( int nList );
  237. bool IsFileInWaitingList( const char *filename );
  238. subChannel_s *GetFreeSubChannel(); // NULL == all subchannels in use
  239. void UpdateSubChannels( void );
  240. void SendTCPData( void );
  241. char const *GetBufferDebugName( EBufType eBufType );
  242. // If we have "slave" channels with data, this adds the appropriate NET_SplitScreenUser guards and combines the payloads
  243. void SplitUserCombineForSending();
  244. void MergeSplitUserBuffers( EBufType eBufType, bf_write &outbuf );
  245. void MaybeAppendBuffer( EBufType eBufType, bf_write &out, SplitPlayer_t &sp, bf_write &src, int *pnCurrentSlot );
  246. void ChangeSplitUser( bf_write &out, int slot );
  247. private:
  248. bool NETMsg_NOP( const CNETMsg_NOP& msg );
  249. bool NETMsg_Disconnect( const CNETMsg_Disconnect& msg );
  250. bool NETMsg_File( const CNETMsg_File& msg );
  251. bool NETMsg_SplitScreenUser( const CNETMsg_SplitScreenUser& msg );
  252. CNetMessageBinder m_NETMsgNOP;
  253. CNetMessageBinder m_NETMsgDisconnect;
  254. CNetMessageBinder m_NETMsgFile;
  255. CNetMessageBinder m_NETMsgSplitScreenUser;
  256. public:
  257. bool m_bProcessingMessages;
  258. bool m_bShouldDelete;
  259. bool m_bStopProcessing;
  260. // last send outgoing sequence number
  261. int m_nOutSequenceNr;
  262. // last received incoming sequnec number
  263. int m_nInSequenceNr;
  264. // last received acknowledge outgoing sequnce number
  265. int m_nOutSequenceNrAck;
  266. // state of outgoing reliable data (0/1) flip flop used for loss detection
  267. int m_nOutReliableState;
  268. // state of incoming reliable data
  269. int m_nInReliableState;
  270. int m_nChokedPackets; //number of choked packets
  271. // Reliable data buffer, send which each packet (or put in waiting list)
  272. bf_write m_StreamReliable;
  273. CUtlMemory<byte> m_ReliableDataBuffer;
  274. // unreliable message buffer, cleared which each packet
  275. bf_write m_StreamUnreliable;
  276. CUtlMemory<byte> m_UnreliableDataBuffer;
  277. bf_write m_StreamVoice;
  278. CUtlMemory<byte> m_VoiceDataBuffer;
  279. // don't use any vars below this (only in net_ws.cpp)
  280. int m_Socket; // NS_SERVER or NS_CLIENT index, depending on channel.
  281. int m_StreamSocket; // TCP socket handle
  282. unsigned int m_MaxReliablePayloadSize; // max size of reliable payload in a single packet
  283. bool m_bWasLastMessageReliable;
  284. // Address this channel is talking to.
  285. ns_address remote_address;
  286. char m_szRemoteAddressName[64];
  287. // For timeouts. Time last message was received.
  288. float last_received;
  289. // Time when channel was connected.
  290. double connect_time;
  291. // Bandwidth choke
  292. // Bytes per second
  293. int m_Rate;
  294. // If realtime > cleartime, free to send next packet
  295. double m_fClearTime;
  296. CUtlVector<dataFragments_t*> m_WaitingList[MAX_STREAMS]; // waiting list for reliable data and file transfer
  297. dataFragments_t m_ReceiveList[MAX_STREAMS]; // receive buffers for streams
  298. subChannel_s m_SubChannels[MAX_SUBCHANNELS];
  299. unsigned int m_FileRequestCounter; // increasing counter with each file request
  300. bool m_bFileBackgroundTranmission; // if true, only send 1 fragment per packet
  301. bool m_bUseCompression; // if true, larger reliable data will be bzip compressed
  302. // TCP stream state maschine:
  303. bool m_StreamActive; // true if TCP is active
  304. int m_SteamType; // STREAM_CMD_*
  305. int m_StreamSeqNr; // each blob send of TCP as an increasing ID
  306. int m_StreamLength; // total length of current stream blob
  307. int m_StreamReceived; // length of already received bytes
  308. char m_SteamFile[MAX_OSPATH]; // if receiving file, this is it's name
  309. CUtlMemory<byte> m_StreamData; // Here goes the stream data (if not file). Only allocated if we're going to use it.
  310. // packet history
  311. netflow_t m_DataFlow[ MAX_FLOWS ];
  312. int m_MsgStats[INetChannelInfo::TOTAL]; // total bytes for each message group
  313. int m_PacketDrop; // packets lost before getting last update (was global net_drop)
  314. char m_Name[32]; // channel name
  315. unsigned int m_ChallengeNr; // unique, random challenge number
  316. float m_Timeout; // in seconds
  317. INetChannelHandler *m_MessageHandler; // who registers and processes messages
  318. CUtlVector< CUtlVector< INetMessageBinder * > > m_NetMessages; // list of registered message
  319. IDemoRecorder *m_DemoRecorder; // if != NULL points to a recording/playback demo object
  320. int m_nQueuedPackets;
  321. float m_flInterpolationAmount;
  322. float m_flRemoteFrameTime;
  323. float m_flRemoteFrameTimeStdDeviation;
  324. float m_flRemoteFrameStartTimeStdDeviation;
  325. int m_nMaxRoutablePayloadSize;
  326. int m_nSplitPacketSequence;
  327. // For split screen support, if we get a message saying we're focusing on another client, then we need to switch to the appropriate handler objects
  328. INetChannel *m_pActiveChannel;
  329. CUtlRBTree< SplitPlayer_t > m_SplitPlayers;
  330. CUtlMemory< byte > m_EncryptionKey;
  331. };
  332. #endif // NET_CHAN_H