EQStream.cpp 38 KB

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