EQStream.cpp 46 KB

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