Team Fortress 2 Source Code as on 22/4/2020
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.

354 lines
12 KiB

  1. //========= Copyright 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. // How fast to converge flow estimates
  22. #define FLOW_AVG ( 3.0 / 4.0 )
  23. // Don't compute more often than this
  24. #define FLOW_INTERVAL 0.25
  25. #define NET_FRAMES_BACKUP 64 // must be power of 2
  26. #define NET_FRAMES_MASK (NET_FRAMES_BACKUP-1)
  27. #define MAX_SUBCHANNELS 8 // we have 8 alternative send&wait bits
  28. #define SUBCHANNEL_FREE 0 // subchannel is free to use
  29. #define SUBCHANNEL_TOSEND 1 // subchannel has data, but not send yet
  30. #define SUBCHANNEL_WAITING 2 // sbuchannel sent data, waiting for ACK
  31. #define SUBCHANNEL_DIRTY 3 // subchannel is marked as dirty during changelevel
  32. class CNetChan : public INetChannel
  33. {
  34. private: // netchan structurs
  35. typedef struct dataFragments_s
  36. {
  37. FileHandle_t file; // open file handle
  38. char filename[MAX_OSPATH]; // filename
  39. char* buffer; // if NULL it's a file
  40. unsigned int bytes; // size in bytes
  41. unsigned int bits; // size in bits
  42. unsigned int transferID; // only for files
  43. bool isCompressed; // true if data is bzip compressed
  44. unsigned int nUncompressedSize; // full size in bytes
  45. bool asTCP; // send as TCP stream
  46. int numFragments; // number of total fragments
  47. int ackedFragments; // number of fragments send & acknowledged
  48. int pendingFragments; // number of fragments send, but not acknowledged yet
  49. } dataFragments_t;
  50. struct subChannel_s
  51. {
  52. int startFraggment[MAX_STREAMS];
  53. int numFragments[MAX_STREAMS];
  54. int sendSeqNr;
  55. int state; // 0 = free, 1 = scheduled to send, 2 = send & waiting, 3 = dirty
  56. int index; // index in m_SubChannels[]
  57. void Free()
  58. {
  59. state = SUBCHANNEL_FREE;
  60. sendSeqNr = -1;
  61. for ( int i = 0; i < MAX_STREAMS; i++ )
  62. {
  63. numFragments[i] = 0;
  64. startFraggment[i] = -1;
  65. }
  66. }
  67. };
  68. // Client's now store the command they sent to the server and the entire results set of
  69. // that command.
  70. typedef struct netframe_s
  71. {
  72. // Data received from server
  73. float time; // net_time received/send
  74. int size; // total size in bytes
  75. float latency; // raw ping for this packet, not cleaned. set when acknowledged otherwise -1.
  76. float avg_latency; // averaged ping for this packet
  77. bool valid; // false if dropped, lost, flushed
  78. int choked; // number of previously chocked packets
  79. int dropped;
  80. float m_flInterpolationAmount;
  81. unsigned short msggroups[INetChannelInfo::TOTAL]; // received bytes for each message group
  82. } netframe_t;
  83. typedef struct
  84. {
  85. float nextcompute; // Time when we should recompute k/sec data
  86. float avgbytespersec; // average bytes/sec
  87. float avgpacketspersec;// average packets/sec
  88. float avgloss; // average packet loss [0..1]
  89. float avgchoke; // average packet choke [0..1]
  90. float avglatency; // average ping, not cleaned
  91. float latency; // current ping, more accurate also more jittering
  92. int totalpackets; // total processed packets
  93. int totalbytes; // total processed bytes
  94. int currentindex; // current frame index
  95. netframe_t frames[ NET_FRAMES_BACKUP ]; // frame history
  96. netframe_t *currentframe; // current frame
  97. } netflow_t;
  98. public:
  99. CNetChan();
  100. ~CNetChan();
  101. public: // INetChannelInfo interface
  102. const char *GetName( void ) const;
  103. const char *GetAddress( void ) const;
  104. float GetTime( void ) const;
  105. float GetTimeConnected( void ) const;
  106. float GetTimeSinceLastReceived( void ) const;
  107. int GetDataRate( void ) const;
  108. int GetBufferSize( void ) const;
  109. bool IsLoopback( void ) const;
  110. bool IsNull() const; // .dem file playback channel is of type NA_NULL!!!
  111. bool IsTimingOut( void ) const;
  112. bool IsPlayback( void ) const;
  113. float GetLatency( int flow ) const;
  114. float GetAvgLatency( int flow ) const;
  115. float GetAvgLoss( int flow ) const;
  116. float GetAvgData( int flow ) const;
  117. float GetAvgChoke( int flow ) const;
  118. float GetAvgPackets( int flow ) const;
  119. int GetTotalData( int flow ) const;
  120. int GetSequenceNr( int flow ) const ;
  121. bool IsValidPacket( int flow, int frame_number ) const ;
  122. float GetPacketTime( int flow, int frame_number ) const ;
  123. int GetPacketBytes( int flow, int frame_number, int group ) const ;
  124. bool GetStreamProgress( int flow, int *received, int *total ) const;
  125. float GetCommandInterpolationAmount( int flow, int frame_number ) const;
  126. void GetPacketResponseLatency( int flow, int frame_number, int *pnLatencyMsecs, int *pnChoke ) const;
  127. void GetRemoteFramerate( float *pflFrameTime, float *pflFrameTimeStdDeviation ) const;
  128. float GetTimeoutSeconds() const;
  129. public: // INetChannel interface
  130. void SetDataRate(float rate);
  131. bool RegisterMessage(INetMessage *msg);
  132. bool StartStreaming( unsigned int challengeNr );
  133. void ResetStreaming( void );
  134. void SetTimeout(float seconds);
  135. void SetDemoRecorder(IDemoRecorder *recorder);
  136. void SetChallengeNr(unsigned int chnr);
  137. void Reset( void );
  138. void Clear( void );
  139. void Shutdown(const char * reason);
  140. void ProcessPlayback( void );
  141. bool ProcessStream( void );
  142. void ProcessPacket( netpacket_t * packet, bool bHasHeader );
  143. void SetCompressionMode( bool bUseCompression );
  144. void SetFileTransmissionMode(bool bBackgroundMode);
  145. bool SendNetMsg( INetMessage &msg, bool bForceReliable = false, bool bVoice = false ); // send a net message
  146. bool SendData(bf_write &msg, bool bReliable = true); // send a chunk of data
  147. bool SendFile(const char *filename, unsigned int transferID); // transmit a local file
  148. void SetChoked( void ); // choke a packet
  149. int SendDatagram(bf_write *data); // build and send datagram packet
  150. unsigned int RequestFile(const char *filename); // request remote file to upload, returns request ID
  151. void RequestFile_OLD(const char *filename, unsigned int transferID); // request remote file to upload, returns request ID
  152. void DenyFile(const char *filename, unsigned int transferID); // deny a file request
  153. bool Transmit(bool onlyReliable = false); // send data from buffers
  154. const netadr_t &GetRemoteAddress( void ) const;
  155. INetChannelHandler *GetMsgHandler( void ) const;
  156. int GetDropNumber( void ) const;
  157. int GetSocket( void ) const;
  158. unsigned int GetChallengeNr( void ) const;
  159. void GetSequenceData( int &nOutSequenceNr, int &nInSequenceNr, int &nOutSequenceNrAck );
  160. void SetSequenceData( int nOutSequenceNr, int nInSequenceNr, int nOutSequenceNrAck );
  161. void UpdateMessageStats( int msggroup, int bits);
  162. bool CanPacket( void ) const;
  163. bool IsOverflowed( void ) const;
  164. bool IsTimedOut( void ) const;
  165. bool HasPendingReliableData( void );
  166. void SetMaxBufferSize(bool bReliable, int nBytes, bool bVoice = false );
  167. virtual int GetNumBitsWritten( bool bReliable );
  168. virtual void SetInterpolationAmount( float flInterpolationAmount );
  169. virtual void SetRemoteFramerate( float flFrameTime, float flFrameTimeStdDeviation );
  170. // Max # of payload bytes before we must split/fragment the packet
  171. virtual void SetMaxRoutablePayloadSize( int nSplitSize );
  172. virtual int GetMaxRoutablePayloadSize();
  173. virtual int GetProtocolVersion();
  174. int IncrementSplitPacketSequence();
  175. public:
  176. static bool IsValidFileForTransfer( const char *pFilename );
  177. void Setup(int sock, netadr_t *adr, const char * name, INetChannelHandler * handler, int nProtocolVersion);
  178. // Send queue management
  179. void IncrementQueuedPackets();
  180. void DecrementQueuedPackets();
  181. bool HasQueuedPackets() const;
  182. private:
  183. void FlowReset( void );
  184. void FlowUpdate( int flow, int addbytes );
  185. void FlowNewPacket(int flow, int seqnr, int acknr, int nChoked, int nDropped, int nSize );
  186. bool ProcessMessages( bf_read &buf );
  187. bool ProcessControlMessage( int cmd, bf_read &buf);
  188. bool SendReliableViaStream( dataFragments_t *data);
  189. bool SendReliableAcknowledge( int seqnr );
  190. int ProcessPacketHeader( netpacket_t *packet );
  191. void AcknowledgeSubChannel(int seqnr, int list );
  192. bool CreateFragmentsFromBuffer( bf_write *buffer, int stream );
  193. bool CreateFragmentsFromFile( const char *filename, int stream, unsigned int transferID);
  194. void CompressFragments();
  195. void UncompressFragments( dataFragments_t *data );
  196. bool SendSubChannelData( bf_write &buf );
  197. bool ReadSubChannelData( bf_read &buf, int stream );
  198. void AcknowledgeSeqNr( int seqnr );
  199. void CheckWaitingList(int nList);
  200. bool CheckReceivingList(int nList);
  201. void RemoveHeadInWaitingList( int nList );
  202. bool IsFileInWaitingList( const char *filename );
  203. subChannel_s *GetFreeSubChannel(); // NULL == all subchannels in use
  204. void UpdateSubChannels( void );
  205. void SendTCPData( void );
  206. INetMessage *FindMessage(int type);
  207. static bool HandleUpload( dataFragments_t *data, INetChannelHandler *MessageHandler );
  208. #ifdef STAGING_ONLY
  209. public:
  210. static bool TestUpload( const char *filename );
  211. #endif
  212. public:
  213. bool m_bProcessingMessages;
  214. bool m_bClearedDuringProcessing;
  215. bool m_bShouldDelete;
  216. // last send outgoing sequence number
  217. int m_nOutSequenceNr;
  218. // last received incoming sequnec number
  219. int m_nInSequenceNr;
  220. // last received acknowledge outgoing sequnce number
  221. int m_nOutSequenceNrAck;
  222. // state of outgoing reliable data (0/1) flip flop used for loss detection
  223. int m_nOutReliableState;
  224. // state of incoming reliable data
  225. int m_nInReliableState;
  226. int m_nChokedPackets; //number of choked packets
  227. // Reliable data buffer, send which each packet (or put in waiting list)
  228. bf_write m_StreamReliable;
  229. CUtlMemory<byte> m_ReliableDataBuffer;
  230. // unreliable message buffer, cleared which each packet
  231. bf_write m_StreamUnreliable;
  232. CUtlMemory<byte> m_UnreliableDataBuffer;
  233. bf_write m_StreamVoice;
  234. CUtlMemory<byte> m_VoiceDataBuffer;
  235. // don't use any vars below this (only in net_ws.cpp)
  236. int m_Socket; // NS_SERVER or NS_CLIENT index, depending on channel.
  237. int m_StreamSocket; // TCP socket handle
  238. unsigned int m_MaxReliablePayloadSize; // max size of reliable payload in a single packet
  239. // Address this channel is talking to.
  240. netadr_t remote_address;
  241. // For timeouts. Time last message was received.
  242. float last_received;
  243. // Time when channel was connected.
  244. double connect_time;
  245. // Bandwidth choke
  246. // Bytes per second
  247. int m_Rate;
  248. // If realtime > cleartime, free to send next packet
  249. double m_fClearTime;
  250. CUtlVector<dataFragments_t*> m_WaitingList[MAX_STREAMS]; // waiting list for reliable data and file transfer
  251. dataFragments_t m_ReceiveList[MAX_STREAMS]; // receive buffers for streams
  252. subChannel_s m_SubChannels[MAX_SUBCHANNELS];
  253. unsigned int m_FileRequestCounter; // increasing counter with each file request
  254. bool m_bFileBackgroundTranmission; // if true, only send 1 fragment per packet
  255. bool m_bUseCompression; // if true, larger reliable data will be bzip compressed
  256. // TCP stream state maschine:
  257. bool m_StreamActive; // true if TCP is active
  258. int m_SteamType; // STREAM_CMD_*
  259. int m_StreamSeqNr; // each blob send of TCP as an increasing ID
  260. int m_StreamLength; // total length of current stream blob
  261. int m_StreamReceived; // length of already received bytes
  262. char m_SteamFile[MAX_OSPATH]; // if receiving file, this is it's name
  263. CUtlMemory<byte> m_StreamData; // Here goes the stream data (if not file). Only allocated if we're going to use it.
  264. // packet history
  265. netflow_t m_DataFlow[ MAX_FLOWS ];
  266. int m_MsgStats[INetChannelInfo::TOTAL]; // total bytes for each message group
  267. int m_PacketDrop; // packets lost before getting last update (was global net_drop)
  268. char m_Name[32]; // channel name
  269. unsigned int m_ChallengeNr; // unique, random challenge number
  270. float m_Timeout; // in seconds
  271. INetChannelHandler *m_MessageHandler; // who registers and processes messages
  272. CUtlVector<INetMessage*> m_NetMessages; // list of registered message
  273. IDemoRecorder *m_DemoRecorder; // if != NULL points to a recording/playback demo object
  274. int m_nQueuedPackets;
  275. float m_flInterpolationAmount;
  276. float m_flRemoteFrameTime;
  277. float m_flRemoteFrameTimeStdDeviation;
  278. int m_nMaxRoutablePayloadSize;
  279. int m_nSplitPacketSequence;
  280. bool m_bStreamContainsChallenge; // true if PACKET_FLAG_CHALLENGE was set when receiving packets from the sender
  281. int m_nProtocolVersion; // PROTOCOL_VERSION if we're not playing a demo - otherwise, whatever was in the demo header's networkprotocol if the CNetChan instance was created by a demo player.
  282. };
  283. #endif // NET_CHAN_H