EQStream.cpp 46 KB

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