9
3

EQStream.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. WAIT_CLOSE,
  42. CLOSING,
  43. DISCONNECTING,
  44. CLOSED
  45. } EQStreamState;
  46. #define FLAG_COMPRESSED 0x01
  47. #define FLAG_ENCODED 0x04
  48. #define RATEBASE 1048576 // 1 MB
  49. #define DECAYBASE 78642 // RATEBASE/10
  50. #ifndef RETRANSMIT_TIMEOUT_MULT
  51. #define RETRANSMIT_TIMEOUT_MULT 3.0
  52. #endif
  53. #ifndef RETRANSMIT_TIMEOUT_MAX
  54. #define RETRANSMIT_TIMEOUT_MAX 5000
  55. #endif
  56. #ifndef AVERAGE_DELTA_MAX
  57. #define AVERAGE_DELTA_MAX 2500
  58. #endif
  59. #pragma pack(1)
  60. struct SessionRequest {
  61. uint32 UnknownA;
  62. uint32 Session;
  63. uint32 MaxLength;
  64. };
  65. struct SessionResponse {
  66. uint32 Session;
  67. uint32 Key;
  68. uint8 UnknownA;
  69. uint8 Format;
  70. uint8 UnknownB;
  71. uint32 MaxLength;
  72. uint32 UnknownD;
  73. };
  74. //Deltas are in ms, representing round trip times
  75. struct ClientSessionStats {
  76. /*000*/ uint16 RequestID;
  77. /*002*/ uint32 last_local_delta;
  78. /*006*/ uint32 average_delta;
  79. /*010*/ uint32 low_delta;
  80. /*014*/ uint32 high_delta;
  81. /*018*/ uint32 last_remote_delta;
  82. /*022*/ uint64 packets_sent;
  83. /*030*/ uint64 packets_recieved;
  84. /*038*/
  85. };
  86. struct ServerSessionStats {
  87. uint16 RequestID;
  88. uint32 current_time;
  89. uint32 unknown1;
  90. uint32 received_packets;
  91. uint32 unknown2;
  92. uint32 sent_packets;
  93. uint32 unknown3;
  94. uint32 sent_packets2;
  95. uint32 unknown4;
  96. uint32 received_packets2;
  97. };
  98. #pragma pack()
  99. class OpcodeManager;
  100. extern OpcodeManager *EQNetworkOpcodeManager;
  101. class EQStreamFactory;
  102. typedef enum {
  103. UnknownStream=0,
  104. LoginStream,
  105. WorldStream,
  106. ZoneStream,
  107. ChatOrMailStream,
  108. ChatStream,
  109. MailStream,
  110. EQ2Stream,
  111. } EQStreamType;
  112. class EQStream {
  113. protected:
  114. typedef enum {
  115. SeqPast,
  116. SeqInOrder,
  117. SeqFuture
  118. } SeqOrder;
  119. uint32 received_packets;
  120. uint32 sent_packets;
  121. uint32 remote_ip;
  122. uint16 remote_port;
  123. uint8 buffer[8192];
  124. unsigned char *oversize_buffer;
  125. uint32 oversize_offset,oversize_length;
  126. unsigned char *rogue_buffer;
  127. uint32 roguebuf_offset,roguebuf_size;
  128. uint8 app_opcode_size;
  129. EQStreamType StreamType;
  130. bool compressed,encoded;
  131. uint32 retransmittimer;
  132. uint32 retransmittimeout;
  133. //uint32 buffer_len;
  134. uint16 sessionAttempts;
  135. uint16 reconnectAttempt;
  136. bool streamactive;
  137. uint32 Session, Key;
  138. uint16 NextInSeq;
  139. uint16 NextOutSeq;
  140. uint16 SequencedBase; //the sequence number of SequencedQueue[0]
  141. uint32 MaxLen;
  142. uint16 MaxSends;
  143. int8 timeout_delays;
  144. uint8 active_users; //how many things are actively using this
  145. Mutex MInUse;
  146. #ifdef WRITE_PACKETS
  147. FILE* write_packets = NULL;
  148. char GetChar(uchar in);
  149. void WriteToFile(char* pFormat, ...);
  150. void WritePackets(const char* opcodeName, uchar* data, int32 size, bool outgoing);
  151. void WritePackets(EQ2Packet* app, bool outgoing);
  152. Mutex MWritePackets;
  153. #endif
  154. EQStreamState State;
  155. Mutex MState;
  156. uint32 LastPacket;
  157. Mutex MVarlock;
  158. EQApplicationPacket* CombinedAppPacket;
  159. Mutex MCombinedAppPacket;
  160. long LastSeqSent;
  161. Mutex MLastSeqSent;
  162. void SetLastSeqSent(uint32);
  163. // Ack sequence tracking.
  164. long MaxAckReceived,NextAckToSend,LastAckSent;
  165. long GetMaxAckReceived();
  166. long GetNextAckToSend();
  167. long GetLastAckSent();
  168. void SetMaxAckReceived(uint32 seq);
  169. void SetNextAckToSend(uint32);
  170. void SetLastAckSent(uint32);
  171. Mutex MAcks;
  172. // Packets waiting to be sent
  173. queue<EQProtocolPacket*> NonSequencedQueue;
  174. deque<EQProtocolPacket*> SequencedQueue;
  175. map<uint16, EQProtocolPacket *> OutOfOrderpackets;
  176. Mutex MOutboundQueue;
  177. // Packes waiting to be processed
  178. deque<EQApplicationPacket *> InboundQueue;
  179. Mutex MInboundQueue;
  180. static uint16 MaxWindowSize;
  181. sint32 BytesWritten;
  182. Mutex MRate;
  183. sint32 RateThreshold;
  184. sint32 DecayRate;
  185. uint32 AverageDelta;
  186. EQStreamFactory *Factory;
  187. public:
  188. Mutex MCombineQueueLock;
  189. bool CheckCombineQueue();
  190. deque<EQ2Packet*> combine_queue;
  191. Timer* combine_timer;
  192. Crypto* crypto;
  193. int8 EQ2_Compress(EQ2Packet* app, int8 offset = 3);
  194. z_stream stream;
  195. uchar* stream_buffer;
  196. int32 stream_buffer_size;
  197. bool eq2_compressed;
  198. int8 compressed_offset;
  199. int16 client_version;
  200. int16 GetClientVersion(){ return client_version; }
  201. void SetClientVersion(int16 version){ client_version = version; }
  202. void ResetSessionAttempts() { reconnectAttempt = 0; }
  203. bool HasSessionAttempts() { return reconnectAttempt>0; }
  204. EQStream() { init(); remote_ip = 0; remote_port = 0; State = CLOSED; StreamType = UnknownStream; compressed = true;
  205. encoded = false; app_opcode_size = 2;}
  206. EQStream(sockaddr_in addr);
  207. virtual ~EQStream() {
  208. MOutboundQueue.lock();
  209. SetState(CLOSED);
  210. MOutboundQueue.unlock();
  211. RemoveData();
  212. safe_delete(crypto);
  213. safe_delete(combine_timer);
  214. safe_delete(resend_que_timer);
  215. safe_delete_array(oversize_buffer);
  216. safe_delete_array(rogue_buffer);
  217. deque<EQ2Packet*>::iterator cmb;
  218. MCombineQueueLock.lock();
  219. for (cmb = combine_queue.begin(); cmb != combine_queue.end(); cmb++){
  220. safe_delete(*cmb);
  221. }
  222. MCombineQueueLock.unlock();
  223. deflateEnd(&stream);
  224. map<int16, EQProtocolPacket*>::iterator oop;
  225. for (oop = OutOfOrderpackets.begin(); oop != OutOfOrderpackets.end(); oop++){
  226. safe_delete(oop->second);
  227. }
  228. #ifdef WRITE_PACKETS
  229. if (write_packets)
  230. fclose(write_packets);
  231. #endif
  232. }
  233. inline void SetFactory(EQStreamFactory *f) { Factory=f; }
  234. void init(bool resetSession = true);
  235. void SetMaxLen(uint32 length) { MaxLen=length; }
  236. int8 getTimeoutDelays(){ return timeout_delays; }
  237. void addTimeoutDelay(){ timeout_delays++; }
  238. void EQ2QueuePacket(EQ2Packet* app, bool attempted_combine = false);
  239. void PreparePacket(EQ2Packet* app, int8 offset = 0);
  240. void UnPreparePacket(EQ2Packet* app);
  241. void EncryptPacket(EQ2Packet* app, int8 compress_offset, int8 offset);
  242. void FlushCombinedPacket();
  243. void SendPacket(EQApplicationPacket *p);
  244. void QueuePacket(EQProtocolPacket *p);
  245. void SendPacket(EQProtocolPacket *p);
  246. vector<EQProtocolPacket *> convert(EQApplicationPacket *p);
  247. void NonSequencedPush(EQProtocolPacket *p);
  248. void SequencedPush(EQProtocolPacket *p);
  249. Mutex MResendQue;
  250. Mutex MCompressData;
  251. deque<EQProtocolPacket*>resend_que;
  252. void CheckResend(int eq_fd);
  253. void AckPackets(uint16 seq);
  254. void Write(int eq_fd);
  255. void SetActive(bool val) { streamactive = val; }
  256. void WritePacket(int fd,EQProtocolPacket *p);
  257. void EncryptPacket(uchar* data, int16 size);
  258. uint32 GetKey() { return Key; }
  259. void SetKey(uint32 k) { Key=k; }
  260. void SetSession(uint32 s) { Session=s; }
  261. void SetLastPacketTime(uint32 t) {LastPacket=t;}
  262. void Process(const unsigned char *data, const uint32 length);
  263. void ProcessPacket(EQProtocolPacket *p, EQProtocolPacket* lastp=NULL);
  264. bool ProcessEmbeddedPacket(uchar* pBuffer, uint16 length, int8 opcode = OP_Packet);
  265. bool HandleEmbeddedPacket(EQProtocolPacket *p, int16 offset = 2, int16 length = 0);
  266. EQProtocolPacket * ProcessEncryptedPacket(EQProtocolPacket *p);
  267. EQProtocolPacket * ProcessEncryptedData(uchar* data, int32 size, int16 opcode);
  268. virtual void DispatchPacket(EQApplicationPacket *p) { p->DumpRaw(); }
  269. void SendSessionResponse();
  270. void SendSessionRequest();
  271. void SendDisconnect(bool setstate = true);
  272. void SendAck(uint16 seq);
  273. void SendOutOfOrderAck(uint16 seq);
  274. bool CheckTimeout(uint32 now, uint32 timeout=30) { return (LastPacket && (now-LastPacket) > timeout); }
  275. bool Stale(uint32 now, uint32 timeout=30) { return (LastPacket && (now-LastPacket) > timeout); }
  276. void InboundQueuePush(EQApplicationPacket *p);
  277. EQApplicationPacket *PopPacket(); // InboundQueuePop
  278. void InboundQueueClear();
  279. void OutboundQueueClear();
  280. bool HasOutgoingData();
  281. void SendKeyRequest();
  282. int16 processRSAKey(EQProtocolPacket *p, uint16 subpacket_length = 0);
  283. void RemoveData() { InboundQueueClear(); OutboundQueueClear(); if (CombinedAppPacket) delete CombinedAppPacket; }
  284. //
  285. inline bool IsInUse() { bool flag; MInUse.lock(); flag=(active_users>0); MInUse.unlock(); return flag; }
  286. inline void PutInUse() { MInUse.lock(); active_users++; MInUse.unlock(); }
  287. inline void ReleaseFromUse() { MInUse.lock(); if(active_users > 0) active_users--; MInUse.unlock(); }
  288. static SeqOrder CompareSequence(uint16 expected_seq, uint16 seq);
  289. inline EQStreamState GetState() { return State; }
  290. inline void SetState(EQStreamState state) { MState.lock(); State = state; MState.unlock(); }
  291. inline uint32 GetRemoteIP() { return remote_ip; }
  292. inline uint32 GetrIP() { return remote_ip; }
  293. inline uint16 GetRemotePort() { return remote_port; }
  294. inline uint16 GetrPort() { return remote_port; }
  295. static EQProtocolPacket *Read(int eq_fd, sockaddr_in *from);
  296. void Close() { SendDisconnect(); }
  297. bool CheckActive() { return (GetState()==ESTABLISHED); }
  298. bool CheckClosed() { return GetState()==CLOSED; }
  299. void SetOpcodeSize(uint8 s) { app_opcode_size = s; }
  300. void SetStreamType(EQStreamType t);
  301. inline const EQStreamType GetStreamType() const { return StreamType; }
  302. void ProcessQueue();
  303. EQProtocolPacket* RemoveQueue(uint16 seq);
  304. void Decay();
  305. void AdjustRates(uint32 average_delta);
  306. Timer* resend_que_timer;
  307. };
  308. #endif