EQStream.cpp 37 KB

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