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. EQProtocolPacket* prevPacket = 0;
  233. while(processed<p->size) {
  234. if ((subpacket_length=(unsigned char)*(p->pBuffer+processed))==0xff) {
  235. subpacket_length = ntohs(*(uint16*)(p->pBuffer + processed + 1));
  236. offset = 3;
  237. }
  238. else
  239. offset = 1;
  240. count++;
  241. #ifdef LE_DEBUG
  242. printf( "OP_Combined Packet %i (%u) (%u):\n", count, subpacket_length, processed);
  243. #endif
  244. bool isSubPacket = EQProtocolPacket::IsProtocolPacket(p->pBuffer + processed + offset, subpacket_length, false);
  245. if (isSubPacket) {
  246. EQProtocolPacket* subp = new EQProtocolPacket(p->pBuffer + processed + offset, subpacket_length);
  247. subp->copyInfo(p);
  248. //I've seen some garbage packets get sent with wrong protocol opcodes but the rest of the combine is still correct
  249. //So don't break if GetProtocolPacket fails
  250. prevPacket = subp;
  251. #ifdef LE_DEBUG
  252. printf( "Opcode %i:\n", subp->opcode);
  253. DumpPacket(subp);
  254. #endif
  255. ProcessPacket(subp, p);
  256. #ifdef LE_DEBUG
  257. DumpPacket(subp);
  258. #endif
  259. delete subp;
  260. }
  261. else if (ntohs(*reinterpret_cast<uint16_t*>(p->pBuffer + processed + offset)) > 0x1e) {
  262. //Garbage packet?
  263. crypto->RC4Decrypt(p->pBuffer + processed + offset, subpacket_length);
  264. LogWrite(PACKET__ERROR, 0, "Packet", "Garbage packet?!:");
  265. printf("!!!!!!!!!Garbage Packet!!!!!!!!!!!!! processed: %u, offset: %u, count: %i\n", processed, offset, count);
  266. if(p->pBuffer[processed + offset] == 0xff)
  267. {
  268. uchar* newbuf = p->pBuffer;
  269. newbuf += processed + offset + 1;
  270. DumpPacket(p->pBuffer + processed + offset, subpacket_length);
  271. EQProtocolPacket *subp=new EQProtocolPacket(newbuf, subpacket_length, OP_Packet);
  272. subp->copyInfo(p);
  273. ProcessPacket(subp, p);
  274. delete subp;
  275. }
  276. if(prevPacket)
  277. {
  278. printf("prevPacketSize: %u\n", prevPacket->size);
  279. DumpPacket(prevPacket);
  280. }
  281. }
  282. processed+=subpacket_length+offset;
  283. }
  284. break;
  285. }
  286. case OP_AppCombined: {
  287. processed=0;
  288. EQProtocolPacket* newpacket = 0;
  289. int8 offset = 0;
  290. #ifdef LE_DEBUG
  291. printf( "OP_AppCombined: \n");
  292. DumpPacket(p);
  293. #endif
  294. int count = 0;
  295. while(processed<p->size) {
  296. count++;
  297. if ((subpacket_length=(unsigned char)*(p->pBuffer+processed))==0xff) {
  298. subpacket_length=ntohs(*(uint16 *)(p->pBuffer+processed+1));
  299. offset = 3;
  300. } else
  301. offset = 1;
  302. if(crypto->getRC4Key()==0 && p->size >= 70){
  303. processRSAKey(p);
  304. }
  305. else if(crypto->isEncrypted()){
  306. #ifdef LE_DEBUG
  307. printf( "OP_AppCombined Packet %i (%u) (%u): \n", count, subpacket_length, processed);
  308. DumpPacket(p->pBuffer+processed+offset, subpacket_length);
  309. #endif
  310. if(!HandleEmbeddedPacket(p, processed + offset, subpacket_length)){
  311. #ifdef LE_DEBUG
  312. printf( "OP_AppCombined Here:\n");
  313. #endif
  314. MCombineQueueLock.lock();
  315. newpacket = ProcessEncryptedData(p->pBuffer+processed + offset, subpacket_length, OP_AppCombined);
  316. MCombineQueueLock.unlock();
  317. if(newpacket){
  318. #ifdef LE_DEBUG
  319. printf( "Opcode %i:\n", newpacket->opcode);
  320. DumpPacket(newpacket);
  321. #endif
  322. EQApplicationPacket* ap = newpacket->MakeApplicationPacket(2);
  323. #ifdef LE_DEBUG
  324. printf( "OP_AppCombined Here2:\n");
  325. DumpPacket(ap);
  326. #endif
  327. if (ap->version == 0)
  328. ap->version = client_version;
  329. #ifdef WRITE_PACKETS
  330. WritePackets(ap->GetOpcodeName(), p->pBuffer + processed + offset, subpacket_length, false);
  331. #endif
  332. InboundQueuePush(ap);
  333. safe_delete(newpacket);
  334. }
  335. }
  336. }
  337. processed+=subpacket_length+offset;
  338. }
  339. }
  340. break;
  341. case OP_Packet: {
  342. if (!p->pBuffer || (p->Size() < 4))
  343. {
  344. break;
  345. }
  346. uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
  347. sint8 check=CompareSequence(NextInSeq,seq);
  348. if (check == SeqFuture) {
  349. #ifdef EQN_DEBUG
  350. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Future packet: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  351. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  352. p->DumpRawHeader(seq);
  353. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  354. #endif
  355. OutOfOrderpackets[seq] = p->Copy();
  356. // Image (2020): Removed as this is bad contributes to infinite loop
  357. //SendOutOfOrderAck(seq);
  358. } else if (check == SeqPast) {
  359. #ifdef EQN_DEBUG
  360. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Duplicate packet: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  361. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  362. p->DumpRawHeader(seq);
  363. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  364. #endif
  365. // Image (2020): Removed as this is bad contributes to infinite loop
  366. //OutOfOrderpackets[seq] = p->Copy();
  367. SendOutOfOrderAck(seq);
  368. } else {
  369. EQProtocolPacket* qp = RemoveQueue(seq);
  370. if (qp) {
  371. LogWrite(PACKET__DEBUG, 1, "Packet", "OP_Fragment: Removing older queued packet with sequence %i", seq);
  372. delete qp;
  373. }
  374. SetNextAckToSend(seq);
  375. NextInSeq++;
  376. if(HandleEmbeddedPacket(p))
  377. break;
  378. if(crypto->getRC4Key()==0 && p && p->size >= 70){
  379. processRSAKey(p);
  380. }
  381. else if(crypto->isEncrypted() && p){
  382. MCombineQueueLock.lock();
  383. EQProtocolPacket* newpacket = ProcessEncryptedPacket(p);
  384. MCombineQueueLock.unlock();
  385. if(newpacket){
  386. EQApplicationPacket* ap = newpacket->MakeApplicationPacket(2);
  387. if (ap->version == 0)
  388. ap->version = client_version;
  389. #ifdef WRITE_PACKETS
  390. WritePackets(ap->GetOpcodeName(), p->pBuffer, p->size, false);
  391. #endif
  392. InboundQueuePush(ap);
  393. safe_delete(newpacket);
  394. }
  395. }
  396. }
  397. }
  398. break;
  399. case OP_Fragment: {
  400. if (!p->pBuffer || (p->Size() < 4))
  401. {
  402. break;
  403. }
  404. uint16 seq=ntohs(*(uint16 *)(p->pBuffer));
  405. sint8 check=CompareSequence(NextInSeq,seq);
  406. if (check == SeqFuture) {
  407. #ifdef EQN_DEBUG
  408. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Future 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 if (check == SeqPast) {
  416. #ifdef EQN_DEBUG
  417. LogWrite(PACKET__DEBUG, 1, "Packet", "*** Duplicate packet2: Expecting Seq=%i, but got Seq=%i", NextInSeq, seq);
  418. LogWrite(PACKET__DEBUG, 1, "Packet", "[Start]");
  419. //p->DumpRawHeader(seq);
  420. LogWrite(PACKET__DEBUG, 1, "Packet", "[End]");
  421. #endif
  422. //OutOfOrderpackets[seq] = p->Copy();
  423. SendOutOfOrderAck(seq);
  424. } else {
  425. // In case we did queue one before as well.
  426. EQProtocolPacket* qp = RemoveQueue(seq);
  427. if (qp) {
  428. LogWrite(PACKET__DEBUG, 1, "Packet", "OP_Fragment: Removing older queued packet with sequence %i", seq);
  429. delete qp;
  430. }
  431. SetNextAckToSend(seq);
  432. NextInSeq++;
  433. if (oversize_buffer) {
  434. memcpy(oversize_buffer+oversize_offset,p->pBuffer+2,p->size-2);
  435. oversize_offset+=p->size-2;
  436. //cout << "Oversized is " << oversize_offset << "/" << oversize_length << " (" << (p->size-2) << ") Seq=" << seq << endl;
  437. if (oversize_offset==oversize_length) {
  438. if (*(p->pBuffer+2)==0x00 && *(p->pBuffer+3)==0x19) {
  439. EQProtocolPacket *subp=new EQProtocolPacket(oversize_buffer,oversize_offset);
  440. subp->copyInfo(p);
  441. ProcessPacket(subp, p);
  442. delete subp;
  443. } else {
  444. if(crypto->isEncrypted() && p && p->size > 2){
  445. MCombineQueueLock.lock();
  446. EQProtocolPacket* p2 = ProcessEncryptedData(oversize_buffer, oversize_offset, p->opcode);
  447. MCombineQueueLock.unlock();
  448. EQApplicationPacket* ap = p2->MakeApplicationPacket(2);
  449. ap->copyInfo(p);
  450. if (ap->version == 0)
  451. ap->version = client_version;
  452. #ifdef WRITE_PACKETS
  453. WritePackets(ap->GetOpcodeName(), oversize_buffer, oversize_offset, false);
  454. #endif
  455. ap->copyInfo(p);
  456. InboundQueuePush(ap);
  457. safe_delete(p2);
  458. }
  459. }
  460. delete[] oversize_buffer;
  461. oversize_buffer=NULL;
  462. oversize_offset=0;
  463. }
  464. } else if (!oversize_buffer) {
  465. oversize_length=ntohl(*(uint32 *)(p->pBuffer+2));
  466. oversize_buffer=new unsigned char[oversize_length];
  467. memcpy(oversize_buffer,p->pBuffer+6,p->size-6);
  468. oversize_offset=p->size-6;
  469. //cout << "Oversized is " << oversize_offset << "/" << oversize_length << " (" << (p->size-6) << ") Seq=" << seq << endl;
  470. }
  471. }
  472. }
  473. break;
  474. case OP_KeepAlive: {
  475. #ifndef COLLECTOR
  476. NonSequencedPush(new EQProtocolPacket(p->opcode,p->pBuffer,p->size));
  477. #endif
  478. }
  479. break;
  480. case OP_Ack: {
  481. if (!p->pBuffer || (p->Size() < 4))
  482. {
  483. LogWrite(PACKET__DEBUG, 9, "Packet", "Received OP_Ack that was of malformed size");
  484. break;
  485. }
  486. uint16 seq = ntohs(*(uint16*)(p->pBuffer));
  487. AckPackets(seq);
  488. retransmittimer = Timer::GetCurrentTime2();
  489. }
  490. break;
  491. case OP_SessionRequest: {
  492. if (p->Size() < sizeof(SessionRequest))
  493. {
  494. break;
  495. }
  496. if (GetState() == ESTABLISHED) {
  497. //_log(NET__ERROR, _L "Received OP_SessionRequest in ESTABLISHED state (%d) streamactive (%i) attempt (%i)" __L, GetState(), streamactive, sessionAttempts);
  498. // client seems to try a max of 4 times (initial +3 retries) then gives up, giving it a few more attempts just in case
  499. // streamactive means we identified the opcode, we cannot re-establish this connection
  500. if (streamactive || (sessionAttempts > 30))
  501. {
  502. SendDisconnect(false);
  503. SetState(CLOSED);
  504. break;
  505. }
  506. }
  507. sessionAttempts++;
  508. init(GetState() != ESTABLISHED);
  509. OutboundQueueClear();
  510. SessionRequest *Request=(SessionRequest *)p->pBuffer;
  511. Session=ntohl(Request->Session);
  512. SetMaxLen(ntohl(Request->MaxLength));
  513. #ifndef COLLECTOR
  514. NextInSeq=0;
  515. Key=0x33624702;
  516. SendSessionResponse();
  517. #endif
  518. SetState(ESTABLISHED);
  519. }
  520. break;
  521. case OP_SessionResponse: {
  522. if (p->Size() < sizeof(SessionResponse))
  523. {
  524. break;
  525. }
  526. init();
  527. OutboundQueueClear();
  528. SetActive(true);
  529. SessionResponse *Response=(SessionResponse *)p->pBuffer;
  530. SetMaxLen(ntohl(Response->MaxLength));
  531. Key=ntohl(Response->Key);
  532. NextInSeq=0;
  533. SetState(ESTABLISHED);
  534. if (!Session)
  535. Session=ntohl(Response->Session);
  536. compressed=(Response->Format&FLAG_COMPRESSED);
  537. encoded=(Response->Format&FLAG_ENCODED);
  538. // Kinda kludgy, but trie for now
  539. if (compressed) {
  540. if (remote_port==9000 || (remote_port==0 && p->src_port==9000))
  541. SetStreamType(WorldStream);
  542. else
  543. SetStreamType(ZoneStream);
  544. } else if (encoded)
  545. SetStreamType(ChatOrMailStream);
  546. else
  547. SetStreamType(LoginStream);
  548. }
  549. break;
  550. case OP_SessionDisconnect: {
  551. //NextInSeq=0;
  552. SendDisconnect();
  553. //SetState(CLOSED);
  554. }
  555. break;
  556. case OP_OutOfOrderAck: {
  557. if (!p->pBuffer || (p->Size() < 4))
  558. {
  559. LogWrite(PACKET__DEBUG, 9, "Packet", "Received OP_OutOfOrderAck that was of malformed size");
  560. break;
  561. }
  562. uint16 seq = ntohs(*(uint16*)(p->pBuffer));
  563. MOutboundQueue.lock();
  564. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  565. LogWrite(PACKET__DEBUG, 9, "Packet", "Pre-OOA Invalid Sequenced queue: BS %u + SQ %u != NOS %u", SequencedBase, SequencedQueue.size(), NextOutSeq);
  566. }
  567. //if the packet they got out of order is between our last acked packet and the last sent packet, then its valid.
  568. if (CompareSequence(SequencedBase, seq) != SeqPast && CompareSequence(NextOutSeq, seq) == SeqPast) {
  569. uint16 sqsize = SequencedQueue.size();
  570. uint16 index = seq - SequencedBase;
  571. LogWrite(PACKET__DEBUG, 9, "Packet", "OP_OutOfOrderAck marking packet acked in queue (queue index = %u, queue size = %u)", index, sqsize);
  572. if (index < sqsize) {
  573. SequencedQueue[index]->acked = true;
  574. // flag packets for a resend
  575. uint16 count = 0;
  576. uint32 timeout = AverageDelta * 2 + 100;
  577. for (auto sitr = SequencedQueue.begin(); sitr != SequencedQueue.end() && count < index; ++sitr, ++count) {
  578. if (!(*sitr)->acked && (*sitr)->sent_time > 0 && (((*sitr)->sent_time + timeout) < Timer::GetCurrentTime2())) {
  579. (*sitr)->sent_time = 0;
  580. LogWrite(PACKET__DEBUG, 9, "Packet", "OP_OutOfOrderAck Flagging packet %u for retransmission", SequencedBase + count);
  581. }
  582. }
  583. }
  584. if (RETRANSMIT_TIMEOUT_MULT) {
  585. retransmittimer = Timer::GetCurrentTime2();
  586. }
  587. }
  588. else {
  589. LogWrite(PACKET__DEBUG, 9, "Packet", "Received OP_OutOfOrderAck for out-of-window %u. Window (%u->%u)", seq, SequencedBase, NextOutSeq);
  590. }
  591. if (uint16(SequencedBase + SequencedQueue.size()) != NextOutSeq) {
  592. LogWrite(PACKET__DEBUG, 9, "Packet", "Post-OOA Invalid Sequenced queue: BS %u + SQ %u != NOS %u", SequencedBase, SequencedQueue.size(), NextOutSeq);
  593. }
  594. MOutboundQueue.unlock();
  595. }
  596. break;
  597. case OP_ServerKeyRequest:{
  598. if (p->Size() < sizeof(ClientSessionStats))
  599. {
  600. //_log(NET__ERROR, _L "Received OP_SessionStatRequest that was of malformed size" __L);
  601. break;
  602. }
  603. ClientSessionStats* Stats = (ClientSessionStats*)p->pBuffer;
  604. int16 request_id = Stats->RequestID;
  605. AdjustRates(ntohl(Stats->average_delta));
  606. ServerSessionStats* stats=(ServerSessionStats*)p->pBuffer;
  607. memset(stats, 0, sizeof(ServerSessionStats));
  608. stats->RequestID = request_id;
  609. stats->current_time = ntohl(Timer::GetCurrentTime2());
  610. stats->sent_packets = ntohl(sent_packets);
  611. stats->sent_packets2 = ntohl(sent_packets);
  612. stats->received_packets = ntohl(received_packets);
  613. stats->received_packets2 = ntohl(received_packets);
  614. NonSequencedPush(new EQProtocolPacket(OP_SessionStatResponse,p->pBuffer,p->size));
  615. if(!crypto->isEncrypted())
  616. SendKeyRequest();
  617. }
  618. break;
  619. case OP_SessionStatResponse: {
  620. LogWrite(PACKET__INFO, 0, "Packet", "OP_SessionStatResponse");
  621. }
  622. break;
  623. case OP_OutOfSession: {
  624. LogWrite(PACKET__INFO, 0, "Packet", "OP_OutOfSession");
  625. SendDisconnect();
  626. SetState(CLOSED);
  627. }
  628. break;
  629. default:
  630. //EQApplicationPacket *ap = p->MakeApplicationPacket(app_opcode_size);
  631. //InboundQueuePush(ap);
  632. cout << "Orig Packet: " << p->opcode << endl;
  633. DumpPacket(p->pBuffer, p->size);
  634. if(p && p->size >= 70){
  635. processRSAKey(p);
  636. }
  637. MCombineQueueLock.lock();
  638. EQProtocolPacket* p2 = ProcessEncryptedData(p->pBuffer, p->size, OP_Packet);
  639. MCombineQueueLock.unlock();
  640. cout << "Decrypted Packet: " << p2->opcode << endl;
  641. DumpPacket(p2->pBuffer, p2->size);
  642. safe_delete(p2);
  643. /* if(p2)
  644. {
  645. EQApplicationPacket* ap = p2->MakeApplicationPacket(2);
  646. if (ap->version == 0)
  647. ap->version = client_version;
  648. InboundQueuePush(ap);
  649. safe_delete(p2);
  650. }*/
  651. //EQProtocolPacket* puse = p2;
  652. /* if (!rogue_buffer) {
  653. roguebuf_size=puse->size;
  654. rogue_buffer=new unsigned char[roguebuf_size];
  655. memcpy(rogue_buffer,puse->pBuffer,puse->size);
  656. roguebuf_offset=puse->size;
  657. cout << "RogueBuf is " << roguebuf_offset << "/" << roguebuf_size << " (" << (p->size-6) << ") NextInSeq=" << NextInSeq << endl;
  658. }
  659. else {
  660. int32 new_size = roguebuf_size + puse->size;
  661. uchar* tmp_buffer = new unsigned char[new_size];
  662. uchar* ptr = tmp_buffer;
  663. memcpy(ptr,rogue_buffer,roguebuf_size);
  664. ptr += roguebuf_size;
  665. memcpy(ptr,puse->pBuffer,puse->size);
  666. roguebuf_offset=puse->size;
  667. safe_delete_array(rogue_buffer);
  668. rogue_buffer = tmp_buffer;
  669. roguebuf_size = new_size;
  670. roguebuf_offset = new_size;
  671. cout << "RogueBuf is " << roguebuf_offset << "/" << roguebuf_size << " (" << (p->size-6) << ") NextInSeq=" << NextInSeq << endl;
  672. }*/
  673. #ifdef WRITE_PACKETS
  674. WritePackets(ap->GetOpcodeName(), p->pBuffer, p->size, false);
  675. #endif
  676. //InboundQueuePush(ap);
  677. LogWrite(PACKET__INFO, 0, "Packet", "Received unknown packet type, not adding to inbound queue");
  678. //safe_delete(p2);
  679. //SendDisconnect();
  680. break;
  681. }
  682. }
  683. }
  684. int8 EQStream::EQ2_Compress(EQ2Packet* app, int8 offset){
  685. #ifdef LE_DEBUG
  686. printf( "Before Compress in %s, line %i:\n", __FUNCTION__, __LINE__);
  687. DumpPacket(app);
  688. #endif
  689. uchar* pDataPtr = app->pBuffer + offset;
  690. int xpandSize = app->size * 2;
  691. uchar* deflate_buff = new uchar[xpandSize];
  692. MCompressData.lock();
  693. stream.next_in = pDataPtr;
  694. stream.avail_in = app->size - offset;
  695. stream.next_out = deflate_buff;
  696. stream.avail_out = xpandSize;
  697. int ret = deflate(&stream, Z_SYNC_FLUSH);
  698. if (ret != Z_OK)
  699. {
  700. printf("ZLIB COMPRESSION RETFAIL: %i, %i (Ret: %i)\n", app->size, stream.avail_out, ret);
  701. MCompressData.unlock();
  702. safe_delete_array(deflate_buff);
  703. return 0;
  704. }
  705. int32 newsize = xpandSize - stream.avail_out;
  706. safe_delete_array(app->pBuffer);
  707. app->size = newsize + offset;
  708. app->pBuffer = new uchar[app->size];
  709. app->pBuffer[(offset - 1)] = 1;
  710. memcpy(app->pBuffer + offset, deflate_buff, newsize);
  711. MCompressData.unlock();
  712. safe_delete_array(deflate_buff);
  713. #ifdef LE_DEBUG
  714. printf( "After Compress in %s, line %i:\n", __FUNCTION__, __LINE__);
  715. DumpPacket(app);
  716. #endif
  717. return offset - 1;
  718. }
  719. int16 EQStream::processRSAKey(EQProtocolPacket *p){
  720. /*int16 limit = 0;
  721. int8 offset = 13;
  722. int8 offset2 = 0;
  723. if(p->pBuffer[2] == 0)
  724. limit = p->pBuffer[9];
  725. else{
  726. limit = p->pBuffer[5];
  727. offset2 = 5;
  728. offset-=1;
  729. }
  730. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + offset + (limit-8), 8));
  731. return (limit + offset +1) - offset2;*/
  732. if(p->pBuffer[0] == 0)
  733. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + 62, 8));
  734. else
  735. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + 61, 8));
  736. return 0;
  737. }
  738. void EQStream::SendKeyRequest(){
  739. int32 crypto_key_size = 60;
  740. int16 size = sizeof(KeyGen_Struct) + sizeof(KeyGen_End_Struct) + crypto_key_size;
  741. EQ2Packet *outapp=new EQ2Packet(OP_WSLoginRequestMsg,NULL,size);
  742. memcpy(&outapp->pBuffer[0], &crypto_key_size, sizeof(int32));
  743. memset(&outapp->pBuffer[4], 0xFF, crypto_key_size);
  744. memset(&outapp->pBuffer[size-5], 1, 1);
  745. memset(&outapp->pBuffer[size-1], 1, 1);
  746. EQ2QueuePacket(outapp, true);
  747. }
  748. void EQStream::EncryptPacket(EQ2Packet* app, int8 compress_offset, int8 offset){
  749. if(app->size>2 && crypto->isEncrypted()){
  750. app->packet_encrypted = true;
  751. uchar* crypt_buff = app->pBuffer;
  752. if(app->eq2_compressed)
  753. crypto->RC4Encrypt(crypt_buff + compress_offset, app->size - compress_offset);
  754. else
  755. crypto->RC4Encrypt(crypt_buff + 2 + offset, app->size - 2 - offset);
  756. }
  757. }
  758. void EQStream::EQ2QueuePacket(EQ2Packet* app, bool attempted_combine){
  759. if(CheckActive()){
  760. if(!attempted_combine){
  761. MCombineQueueLock.lock();
  762. combine_queue.push_back(app);
  763. MCombineQueueLock.unlock();
  764. }
  765. else{
  766. MCombineQueueLock.lock();
  767. PreparePacket(app);
  768. MCombineQueueLock.unlock();
  769. #ifdef LE_DEBUG
  770. printf( "After B in %s, line %i:\n", __FUNCTION__, __LINE__);
  771. DumpPacket(app);
  772. #endif
  773. SendPacket(app);
  774. }
  775. }
  776. }
  777. void EQStream::UnPreparePacket(EQ2Packet* app){
  778. if(app->pBuffer[2] == 0 && app->pBuffer[3] == 19){
  779. uchar* new_buffer = new uchar[app->size-3];
  780. memcpy(new_buffer+2, app->pBuffer+5, app->size-3);
  781. delete[] app->pBuffer;
  782. app->size-=3;
  783. app->pBuffer = new_buffer;
  784. }
  785. }
  786. #ifdef WRITE_PACKETS
  787. char EQStream::GetChar(uchar in)
  788. {
  789. if (in < ' ' || in > '~')
  790. return '.';
  791. return (char)in;
  792. }
  793. void EQStream::WriteToFile(char* pFormat, ...) {
  794. va_list args;
  795. va_start(args, pFormat);
  796. vfprintf(write_packets, pFormat, args);
  797. va_end(args);
  798. }
  799. void EQStream::WritePackets(const char* opcodeName, uchar* data, int32 size, bool outgoing) {
  800. MWritePackets.lock();
  801. struct in_addr ip_addr;
  802. ip_addr.s_addr = remote_ip;
  803. char timebuffer[80];
  804. time_t rawtime;
  805. struct tm* timeinfo;
  806. time(&rawtime);
  807. timeinfo = localtime(&rawtime);
  808. strftime(timebuffer, 80, "%m/%d/%Y %H:%M:%S", timeinfo);
  809. if (outgoing)
  810. WriteToFile("-- %s --\n%s\nSERVER -> %s\n", opcodeName, timebuffer, inet_ntoa(ip_addr));
  811. else
  812. WriteToFile("-- %s --\n%s\n%s -> SERVER\n", opcodeName, timebuffer, inet_ntoa(ip_addr));
  813. int i;
  814. int nLines = size / 16;
  815. int nExtra = size % 16;
  816. uchar* pPtr = data;
  817. for (i = 0; i < nLines; i++)
  818. {
  819. 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]));
  820. pPtr += 16;
  821. }
  822. if (nExtra)
  823. {
  824. WriteToFile("%4.4X\t", nLines * 16);
  825. for (i = 0; i < nExtra; i++)
  826. {
  827. WriteToFile("%2.2X ", pPtr[i]);
  828. }
  829. for (i; i < 16; i++)
  830. WriteToFile(" ");
  831. for (i = 0; i < nExtra; i++)
  832. {
  833. WriteToFile("%c", GetChar(pPtr[i]));
  834. }
  835. WriteToFile("\n");
  836. }
  837. WriteToFile("\n\n");
  838. fflush(write_packets);
  839. MWritePackets.unlock();
  840. }
  841. void EQStream::WritePackets(EQ2Packet* app, bool outgoing) {
  842. if (app->version == 0)
  843. app->version = client_version;
  844. WritePackets(app->GetOpcodeName(), app->pBuffer, app->size, outgoing);
  845. }
  846. #endif
  847. void EQStream::PreparePacket(EQ2Packet* app, int8 offset){
  848. app->setVersion(client_version);
  849. compressed_offset = 0;
  850. #ifdef LE_DEBUG
  851. printf( "Before A in %s, line %i:\n", __FUNCTION__, __LINE__);
  852. DumpPacket(app);
  853. #endif
  854. 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(!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 <= 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. }