EQStream.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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. DumpPacket(deflate_buff, newsize);
  580. safe_delete_array(app->pBuffer);
  581. app->size = newsize + offset;
  582. app->pBuffer = new uchar[app->size];
  583. app->pBuffer[(offset - 1)] = 1;
  584. memcpy(app->pBuffer + offset, deflate_buff, newsize);
  585. MCompressData.unlock();
  586. safe_delete_array(deflate_buff);
  587. #ifdef LE_DEBUG
  588. LogWrite(PACKET__DEBUG, 0, "Packet", "After Compress in %s, line %i:", __FUNCTION__, __LINE__);
  589. DumpPacket(app);
  590. #endif
  591. return offset - 1;
  592. }
  593. int16 EQStream::processRSAKey(EQProtocolPacket *p){
  594. /*int16 limit = 0;
  595. int8 offset = 13;
  596. int8 offset2 = 0;
  597. if(p->pBuffer[2] == 0)
  598. limit = p->pBuffer[9];
  599. else{
  600. limit = p->pBuffer[5];
  601. offset2 = 5;
  602. offset-=1;
  603. }
  604. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + offset + (limit-8), 8));
  605. return (limit + offset +1) - offset2;*/
  606. if(p->pBuffer[0] == 0)
  607. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + 62, 8));
  608. else
  609. crypto->setRC4Key(Crypto::RSADecrypt(p->pBuffer + 61, 8));
  610. return 0;
  611. }
  612. void EQStream::SendKeyRequest(){
  613. int32 crypto_key_size = 60;
  614. int16 size = sizeof(KeyGen_Struct) + sizeof(KeyGen_End_Struct) + crypto_key_size;
  615. EQ2Packet *outapp=new EQ2Packet(OP_WSLoginRequestMsg,NULL,size);
  616. memcpy(&outapp->pBuffer[0], &crypto_key_size, sizeof(int32));
  617. memset(&outapp->pBuffer[4], 0xFF, crypto_key_size);
  618. memset(&outapp->pBuffer[size-5], 1, 1);
  619. memset(&outapp->pBuffer[size-1], 1, 1);
  620. EQ2QueuePacket(outapp);
  621. }
  622. void EQStream::EncryptPacket(EQ2Packet* app, int8 compress_offset, int8 offset){
  623. if(app->size>2 && crypto->isEncrypted()){
  624. app->packet_encrypted = true;
  625. uchar* crypt_buff = app->pBuffer;
  626. if(app->eq2_compressed)
  627. crypto->RC4Encrypt(crypt_buff + compress_offset, app->size - compress_offset);
  628. else
  629. crypto->RC4Encrypt(crypt_buff + 2 + offset, app->size - 2 - offset);
  630. }
  631. }
  632. void EQStream::EQ2QueuePacket(EQ2Packet* app, bool attempted_combine){
  633. if(CheckActive()){
  634. if(!attempted_combine){
  635. MCombineQueueLock.lock();
  636. combine_queue.push_back(app);
  637. MCombineQueueLock.unlock();
  638. }
  639. else{
  640. PreparePacket(app);
  641. #ifdef LE_DEBUG
  642. LogWrite(PACKET__DEBUG, 0, "Packet", "After B in %s, line %i:", __FUNCTION__, __LINE__);
  643. DumpPacket(app);
  644. #endif
  645. SendPacket(app);
  646. }
  647. }
  648. }
  649. void EQStream::UnPreparePacket(EQ2Packet* app){
  650. if(app->pBuffer[2] == 0 && app->pBuffer[3] == 19){
  651. uchar* new_buffer = new uchar[app->size-3];
  652. memcpy(new_buffer+2, app->pBuffer+5, app->size-3);
  653. delete[] app->pBuffer;
  654. app->size-=3;
  655. app->pBuffer = new_buffer;
  656. }
  657. }
  658. void EQStream::PreparePacket(EQ2Packet* app, int8 offset){
  659. app->setVersion(client_version);
  660. compressed_offset = 0;
  661. #ifdef LE_DEBUG
  662. LogWrite(PACKET__DEBUG, 0, "Packet", "Before A in %s, line %i:", __FUNCTION__, __LINE__);
  663. DumpPacket(app);
  664. #endif
  665. if(!app->packet_prepared){
  666. if(app->PreparePacket(MaxLen) == 255) //invalid version
  667. return;
  668. }
  669. #ifdef LE_DEBUG
  670. LogWrite(PACKET__DEBUG, 0, "Packet", "After Prepare in %s, line %i:", __FUNCTION__, __LINE__);
  671. DumpPacket(app);
  672. #endif
  673. if(!app->eq2_compressed && app->size>128){
  674. compressed_offset = EQ2_Compress(app);
  675. if (compressed_offset)
  676. app->eq2_compressed = true;
  677. }
  678. if(!app->packet_encrypted){
  679. EncryptPacket(app, compressed_offset, offset);
  680. if(app->size > 2 && app->pBuffer[2] == 0){
  681. uchar* new_buffer = new uchar[app->size+1];
  682. new_buffer[2] = 0;
  683. memcpy(new_buffer+3, app->pBuffer+2, app->size-2);
  684. delete[] app->pBuffer;
  685. app->pBuffer = new_buffer;
  686. app->size++;
  687. }
  688. }
  689. #ifdef LE_DEBUG
  690. LogWrite(PACKET__DEBUG, 0, "Packet", "After A in %s, line %i:", __FUNCTION__, __LINE__);
  691. DumpPacket(app);
  692. #endif
  693. }
  694. void EQStream::SendPacket(EQProtocolPacket *p)
  695. {
  696. uint32 chunksize,used;
  697. uint32 length;
  698. // Convert the EQApplicationPacket to 1 or more EQProtocolPackets
  699. if (p->size>( MaxLen-8)) { // proto-op(2), seq(2), app-op(2) ... data ... crc(2)
  700. uchar* tmpbuff=p->pBuffer;
  701. length=p->size - 2;
  702. EQProtocolPacket *out=new EQProtocolPacket(OP_Fragment,NULL,MaxLen-4);
  703. *(uint32 *)(out->pBuffer+2)=htonl(length);
  704. used=MaxLen-10;
  705. memcpy(out->pBuffer+6,tmpbuff+2,used);
  706. #ifdef LE_DEBUG
  707. LogWrite(PACKET__DEBUG, 0, "Packet", "(%s, %i) New Fragment: ", __FUNCTION__, __LINE__);
  708. DumpPacket(out);
  709. #endif
  710. SequencedPush(out);
  711. while (used<length) {
  712. chunksize=min(length-used,MaxLen-6);
  713. out=new EQProtocolPacket(OP_Fragment,NULL,chunksize+2);
  714. //memcpy(out->pBuffer+2,tmpbuff,1);
  715. memcpy(out->pBuffer+2,tmpbuff+used+2,chunksize);
  716. #ifdef LE_DEBUG
  717. LogWrite(PACKET__DEBUG, 0, "Packet", "Chunk: ");
  718. DumpPacket(out);
  719. #endif
  720. SequencedPush(out);
  721. used+=chunksize;
  722. }
  723. #ifdef LE_DEBUG
  724. LogWrite(PACKET__DEBUG, 0, "Packet", "Chunk: ");
  725. DumpPacket(out);
  726. cerr << "1: Deleting 0x" << hex << (uint32)(p) << dec << endl;
  727. #endif
  728. delete p;
  729. } else {
  730. SequencedPush(p);
  731. }
  732. }
  733. void EQStream::SendPacket(EQApplicationPacket *p)
  734. {
  735. uint32 chunksize,used;
  736. uint32 length;
  737. // Convert the EQApplicationPacket to 1 or more EQProtocolPackets
  738. if (p->size>(MaxLen-8)) { // proto-op(2), seq(2), app-op(2) ... data ... crc(2)
  739. //cout << "Making oversized packet for: " << endl;
  740. //cout << p->size << endl;
  741. //p->DumpRawHeader();
  742. //dump_message(p->pBuffer,p->size,timestamp());
  743. //cout << p->size << endl;
  744. unsigned char *tmpbuff=new unsigned char[p->size+2];
  745. //cout << hex << (int)tmpbuff << dec << endl;
  746. length=p->serialize(tmpbuff);
  747. EQProtocolPacket *out=new EQProtocolPacket(OP_Fragment,NULL,MaxLen-4);
  748. *(uint32 *)(out->pBuffer+2)=htonl(p->Size());
  749. memcpy(out->pBuffer+6,tmpbuff,MaxLen-10);
  750. used=MaxLen-10;
  751. SequencedPush(out);
  752. //cout << "Chunk #" << ++i << " size=" << used << ", length-used=" << (length-used) << endl;
  753. while (used<length) {
  754. out=new EQProtocolPacket(OP_Fragment,NULL,MaxLen-4);
  755. chunksize=min(length-used,MaxLen-6);
  756. memcpy(out->pBuffer+2,tmpbuff+used,chunksize);
  757. out->size=chunksize+2;
  758. SequencedPush(out);
  759. used+=chunksize;
  760. //cout << "Chunk #"<< ++i << " size=" << chunksize << ", length-used=" << (length-used) << endl;
  761. }
  762. //cerr << "1: Deleting 0x" << hex << (uint32)(p) << dec << endl;
  763. delete p;
  764. delete[] tmpbuff;
  765. } else {
  766. EQProtocolPacket *out=new EQProtocolPacket(OP_Packet,NULL,p->Size()+2);
  767. p->serialize(out->pBuffer+2);
  768. SequencedPush(out);
  769. //cerr << "2: Deleting 0x" << hex << (uint32)(p) << dec << endl;
  770. delete p;
  771. }
  772. }
  773. void EQStream::SequencedPush(EQProtocolPacket *p)
  774. {
  775. p->setVersion(client_version);
  776. MOutboundQueue.lock();
  777. *(uint16 *)(p->pBuffer)=htons(NextOutSeq);
  778. SequencedQueue.push_back(p);
  779. p->sequence = NextOutSeq;
  780. NextOutSeq++;
  781. MOutboundQueue.unlock();
  782. }
  783. void EQStream::NonSequencedPush(EQProtocolPacket *p)
  784. {
  785. p->setVersion(client_version);
  786. MOutboundQueue.lock();
  787. NonSequencedQueue.push_back(p);
  788. MOutboundQueue.unlock();
  789. }
  790. void EQStream::SendAck(uint16 seq)
  791. {
  792. uint16 Seq=htons(seq);
  793. SetLastAckSent(seq);
  794. NonSequencedPush(new EQProtocolPacket(OP_Ack,(unsigned char *)&Seq,sizeof(uint16)));
  795. }
  796. void EQStream::SendOutOfOrderAck(uint16 seq)
  797. {
  798. uint16 Seq=htons(seq);
  799. NonSequencedPush(new EQProtocolPacket(OP_OutOfOrderAck,(unsigned char *)&Seq,sizeof(uint16)));
  800. }
  801. bool EQStream::CheckCombineQueue(){
  802. bool ret = true; //processed all packets
  803. MCombineQueueLock.lock();
  804. if(combine_queue.size() > 0){
  805. EQ2Packet* first = combine_queue.front();
  806. combine_queue.pop_front();
  807. if(combine_queue.size() == 0){ //nothing to combine this with
  808. EQ2QueuePacket(first, true);
  809. }
  810. else{
  811. PreparePacket(first);
  812. EQ2Packet* second = 0;
  813. bool combine_worked = false;
  814. int16 count = 0;
  815. while(combine_queue.size()){
  816. count++;
  817. second = combine_queue.front();
  818. combine_queue.pop_front();
  819. MCombineQueueLock.unlock();
  820. PreparePacket(second);
  821. /*if(first->GetRawOpcode() != OP_AppCombined && first->pBuffer[2] == 0){
  822. EQ2Packet* tmp = second;
  823. second = first;
  824. first = tmp;
  825. }*/
  826. if(!first->AppCombine(second)){
  827. first->SetProtocolOpcode(OP_Packet);
  828. if(combine_worked){
  829. SequencedPush(first);
  830. }
  831. else{
  832. EQ2QueuePacket(first, true);
  833. }
  834. first = second;
  835. combine_worked = false;
  836. }
  837. else{
  838. combine_worked = true;
  839. //DumpPacket(first);
  840. }
  841. MCombineQueueLock.lock();
  842. if(count >= 60 || first->size > 4000){ //other clients need packets too
  843. ret = false;
  844. break;
  845. }
  846. }
  847. if(first){
  848. first->SetProtocolOpcode(OP_Packet);
  849. if(combine_worked){
  850. SequencedPush(first);
  851. }
  852. else{
  853. EQ2QueuePacket(first, true);
  854. }
  855. }
  856. }
  857. }
  858. MCombineQueueLock.unlock();
  859. return ret;
  860. }
  861. void EQStream::CheckResend(int eq_fd){
  862. int32 curr = Timer::GetCurrentTime2();
  863. EQProtocolPacket* packet = 0;
  864. deque<EQProtocolPacket*>::iterator itr;
  865. MResendQue.lock();
  866. for(itr=resend_que.begin();itr!=resend_que.end();itr++){
  867. packet = *itr;
  868. if(packet->attempt_count >= 5){//tried to resend this packet 5 times, client must already have it but didnt ack it
  869. safe_delete(packet);
  870. itr = resend_que.erase(itr);
  871. if(itr == resend_que.end())
  872. break;
  873. }
  874. else{
  875. if((curr - packet->sent_time) < 1000)
  876. continue;
  877. packet->sent_time -=1000;
  878. packet->attempt_count++;
  879. WritePacket(eq_fd, packet);
  880. }
  881. }
  882. MResendQue.unlock();
  883. }
  884. void EQStream::Write(int eq_fd)
  885. {
  886. deque<EQProtocolPacket *> ReadyToSend;
  887. deque<EQProtocolPacket *> SeqReadyToSend;
  888. long maxack;
  889. map<uint16, EQProtocolPacket *>::iterator sitr;
  890. // Check our rate to make sure we can send more
  891. MRate.lock();
  892. sint32 threshold=RateThreshold;
  893. MRate.unlock();
  894. if (BytesWritten > threshold) {
  895. //cout << "Over threshold: " << BytesWritten << " > " << threshold << endl;
  896. return;
  897. }
  898. MCombinedAppPacket.lock();
  899. EQApplicationPacket *CombPack=CombinedAppPacket;
  900. CombinedAppPacket=NULL;
  901. MCombinedAppPacket.unlock();
  902. if (CombPack) {
  903. SendPacket(CombPack);
  904. }
  905. // If we got more packets to we need to ack, send an ack on the highest one
  906. MAcks.lock();
  907. maxack=MaxAckReceived;
  908. // Added from peaks findings
  909. if (NextAckToSend>LastAckSent || LastAckSent == 0x0000ffff)
  910. SendAck(NextAckToSend);
  911. MAcks.unlock();
  912. // Lock the outbound queues while we process
  913. MOutboundQueue.lock();
  914. // Adjust where we start sending in case we get a late ack
  915. if (maxack>LastSeqSent)
  916. LastSeqSent=maxack;
  917. // Place to hold the base packet t combine into
  918. EQProtocolPacket *p=NULL;
  919. // Loop until both are empty or MaxSends is reached
  920. // See if there are more non-sequenced packets left
  921. while (NonSequencedQueue.size()) {
  922. if (!p) {
  923. // If we don't have a packet to try to combine into, use this one as the base
  924. // And remove it form the queue
  925. p = NonSequencedQueue.front();
  926. NonSequencedQueue.pop_front();
  927. }
  928. //Check if we have a packet to combine p with...
  929. if (NonSequencedQueue.size()){
  930. if (!p->combine(NonSequencedQueue.front())) {
  931. // Tryint to combine this packet with the base didn't work (too big maybe)
  932. // So just send the base packet (we'll try this packet again later)
  933. ReadyToSend.push_back(p);
  934. BytesWritten += p->size;
  935. p = NULL;
  936. }
  937. else {
  938. // Combine worked, so just remove this packet and it's spot in the queue
  939. delete NonSequencedQueue.front();
  940. NonSequencedQueue.pop_front();
  941. }
  942. }
  943. else {
  944. //We have no packets to combine p with so just send it...
  945. ReadyToSend.push_back(p);
  946. BytesWritten += p->size;
  947. p = NULL;
  948. }
  949. if (BytesWritten > threshold) {
  950. // Sent enough this round, lets stop to be fair
  951. break;
  952. }
  953. }
  954. //The non-seq loop must have broke before we sent this packet, send it now
  955. if (p){
  956. ReadyToSend.push_back(p);
  957. BytesWritten += p->size;
  958. }
  959. if (SequencedQueue.size() && BytesWritten < threshold) {
  960. while(SequencedQueue.size()) {
  961. p = SequencedQueue.front();
  962. BytesWritten+=p->size;
  963. SeqReadyToSend.push_back(p);
  964. p->sent_time = Timer::GetCurrentTime2();
  965. resend_que.push_back(p);
  966. SequencedQueue.pop_front();
  967. LastSeqSent=p->sequence;
  968. if (BytesWritten > threshold) {
  969. break;
  970. }
  971. }
  972. }
  973. // Unlock the queue
  974. MOutboundQueue.unlock();
  975. // Send all the packets we "made"
  976. while(ReadyToSend.size()) {
  977. WritePacket(eq_fd,ReadyToSend.front());
  978. delete ReadyToSend.front();
  979. ReadyToSend.pop_front();
  980. }
  981. while(SeqReadyToSend.size()){
  982. WritePacket(eq_fd,SeqReadyToSend.front());
  983. SeqReadyToSend.pop_front();
  984. }
  985. }
  986. void EQStream::WritePacket(int eq_fd, EQProtocolPacket *p)
  987. {
  988. uint32 length = 0;
  989. sockaddr_in address;
  990. unsigned char tmpbuffer[1024];
  991. address.sin_family = AF_INET;
  992. address.sin_addr.s_addr=remote_ip;
  993. address.sin_port=remote_port;
  994. #ifdef NOWAY
  995. uint32 ip=address.sin_addr.s_addr;
  996. cout << "Sending to: "
  997. << (int)*(unsigned char *)&ip
  998. << "." << (int)*((unsigned char *)&ip+1)
  999. << "." << (int)*((unsigned char *)&ip+2)
  1000. << "." << (int)*((unsigned char *)&ip+3)
  1001. << "," << (int)ntohs(address.sin_port) << "(" << p->size << ")" << endl;
  1002. p->DumpRaw();
  1003. cout << "-------------" << endl;
  1004. #endif
  1005. length=p->serialize(buffer);
  1006. if (p->opcode!=OP_SessionRequest && p->opcode!=OP_SessionResponse) {
  1007. if (compressed) {
  1008. uint32 newlen=EQProtocolPacket::Compress(buffer,length,tmpbuffer,1024);
  1009. memcpy(buffer,tmpbuffer,newlen);
  1010. length=newlen;
  1011. }
  1012. if (encoded) {
  1013. EQProtocolPacket::ChatEncode(buffer,length,Key);
  1014. }
  1015. *(uint16 *)(buffer+length)=htons(CRC16(buffer,length,Key));
  1016. length+=2;
  1017. }
  1018. sent_packets++;
  1019. //dump_message_column(buffer,length,"Writer: ");
  1020. //cout << "Raw Data:\n";
  1021. //DumpPacket(buffer, length);
  1022. sendto(eq_fd,(char *)buffer,length,0,(sockaddr *)&address,sizeof(address));
  1023. }
  1024. EQProtocolPacket *EQStream::Read(int eq_fd, sockaddr_in *from)
  1025. {
  1026. int socklen;
  1027. int length=0;
  1028. unsigned char buffer[2048];
  1029. EQProtocolPacket *p=NULL;
  1030. char temp[15];
  1031. socklen=sizeof(sockaddr);
  1032. #ifdef WIN32
  1033. length=recvfrom(eq_fd, (char *)buffer, 2048, 0, (struct sockaddr*)from, (int *)&socklen);
  1034. #else
  1035. length=recvfrom(eq_fd, buffer, 2048, 0, (struct sockaddr*)from, (socklen_t *)&socklen);
  1036. #endif
  1037. if (length>=2) {
  1038. DumpPacket(buffer, length);
  1039. p=new EQProtocolPacket(buffer[1],&buffer[2],length-2);
  1040. uint32 ip=from->sin_addr.s_addr;
  1041. sprintf(temp,"%d.%d.%d.%d:%d",
  1042. *(unsigned char *)&ip,
  1043. *((unsigned char *)&ip+1),
  1044. *((unsigned char *)&ip+2),
  1045. *((unsigned char *)&ip+3),
  1046. ntohs(from->sin_port));
  1047. //cout << timestamp() << "Data from: " << temp << " OpCode 0x" << hex << setw(2) << setfill('0') << (int)p->opcode << dec << endl;
  1048. //dump_message(p->pBuffer,p->size,timestamp());
  1049. }
  1050. return p;
  1051. }
  1052. void EQStream::SendSessionResponse()
  1053. {
  1054. EQProtocolPacket *out=new EQProtocolPacket(OP_SessionResponse,NULL,sizeof(SessionResponse));
  1055. SessionResponse *Response=(SessionResponse *)out->pBuffer;
  1056. Response->Session=htonl(Session);
  1057. Response->MaxLength=htonl(MaxLen);
  1058. Response->UnknownA=2;
  1059. Response->Format=0;
  1060. if (compressed)
  1061. Response->Format|=FLAG_COMPRESSED;
  1062. if (encoded)
  1063. Response->Format|=FLAG_ENCODED;
  1064. Response->Key=htonl(Key);
  1065. out->size=sizeof(SessionResponse);
  1066. NonSequencedPush(out);
  1067. }
  1068. void EQStream::SendSessionRequest()
  1069. {
  1070. EQProtocolPacket *out=new EQProtocolPacket(OP_SessionRequest,NULL,sizeof(SessionRequest));
  1071. SessionRequest *Request=(SessionRequest *)out->pBuffer;
  1072. memset(Request,0,sizeof(SessionRequest));
  1073. Request->Session=htonl(time(NULL));
  1074. Request->MaxLength=htonl(512);
  1075. NonSequencedPush(out);
  1076. }
  1077. void EQStream::SendDisconnect(bool setstate)
  1078. {
  1079. try{
  1080. if(GetState() != ESTABLISHED)
  1081. return;
  1082. EQProtocolPacket *out=new EQProtocolPacket(OP_SessionDisconnect,NULL,sizeof(uint32)+sizeof(int16));
  1083. *(uint32 *)out->pBuffer=htonl(Session);
  1084. out->pBuffer[4] = 0;
  1085. out->pBuffer[5] = 6;
  1086. NonSequencedPush(out);
  1087. if(setstate)
  1088. SetState(CLOSING);
  1089. }
  1090. catch(...){}
  1091. }
  1092. void EQStream::InboundQueuePush(EQApplicationPacket *p)
  1093. {
  1094. MInboundQueue.lock();
  1095. InboundQueue.push_back(p);
  1096. MInboundQueue.unlock();
  1097. }
  1098. EQApplicationPacket *EQStream::PopPacket()
  1099. {
  1100. EQApplicationPacket *p=NULL;
  1101. MInboundQueue.lock();
  1102. if (InboundQueue.size()) {
  1103. p=InboundQueue.front();
  1104. InboundQueue.pop_front();
  1105. }
  1106. MInboundQueue.unlock();
  1107. if(p)
  1108. p->setVersion(client_version);
  1109. return p;
  1110. }
  1111. void EQStream::InboundQueueClear()
  1112. {
  1113. MInboundQueue.lock();
  1114. while(InboundQueue.size()){
  1115. delete InboundQueue.front();
  1116. InboundQueue.pop_front();
  1117. }
  1118. MInboundQueue.unlock();
  1119. }
  1120. void EQStream::EncryptPacket(uchar* data, int16 size){
  1121. if(size>6){
  1122. }
  1123. }
  1124. bool EQStream::HasOutgoingData()
  1125. {
  1126. bool flag;
  1127. //once closed, we have nothing more to say
  1128. if(CheckClosed())
  1129. return(false);
  1130. MOutboundQueue.lock();
  1131. flag=(!NonSequencedQueue.empty());
  1132. if (!flag) {
  1133. flag = (!SequencedQueue.empty());
  1134. }
  1135. MOutboundQueue.unlock();
  1136. if (!flag) {
  1137. MAcks.lock();
  1138. flag= (NextAckToSend>LastAckSent);
  1139. MAcks.unlock();
  1140. }
  1141. if (!flag) {
  1142. MCombinedAppPacket.lock();
  1143. flag=(CombinedAppPacket!=NULL);
  1144. MCombinedAppPacket.unlock();
  1145. }
  1146. return flag;
  1147. }
  1148. void EQStream::OutboundQueueClear()
  1149. {
  1150. MOutboundQueue.lock();
  1151. while(NonSequencedQueue.size()) {
  1152. delete NonSequencedQueue.front();
  1153. NonSequencedQueue.pop_front();
  1154. }
  1155. while(SequencedQueue.size()) {
  1156. delete SequencedQueue.front();
  1157. SequencedQueue.pop_front();
  1158. }
  1159. MOutboundQueue.unlock();
  1160. }
  1161. void EQStream::Process(const unsigned char *buffer, const uint32 length)
  1162. {
  1163. received_packets++;
  1164. static unsigned char newbuffer[2048];
  1165. uint32 newlength=0;
  1166. if (EQProtocolPacket::ValidateCRC(buffer,length,Key)) {
  1167. if (compressed) {
  1168. newlength=EQProtocolPacket::Decompress(buffer,length,newbuffer,2048);
  1169. } else {
  1170. memcpy(newbuffer,buffer,length);
  1171. newlength=length;
  1172. if (encoded)
  1173. EQProtocolPacket::ChatDecode(newbuffer,newlength-2,Key);
  1174. }
  1175. if (buffer[1]!=0x01 && buffer[1]!=0x02 && buffer[1]!=0x1d)
  1176. newlength-=2;
  1177. EQProtocolPacket p(newbuffer,newlength);
  1178. ProcessPacket(&p);
  1179. ProcessQueue();
  1180. } else {
  1181. #ifdef EQN_DEBUG
  1182. cout << "Incoming packet failed checksum:" <<endl;
  1183. dump_message_column(const_cast<unsigned char *>(buffer),length,"CRC failed: ");
  1184. #endif
  1185. }
  1186. }
  1187. long EQStream::GetMaxAckReceived()
  1188. {
  1189. MAcks.lock();
  1190. long l=MaxAckReceived;
  1191. MAcks.unlock();
  1192. return l;
  1193. }
  1194. long EQStream::GetNextAckToSend()
  1195. {
  1196. MAcks.lock();
  1197. long l=NextAckToSend;
  1198. MAcks.unlock();
  1199. return l;
  1200. }
  1201. long EQStream::GetLastAckSent()
  1202. {
  1203. MAcks.lock();
  1204. long l=LastAckSent;
  1205. MAcks.unlock();
  1206. return l;
  1207. }
  1208. void EQStream::SetMaxAckReceived(uint32 seq)
  1209. {
  1210. deque<EQProtocolPacket *>::iterator itr;
  1211. MAcks.lock();
  1212. MaxAckReceived=seq;
  1213. MAcks.unlock();
  1214. MOutboundQueue.lock();
  1215. if (long(seq) > LastSeqSent)
  1216. LastSeqSent=seq;
  1217. MResendQue.lock();
  1218. EQProtocolPacket* packet = 0;
  1219. for(itr=resend_que.begin();itr!=resend_que.end();itr++){
  1220. packet = *itr;
  1221. if(packet && packet->sequence <= seq){
  1222. safe_delete(packet);
  1223. itr = resend_que.erase(itr);
  1224. if(itr == resend_que.end())
  1225. break;
  1226. }
  1227. }
  1228. MResendQue.unlock();
  1229. MOutboundQueue.unlock();
  1230. }
  1231. void EQStream::SetNextAckToSend(uint32 seq)
  1232. {
  1233. MAcks.lock();
  1234. NextAckToSend=seq;
  1235. MAcks.unlock();
  1236. }
  1237. void EQStream::SetLastAckSent(uint32 seq)
  1238. {
  1239. MAcks.lock();
  1240. LastAckSent=seq;
  1241. MAcks.unlock();
  1242. }
  1243. void EQStream::SetLastSeqSent(uint32 seq)
  1244. {
  1245. MOutboundQueue.lock();
  1246. LastSeqSent=seq;
  1247. MOutboundQueue.unlock();
  1248. }
  1249. void EQStream::SetStreamType(EQStreamType type)
  1250. {
  1251. StreamType=type;
  1252. switch (StreamType) {
  1253. case LoginStream:
  1254. app_opcode_size=1;
  1255. compressed=false;
  1256. encoded=false;
  1257. break;
  1258. case EQ2Stream:
  1259. app_opcode_size=2;
  1260. compressed=false;
  1261. encoded=false;
  1262. break;
  1263. case ChatOrMailStream:
  1264. case ChatStream:
  1265. case MailStream:
  1266. app_opcode_size=1;
  1267. compressed=false;
  1268. encoded=true;
  1269. break;
  1270. case ZoneStream:
  1271. case WorldStream:
  1272. default:
  1273. app_opcode_size=2;
  1274. compressed=true;
  1275. encoded=false;
  1276. break;
  1277. }
  1278. }
  1279. void EQStream::ProcessQueue()
  1280. {
  1281. if (OutOfOrderpackets.empty()) {
  1282. return;
  1283. }
  1284. EQProtocolPacket* qp = NULL;
  1285. while ((qp = RemoveQueue(NextInSeq)) != NULL) {
  1286. //_log(NET__DEBUG, _L "Processing Queued Packet: Seq=%d" __L, NextInSeq);
  1287. ProcessPacket(qp);
  1288. delete qp;
  1289. //_log(NET__APP_TRACE, _L "OP_Packet Queue size=%d" __L, PacketQueue.size());
  1290. }
  1291. }
  1292. EQProtocolPacket* EQStream::RemoveQueue(uint16 seq)
  1293. {
  1294. map<unsigned short, EQProtocolPacket*>::iterator itr;
  1295. EQProtocolPacket* qp = NULL;
  1296. if ((itr = OutOfOrderpackets.find(seq)) != OutOfOrderpackets.end()) {
  1297. qp = itr->second;
  1298. OutOfOrderpackets.erase(itr);
  1299. //_log(NET__APP_TRACE, _L "OP_Packet Queue size=%d" __L, PacketQueue.size());
  1300. }
  1301. return qp;
  1302. }
  1303. sint8 EQStream::CompareSequence(uint16 expected_seq , uint16 seq)
  1304. {
  1305. if (expected_seq==seq) {
  1306. // Curent
  1307. return 0;
  1308. } else if ((seq > expected_seq && (uint32)seq < ((uint32)expected_seq + EQStream::MaxWindowSize)) || seq < (expected_seq - EQStream::MaxWindowSize)) {
  1309. // Future
  1310. return 1;
  1311. } else {
  1312. // Past
  1313. return -1;
  1314. }
  1315. }
  1316. void EQStream::Decay()
  1317. {
  1318. MRate.lock();
  1319. uint32 rate=DecayRate;
  1320. MRate.unlock();
  1321. if (BytesWritten>0) {
  1322. BytesWritten-=rate;
  1323. if (BytesWritten<0)
  1324. BytesWritten=0;
  1325. }
  1326. }
  1327. void EQStream::AdjustRates(uint32 average_delta)
  1328. {
  1329. if (average_delta) {
  1330. MRate.lock();
  1331. RateThreshold=RATEBASE/average_delta;
  1332. DecayRate=DECAYBASE/average_delta;
  1333. MRate.unlock();
  1334. }
  1335. }