EQStream.cpp 54 KB

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