EQStream.cpp 52 KB

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