9
3

EQStream.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  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. #ifdef WIN32
  17. #include <WinSock2.h>
  18. #include <windows.h>
  19. #endif
  20. #include "debug.h"
  21. #include <string>
  22. #include <iomanip>
  23. #include <iostream>
  24. #include <vector>
  25. #include <time.h>
  26. #include <sys/types.h>
  27. #ifdef WIN32
  28. #include <time.h>
  29. #else
  30. #include <sys/socket.h>
  31. #include <netinet/in.h>
  32. #include <sys/time.h>
  33. #include <sys/socket.h>
  34. #include <netdb.h>
  35. #include <fcntl.h>
  36. #include <arpa/inet.h>
  37. #endif
  38. #include "EQPacket.h"
  39. #include "EQStream.h"
  40. #include "EQStreamFactory.h"
  41. #include "misc.h"
  42. #include "Mutex.h"
  43. #include "op_codes.h"
  44. #include "CRC16.h"
  45. #include "packet_dump.h"
  46. #ifdef LOGIN
  47. #include "../LoginServer/login_structs.h"
  48. #endif
  49. #include "EQ2_Common_Structs.h"
  50. #include "Log.h"
  51. uint16 EQStream::MaxWindowSize=2048;
  52. void EQStream::init(bool resetSession) {
  53. if (resetSession)
  54. {
  55. streamactive = false;
  56. sessionAttempts = 0;
  57. }
  58. timeout_delays = 0;
  59. MInUse.lock();
  60. active_users = 0;
  61. MInUse.unlock();
  62. Session=0;
  63. Key=0;
  64. MaxLen=0;
  65. NextInSeq=0;
  66. NextOutSeq=0;
  67. CombinedAppPacket=NULL;
  68. MAcks.lock();
  69. MaxAckReceived = -1;
  70. NextAckToSend = -1;
  71. LastAckSent = -1;
  72. MAcks.unlock();
  73. LastSeqSent=-1;
  74. MaxSends=5;
  75. LastPacket=Timer::GetCurrentTime2();
  76. oversize_buffer=NULL;
  77. oversize_length=0;
  78. oversize_offset=0;
  79. Factory = NULL;
  80. rogue_buffer=NULL;
  81. roguebuf_offset=0;
  82. roguebuf_size=0;
  83. MRate.lock();
  84. RateThreshold=RATEBASE/250;
  85. DecayRate=DECAYBASE/250;
  86. MRate.unlock();
  87. BytesWritten=0;
  88. SequencedBase = 0;
  89. AverageDelta = 500;
  90. crypto->setRC4Key(0);
  91. retransmittimer = Timer::GetCurrentTime2();
  92. retransmittimeout = 500 * RETRANSMIT_TIMEOUT_MULT;
  93. reconnectAttempt = 0;
  94. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  95. LogWrite(PACKET__DEBUG, 9, "Packet", "init Invalid Sequenced queue: BS %u + SQ %u != NOS %u", SequencedBase, SequencedQueue.size(), NextOutSeq);
  96. }
  97. }
  98. EQStream::EQStream(sockaddr_in addr){
  99. crypto = new Crypto();
  100. resend_que_timer = new Timer(1000);
  101. combine_timer = new Timer(250); //250 milliseconds
  102. combine_timer->Start();
  103. resend_que_timer->Start();
  104. init();
  105. remote_ip=addr.sin_addr.s_addr;
  106. remote_port=addr.sin_port;
  107. State=CLOSED;
  108. StreamType=UnknownStream;
  109. compressed=true;
  110. encoded=false;
  111. app_opcode_size=2;
  112. #ifdef WIN32
  113. ZeroMemory(&stream, sizeof(z_stream));
  114. #else
  115. bzero(&stream, sizeof(z_stream));
  116. #endif
  117. stream.zalloc = (alloc_func)0;
  118. stream.zfree = (free_func)0;
  119. stream.opaque = (voidpf)0;
  120. deflateInit2(&stream, 9, Z_DEFLATED, 13, 9, Z_DEFAULT_STRATEGY);
  121. //deflateInit(&stream, 5);
  122. compressed_offset = 0;
  123. client_version = 0;
  124. received_packets = 0;
  125. sent_packets = 0;
  126. #ifdef WRITE_PACKETS
  127. write_packets = 0;
  128. char write_packets_filename[64];
  129. snprintf(write_packets_filename, sizeof(write_packets_filename), "PacketLog%i.log", Timer::GetCurrentTime2());
  130. write_packets = fopen(write_packets_filename, "w+");
  131. #endif
  132. }
  133. EQProtocolPacket* EQStream::ProcessEncryptedData(uchar* data, int32 size, int16 opcode){
  134. //cout << "B4:\n";
  135. //DumpPacket(data, size);
  136. /*if(size >= 2 && data[0] == 0 && data[1] == 0){
  137. cout << "Attempting to fix packet!\n";
  138. //Have to fix bad packet from client or it will screw up encryption :P
  139. size--;
  140. data++;
  141. }*/
  142. crypto->RC4Decrypt(data,size);
  143. int8 offset = 0;
  144. if(data[0] == 0xFF && size > 2){
  145. offset = 3;
  146. memcpy(&opcode, data+sizeof(int8), sizeof(int16));
  147. }
  148. else{
  149. offset = 1;
  150. memcpy(&opcode, data, sizeof(int8));
  151. }
  152. //cout << "After:\n";
  153. //DumpPacket(data, size);
  154. return new EQProtocolPacket(opcode, data+offset, size - offset);
  155. }
  156. EQProtocolPacket* EQStream::ProcessEncryptedPacket(EQProtocolPacket *p){
  157. EQProtocolPacket* ret = NULL;
  158. if(p->opcode == OP_Packet && p->size > 2)
  159. ret = ProcessEncryptedData(p->pBuffer+2, p->size-2, p->opcode);
  160. else
  161. ret = ProcessEncryptedData(p->pBuffer, p->size, p->opcode);
  162. return ret;
  163. }
  164. bool EQStream::HandleEmbeddedPacket(EQProtocolPacket *p, int16 offset, int16 length){
  165. if(p && p->size >= ((uint32)(offset+2))){
  166. if(p->pBuffer[offset] == 0 && p->pBuffer[offset+1] == 0x19){
  167. if(length == 0)
  168. length = p->size-2-offset;
  169. else
  170. length-=2;
  171. #ifdef LE_DEBUG
  172. printf( "Creating OP_AppCombined Packet!\n");
  173. #endif
  174. EQProtocolPacket *subp=new EQProtocolPacket(OP_AppCombined, p->pBuffer+2+offset, length);
  175. subp->copyInfo(p);
  176. ProcessPacket(subp, p);
  177. safe_delete(subp);
  178. return true;
  179. }
  180. else if (p->pBuffer[offset] == 0 && p->pBuffer[offset + 1] == 0) {
  181. if (length == 0)
  182. length = p->size - 1 - offset;
  183. else
  184. length--;
  185. #ifdef LE_DEBUG
  186. LogWrite(PACKET__DEBUG, 0, "Packet", "Creating Opcode 0 Packet!");
  187. DumpPacket(p->pBuffer + 1 + offset, length);
  188. #endif
  189. EQProtocolPacket* newpacket = ProcessEncryptedData(p->pBuffer + 1 + offset, length, OP_Packet);
  190. if (newpacket) {
  191. #ifdef LE_DEBUG
  192. LogWrite(PACKET__DEBUG, 0, "Packet", "Result: ");
  193. DumpPacket(newpacket);
  194. #endif
  195. EQApplicationPacket* ap = newpacket->MakeApplicationPacket(2);
  196. if (ap->version == 0)
  197. ap->version = client_version;
  198. InboundQueuePush(ap);
  199. #ifdef WRITE_PACKETS
  200. WritePackets(ap->GetOpcodeName(), p->pBuffer + 1 + offset, length, false);
  201. #endif
  202. safe_delete(newpacket);
  203. }
  204. else
  205. LogWrite(PACKET__ERROR, 0, "Packet", "No Packet!");
  206. return true;
  207. }
  208. }
  209. return false;
  210. }
  211. void EQStream::ProcessPacket(EQProtocolPacket *p, EQProtocolPacket* lastp)
  212. {
  213. uint32 processed=0,subpacket_length=0;
  214. if (p) {
  215. if (p->opcode!=OP_SessionRequest && p->opcode!=OP_SessionResponse && !Session) {
  216. #ifdef EQN_DEBUG
  217. LogWrite(PACKET__ERROR, 0, "Packet", "*** Session not initialized, packet ignored ");
  218. //p->DumpRaw();
  219. #endif
  220. return;
  221. }
  222. //cout << "Received " << (int)p->opcode << ":\n";
  223. //DumpPacket(p->pBuffer, p->size);
  224. switch (p->opcode) {
  225. case OP_Combined: {
  226. processed=0;
  227. int8 offset = 0;
  228. int count = 0;
  229. #ifdef LE_DEBUG
  230. printf( "OP_Combined:\n");
  231. DumpPacket(p);
  232. #endif
  233. while(processed<p->size) {
  234. if ((subpacket_length=(unsigned char)*(p->pBuffer+processed))==0xff) {
  235. subpacket_length = ntohs(*(uint16*)(p->pBuffer + processed + 1));
  236. //printf("OP_Combined subpacket_length %u\n",subpacket_length);
  237. offset = 3;
  238. }
  239. else
  240. offset = 1;
  241. //printf("OP_Combined processed %u p->size %u subpacket length %u count %i\n",processed, p->size, subpacket_length, count);
  242. count++;
  243. #ifdef LE_DEBUG
  244. printf( "OP_Combined Packet %i (%u) (%u):\n", count, subpacket_length, processed);
  245. #endif
  246. bool isSubPacket = EQProtocolPacket::IsProtocolPacket(p->pBuffer + processed + offset, subpacket_length, false);
  247. if (isSubPacket) {
  248. EQProtocolPacket* subp = new EQProtocolPacket(p->pBuffer + processed + offset, subpacket_length);
  249. subp->copyInfo(p);
  250. #ifdef LE_DEBUG
  251. printf( "Opcode %i:\n", subp->opcode);
  252. DumpPacket(subp);
  253. #endif
  254. ProcessPacket(subp, p);
  255. #ifdef LE_DEBUG
  256. DumpPacket(subp);
  257. #endif
  258. delete subp;
  259. }
  260. else if (ntohs(*reinterpret_cast<uint16_t*>(p->pBuffer + processed + offset)) > 0x1e) {
  261. //Garbage packet?
  262. crypto->RC4Decrypt(p->pBuffer + processed + offset, subpacket_length);
  263. LogWrite(PACKET__ERROR, 0, "Packet", "Garbage packet?!:");
  264. printf("!!!!!!!!!Garbage Packet!!!!!!!!!!!!! processed: %u, offset: %u, count: %i\n", processed, offset, count);
  265. if(p->pBuffer[processed + offset] == 0xff)
  266. {
  267. uchar* newbuf = p->pBuffer;
  268. newbuf += processed + offset + 1;
  269. DumpPacket(p->pBuffer + processed + offset, subpacket_length);
  270. EQProtocolPacket *subp=new EQProtocolPacket(newbuf, subpacket_length, OP_Packet);
  271. subp->copyInfo(p);
  272. ProcessPacket(subp, p);
  273. delete subp;
  274. }
  275. else
  276. {
  277. printf("!!!!!!!!!Garbage Packet Unknown DISCARD!!!!!!!!!!!!!\n");
  278. DumpPacket(p->pBuffer + processed + offset, subpacket_length);
  279. break;
  280. }
  281. }
  282. processed+=subpacket_length+offset;
  283. }
  284. break;
  285. }
  286. case OP_AppCombined: {
  287. processed=0;
  288. EQProtocolPacket* newpacket = 0;
  289. int8 offset = 0;
  290. #ifdef LE_DEBUG
  291. printf( "OP_AppCombined: \n");
  292. DumpPacket(p);
  293. #endif
  294. int count = 0;
  295. while(processed<p->size) {
  296. count++;
  297. if ((subpacket_length=(unsigned char)*(p->pBuffer+processed))==0xff) {
  298. subpacket_length=ntohs(*(uint16 *)(p->pBuffer+processed+1));
  299. offset = 3;
  300. } else
  301. offset = 1;
  302. if(crypto->getRC4Key()==0 && p->size >= 70){
  303. processRSAKey(p);
  304. }
  305. else if(crypto->isEncrypted()){
  306. #ifdef LE_DEBUG
  307. printf( "OP_AppCombined Packet %i (%u) (%u): \n", count, subpacket_length, processed);
  308. DumpPacket(p->pBuffer+processed+offset, subpacket_length);
  309. #endif
  310. if(!HandleEmbeddedPacket(p, processed + offset, subpacket_length)){
  311. #ifdef LE_DEBUG
  312. printf( "OP_AppCombined Here:\n");
  313. #endif
  314. MCombineQueueLock.lock();
  315. newpacket = ProcessEncryptedData(p->pBuffer+processed + offset, subpacket_length, OP_AppCombined);
  316. MCombineQueueLock.unlock();
  317. if(newpacket){
  318. #ifdef LE_DEBUG
  319. printf( "Opcode %i:\n", newpacket->opcode);
  320. DumpPacket(newpacket);
  321. #endif
  322. EQApplicationPacket* ap = newpacket->MakeApplicationPacket(2);
  323. #ifdef LE_DEBUG
  324. printf( "OP_AppCombined Here2:\n");
  325. DumpPacket(ap);
  326. #endif
  327. if (ap->version == 0)
  328. ap->version = client_version;
  329. #ifdef WRITE_PACKETS
  330. WritePackets(ap->GetOpcodeName(), p->pBuffer + processed + offset, subpacket_length, false);
  331. #endif
  332. InboundQueuePush(ap);
  333. safe_delete(newpacket);
  334. }
  335. }
  336. }
  337. processed+=subpacket_length+offset;
  338. }
  339. }
  340. break;
  341. case OP_Packet: {
  342. if (!p->pBuffer || (p->Size() < 4))
  343. {
  344. break;
  345. }
  346. uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
  347. sint8 check=CompareSequence(NextInSeq,seq);
  348. if (check == SeqFuture) {
  349. #ifdef EQN_DEBUG
  350. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Future packet: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  351. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  352. p->DumpRawHeader(seq);
  353. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  354. #endif
  355. OutOfOrderpackets[seq] = p->Copy();
  356. // Image (2020): Removed as this is bad contributes to infinite loop
  357. //SendOutOfOrderAck(seq);
  358. } else if (check == SeqPast) {
  359. #ifdef EQN_DEBUG
  360. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Duplicate packet: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  361. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  362. p->DumpRawHeader(seq);
  363. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  364. #endif
  365. // Image (2020): Removed as this is bad contributes to infinite loop
  366. //OutOfOrderpackets[seq] = p->Copy();
  367. SendOutOfOrderAck(seq);
  368. } else {
  369. EQProtocolPacket* qp = RemoveQueue(seq);
  370. if (qp) {
  371. LogWrite(PACKET__DEBUG, 1, "Packet", "OP_Fragment: Removing older queued packet with sequence %i", seq);
  372. delete qp;
  373. }
  374. SetNextAckToSend(seq);
  375. NextInSeq++;
  376. if(HandleEmbeddedPacket(p))
  377. break;
  378. if(crypto->getRC4Key()==0 && p && p->size >= 70){
  379. processRSAKey(p);
  380. }
  381. else if(crypto->isEncrypted() && p){
  382. MCombineQueueLock.lock();
  383. EQProtocolPacket* newpacket = ProcessEncryptedPacket(p);
  384. MCombineQueueLock.unlock();
  385. if(newpacket){
  386. EQApplicationPacket* ap = newpacket->MakeApplicationPacket(2);
  387. if (ap->version == 0)
  388. ap->version = client_version;
  389. #ifdef WRITE_PACKETS
  390. WritePackets(ap->GetOpcodeName(), p->pBuffer, p->size, false);
  391. #endif
  392. InboundQueuePush(ap);
  393. safe_delete(newpacket);
  394. }
  395. }
  396. }
  397. }
  398. break;
  399. case OP_Fragment: {
  400. if (!p->pBuffer || (p->Size() < 4))
  401. {
  402. break;
  403. }
  404. uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
  405. sint8 check=CompareSequence(NextInSeq,seq);
  406. if (check == SeqFuture) {
  407. #ifdef EQN_DEBUG
  408. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Future packet2: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  409. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  410. //p->DumpRawHeader(seq);
  411. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  412. #endif
  413. OutOfOrderpackets[seq] = p->Copy();
  414. //SendOutOfOrderAck(seq);
  415. } else if (check == SeqPast) {
  416. #ifdef EQN_DEBUG
  417. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Duplicate packet2: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  418. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  419. //p->DumpRawHeader(seq);
  420. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  421. #endif
  422. //OutOfOrderpackets[seq] = p->Copy();
  423. SendOutOfOrderAck(seq);
  424. } else {
  425. // In case we did queue one before as well.
  426. EQProtocolPacket* qp = RemoveQueue(seq);
  427. if (qp) {
  428. LogWrite(PACKET__DEBUG, 1, "Packet", "OP_Fragment: Removing older queued packet with sequence %i", seq);
  429. delete qp;
  430. }
  431. SetNextAckToSend(seq);
  432. NextInSeq++;
  433. if (oversize_buffer) {
  434. memcpy(oversize_buffer+oversize_offset,p->pBuffer+2,p->size-2);
  435. oversize_offset+=p->size-2;
  436. //cout << "Oversized is " << oversize_offset << "/" << oversize_length << " (" << (p->size-2) << ") Seq=" << seq << endl;
  437. if (oversize_offset==oversize_length) {
  438. if (*(p->pBuffer+2)==0x00 && *(p->pBuffer+3)==0x19) {
  439. EQProtocolPacket *subp=new EQProtocolPacket(oversize_buffer,oversize_offset);
  440. subp->copyInfo(p);
  441. ProcessPacket(subp, p);
  442. delete subp;
  443. } else {
  444. if(crypto->isEncrypted() && p && p->size > 2){
  445. MCombineQueueLock.lock();
  446. EQProtocolPacket* p2 = ProcessEncryptedData(oversize_buffer, oversize_offset, p->opcode);
  447. MCombineQueueLock.unlock();
  448. EQApplicationPacket* ap = p2->MakeApplicationPacket(2);
  449. ap->copyInfo(p);
  450. if (ap->version == 0)
  451. ap->version = client_version;
  452. #ifdef WRITE_PACKETS
  453. WritePackets(ap->GetOpcodeName(), oversize_buffer, oversize_offset, false);
  454. #endif
  455. ap->copyInfo(p);
  456. InboundQueuePush(ap);
  457. safe_delete(p2);
  458. }
  459. }
  460. delete[] oversize_buffer;
  461. oversize_buffer=NULL;
  462. oversize_offset=0;
  463. }
  464. } else if (!oversize_buffer) {
  465. oversize_length=ntohl(*(uint32 *)(p->pBuffer+2));
  466. oversize_buffer=new unsigned char[oversize_length];
  467. memcpy(oversize_buffer,p->pBuffer+6,p->size-6);
  468. oversize_offset=p->size-6;
  469. //cout << "Oversized is " << oversize_offset << "/" << oversize_length << " (" << (p->size-6) << ") Seq=" << seq << endl;
  470. }
  471. }
  472. }
  473. break;
  474. case OP_KeepAlive: {
  475. #ifndef COLLECTOR
  476. NonSequencedPush(new EQProtocolPacket(p->opcode,p->pBuffer,p->size));
  477. #endif
  478. }
  479. break;
  480. case OP_Ack: {
  481. if (!p->pBuffer || (p->Size() < 4))
  482. {
  483. LogWrite(PACKET__DEBUG, 9, "Packet", "Received OP_Ack that was of malformed size");
  484. break;
  485. }
  486. uint16 seq = ntohs(*(uint16*)(p->pBuffer));
  487. AckPackets(seq);
  488. retransmittimer = Timer::GetCurrentTime2();
  489. }
  490. break;
  491. case OP_SessionRequest: {
  492. if (p->Size() < sizeof(SessionRequest))
  493. {
  494. break;
  495. }
  496. if (GetState() == ESTABLISHED) {
  497. //_log(NET__ERROR, _L "Received OP_SessionRequest in ESTABLISHED state (%d) streamactive (%i) attempt (%i)" __L, GetState(), streamactive, sessionAttempts);
  498. // client seems to try a max of 4 times (initial +3 retries) then gives up, giving it a few more attempts just in case
  499. // streamactive means we identified the opcode, we cannot re-establish this connection
  500. if (streamactive || (sessionAttempts > 30))
  501. {
  502. SendDisconnect(false);
  503. SetState(CLOSED);
  504. break;
  505. }
  506. }
  507. sessionAttempts++;
  508. if(GetState() == WAIT_CLOSE) {
  509. printf("WAIT_CLOSE Reconnect with streamactive %u, sessionAttempts %u\n", streamactive, sessionAttempts);
  510. reconnectAttempt++;
  511. }
  512. init(GetState() != ESTABLISHED);
  513. OutboundQueueClear();
  514. SessionRequest *Request=(SessionRequest *)p->pBuffer;
  515. Session=ntohl(Request->Session);
  516. SetMaxLen(ntohl(Request->MaxLength));
  517. #ifndef COLLECTOR
  518. NextInSeq=0;
  519. Key=0x33624702;
  520. SendSessionResponse();
  521. #endif
  522. SetState(ESTABLISHED);
  523. }
  524. break;
  525. case OP_SessionResponse: {
  526. if (p->Size() < sizeof(SessionResponse))
  527. {
  528. break;
  529. }
  530. init();
  531. OutboundQueueClear();
  532. SetActive(true);
  533. SessionResponse *Response=(SessionResponse *)p->pBuffer;
  534. SetMaxLen(ntohl(Response->MaxLength));
  535. Key=ntohl(Response->Key);
  536. NextInSeq=0;
  537. SetState(ESTABLISHED);
  538. if (!Session)
  539. Session=ntohl(Response->Session);
  540. compressed=(Response->Format&FLAG_COMPRESSED);
  541. encoded=(Response->Format&FLAG_ENCODED);
  542. // Kinda kludgy, but trie for now
  543. if (compressed) {
  544. if (remote_port==9000 || (remote_port==0 && p->src_port==9000))
  545. SetStreamType(WorldStream);
  546. else
  547. SetStreamType(ZoneStream);
  548. } else if (encoded)
  549. SetStreamType(ChatOrMailStream);
  550. else
  551. SetStreamType(LoginStream);
  552. }
  553. break;
  554. case OP_SessionDisconnect: {
  555. //NextInSeq=0;
  556. SendDisconnect();
  557. //SetState(CLOSED);
  558. }
  559. break;
  560. case OP_OutOfOrderAck: {
  561. if (!p->pBuffer || (p->Size() < 4))
  562. {
  563. LogWrite(PACKET__DEBUG, 9, "Packet", "Received OP_OutOfOrderAck that was of malformed size");
  564. break;
  565. }
  566. uint16 seq = ntohs(*(uint16*)(p->pBuffer));
  567. MOutboundQueue.lock();
  568. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  569. LogWrite(PACKET__DEBUG, 9, "Packet", "Pre-OOA Invalid Sequenced queue: BS %u + SQ %u != NOS %u", SequencedBase, SequencedQueue.size(), NextOutSeq);
  570. }
  571. //if the packet they got out of order is between our last acked packet and the last sent packet, then its valid.
  572. if (CompareSequence(SequencedBase, seq) != SeqPast && CompareSequence(NextOutSeq, seq) == SeqPast) {
  573. uint16 sqsize = SequencedQueue.size();
  574. uint16 index = seq - SequencedBase;
  575. LogWrite(PACKET__DEBUG, 9, "Packet", "OP_OutOfOrderAck marking packet acked in queue (queue index = %u, queue size = %u)", index, sqsize);
  576. if (index < sqsize) {
  577. SequencedQueue[index]->acked = true;
  578. // flag packets for a resend
  579. uint16 count = 0;
  580. uint32 timeout = AverageDelta * 2 + 100;
  581. for (auto sitr = SequencedQueue.begin(); sitr != SequencedQueue.end() && count < index; ++sitr, ++count) {
  582. if (!(*sitr)->acked && (*sitr)->sent_time > 0 && (((*sitr)->sent_time + timeout) < Timer::GetCurrentTime2())) {
  583. (*sitr)->sent_time = 0;
  584. LogWrite(PACKET__DEBUG, 9, "Packet", "OP_OutOfOrderAck Flagging packet %u for retransmission", SequencedBase + count);
  585. }
  586. }
  587. }
  588. if (RETRANSMIT_TIMEOUT_MULT) {
  589. retransmittimer = Timer::GetCurrentTime2();
  590. }
  591. }
  592. else {
  593. LogWrite(PACKET__DEBUG, 9, "Packet", "Received OP_OutOfOrderAck for out-of-window %u. Window (%u->%u)", seq, SequencedBase, NextOutSeq);
  594. }
  595. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  596. LogWrite(PACKET__DEBUG, 9, "Packet", "Post-OOA Invalid Sequenced queue: BS %u + SQ %u != NOS %u", SequencedBase, SequencedQueue.size(), NextOutSeq);
  597. }
  598. MOutboundQueue.unlock();
  599. }
  600. break;
  601. case OP_ServerKeyRequest:{
  602. if (p->Size() < sizeof(ClientSessionStats))
  603. {
  604. //_log(NET__ERROR, _L "Received OP_SessionStatRequest that was of malformed size" __L);
  605. break;
  606. }
  607. ClientSessionStats* Stats = (ClientSessionStats*)p->pBuffer;
  608. int16 request_id = Stats->RequestID;
  609. AdjustRates(ntohl(Stats->average_delta));
  610. ServerSessionStats* stats=(ServerSessionStats*)p->pBuffer;
  611. memset(stats, 0, sizeof(ServerSessionStats));
  612. stats->RequestID = request_id;
  613. stats->current_time = ntohl(Timer::GetCurrentTime2());
  614. stats->sent_packets = ntohl(sent_packets);
  615. stats->sent_packets2 = ntohl(sent_packets);
  616. stats->received_packets = ntohl(received_packets);
  617. stats->received_packets2 = ntohl(received_packets);
  618. NonSequencedPush(new EQProtocolPacket(OP_SessionStatResponse,p->pBuffer,p->size));
  619. if(!crypto->isEncrypted())
  620. SendKeyRequest();
  621. else
  622. SendSessionResponse();
  623. }
  624. break;
  625. case OP_SessionStatResponse: {
  626. LogWrite(PACKET__INFO, 0, "Packet", "OP_SessionStatResponse");
  627. }
  628. break;
  629. case OP_OutOfSession: {
  630. LogWrite(PACKET__INFO, 0, "Packet", "OP_OutOfSession");
  631. SendDisconnect();
  632. SetState(CLOSED);
  633. }
  634. break;
  635. default:
  636. //EQApplicationPacket *ap = p->MakeApplicationPacket(app_opcode_size);
  637. //InboundQueuePush(ap);
  638. cout << "Orig Packet: " << p->opcode << endl;
  639. DumpPacket(p->pBuffer, p->size);
  640. if(p && p->size >= 70){
  641. processRSAKey(p);
  642. }
  643. MCombineQueueLock.lock();
  644. EQProtocolPacket* p2 = ProcessEncryptedData(p->pBuffer, p->size, OP_Packet);
  645. MCombineQueueLock.unlock();
  646. cout << "Decrypted Packet: " << p2->opcode << endl;
  647. DumpPacket(p2->pBuffer, p2->size);
  648. safe_delete(p2);
  649. /* if(p2)
  650. {
  651. EQApplicationPacket* ap = p2->MakeApplicationPacket(2);
  652. if (ap->version == 0)
  653. ap->version = client_version;
  654. InboundQueuePush(ap);
  655. safe_delete(p2);
  656. }*/
  657. //EQProtocolPacket* puse = p2;
  658. /* if (!rogue_buffer) {
  659. roguebuf_size=puse->size;
  660. rogue_buffer=new unsigned char[roguebuf_size];
  661. memcpy(rogue_buffer,puse->pBuffer,puse->size);
  662. roguebuf_offset=puse->size;
  663. cout << "RogueBuf is " << roguebuf_offset << "/" << roguebuf_size << " (" << (p->size-6) << ") NextInSeq=" << NextInSeq << endl;
  664. }
  665. else {
  666. int32 new_size = roguebuf_size + puse->size;
  667. uchar* tmp_buffer = new unsigned char[new_size];
  668. uchar* ptr = tmp_buffer;
  669. memcpy(ptr,rogue_buffer,roguebuf_size);
  670. ptr += roguebuf_size;
  671. memcpy(ptr,puse->pBuffer,puse->size);
  672. roguebuf_offset=puse->size;
  673. safe_delete_array(rogue_buffer);
  674. rogue_buffer = tmp_buffer;
  675. roguebuf_size = new_size;
  676. roguebuf_offset = new_size;
  677. cout << "RogueBuf is " << roguebuf_offset << "/" << roguebuf_size << " (" << (p->size-6) << ") NextInSeq=" << NextInSeq << endl;
  678. }*/
  679. #ifdef WRITE_PACKETS
  680. WritePackets(ap->GetOpcodeName(), p->pBuffer, p->size, false);
  681. #endif
  682. //InboundQueuePush(ap);
  683. LogWrite(PACKET__INFO, 0, "Packet", "Received unknown packet type, not adding to inbound queue");
  684. //safe_delete(p2);
  685. //SendDisconnect();
  686. break;
  687. }
  688. }
  689. }
  690. int8 EQStream::EQ2_Compress(EQ2Packet* app, int8 offset){
  691. #ifdef LE_DEBUG
  692. printf( "Before Compress in %s, line %i:\n", __FUNCTION__, __LINE__);
  693. DumpPacket(app);
  694. #endif
  695. uchar* pDataPtr = app->pBuffer + offset;
  696. int xpandSize = app->size * 2;
  697. uchar* deflate_buff = new uchar[xpandSize];
  698. MCompressData.lock();
  699. stream.next_in = pDataPtr;
  700. stream.avail_in = app->size - offset;
  701. stream.next_out = deflate_buff;
  702. stream.avail_out = xpandSize;
  703. int ret = deflate(&stream, Z_SYNC_FLUSH);
  704. if (ret != Z_OK)
  705. {
  706. printf("ZLIB COMPRESSION RETFAIL: %i, %i (Ret: %i)\n", app->size, stream.avail_out, ret);
  707. MCompressData.unlock();
  708. safe_delete_array(deflate_buff);
  709. return 0;
  710. }
  711. int32 newsize = xpandSize - stream.avail_out;
  712. safe_delete_array(app->pBuffer);
  713. app->size = newsize + offset;
  714. app->pBuffer = new uchar[app->size];
  715. app->pBuffer[(offset - 1)] = 1;
  716. memcpy(app->pBuffer + offset, deflate_buff, newsize);
  717. MCompressData.unlock();
  718. safe_delete_array(deflate_buff);
  719. #ifdef LE_DEBUG
  720. printf( "After Compress in %s, line %i:\n", __FUNCTION__, __LINE__);
  721. DumpPacket(app);
  722. #endif
  723. return offset - 1;
  724. }
  725. int16 EQStream::processRSAKey(EQProtocolPacket *p){
  726. /*int16 limit = 0;
  727. int8 offset = 13;
  728. int8 offset2 = 0;
  729. if(p->pBuffer[2] == 0)
  730. limit = p->pBuffer[9];
  731. else{
  732. limit = p->pBuffer[5];
  733. offset2 = 5;
  734. offset-=1;
  735. }
  736. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + offset + (limit-8), 8));
  737. return (limit + offset +1) - offset2;*/
  738. if(p->pBuffer[0] == 0)
  739. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + 62, 8));
  740. else
  741. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + 61, 8));
  742. return 0;
  743. }
  744. void EQStream::SendKeyRequest(){
  745. int32 crypto_key_size = 60;
  746. int16 size = sizeof(KeyGen_Struct) + sizeof(KeyGen_End_Struct) + crypto_key_size;
  747. EQ2Packet *outapp=new EQ2Packet(OP_WSLoginRequestMsg,NULL,size);
  748. memcpy(&outapp->pBuffer[0], &crypto_key_size, sizeof(int32));
  749. memset(&outapp->pBuffer[4], 0xFF, crypto_key_size);
  750. memset(&outapp->pBuffer[size-5], 1, 1);
  751. memset(&outapp->pBuffer[size-1], 1, 1);
  752. EQ2QueuePacket(outapp, true);
  753. }
  754. void EQStream::EncryptPacket(EQ2Packet* app, int8 compress_offset, int8 offset){
  755. if(app->size>2 && crypto->isEncrypted()){
  756. app->packet_encrypted = true;
  757. uchar* crypt_buff = app->pBuffer;
  758. if(app->eq2_compressed)
  759. crypto->RC4Encrypt(crypt_buff + compress_offset, app->size - compress_offset);
  760. else
  761. crypto->RC4Encrypt(crypt_buff + 2 + offset, app->size - 2 - offset);
  762. }
  763. }
  764. void EQStream::EQ2QueuePacket(EQ2Packet* app, bool attempted_combine){
  765. if(CheckActive()){
  766. if(!attempted_combine){
  767. MCombineQueueLock.lock();
  768. combine_queue.push_back(app);
  769. MCombineQueueLock.unlock();
  770. }
  771. else{
  772. MCombineQueueLock.lock();
  773. PreparePacket(app);
  774. MCombineQueueLock.unlock();
  775. #ifdef LE_DEBUG
  776. printf( "After B in %s, line %i:\n", __FUNCTION__, __LINE__);
  777. DumpPacket(app);
  778. #endif
  779. SendPacket(app);
  780. }
  781. }
  782. }
  783. void EQStream::UnPreparePacket(EQ2Packet* app){
  784. if(app->pBuffer[2] == 0 && app->pBuffer[3] == 19){
  785. uchar* new_buffer = new uchar[app->size-3];
  786. memcpy(new_buffer+2, app->pBuffer+5, app->size-3);
  787. delete[] app->pBuffer;
  788. app->size-=3;
  789. app->pBuffer = new_buffer;
  790. }
  791. }
  792. #ifdef WRITE_PACKETS
  793. char EQStream::GetChar(uchar in)
  794. {
  795. if (in < ' ' || in > '~')
  796. return '.';
  797. return (char)in;
  798. }
  799. void EQStream::WriteToFile(char* pFormat, ...) {
  800. va_list args;
  801. va_start(args, pFormat);
  802. vfprintf(write_packets, pFormat, args);
  803. va_end(args);
  804. }
  805. void EQStream::WritePackets(const char* opcodeName, uchar* data, int32 size, bool outgoing) {
  806. MWritePackets.lock();
  807. struct in_addr ip_addr;
  808. ip_addr.s_addr = remote_ip;
  809. char timebuffer[80];
  810. time_t rawtime;
  811. struct tm* timeinfo;
  812. time(&rawtime);
  813. timeinfo = localtime(&rawtime);
  814. strftime(timebuffer, 80, "%m/%d/%Y %H:%M:%S", timeinfo);
  815. if (outgoing)
  816. WriteToFile("-- %s --\n%s\nSERVER -> %s\n", opcodeName, timebuffer, inet_ntoa(ip_addr));
  817. else
  818. WriteToFile("-- %s --\n%s\n%s -> SERVER\n", opcodeName, timebuffer, inet_ntoa(ip_addr));
  819. int i;
  820. int nLines = size / 16;
  821. int nExtra = size % 16;
  822. uchar* pPtr = data;
  823. for (i = 0; i < nLines; i++)
  824. {
  825. WriteToFile("%4.4X:\t%2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n", i * 16, pPtr[0], pPtr[1], pPtr[2], pPtr[3], pPtr[4], pPtr[5], pPtr[6], pPtr[7], pPtr[8], pPtr[9], pPtr[10], pPtr[11], pPtr[12], pPtr[13], pPtr[14], pPtr[15], GetChar(pPtr[0]), GetChar(pPtr[1]), GetChar(pPtr[2]), GetChar(pPtr[3]), GetChar(pPtr[4]), GetChar(pPtr[5]), GetChar(pPtr[6]), GetChar(pPtr[7]), GetChar(pPtr[8]), GetChar(pPtr[9]), GetChar(pPtr[10]), GetChar(pPtr[11]), GetChar(pPtr[12]), GetChar(pPtr[13]), GetChar(pPtr[14]), GetChar(pPtr[15]));
  826. pPtr += 16;
  827. }
  828. if (nExtra)
  829. {
  830. WriteToFile("%4.4X\t", nLines * 16);
  831. for (i = 0; i < nExtra; i++)
  832. {
  833. WriteToFile("%2.2X ", pPtr[i]);
  834. }
  835. for (i; i < 16; i++)
  836. WriteToFile(" ");
  837. for (i = 0; i < nExtra; i++)
  838. {
  839. WriteToFile("%c", GetChar(pPtr[i]));
  840. }
  841. WriteToFile("\n");
  842. }
  843. WriteToFile("\n\n");
  844. fflush(write_packets);
  845. MWritePackets.unlock();
  846. }
  847. void EQStream::WritePackets(EQ2Packet* app, bool outgoing) {
  848. if (app->version == 0)
  849. app->version = client_version;
  850. WritePackets(app->GetOpcodeName(), app->pBuffer, app->size, outgoing);
  851. }
  852. #endif
  853. void EQStream::PreparePacket(EQ2Packet* app, int8 offset){
  854. app->setVersion(client_version);
  855. compressed_offset = 0;
  856. #ifdef LE_DEBUG
  857. printf( "Before A in %s, line %i:\n", __FUNCTION__, __LINE__);
  858. DumpPacket(app);
  859. #endif
  860. if(!app->packet_prepared){
  861. if(app->PreparePacket(MaxLen) == 255) //invalid version
  862. return;
  863. }
  864. #ifdef LE_DEBUG
  865. printf( "After Prepare in %s, line %i:\n", __FUNCTION__, __LINE__);
  866. DumpPacket(app);
  867. #endif
  868. #ifdef WRITE_PACKETS
  869. if (!app->eq2_compressed && !app->packet_encrypted)
  870. WritePackets(app, true);
  871. #endif
  872. if(!app->eq2_compressed && app->size>128){
  873. compressed_offset = EQ2_Compress(app);
  874. if (compressed_offset)
  875. app->eq2_compressed = true;
  876. }
  877. if(!app->packet_encrypted){
  878. EncryptPacket(app, compressed_offset, offset);
  879. if(app->size > 2 && app->pBuffer[2] == 0){
  880. uchar* new_buffer = new uchar[app->size+1];
  881. new_buffer[2] = 0;
  882. memcpy(new_buffer+3, app->pBuffer+2, app->size-2);
  883. delete[] app->pBuffer;
  884. app->pBuffer = new_buffer;
  885. app->size++;
  886. }
  887. }
  888. #ifdef LE_DEBUG
  889. printf( "After A in %s, line %i:\n", __FUNCTION__, __LINE__);
  890. DumpPacket(app);
  891. #endif
  892. }
  893. void EQStream::SendPacket(EQProtocolPacket *p)
  894. {
  895. uint32 chunksize,used;
  896. uint32 length;
  897. // Convert the EQApplicationPacket to 1 or more EQProtocolPackets
  898. if (p->size>( MaxLen-8)) { // proto-op(2), seq(2), app-op(2) ... data ... crc(2)
  899. uchar* tmpbuff=p->pBuffer;
  900. length=p->size - 2;
  901. EQProtocolPacket *out=new EQProtocolPacket(OP_Fragment,NULL,MaxLen-4);
  902. *(uint32 *)(out->pBuffer+2)=htonl(length);
  903. used=MaxLen-10;
  904. memcpy(out->pBuffer+6,tmpbuff+2,used);
  905. #ifdef LE_DEBUG
  906. printf("(%s, %i) New Fragment:\n ", __FUNCTION__, __LINE__);
  907. DumpPacket(out);
  908. #endif
  909. SequencedPush(out);
  910. while (used<length) {
  911. chunksize=min(length-used,MaxLen-6);
  912. out=new EQProtocolPacket(OP_Fragment,NULL,chunksize+2);
  913. //memcpy(out->pBuffer+2,tmpbuff,1);
  914. memcpy(out->pBuffer+2,tmpbuff+used+2,chunksize);
  915. #ifdef LE_DEBUG
  916. printf("Chunk: \n");
  917. DumpPacket(out);
  918. #endif
  919. SequencedPush(out);
  920. used+=chunksize;
  921. }
  922. #ifdef LE_DEBUG
  923. printf( "ChunkDelete: \n");
  924. DumpPacket(out);
  925. //cerr << "1: Deleting 0x" << hex << (uint32)(p) << dec << endl;
  926. #endif
  927. delete p;
  928. } else {
  929. SequencedPush(p);
  930. }
  931. }
  932. void EQStream::SendPacket(EQApplicationPacket *p)
  933. {
  934. uint32 chunksize,used;
  935. uint32 length;
  936. // Convert the EQApplicationPacket to 1 or more EQProtocolPackets
  937. if (p->size>(MaxLen-8)) { // proto-op(2), seq(2), app-op(2) ... data ... crc(2)
  938. //cout << "Making oversized packet for: " << endl;
  939. //cout << p->size << endl;
  940. //p->DumpRawHeader();
  941. //dump_message(p->pBuffer,p->size,timestamp());
  942. //cout << p->size << endl;
  943. unsigned char *tmpbuff=new unsigned char[p->size+2];
  944. //cout << hex << (int)tmpbuff << dec << endl;
  945. length=p->serialize(tmpbuff);
  946. EQProtocolPacket *out=new EQProtocolPacket(OP_Fragment,NULL,MaxLen-4);
  947. *(uint32 *)(out->pBuffer+2)=htonl(p->Size());
  948. memcpy(out->pBuffer+6,tmpbuff,MaxLen-10);
  949. used=MaxLen-10;
  950. SequencedPush(out);
  951. //cout << "Chunk #" << ++i << " size=" << used << ", length-used=" << (length-used) << endl;
  952. while (used<length) {
  953. out=new EQProtocolPacket(OP_Fragment,NULL,MaxLen-4);
  954. chunksize=min(length-used,MaxLen-6);
  955. memcpy(out->pBuffer+2,tmpbuff+used,chunksize);
  956. out->size=chunksize+2;
  957. SequencedPush(out);
  958. used+=chunksize;
  959. //cout << "Chunk #"<< ++i << " size=" << chunksize << ", length-used=" << (length-used) << endl;
  960. }
  961. //cerr << "1: Deleting 0x" << hex << (uint32)(p) << dec << endl;
  962. delete p;
  963. delete[] tmpbuff;
  964. } else {
  965. EQProtocolPacket *out=new EQProtocolPacket(OP_Packet,NULL,p->Size()+2);
  966. p->serialize(out->pBuffer+2);
  967. SequencedPush(out);
  968. //cerr << "2: Deleting 0x" << hex << (uint32)(p) << dec << endl;
  969. delete p;
  970. }
  971. }
  972. void EQStream::SequencedPush(EQProtocolPacket *p)
  973. {
  974. p->setVersion(client_version);
  975. MOutboundQueue.lock();
  976. *(uint16 *)(p->pBuffer)=htons(NextOutSeq);
  977. SequencedQueue.push_back(p);
  978. p->sequence = NextOutSeq;
  979. NextOutSeq++;
  980. MOutboundQueue.unlock();
  981. }
  982. void EQStream::NonSequencedPush(EQProtocolPacket *p)
  983. {
  984. p->setVersion(client_version);
  985. MOutboundQueue.lock();
  986. NonSequencedQueue.push(p);
  987. MOutboundQueue.unlock();
  988. }
  989. void EQStream::SendAck(uint16 seq)
  990. {
  991. uint16 Seq=htons(seq);
  992. SetLastAckSent(seq);
  993. NonSequencedPush(new EQProtocolPacket(OP_Ack,(unsigned char *)&Seq,sizeof(uint16)));
  994. }
  995. void EQStream::SendOutOfOrderAck(uint16 seq)
  996. {
  997. uint16 Seq=htons(seq);
  998. NonSequencedPush(new EQProtocolPacket(OP_OutOfOrderAck,(unsigned char *)&Seq,sizeof(uint16)));
  999. }
  1000. bool EQStream::CheckCombineQueue(){
  1001. bool ret = true; //processed all packets
  1002. MCombineQueueLock.lock();
  1003. if(combine_queue.size() > 0){
  1004. EQ2Packet* first = combine_queue.front();
  1005. combine_queue.pop_front();
  1006. if(combine_queue.size() == 0){ //nothing to combine this with
  1007. EQ2QueuePacket(first, true);
  1008. }
  1009. else{
  1010. PreparePacket(first);
  1011. EQ2Packet* second = 0;
  1012. bool combine_worked = false;
  1013. int16 count = 0;
  1014. while(combine_queue.size()){
  1015. count++;
  1016. second = combine_queue.front();
  1017. combine_queue.pop_front();
  1018. PreparePacket(second);
  1019. /*if(first->GetRawOpcode() != OP_AppCombined && first->pBuffer[2] == 0){
  1020. EQ2Packet* tmp = second;
  1021. second = first;
  1022. first = tmp;
  1023. }*/
  1024. if(!first->AppCombine(second)){
  1025. first->SetProtocolOpcode(OP_Packet);
  1026. if(combine_worked){
  1027. SequencedPush(first);
  1028. }
  1029. else{
  1030. EQ2QueuePacket(first, true);
  1031. }
  1032. first = second;
  1033. combine_worked = false;
  1034. }
  1035. else{
  1036. combine_worked = true;
  1037. //DumpPacket(first);
  1038. }
  1039. if(count >= 60 || first->size > 4000){ //other clients need packets too
  1040. ret = false;
  1041. break;
  1042. }
  1043. }
  1044. if(first){
  1045. first->SetProtocolOpcode(OP_Packet);
  1046. if(combine_worked){
  1047. SequencedPush(first);
  1048. }
  1049. else{
  1050. EQ2QueuePacket(first, true);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. MCombineQueueLock.unlock();
  1056. return ret;
  1057. }
  1058. void EQStream::CheckResend(int eq_fd){
  1059. int32 curr = Timer::GetCurrentTime2();
  1060. EQProtocolPacket* packet = 0;
  1061. deque<EQProtocolPacket*>::iterator itr;
  1062. MResendQue.lock();
  1063. for(itr=resend_que.begin();itr!=resend_que.end();itr++){
  1064. packet = *itr;
  1065. if(packet->attempt_count >= 5){//tried to resend this packet 5 times, client must already have it but didnt ack it
  1066. safe_delete(packet);
  1067. itr = resend_que.erase(itr);
  1068. if(itr == resend_que.end())
  1069. break;
  1070. }
  1071. else{
  1072. if((curr - packet->sent_time) < 1000)
  1073. continue;
  1074. packet->sent_time -=1000;
  1075. packet->attempt_count++;
  1076. WritePacket(eq_fd, packet);
  1077. }
  1078. }
  1079. MResendQue.unlock();
  1080. }
  1081. //returns SeqFuture if `seq` is later than `expected_seq`
  1082. EQStream::SeqOrder EQStream::CompareSequence(uint16 expected_seq, uint16 seq)
  1083. {
  1084. if (expected_seq == seq) {
  1085. // Curent
  1086. return SeqInOrder;
  1087. }
  1088. else if ((seq > expected_seq && (uint32)seq < ((uint32)expected_seq + EQStream::MaxWindowSize)) || seq < (expected_seq - EQStream::MaxWindowSize)) {
  1089. // Future
  1090. return SeqFuture;
  1091. }
  1092. else {
  1093. // Past
  1094. return SeqPast;
  1095. }
  1096. }
  1097. void EQStream::AckPackets(uint16 seq)
  1098. {
  1099. std::deque<EQProtocolPacket*>::iterator itr, tmp;
  1100. MOutboundQueue.lock();
  1101. SeqOrder ord = CompareSequence(SequencedBase, seq);
  1102. if (ord == SeqInOrder) {
  1103. //they are not acking anything new...
  1104. LogWrite(PACKET__DEBUG, 9, "Packet", "Received an ack with no window advancement (seq %u)", seq);
  1105. }
  1106. else if (ord == SeqPast) {
  1107. //they are nacking blocks going back before our buffer, wtf?
  1108. LogWrite(PACKET__DEBUG, 9, "Packet", "Received an ack with backward window advancement (they gave %u, our window starts at %u). This is bad" , seq, SequencedBase);
  1109. }
  1110. else {
  1111. LogWrite(PACKET__DEBUG, 9, "Packet", "Received an ack up through sequence %u. Our base is %u", seq, SequencedBase);
  1112. //this is a good ack, we get to ack some blocks.
  1113. seq++; //we stop at the block right after their ack, counting on the wrap of both numbers.
  1114. while (SequencedBase != seq) {
  1115. if (SequencedQueue.empty()) {
  1116. LogWrite(PACKET__DEBUG, 9, "Packet", "OUT OF PACKETS acked packet with sequence %u. Next send is %u before this", (unsigned long)SequencedBase, SequencedQueue.size());
  1117. SequencedBase = NextOutSeq;
  1118. break;
  1119. }
  1120. LogWrite(PACKET__DEBUG, 9, "Packet", "Removing acked packet with sequence %u", (unsigned long)SequencedBase);
  1121. //clean out the acked packet
  1122. delete SequencedQueue.front();
  1123. SequencedQueue.pop_front();
  1124. //advance the base sequence number to the seq of the block after the one we just got rid of.
  1125. SequencedBase++;
  1126. }
  1127. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  1128. LogWrite(PACKET__DEBUG, 9, "Packet", "Post-Ack on %u Invalid Sequenced queue: BS %u + SQ %u != NOS %u", seq, SequencedBase, SequencedQueue.size(), NextOutSeq);
  1129. }
  1130. }
  1131. MOutboundQueue.unlock();
  1132. }
  1133. void EQStream::Write(int eq_fd)
  1134. {
  1135. queue<EQProtocolPacket *> ReadyToSend;
  1136. long maxack;
  1137. // Check our rate to make sure we can send more
  1138. MRate.lock();
  1139. sint32 threshold=RateThreshold;
  1140. MRate.unlock();
  1141. if (BytesWritten > threshold) {
  1142. //cout << "Over threshold: " << BytesWritten << " > " << threshold << endl;
  1143. return;
  1144. }
  1145. MCombinedAppPacket.lock();
  1146. EQApplicationPacket *CombPack=CombinedAppPacket;
  1147. CombinedAppPacket=NULL;
  1148. MCombinedAppPacket.unlock();
  1149. if (CombPack) {
  1150. SendPacket(CombPack);
  1151. }
  1152. // If we got more packets to we need to ack, send an ack on the highest one
  1153. MAcks.lock();
  1154. maxack=MaxAckReceived;
  1155. // Added from peaks findings
  1156. if (NextAckToSend>LastAckSent || LastAckSent == 0x0000ffff)
  1157. SendAck(NextAckToSend);
  1158. MAcks.unlock();
  1159. // Lock the outbound queues while we process
  1160. MOutboundQueue.lock();
  1161. // Adjust where we start sending in case we get a late ack
  1162. //if (maxack>LastSeqSent)
  1163. // LastSeqSent=maxack;
  1164. // Place to hold the base packet t combine into
  1165. EQProtocolPacket *p=NULL;
  1166. std::deque<EQProtocolPacket*>::iterator sitr;
  1167. // Find the next sequenced packet to send from the "queue"
  1168. sitr = SequencedQueue.begin();
  1169. uint16 count = 0;
  1170. // get to start of packets
  1171. while (sitr != SequencedQueue.end() && (*sitr)->sent_time > 0) {
  1172. ++sitr;
  1173. ++count;
  1174. }
  1175. bool SeqEmpty = false, NonSeqEmpty = false;
  1176. // Loop until both are empty or MaxSends is reached
  1177. while (!SeqEmpty || !NonSeqEmpty) {
  1178. // See if there are more non-sequenced packets left
  1179. if (!NonSequencedQueue.empty()) {
  1180. if (!p) {
  1181. // If we don't have a packet to try to combine into, use this one as the base
  1182. // And remove it form the queue
  1183. p = NonSequencedQueue.front();
  1184. LogWrite(PACKET__DEBUG, 9, "Packet", "Starting combined packet with non-seq packet of len %u",p->size);
  1185. NonSequencedQueue.pop();
  1186. }
  1187. else if (!p->combine(NonSequencedQueue.front())) {
  1188. // Trying to combine this packet with the base didn't work (too big maybe)
  1189. // So just send the base packet (we'll try this packet again later)
  1190. LogWrite(PACKET__DEBUG, 9, "Packet", "Combined packet full at len %u, next non-seq packet is len %u", p->size, (NonSequencedQueue.front())->size);
  1191. ReadyToSend.push(p);
  1192. BytesWritten += p->size;
  1193. p = nullptr;
  1194. if (BytesWritten > threshold) {
  1195. // Sent enough this round, lets stop to be fair
  1196. LogWrite(PACKET__DEBUG, 9, "Packet", "Exceeded write threshold in nonseq (%u > %u)", BytesWritten, threshold);
  1197. break;
  1198. }
  1199. }
  1200. else {
  1201. // Combine worked, so just remove this packet and it's spot in the queue
  1202. LogWrite(PACKET__DEBUG, 9, "Packet", "Combined non-seq packet of len %u, yeilding %u combined", (NonSequencedQueue.front())->size, p->size);
  1203. delete NonSequencedQueue.front();
  1204. NonSequencedQueue.pop();
  1205. }
  1206. }
  1207. else {
  1208. // No more non-sequenced packets
  1209. NonSeqEmpty = true;
  1210. }
  1211. if (sitr != SequencedQueue.end()) {
  1212. uint16 seq_send = SequencedBase + count; //just for logging...
  1213. if (SequencedQueue.empty()) {
  1214. LogWrite(PACKET__DEBUG, 9, "Packet", "Tried to write a packet with an empty queue (%u is past next out %u)", seq_send, NextOutSeq);
  1215. SeqEmpty = true;
  1216. continue;
  1217. }
  1218. if ((*sitr)->acked || (*sitr)->sent_time != 0) {
  1219. ++sitr;
  1220. ++count;
  1221. if (p) {
  1222. LogWrite(PACKET__DEBUG, 9, "Packet", "Final combined packet not full, len %u", p->size);
  1223. ReadyToSend.push(p);
  1224. BytesWritten += p->size;
  1225. p = nullptr;
  1226. }
  1227. LogWrite(PACKET__DEBUG, 9, "Packet", "Not retransmitting seq packet %u because already marked as acked", seq_send);
  1228. }
  1229. else if (!p) {
  1230. // If we don't have a packet to try to combine into, use this one as the base
  1231. // Copy it first as it will still live until it is acked
  1232. p = (*sitr)->Copy();
  1233. LogWrite(PACKET__DEBUG, 9, "Packet", "Starting combined packet with seq packet %u of len %u", seq_send, p->size);
  1234. (*sitr)->sent_time = Timer::GetCurrentTime2();
  1235. ++sitr;
  1236. ++count;
  1237. }
  1238. else if (!p->combine(*sitr)) {
  1239. // Trying to combine this packet with the base didn't work (too big maybe)
  1240. // So just send the base packet (we'll try this packet again later)
  1241. LogWrite(PACKET__DEBUG, 9, "Packet", "Combined packet full at len %u, next seq packet %u is len %u", p->size, seq_send + 1, (*sitr)->size);
  1242. ReadyToSend.push(p);
  1243. BytesWritten += p->size;
  1244. p = nullptr;
  1245. if ((*sitr)->opcode != OP_Fragment && BytesWritten > threshold) {
  1246. // Sent enough this round, lets stop to be fair
  1247. LogWrite(PACKET__DEBUG, 9, "Packet", "Exceeded write threshold in seq (%u > %u)", BytesWritten, threshold);
  1248. break;
  1249. }
  1250. }
  1251. else {
  1252. // Combine worked
  1253. LogWrite(PACKET__DEBUG, 9, "Packet", "Combined seq packet %u of len %u, yeilding %u combined", seq_send, (*sitr)->size, p->size);
  1254. (*sitr)->sent_time = Timer::GetCurrentTime2();
  1255. ++sitr;
  1256. ++count;
  1257. }
  1258. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  1259. LogWrite(PACKET__DEBUG, 9, "Packet", "Post send Invalid Sequenced queue: BS %u + SQ %u != NOS %u", SequencedBase, SequencedQueue.size(), NextOutSeq);
  1260. }
  1261. }
  1262. else {
  1263. // No more sequenced packets
  1264. SeqEmpty = true;
  1265. }
  1266. }
  1267. MOutboundQueue.unlock(); // Unlock the queue
  1268. // We have a packet still, must have run out of both seq and non-seq, so send it
  1269. if (p) {
  1270. LogWrite(PACKET__DEBUG, 9, "Packet", "Final combined packet not full, len %u", p->size);
  1271. ReadyToSend.push(p);
  1272. BytesWritten += p->size;
  1273. }
  1274. // Send all the packets we "made"
  1275. while (!ReadyToSend.empty()) {
  1276. p = ReadyToSend.front();
  1277. WritePacket(eq_fd, p);
  1278. delete p;
  1279. ReadyToSend.pop();
  1280. }
  1281. //see if we need to send our disconnect and finish our close
  1282. if (SeqEmpty && NonSeqEmpty) {
  1283. //no more data to send
  1284. if (GetState() == CLOSING) {
  1285. MOutboundQueue.lock();
  1286. if (SequencedQueue.size() > 0 )
  1287. LogWrite(PACKET__DEBUG, 9, "Packet", "All outgoing data flushed, client should be disconnecting, awaiting acknowledgement of SequencedQueue.");
  1288. else
  1289. {
  1290. LogWrite(PACKET__DEBUG, 9, "Packet", "All outgoing data flushed, disconnecting client.");
  1291. //we are waiting for the queues to empty, now we can do our disconnect.
  1292. //this packet will not actually go out until the next call to Write().
  1293. SendDisconnect();
  1294. //SetState(CLOSED);
  1295. }
  1296. MOutboundQueue.unlock();
  1297. }
  1298. }
  1299. }
  1300. void EQStream::WritePacket(int eq_fd, EQProtocolPacket *p)
  1301. {
  1302. uint32 length = 0;
  1303. sockaddr_in address;
  1304. unsigned char tmpbuffer[2048];
  1305. address.sin_family = AF_INET;
  1306. address.sin_addr.s_addr=remote_ip;
  1307. address.sin_port=remote_port;
  1308. #ifdef NOWAY
  1309. uint32 ip=address.sin_addr.s_addr;
  1310. cout << "Sending to: "
  1311. << (int)*(unsigned char *)&ip
  1312. << "." << (int)*((unsigned char *)&ip+1)
  1313. << "." << (int)*((unsigned char *)&ip+2)
  1314. << "." << (int)*((unsigned char *)&ip+3)
  1315. << "," << (int)ntohs(address.sin_port) << "(" << p->size << ")" << endl;
  1316. p->DumpRaw();
  1317. cout << "-------------" << endl;
  1318. #endif
  1319. length=p->serialize(buffer);
  1320. if (p->opcode!=OP_SessionRequest && p->opcode!=OP_SessionResponse) {
  1321. if (compressed) {
  1322. BytesWritten -= p->size;
  1323. uint32 newlen=EQProtocolPacket::Compress(buffer,length,tmpbuffer,2048);
  1324. memcpy(buffer,tmpbuffer,newlen);
  1325. length=newlen;
  1326. BytesWritten += newlen;
  1327. }
  1328. if (encoded) {
  1329. EQProtocolPacket::ChatEncode(buffer,length,Key);
  1330. }
  1331. *(uint16 *)(buffer+length)=htons(CRC16(buffer,length,Key));
  1332. length+=2;
  1333. }
  1334. sent_packets++;
  1335. //dump_message_column(buffer,length,"Writer: ");
  1336. //cout << "Raw Data:\n";
  1337. //DumpPacket(buffer, length);
  1338. sendto(eq_fd,(char *)buffer,length,0,(sockaddr *)&address,sizeof(address));
  1339. }
  1340. EQProtocolPacket *EQStream::Read(int eq_fd, sockaddr_in *from)
  1341. {
  1342. int socklen;
  1343. int length=0;
  1344. unsigned char buffer[2048];
  1345. EQProtocolPacket *p=NULL;
  1346. char temp[15];
  1347. socklen=sizeof(sockaddr);
  1348. #ifdef WIN32
  1349. length=recvfrom(eq_fd, (char *)buffer, 2048, 0, (struct sockaddr*)from, (int *)&socklen);
  1350. #else
  1351. length=recvfrom(eq_fd, buffer, 2048, 0, (struct sockaddr*)from, (socklen_t *)&socklen);
  1352. #endif
  1353. if (length>=2) {
  1354. DumpPacket(buffer, length);
  1355. p=new EQProtocolPacket(buffer[1],&buffer[2],length-2);
  1356. //printf("Read packet: opcode %i length %u, expected-length: %u\n",buffer[1], length, p->size);
  1357. uint32 ip=from->sin_addr.s_addr;
  1358. sprintf(temp,"%d.%d.%d.%d:%d",
  1359. *(unsigned char *)&ip,
  1360. *((unsigned char *)&ip+1),
  1361. *((unsigned char *)&ip+2),
  1362. *((unsigned char *)&ip+3),
  1363. ntohs(from->sin_port));
  1364. //cout << timestamp() << "Data from: " << temp << " OpCode 0x" << hex << setw(2) << setfill('0') << (int)p->opcode << dec << endl;
  1365. //dump_message(p->pBuffer,p->size,timestamp());
  1366. }
  1367. return p;
  1368. }
  1369. void EQStream::SendSessionResponse()
  1370. {
  1371. EQProtocolPacket *out=new EQProtocolPacket(OP_SessionResponse,NULL,sizeof(SessionResponse));
  1372. SessionResponse *Response=(SessionResponse *)out->pBuffer;
  1373. Response->Session=htonl(Session);
  1374. Response->MaxLength=htonl(MaxLen);
  1375. Response->UnknownA=2;
  1376. Response->Format=0;
  1377. if (compressed)
  1378. Response->Format|=FLAG_COMPRESSED;
  1379. if (encoded)
  1380. Response->Format|=FLAG_ENCODED;
  1381. Response->Key=htonl(Key);
  1382. out->size=sizeof(SessionResponse);
  1383. NonSequencedPush(out);
  1384. }
  1385. void EQStream::SendSessionRequest()
  1386. {
  1387. EQProtocolPacket *out=new EQProtocolPacket(OP_SessionRequest,NULL,sizeof(SessionRequest));
  1388. SessionRequest *Request=(SessionRequest *)out->pBuffer;
  1389. memset(Request,0,sizeof(SessionRequest));
  1390. Request->Session=htonl(time(NULL));
  1391. Request->MaxLength=htonl(512);
  1392. NonSequencedPush(out);
  1393. }
  1394. void EQStream::SendDisconnect(bool setstate)
  1395. {
  1396. try{
  1397. if(GetState() != ESTABLISHED && GetState() != WAIT_CLOSE)
  1398. return;
  1399. EQProtocolPacket *out=new EQProtocolPacket(OP_SessionDisconnect,NULL,sizeof(uint32)+sizeof(int16));
  1400. *(uint32 *)out->pBuffer=htonl(Session);
  1401. out->pBuffer[4] = 0;
  1402. out->pBuffer[5] = 6;
  1403. NonSequencedPush(out);
  1404. if(setstate)
  1405. SetState(CLOSING);
  1406. }
  1407. catch(...){}
  1408. }
  1409. void EQStream::InboundQueuePush(EQApplicationPacket *p)
  1410. {
  1411. MInboundQueue.lock();
  1412. InboundQueue.push_back(p);
  1413. MInboundQueue.unlock();
  1414. }
  1415. EQApplicationPacket *EQStream::PopPacket()
  1416. {
  1417. EQApplicationPacket *p=NULL;
  1418. MInboundQueue.lock();
  1419. if (InboundQueue.size()) {
  1420. p=InboundQueue.front();
  1421. InboundQueue.pop_front();
  1422. }
  1423. MInboundQueue.unlock();
  1424. if(p)
  1425. p->setVersion(client_version);
  1426. return p;
  1427. }
  1428. void EQStream::InboundQueueClear()
  1429. {
  1430. MInboundQueue.lock();
  1431. while(InboundQueue.size()){
  1432. delete InboundQueue.front();
  1433. InboundQueue.pop_front();
  1434. }
  1435. MInboundQueue.unlock();
  1436. }
  1437. void EQStream::EncryptPacket(uchar* data, int16 size){
  1438. if(size>6){
  1439. }
  1440. }
  1441. bool EQStream::HasOutgoingData()
  1442. {
  1443. bool flag;
  1444. //once closed, we have nothing more to say
  1445. if(CheckClosed())
  1446. return(false);
  1447. MOutboundQueue.lock();
  1448. flag=(!NonSequencedQueue.empty());
  1449. if (!flag) {
  1450. flag = (!SequencedQueue.empty());
  1451. }
  1452. MOutboundQueue.unlock();
  1453. if (!flag) {
  1454. MAcks.lock();
  1455. flag= (NextAckToSend>LastAckSent);
  1456. MAcks.unlock();
  1457. }
  1458. if (!flag) {
  1459. MCombinedAppPacket.lock();
  1460. flag=(CombinedAppPacket!=NULL);
  1461. MCombinedAppPacket.unlock();
  1462. }
  1463. return flag;
  1464. }
  1465. void EQStream::OutboundQueueClear()
  1466. {
  1467. MOutboundQueue.lock();
  1468. while(NonSequencedQueue.size()) {
  1469. delete NonSequencedQueue.front();
  1470. NonSequencedQueue.pop();
  1471. }
  1472. while(SequencedQueue.size()) {
  1473. delete SequencedQueue.front();
  1474. SequencedQueue.pop_front();
  1475. }
  1476. MOutboundQueue.unlock();
  1477. }
  1478. void EQStream::Process(const unsigned char *buffer, const uint32 length)
  1479. {
  1480. received_packets++;
  1481. static unsigned char newbuffer[2048];
  1482. uint32 newlength=0;
  1483. #ifdef LE_DEBUG
  1484. printf("ProcessBuffer:\n");
  1485. DumpPacket(buffer, length);
  1486. #endif
  1487. if (EQProtocolPacket::ValidateCRC(buffer,length,Key)) {
  1488. if (compressed) {
  1489. newlength=EQProtocolPacket::Decompress(buffer,length,newbuffer,2048);
  1490. #ifdef LE_DEBUG
  1491. printf("ProcessBufferDecompress:\n");
  1492. DumpPacket(buffer, newlength);
  1493. #endif
  1494. } else {
  1495. memcpy(newbuffer,buffer,length);
  1496. newlength=length;
  1497. if (encoded)
  1498. EQProtocolPacket::ChatDecode(newbuffer,newlength-2,Key);
  1499. }
  1500. if (buffer[1]!=0x01 && buffer[1]!=0x02 && buffer[1]!=0x1d)
  1501. newlength-=2;
  1502. #ifdef LE_DEBUG
  1503. printf("ResultProcessBuffer:\n");
  1504. DumpPacket(buffer, newlength);
  1505. #endif
  1506. uint16 opcode=ntohs(*(const uint16 *)newbuffer);
  1507. //printf("Read packet: opcode %i newlength %u, newbuffer2len: %u, newbuffer3len: %u\n",opcode, newlength, newbuffer[2], newbuffer[3]);
  1508. if(opcode > 0 && opcode <= OP_OutOfSession)
  1509. {
  1510. EQProtocolPacket p(newbuffer,newlength);
  1511. if(opcode == 3)
  1512. DumpPacket(newbuffer, newlength);
  1513. ProcessPacket(&p);
  1514. }
  1515. else
  1516. {
  1517. cout << "2Orig Packet: " << opcode << endl;
  1518. DumpPacket(newbuffer, newlength);
  1519. MCombineQueueLock.lock();
  1520. EQProtocolPacket* p2 = ProcessEncryptedData(newbuffer, newlength, OP_Packet);
  1521. MCombineQueueLock.unlock();
  1522. cout << "2Decrypted Packet: " << p2->opcode << endl;
  1523. DumpPacket(p2->pBuffer, p2->size);
  1524. EQApplicationPacket* ap = p2->MakeApplicationPacket(2);
  1525. if (ap->version == 0)
  1526. ap->version = client_version;
  1527. InboundQueuePush(ap);
  1528. safe_delete(p2);
  1529. }
  1530. ProcessQueue();
  1531. } else {
  1532. cout << "Incoming packet failed checksum:" <<endl;
  1533. dump_message_column(const_cast<unsigned char *>(buffer),length,"CRC failed: ");
  1534. }
  1535. }
  1536. long EQStream::GetMaxAckReceived()
  1537. {
  1538. MAcks.lock();
  1539. long l=MaxAckReceived;
  1540. MAcks.unlock();
  1541. return l;
  1542. }
  1543. long EQStream::GetNextAckToSend()
  1544. {
  1545. MAcks.lock();
  1546. long l=NextAckToSend;
  1547. MAcks.unlock();
  1548. return l;
  1549. }
  1550. long EQStream::GetLastAckSent()
  1551. {
  1552. MAcks.lock();
  1553. long l=LastAckSent;
  1554. MAcks.unlock();
  1555. return l;
  1556. }
  1557. void EQStream::SetMaxAckReceived(uint32 seq)
  1558. {
  1559. deque<EQProtocolPacket *>::iterator itr;
  1560. MAcks.lock();
  1561. MaxAckReceived=seq;
  1562. MAcks.unlock();
  1563. MOutboundQueue.lock();
  1564. if (long(seq) > LastSeqSent)
  1565. LastSeqSent=seq;
  1566. MResendQue.lock();
  1567. EQProtocolPacket* packet = 0;
  1568. for(itr=resend_que.begin();itr!=resend_que.end();itr++){
  1569. packet = *itr;
  1570. if(packet && packet->sequence <= seq){
  1571. safe_delete(packet);
  1572. itr = resend_que.erase(itr);
  1573. if(itr == resend_que.end())
  1574. break;
  1575. }
  1576. }
  1577. MResendQue.unlock();
  1578. MOutboundQueue.unlock();
  1579. }
  1580. void EQStream::SetNextAckToSend(uint32 seq)
  1581. {
  1582. MAcks.lock();
  1583. NextAckToSend=seq;
  1584. MAcks.unlock();
  1585. }
  1586. void EQStream::SetLastAckSent(uint32 seq)
  1587. {
  1588. MAcks.lock();
  1589. LastAckSent=seq;
  1590. MAcks.unlock();
  1591. }
  1592. void EQStream::SetLastSeqSent(uint32 seq)
  1593. {
  1594. MOutboundQueue.lock();
  1595. LastSeqSent=seq;
  1596. MOutboundQueue.unlock();
  1597. }
  1598. void EQStream::SetStreamType(EQStreamType type)
  1599. {
  1600. StreamType=type;
  1601. switch (StreamType) {
  1602. case LoginStream:
  1603. app_opcode_size=1;
  1604. compressed=false;
  1605. encoded=false;
  1606. break;
  1607. case EQ2Stream:
  1608. app_opcode_size=2;
  1609. compressed=false;
  1610. encoded=false;
  1611. break;
  1612. case ChatOrMailStream:
  1613. case ChatStream:
  1614. case MailStream:
  1615. app_opcode_size=1;
  1616. compressed=false;
  1617. encoded=true;
  1618. break;
  1619. case ZoneStream:
  1620. case WorldStream:
  1621. default:
  1622. app_opcode_size=2;
  1623. compressed=true;
  1624. encoded=false;
  1625. break;
  1626. }
  1627. }
  1628. void EQStream::ProcessQueue()
  1629. {
  1630. if (OutOfOrderpackets.empty()) {
  1631. return;
  1632. }
  1633. EQProtocolPacket* qp = NULL;
  1634. while ((qp = RemoveQueue(NextInSeq)) != NULL) {
  1635. //_log(NET__DEBUG, _L "Processing Queued Packet: Seq=%d" __L, NextInSeq);
  1636. ProcessPacket(qp);
  1637. delete qp;
  1638. //_log(NET__APP_TRACE, _L "OP_Packet Queue size=%d" __L, PacketQueue.size());
  1639. }
  1640. }
  1641. EQProtocolPacket* EQStream::RemoveQueue(uint16 seq)
  1642. {
  1643. map<unsigned short, EQProtocolPacket*>::iterator itr;
  1644. EQProtocolPacket* qp = NULL;
  1645. if ((itr = OutOfOrderpackets.find(seq)) != OutOfOrderpackets.end()) {
  1646. qp = itr->second;
  1647. OutOfOrderpackets.erase(itr);
  1648. //_log(NET__APP_TRACE, _L "OP_Packet Queue size=%d" __L, PacketQueue.size());
  1649. }
  1650. return qp;
  1651. }
  1652. void EQStream::Decay()
  1653. {
  1654. MRate.lock();
  1655. uint32 rate=DecayRate;
  1656. MRate.unlock();
  1657. if (BytesWritten>0) {
  1658. BytesWritten-=rate;
  1659. if (BytesWritten<0)
  1660. BytesWritten=0;
  1661. }
  1662. int count = 0;
  1663. MOutboundQueue.lock();
  1664. for (auto sitr = SequencedQueue.begin(); sitr != SequencedQueue.end(); ++sitr, count++) {
  1665. if (!(*sitr)->acked && (*sitr)->sent_time > 0 && ((*sitr)->sent_time + retransmittimeout) < Timer::GetCurrentTime2()) {
  1666. (*sitr)->sent_time = 0;
  1667. LogWrite(PACKET__DEBUG, 9, "Packet", "Timeout exceeded for seq %u. Flagging packet for retransmission", SequencedBase + count);
  1668. }
  1669. }
  1670. MOutboundQueue.unlock();
  1671. }
  1672. void EQStream::AdjustRates(uint32 average_delta)
  1673. {
  1674. if (average_delta && (average_delta <= AVERAGE_DELTA_MAX)) {
  1675. MRate.lock();
  1676. AverageDelta = average_delta;
  1677. RateThreshold = RATEBASE / average_delta;
  1678. DecayRate = DECAYBASE / average_delta;
  1679. if (BytesWritten > RateThreshold)
  1680. BytesWritten = RateThreshold + DecayRate;
  1681. MRate.unlock();
  1682. }
  1683. else {
  1684. AverageDelta = AVERAGE_DELTA_MAX;
  1685. }
  1686. }