EQStream.cpp 55 KB

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