EQStream.cpp 36 KB

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