EQStream.cpp 51 KB

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