9
3

EQStream.cpp 35 KB

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