EQStream.cpp 52 KB

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