EQStream.cpp 52 KB

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