9
3

EQStream.cpp 52 KB

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