EQStream.cpp 50 KB

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