EQStream.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #ifndef _EQPROTOCOL_H
  17. #define _EQPROTOCOL_H
  18. #include <string>
  19. #include <vector>
  20. #include <deque>
  21. #include <queue>
  22. #include <map>
  23. #include <set>
  24. #ifndef WIN32
  25. #include <netinet/in.h>
  26. #endif
  27. #include "EQPacket.h"
  28. #include "Mutex.h"
  29. #include "opcodemgr.h"
  30. #include "misc.h"
  31. #include "Condition.h"
  32. #include "Crypto.h"
  33. #include "zlib.h"
  34. #include "timer.h"
  35. #ifdef WRITE_PACKETS
  36. #include <stdarg.h>
  37. #endif
  38. using namespace std;
  39. typedef enum {
  40. ESTABLISHED,
  41. CLOSING,
  42. DISCONNECTING,
  43. CLOSED
  44. } EQStreamState;
  45. #define FLAG_COMPRESSED 0x01
  46. #define FLAG_ENCODED 0x04
  47. #define RATEBASE 1048576 // 1 MB
  48. #define DECAYBASE 78642 // RATEBASE/10
  49. #ifndef RETRANSMIT_TIMEOUT_MULT
  50. #define RETRANSMIT_TIMEOUT_MULT 3.0
  51. #endif
  52. #ifndef RETRANSMIT_TIMEOUT_MAX
  53. #define RETRANSMIT_TIMEOUT_MAX 5000
  54. #endif
  55. #ifndef AVERAGE_DELTA_MAX
  56. #define AVERAGE_DELTA_MAX 2500
  57. #endif
  58. #pragma pack(1)
  59. struct SessionRequest {
  60. uint32 UnknownA;
  61. uint32 Session;
  62. uint32 MaxLength;
  63. };
  64. struct SessionResponse {
  65. uint32 Session;
  66. uint32 Key;
  67. uint8 UnknownA;
  68. uint8 Format;
  69. uint8 UnknownB;
  70. uint32 MaxLength;
  71. uint32 UnknownD;
  72. };
  73. //Deltas are in ms, representing round trip times
  74. struct ClientSessionStats {
  75. /*000*/ uint16 RequestID;
  76. /*002*/ uint32 last_local_delta;
  77. /*006*/ uint32 average_delta;
  78. /*010*/ uint32 low_delta;
  79. /*014*/ uint32 high_delta;
  80. /*018*/ uint32 last_remote_delta;
  81. /*022*/ uint64 packets_sent;
  82. /*030*/ uint64 packets_recieved;
  83. /*038*/
  84. };
  85. struct ServerSessionStats {
  86. uint16 RequestID;
  87. uint32 current_time;
  88. uint32 unknown1;
  89. uint32 received_packets;
  90. uint32 unknown2;
  91. uint32 sent_packets;
  92. uint32 unknown3;
  93. uint32 sent_packets2;
  94. uint32 unknown4;
  95. uint32 received_packets2;
  96. };
  97. #pragma pack()
  98. class OpcodeManager;
  99. extern OpcodeManager *EQNetworkOpcodeManager;
  100. class EQStreamFactory;
  101. typedef enum {
  102. UnknownStream=0,
  103. LoginStream,
  104. WorldStream,
  105. ZoneStream,
  106. ChatOrMailStream,
  107. ChatStream,
  108. MailStream,
  109. EQ2Stream,
  110. } EQStreamType;
  111. class EQStream {
  112. protected:
  113. typedef enum {
  114. SeqPast,
  115. SeqInOrder,
  116. SeqFuture
  117. } SeqOrder;
  118. uint32 received_packets;
  119. uint32 sent_packets;
  120. uint32 remote_ip;
  121. uint16 remote_port;
  122. uint8 buffer[8192];
  123. unsigned char *oversize_buffer;
  124. uint32 oversize_offset,oversize_length;
  125. uint8 app_opcode_size;
  126. EQStreamType StreamType;
  127. bool compressed,encoded;
  128. uint32 retransmittimer;
  129. uint32 retransmittimeout;
  130. //uint32 buffer_len;
  131. uint16 sessionAttempts;
  132. bool streamactive;
  133. uint32 Session, Key;
  134. uint16 NextInSeq;
  135. uint16 NextOutSeq;
  136. uint16 SequencedBase; //the sequence number of SequencedQueue[0]
  137. uint32 MaxLen;
  138. uint16 MaxSends;
  139. int8 timeout_delays;
  140. uint8 active_users; //how many things are actively using this
  141. Mutex MInUse;
  142. #ifdef WRITE_PACKETS
  143. FILE* write_packets = NULL;
  144. char GetChar(uchar in);
  145. void WriteToFile(char* pFormat, ...);
  146. void WritePackets(const char* opcodeName, uchar* data, int32 size, bool outgoing);
  147. void WritePackets(EQ2Packet* app, bool outgoing);
  148. Mutex MWritePackets;
  149. #endif
  150. EQStreamState State;
  151. Mutex MState;
  152. uint32 LastPacket;
  153. Mutex MVarlock;
  154. EQApplicationPacket* CombinedAppPacket;
  155. Mutex MCombinedAppPacket;
  156. long LastSeqSent;
  157. Mutex MLastSeqSent;
  158. void SetLastSeqSent(uint32);
  159. // Ack sequence tracking.
  160. long MaxAckReceived,NextAckToSend,LastAckSent;
  161. long GetMaxAckReceived();
  162. long GetNextAckToSend();
  163. long GetLastAckSent();
  164. void SetMaxAckReceived(uint32 seq);
  165. void SetNextAckToSend(uint32);
  166. void SetLastAckSent(uint32);
  167. Mutex MAcks;
  168. // Packets waiting to be sent
  169. queue<EQProtocolPacket*> NonSequencedQueue;
  170. deque<EQProtocolPacket*> SequencedQueue;
  171. map<uint16, EQProtocolPacket *> OutOfOrderpackets;
  172. Mutex MOutboundQueue;
  173. // Packes waiting to be processed
  174. deque<EQApplicationPacket *> InboundQueue;
  175. Mutex MInboundQueue;
  176. static uint16 MaxWindowSize;
  177. sint32 BytesWritten;
  178. Mutex MRate;
  179. sint32 RateThreshold;
  180. sint32 DecayRate;
  181. uint32 AverageDelta;
  182. EQStreamFactory *Factory;
  183. public:
  184. Mutex MCombineQueueLock;
  185. bool CheckCombineQueue();
  186. deque<EQ2Packet*> combine_queue;
  187. Timer* combine_timer;
  188. Crypto* crypto;
  189. int8 EQ2_Compress(EQ2Packet* app, int8 offset = 3);
  190. z_stream stream;
  191. uchar* stream_buffer;
  192. int32 stream_buffer_size;
  193. bool eq2_compressed;
  194. int8 compressed_offset;
  195. int16 client_version;
  196. int16 GetClientVersion(){ return client_version; }
  197. void SetClientVersion(int16 version){ client_version = version; }
  198. EQStream() { init(); remote_ip = 0; remote_port = 0; State = CLOSED; StreamType = UnknownStream; compressed = true;
  199. encoded = false; app_opcode_size = 2;}
  200. EQStream(sockaddr_in addr);
  201. virtual ~EQStream() {
  202. MOutboundQueue.lock();
  203. SetState(CLOSED);
  204. MOutboundQueue.unlock();
  205. RemoveData();
  206. safe_delete(crypto);
  207. safe_delete(combine_timer);
  208. safe_delete(resend_que_timer);
  209. safe_delete_array(oversize_buffer);
  210. deque<EQ2Packet*>::iterator cmb;
  211. MCombineQueueLock.lock();
  212. for (cmb = combine_queue.begin(); cmb != combine_queue.end(); cmb++){
  213. safe_delete(*cmb);
  214. }
  215. MCombineQueueLock.unlock();
  216. deflateEnd(&stream);
  217. map<int16, EQProtocolPacket*>::iterator oop;
  218. for (oop = OutOfOrderpackets.begin(); oop != OutOfOrderpackets.end(); oop++){
  219. safe_delete(oop->second);
  220. }
  221. #ifdef WRITE_PACKETS
  222. if (write_packets)
  223. fclose(write_packets);
  224. #endif
  225. }
  226. inline void SetFactory(EQStreamFactory *f) { Factory=f; }
  227. void init(bool resetSession = true);
  228. void SetMaxLen(uint32 length) { MaxLen=length; }
  229. int8 getTimeoutDelays(){ return timeout_delays; }
  230. void addTimeoutDelay(){ timeout_delays++; }
  231. void EQ2QueuePacket(EQ2Packet* app, bool attempted_combine = false);
  232. void PreparePacket(EQ2Packet* app, int8 offset = 0);
  233. void UnPreparePacket(EQ2Packet* app);
  234. void EncryptPacket(EQ2Packet* app, int8 compress_offset, int8 offset);
  235. void FlushCombinedPacket();
  236. void SendPacket(EQApplicationPacket *p);
  237. void QueuePacket(EQProtocolPacket *p);
  238. void SendPacket(EQProtocolPacket *p);
  239. vector<EQProtocolPacket *> convert(EQApplicationPacket *p);
  240. void NonSequencedPush(EQProtocolPacket *p);
  241. void SequencedPush(EQProtocolPacket *p);
  242. Mutex MResendQue;
  243. Mutex MCompressData;
  244. deque<EQProtocolPacket*>resend_que;
  245. void CheckResend(int eq_fd);
  246. void AckPackets(uint16 seq);
  247. void Write(int eq_fd);
  248. void SetActive(bool val) { streamactive = val; }
  249. void WritePacket(int fd,EQProtocolPacket *p);
  250. void EncryptPacket(uchar* data, int16 size);
  251. uint32 GetKey() { return Key; }
  252. void SetKey(uint32 k) { Key=k; }
  253. void SetSession(uint32 s) { Session=s; }
  254. void SetLastPacketTime(uint32 t) {LastPacket=t;}
  255. void Process(const unsigned char *data, const uint32 length);
  256. void ProcessPacket(EQProtocolPacket *p, EQProtocolPacket* lastp=NULL);
  257. bool HandleEmbeddedPacket(EQProtocolPacket *p, int16 offset = 2, int16 length = 0);
  258. EQProtocolPacket * ProcessEncryptedPacket(EQProtocolPacket *p);
  259. EQProtocolPacket * ProcessEncryptedData(uchar* data, int32 size, int16 opcode);
  260. virtual void DispatchPacket(EQApplicationPacket *p) { p->DumpRaw(); }
  261. void SendSessionResponse();
  262. void SendSessionRequest();
  263. void SendDisconnect(bool setstate = true);
  264. void SendAck(uint16 seq);
  265. void SendOutOfOrderAck(uint16 seq);
  266. bool CheckTimeout(uint32 now, uint32 timeout=30) { return (LastPacket && (now-LastPacket) > timeout); }
  267. bool Stale(uint32 now, uint32 timeout=30) { return (LastPacket && (now-LastPacket) > timeout); }
  268. void InboundQueuePush(EQApplicationPacket *p);
  269. EQApplicationPacket *PopPacket(); // InboundQueuePop
  270. void InboundQueueClear();
  271. void OutboundQueueClear();
  272. bool HasOutgoingData();
  273. void SendKeyRequest();
  274. int16 processRSAKey(EQProtocolPacket *p);
  275. void RemoveData() { InboundQueueClear(); OutboundQueueClear(); if (CombinedAppPacket) delete CombinedAppPacket; }
  276. //
  277. inline bool IsInUse() { bool flag; MInUse.lock(); flag=(active_users>0); MInUse.unlock(); return flag; }
  278. inline void PutInUse() { MInUse.lock(); active_users++; MInUse.unlock(); }
  279. inline void ReleaseFromUse() { MInUse.lock(); if(active_users > 0) active_users--; MInUse.unlock(); }
  280. static SeqOrder CompareSequence(uint16 expected_seq, uint16 seq);
  281. inline EQStreamState GetState() { return State; }
  282. inline void SetState(EQStreamState state) { MState.lock(); State = state; MState.unlock(); }
  283. inline uint32 GetRemoteIP() { return remote_ip; }
  284. inline uint32 GetrIP() { return remote_ip; }
  285. inline uint16 GetRemotePort() { return remote_port; }
  286. inline uint16 GetrPort() { return remote_port; }
  287. static EQProtocolPacket *Read(int eq_fd, sockaddr_in *from);
  288. void Close() { SendDisconnect(); }
  289. bool CheckActive() { return GetState()==ESTABLISHED; }
  290. bool CheckClosed() { return GetState()==CLOSED; }
  291. void SetOpcodeSize(uint8 s) { app_opcode_size = s; }
  292. void SetStreamType(EQStreamType t);
  293. inline const EQStreamType GetStreamType() const { return StreamType; }
  294. void ProcessQueue();
  295. EQProtocolPacket* RemoveQueue(uint16 seq);
  296. void Decay();
  297. void AdjustRates(uint32 average_delta);
  298. Timer* resend_que_timer;
  299. };
  300. #endif