EQStream.cpp 38 KB

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