EQStream.cpp 49 KB

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