EQStream.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. unsigned char *rogue_buffer;
  126. uint32 roguebuf_offset,roguebuf_size;
  127. uint8 app_opcode_size;
  128. EQStreamType StreamType;
  129. bool compressed,encoded;
  130. uint32 retransmittimer;
  131. uint32 retransmittimeout;
  132. //uint32 buffer_len;
  133. uint16 sessionAttempts;
  134. bool streamactive;
  135. uint32 Session, Key;
  136. uint16 NextInSeq;
  137. uint16 NextOutSeq;
  138. uint16 SequencedBase; //the sequence number of SequencedQueue[0]
  139. uint32 MaxLen;
  140. uint16 MaxSends;
  141. int8 timeout_delays;
  142. uint8 active_users; //how many things are actively using this
  143. Mutex MInUse;
  144. #ifdef WRITE_PACKETS
  145. FILE* write_packets = NULL;
  146. char GetChar(uchar in);
  147. void WriteToFile(char* pFormat, ...);
  148. void WritePackets(const char* opcodeName, uchar* data, int32 size, bool outgoing);
  149. void WritePackets(EQ2Packet* app, bool outgoing);
  150. Mutex MWritePackets;
  151. #endif
  152. EQStreamState State;
  153. Mutex MState;
  154. uint32 LastPacket;
  155. Mutex MVarlock;
  156. EQApplicationPacket* CombinedAppPacket;
  157. Mutex MCombinedAppPacket;
  158. long LastSeqSent;
  159. Mutex MLastSeqSent;
  160. void SetLastSeqSent(uint32);
  161. // Ack sequence tracking.
  162. long MaxAckReceived,NextAckToSend,LastAckSent;
  163. long GetMaxAckReceived();
  164. long GetNextAckToSend();
  165. long GetLastAckSent();
  166. void SetMaxAckReceived(uint32 seq);
  167. void SetNextAckToSend(uint32);
  168. void SetLastAckSent(uint32);
  169. Mutex MAcks;
  170. // Packets waiting to be sent
  171. queue<EQProtocolPacket*> NonSequencedQueue;
  172. deque<EQProtocolPacket*> SequencedQueue;
  173. map<uint16, EQProtocolPacket *> OutOfOrderpackets;
  174. Mutex MOutboundQueue;
  175. // Packes waiting to be processed
  176. deque<EQApplicationPacket *> InboundQueue;
  177. Mutex MInboundQueue;
  178. static uint16 MaxWindowSize;
  179. sint32 BytesWritten;
  180. Mutex MRate;
  181. sint32 RateThreshold;
  182. sint32 DecayRate;
  183. uint32 AverageDelta;
  184. EQStreamFactory *Factory;
  185. public:
  186. Mutex MCombineQueueLock;
  187. bool CheckCombineQueue();
  188. deque<EQ2Packet*> combine_queue;
  189. Timer* combine_timer;
  190. Crypto* crypto;
  191. int8 EQ2_Compress(EQ2Packet* app, int8 offset = 3);
  192. z_stream stream;
  193. uchar* stream_buffer;
  194. int32 stream_buffer_size;
  195. bool eq2_compressed;
  196. int8 compressed_offset;
  197. int16 client_version;
  198. int16 GetClientVersion(){ return client_version; }
  199. void SetClientVersion(int16 version){ client_version = version; }
  200. EQStream() { init(); remote_ip = 0; remote_port = 0; State = CLOSED; StreamType = UnknownStream; compressed = true;
  201. encoded = false; app_opcode_size = 2;}
  202. EQStream(sockaddr_in addr);
  203. virtual ~EQStream() {
  204. MOutboundQueue.lock();
  205. SetState(CLOSED);
  206. MOutboundQueue.unlock();
  207. RemoveData();
  208. safe_delete(crypto);
  209. safe_delete(combine_timer);
  210. safe_delete(resend_que_timer);
  211. safe_delete_array(oversize_buffer);
  212. safe_delete_array(rogue_buffer);
  213. deque<EQ2Packet*>::iterator cmb;
  214. MCombineQueueLock.lock();
  215. for (cmb = combine_queue.begin(); cmb != combine_queue.end(); cmb++){
  216. safe_delete(*cmb);
  217. }
  218. MCombineQueueLock.unlock();
  219. deflateEnd(&stream);
  220. map<int16, EQProtocolPacket*>::iterator oop;
  221. for (oop = OutOfOrderpackets.begin(); oop != OutOfOrderpackets.end(); oop++){
  222. safe_delete(oop->second);
  223. }
  224. #ifdef WRITE_PACKETS
  225. if (write_packets)
  226. fclose(write_packets);
  227. #endif
  228. }
  229. inline void SetFactory(EQStreamFactory *f) { Factory=f; }
  230. void init(bool resetSession = true);
  231. void SetMaxLen(uint32 length) { MaxLen=length; }
  232. int8 getTimeoutDelays(){ return timeout_delays; }
  233. void addTimeoutDelay(){ timeout_delays++; }
  234. void EQ2QueuePacket(EQ2Packet* app, bool attempted_combine = false);
  235. void PreparePacket(EQ2Packet* app, int8 offset = 0);
  236. void UnPreparePacket(EQ2Packet* app);
  237. void EncryptPacket(EQ2Packet* app, int8 compress_offset, int8 offset);
  238. void FlushCombinedPacket();
  239. void SendPacket(EQApplicationPacket *p);
  240. void QueuePacket(EQProtocolPacket *p);
  241. void SendPacket(EQProtocolPacket *p);
  242. vector<EQProtocolPacket *> convert(EQApplicationPacket *p);
  243. void NonSequencedPush(EQProtocolPacket *p);
  244. void SequencedPush(EQProtocolPacket *p);
  245. Mutex MResendQue;
  246. Mutex MCompressData;
  247. deque<EQProtocolPacket*>resend_que;
  248. void CheckResend(int eq_fd);
  249. void AckPackets(uint16 seq);
  250. void Write(int eq_fd);
  251. void SetActive(bool val) { streamactive = val; }
  252. void WritePacket(int fd,EQProtocolPacket *p);
  253. void EncryptPacket(uchar* data, int16 size);
  254. uint32 GetKey() { return Key; }
  255. void SetKey(uint32 k) { Key=k; }
  256. void SetSession(uint32 s) { Session=s; }
  257. void SetLastPacketTime(uint32 t) {LastPacket=t;}
  258. void Process(const unsigned char *data, const uint32 length);
  259. void ProcessPacket(EQProtocolPacket *p, EQProtocolPacket* lastp=NULL);
  260. bool HandleEmbeddedPacket(EQProtocolPacket *p, int16 offset = 2, int16 length = 0);
  261. EQProtocolPacket * ProcessEncryptedPacket(EQProtocolPacket *p);
  262. EQProtocolPacket * ProcessEncryptedData(uchar* data, int32 size, int16 opcode);
  263. virtual void DispatchPacket(EQApplicationPacket *p) { p->DumpRaw(); }
  264. void SendSessionResponse();
  265. void SendSessionRequest();
  266. void SendDisconnect(bool setstate = true);
  267. void SendAck(uint16 seq);
  268. void SendOutOfOrderAck(uint16 seq);
  269. bool CheckTimeout(uint32 now, uint32 timeout=30) { return (LastPacket && (now-LastPacket) > timeout); }
  270. bool Stale(uint32 now, uint32 timeout=30) { return (LastPacket && (now-LastPacket) > timeout); }
  271. void InboundQueuePush(EQApplicationPacket *p);
  272. EQApplicationPacket *PopPacket(); // InboundQueuePop
  273. void InboundQueueClear();
  274. void OutboundQueueClear();
  275. bool HasOutgoingData();
  276. void SendKeyRequest();
  277. int16 processRSAKey(EQProtocolPacket *p);
  278. void RemoveData() { InboundQueueClear(); OutboundQueueClear(); if (CombinedAppPacket) delete CombinedAppPacket; }
  279. //
  280. inline bool IsInUse() { bool flag; MInUse.lock(); flag=(active_users>0); MInUse.unlock(); return flag; }
  281. inline void PutInUse() { MInUse.lock(); active_users++; MInUse.unlock(); }
  282. inline void ReleaseFromUse() { MInUse.lock(); if(active_users > 0) active_users--; MInUse.unlock(); }
  283. static SeqOrder CompareSequence(uint16 expected_seq, uint16 seq);
  284. inline EQStreamState GetState() { return State; }
  285. inline void SetState(EQStreamState state) { MState.lock(); State = state; MState.unlock(); }
  286. inline uint32 GetRemoteIP() { return remote_ip; }
  287. inline uint32 GetrIP() { return remote_ip; }
  288. inline uint16 GetRemotePort() { return remote_port; }
  289. inline uint16 GetrPort() { return remote_port; }
  290. static EQProtocolPacket *Read(int eq_fd, sockaddr_in *from);
  291. void Close() { SendDisconnect(); }
  292. bool CheckActive() { return GetState()==ESTABLISHED; }
  293. bool CheckClosed() { return GetState()==CLOSED; }
  294. void SetOpcodeSize(uint8 s) { app_opcode_size = s; }
  295. void SetStreamType(EQStreamType t);
  296. inline const EQStreamType GetStreamType() const { return StreamType; }
  297. void ProcessQueue();
  298. EQProtocolPacket* RemoveQueue(uint16 seq);
  299. void Decay();
  300. void AdjustRates(uint32 average_delta);
  301. Timer* resend_que_timer;
  302. };
  303. #endif