EQStream.cpp 46 KB

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