EQStream.cpp 38 KB

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