EQStream.cpp 54 KB

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