1. #include "stdafx.h"
  2. #include "config.h"
  3. #include "utils.h"
  4. #include "desc.h"
  5. #include "desc_client.h"
  6. #include "desc_manager.h"
  7. #include "char.h"
  8. #include "protocol.h"
  9. #include "packet.h"
  10. #include "messenger_manager.h"
  11. #include "sectree_manager.h"
  12. #include "p2p.h"
  13. #include "buffer_manager.h"
  14. #include "sequence.h"
  15. #include "guild.h"
  16. #include "guild_manager.h"
  17. #include "TrafficProfiler.h"
  18. #include "locale_service.h"
  19. #include "log.h"
  20. extern int max_bytes_written;
  21. extern int current_bytes_written;
  22. extern int total_bytes_written;
  23. DESC::DESC()
  24. {
  25. Initialize();
  26. }
  27. DESC::~DESC()
  28. {
  29. }
  30. void DESC::Initialize()
  31. {
  32. m_bDestroyed = false;
  33. m_pInputProcessor = NULL;
  34. m_lpFdw = NULL;
  35. m_sock = INVALID_SOCKET;
  36. m_iPhase = PHASE_CLOSE;
  37. m_dwHandle = 0;
  38. m_wPort = 0;
  39. m_LastTryToConnectTime = 0;
  40. m_lpInputBuffer = NULL;
  41. m_iMinInputBufferLen = 0;
  42. m_dwHandshake = 0;
  43. m_dwHandshakeSentTime = 0;
  44. m_iHandshakeRetry = 0;
  45. m_dwClientTime = 0;
  46. m_bHandshaking = false;
  47. m_lpBufferedOutputBuffer = NULL;
  48. m_lpOutputBuffer = NULL;
  49. m_pkPingEvent = NULL;
  50. m_lpCharacter = NULL;
  51. memset( &m_accountTable, 0, sizeof(m_accountTable) );
  52. memset( &m_SockAddr, 0, sizeof(m_SockAddr) );
  53. memset( &m_UDPSockAddr, 0, sizeof(m_UDPSockAddr) );
  54. m_pLogFile = NULL;
  55. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  56. m_bEncrypted = false;
  57. #endif
  58. m_wP2PPort = 0;
  59. m_bP2PChannel = 0;
  60. m_bAdminMode = false;
  61. m_bPong = true;
  62. m_bChannelStatusRequested = false;
  63. m_iCurrentSequence = 0;
  64. m_pkLoginKey = NULL;
  65. m_dwLoginKey = 0;
  66. m_dwPanamaKey = 0;
  67. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  68. memset( m_adwDecryptionKey, 0, sizeof(m_adwDecryptionKey) );
  69. memset( m_adwEncryptionKey, 0, sizeof(m_adwEncryptionKey) );
  70. #endif
  71. m_bCRCMagicCubeIdx = 0;
  72. m_dwProcCRC = 0;
  73. m_dwFileCRC = 0;
  74. m_bHackCRCQuery = 0;
  75. m_outtime = 0;
  76. m_playtime = 0;
  77. m_offtime = 0;
  78. m_pkDisconnectEvent = NULL;
  79. m_seq_vector.clear();
  80. }
  81. void DESC::Destroy()
  82. {
  83. if (m_bDestroyed) {
  84. return;
  85. }
  86. m_bDestroyed = true;
  87. if (m_pkLoginKey)
  88. m_pkLoginKey->Expire();
  89. if (GetAccountTable().id)
  90. DESC_MANAGER::instance().DisconnectAccount(GetAccountTable().login);
  91. if (m_pLogFile)
  92. {
  93. fclose(m_pLogFile);
  94. m_pLogFile = NULL;
  95. }
  96. if (m_lpCharacter)
  97. {
  98. m_lpCharacter->Disconnect("DESC::~DESC");
  99. m_lpCharacter = NULL;
  100. }
  101. SAFE_BUFFER_DELETE(m_lpOutputBuffer);
  102. SAFE_BUFFER_DELETE(m_lpInputBuffer);
  103. event_cancel(&m_pkPingEvent);
  104. event_cancel(&m_pkDisconnectEvent);
  105. if (!g_bAuthServer)
  106. {
  107. if (m_accountTable.login[0] && m_accountTable.passwd[0])
  108. {
  109. TLogoutPacket pack;
  110. strlcpy(pack.login, m_accountTable.login, sizeof(pack.login));
  111. strlcpy(pack.passwd, m_accountTable.passwd, sizeof(pack.passwd));
  112. db_clientdesc->DBPacket(HEADER_GD_LOGOUT, m_dwHandle, &pack, sizeof(TLogoutPacket));
  113. }
  114. }
  115. if (m_sock != INVALID_SOCKET)
  116. {
  117. sys_log(0, "SYSTEM: closing socket. DESC #%d", m_sock);
  118. Log("SYSTEM: closing socket. DESC #%d", m_sock);
  119. fdwatch_del_fd(m_lpFdw, m_sock);
  120. #ifdef _IMPROVED_PACKET_ENCRYPTION_
  121. cipher_.CleanUp();
  122. #endif
  123. socket_close(m_sock);
  124. m_sock = INVALID_SOCKET;
  125. }
  126. m_seq_vector.clear();
  127. }
  128. EVENTFUNC(ping_event)
  129. {
  130. DESC::desc_event_info* info = dynamic_cast<DESC::desc_event_info*>( event->info );
  131. if ( info == NULL )
  132. {
  133. sys_err( "ping_event> <Factor> Null pointer" );
  134. return 0;
  135. }
  136. LPDESC desc = info->desc;
  137. if (desc->IsAdminMode())
  138. return (ping_event_second_cycle);
  139. if (!desc->IsPong())
  140. {
  141. sys_log(0, "PING_EVENT: no pong %s", desc->GetHostName());
  142. desc->SetPhase(PHASE_CLOSE);
  143. return (ping_event_second_cycle);
  144. }
  145. else
  146. {
  147. TPacketGCPing p;
  148. p.header = HEADER_GC_PING;
  149. desc->Packet(&p, sizeof(struct packet_ping));
  150. desc->SetPong(false);
  151. }
  152. #ifdef ENABLE_LIMIT_TIME
  153. if ((unsigned)get_global_time() >= GLOBAL_LIMIT_TIME)
  154. {
  155. extern void ClearAdminPages();
  156. ClearAdminPages();
  157. extern g_bShutdown;
  158. g_bShutdown = true;
  159. }
  160. #endif
  161. desc->SendHandshake(get_dword_time(), 0);
  162. return (ping_event_second_cycle);
  163. }
  164. bool DESC::IsPong()
  165. {
  166. return m_bPong;
  167. }
  168. void DESC::SetPong(bool b)
  169. {
  170. m_bPong = b;
  171. }
  172. bool DESC::Setup(LPFDWATCH _fdw, socket_t _fd, const struct sockaddr_in & c_rSockAddr, DWORD _handle, DWORD _handshake)
  173. {
  174. m_lpFdw = _fdw;
  175. m_sock = _fd;
  176. m_stHost = inet_ntoa(c_rSockAddr.sin_addr);
  177. m_wPort = c_rSockAddr.sin_port;
  178. m_dwHandle = _handle;
  179. //if (LC_IsEurope() == true || LC_IsNewCIBN())
  180. // m_lpOutputBuffer = buffer_new(DEFAULT_PACKET_BUFFER_SIZE * 2);
  181. //else
  182. //NOTE: ÀÌ°É ³ª¶óº°·Î ´Ù¸£°Ô Àâ¾Æ¾ßÇÒ ÀÌÀ¯°¡ ÀÖ³ª?
  183. m_lpOutputBuffer = buffer_new(DEFAULT_PACKET_BUFFER_SIZE * 2);
  184. m_iMinInputBufferLen = MAX_INPUT_LEN >> 1;
  185. m_lpInputBuffer = buffer_new(MAX_INPUT_LEN);
  186. m_SockAddr = c_rSockAddr;
  187. fdwatch_add_fd(m_lpFdw, m_sock, this, FDW_READ, false);
  188. // Ping Event
  189. desc_event_info* info = AllocEventInfo<desc_event_info>();
  190. info->desc = this;
  191. assert(m_pkPingEvent == NULL);
  192. m_pkPingEvent = event_create(ping_event, info, ping_event_second_cycle);
  193. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  194. if (LC_IsEurope())
  195. {
  196. thecore_memcpy(m_adwEncryptionKey, "1234abcd5678efgh", sizeof(DWORD) * 4);
  197. thecore_memcpy(m_adwDecryptionKey, "1234abcd5678efgh", sizeof(DWORD) * 4);
  198. }
  199. else
  200. {
  201. thecore_memcpy(m_adwEncryptionKey, "testtesttesttest", sizeof(DWORD) * 4);
  202. thecore_memcpy(m_adwDecryptionKey, "testtesttesttest", sizeof(DWORD) * 4);
  203. }
  204. #endif // _IMPROVED_PACKET_ENCRYPTION_
  205. // Set Phase to handshake
  206. SetPhase(PHASE_HANDSHAKE);
  207. StartHandshake(_handshake);
  208. sys_log(0, "SYSTEM: new connection from [%s] fd: %d handshake %u output input_len %d, ptr %p",
  209. m_stHost.c_str(), m_sock, m_dwHandshake, buffer_size(m_lpInputBuffer), this);
  210. Log("SYSTEM: new connection from [%s] fd: %d handshake %u ptr %p", m_stHost.c_str(), m_sock, m_dwHandshake, this);
  211. return true;
  212. }
  213. int DESC::ProcessInput()
  214. {
  215. ssize_t bytes_read;
  216. if (!m_lpInputBuffer)
  217. {
  218. sys_err("DESC::ProcessInput : nil input buffer");
  219. return -1;
  220. }
  221. buffer_adjust_size(m_lpInputBuffer, m_iMinInputBufferLen);
  222. bytes_read = socket_read(m_sock, (char *) buffer_write_peek(m_lpInputBuffer), buffer_has_space(m_lpInputBuffer));
  223. if (bytes_read < 0)
  224. return -1;
  225. else if (bytes_read == 0)
  226. return 0;
  227. buffer_write_proceed(m_lpInputBuffer, bytes_read);
  228. if (!m_pInputProcessor)
  229. sys_err("no input processor");
  230. #ifdef _IMPROVED_PACKET_ENCRYPTION_
  231. else
  232. {
  233. if (cipher_.activated()) {
  234. cipher_.Decrypt(const_cast<void*>(buffer_read_peek(m_lpInputBuffer)), buffer_size(m_lpInputBuffer));
  235. }
  236. int iBytesProceed = 0;
  237. // false°¡ ¸®ÅÏ µÇ¸é ´Ù¸¥ phase·Î ¹Ù²ï °ÍÀ̹ǷΠ´Ù½Ã ÇÁ·Î¼¼½º·Î µ¹ÀÔÇÑ´Ù!
  238. while (!m_pInputProcessor->Process(this, buffer_read_peek(m_lpInputBuffer), buffer_size(m_lpInputBuffer), iBytesProceed))
  239. {
  240. buffer_read_proceed(m_lpInputBuffer, iBytesProceed);
  241. iBytesProceed = 0;
  242. }
  243. buffer_read_proceed(m_lpInputBuffer, iBytesProceed);
  244. }
  245. #else
  246. else if (!m_bEncrypted)
  247. {
  248. int iBytesProceed = 0;
  249. // false°¡ ¸®ÅÏ µÇ¸é ´Ù¸¥ phase·Î ¹Ù²ï °ÍÀ̹ǷΠ´Ù½Ã ÇÁ·Î¼¼½º·Î µ¹ÀÔÇÑ´Ù!
  250. while (!m_pInputProcessor->Process(this, buffer_read_peek(m_lpInputBuffer), buffer_size(m_lpInputBuffer), iBytesProceed))
  251. {
  252. buffer_read_proceed(m_lpInputBuffer, iBytesProceed);
  253. iBytesProceed = 0;
  254. }
  255. buffer_read_proceed(m_lpInputBuffer, iBytesProceed);
  256. }
  257. else
  258. {
  259. int iSizeBuffer = buffer_size(m_lpInputBuffer);
  260. // 8¹ÙÀÌÆ® ´ÜÀ§·Î¸¸ ó¸®ÇÑ´Ù. 8¹ÙÀÌÆ® ´ÜÀ§¿¡ ºÎÁ·Çϸé À߸øµÈ ¾Ïȣȭ ¹öÆÛ¸¦ º¹È£È­
  261. // ÇÒ °¡´É¼ºÀÌ ÀÖÀ¸¹Ç·Î ©¶ó¼­ ó¸®Çϱâ·Î ÇÑ´Ù.
  262. if (iSizeBuffer & 7) // & 7Àº % 8°ú °°´Ù. 2ÀÇ ½Â¼ö¿¡¼­¸¸ °¡´É
  263. iSizeBuffer -= iSizeBuffer & 7;
  264. if (iSizeBuffer > 0)
  265. {
  266. TEMP_BUFFER tempbuf;
  267. LPBUFFER lpBufferDecrypt = tempbuf.getptr();
  268. buffer_adjust_size(lpBufferDecrypt, iSizeBuffer);
  269. int iSizeAfter = TEA_Decrypt((DWORD *) buffer_write_peek(lpBufferDecrypt),
  270. (DWORD *) buffer_read_peek(m_lpInputBuffer),
  271. GetDecryptionKey(),
  272. iSizeBuffer);
  273. buffer_write_proceed(lpBufferDecrypt, iSizeAfter);
  274. int iBytesProceed = 0;
  275. // false°¡ ¸®ÅÏ µÇ¸é ´Ù¸¥ phase·Î ¹Ù²ï °ÍÀ̹ǷΠ´Ù½Ã ÇÁ·Î¼¼½º·Î µ¹ÀÔÇÑ´Ù!
  276. while (!m_pInputProcessor->Process(this, buffer_read_peek(lpBufferDecrypt), buffer_size(lpBufferDecrypt), iBytesProceed))
  277. {
  278. if (iBytesProceed > iSizeBuffer)
  279. {
  280. buffer_read_proceed(m_lpInputBuffer, iSizeBuffer);
  281. iSizeBuffer = 0;
  282. iBytesProceed = 0;
  283. break;
  284. }
  285. buffer_read_proceed(m_lpInputBuffer, iBytesProceed);
  286. iSizeBuffer -= iBytesProceed;
  287. buffer_read_proceed(lpBufferDecrypt, iBytesProceed);
  288. iBytesProceed = 0;
  289. }
  290. buffer_read_proceed(m_lpInputBuffer, iBytesProceed);
  291. }
  292. }
  293. #endif // _IMPROVED_PACKET_ENCRYPTION_
  294. return (bytes_read);
  295. }
  296. int DESC::ProcessOutput()
  297. {
  298. if (buffer_size(m_lpOutputBuffer) <= 0)
  299. return 0;
  300. int buffer_left = fdwatch_get_buffer_size(m_lpFdw, m_sock);
  301. if (buffer_left <= 0)
  302. return 0;
  303. int bytes_to_write = MIN(buffer_left, buffer_size(m_lpOutputBuffer));
  304. if (bytes_to_write == 0)
  305. return 0;
  306. int result = socket_write(m_sock, (const char *) buffer_read_peek(m_lpOutputBuffer), bytes_to_write);
  307. if (result == 0)
  308. {
  309. //sys_log(0, "%d bytes written to %s first %u", bytes_to_write, GetHostName(), *(BYTE *) buffer_read_peek(m_lpOutputBuffer));
  310. //Log("%d bytes written", bytes_to_write);
  311. max_bytes_written = MAX(bytes_to_write, max_bytes_written);
  312. total_bytes_written += bytes_to_write;
  313. current_bytes_written += bytes_to_write;
  314. buffer_read_proceed(m_lpOutputBuffer, bytes_to_write);
  315. if (buffer_size(m_lpOutputBuffer) != 0)
  316. fdwatch_add_fd(m_lpFdw, m_sock, this, FDW_WRITE, true);
  317. }
  318. return (result);
  319. }
  320. void DESC::BufferedPacket(const void * c_pvData, int iSize)
  321. {
  322. if (m_iPhase == PHASE_CLOSE)
  323. return;
  324. if (!m_lpBufferedOutputBuffer)
  325. m_lpBufferedOutputBuffer = buffer_new(MAX(1024, iSize));
  326. buffer_write(m_lpBufferedOutputBuffer, c_pvData, iSize);
  327. }
  328. void DESC::Packet(const void * c_pvData, int iSize)
  329. {
  330. assert(iSize > 0);
  331. if (m_iPhase == PHASE_CLOSE) // ²÷´Â »óÅÂ¸é º¸³»Áö ¾Ê´Â´Ù.
  332. return;
  333. if (m_stRelayName.length() != 0)
  334. {
  335. // Relay ÆĞŶÀº ¾ÏȣȭÇÏÁö ¾Ê´Â´Ù.
  336. TPacketGGRelay p;
  337. p.bHeader = HEADER_GG_RELAY;
  338. strlcpy(p.szName, m_stRelayName.c_str(), sizeof(p.szName));
  339. p.lSize = iSize;
  340. if (!packet_encode(m_lpOutputBuffer, &p, sizeof(p)))
  341. {
  342. m_iPhase = PHASE_CLOSE;
  343. return;
  344. }
  345. m_stRelayName.clear();
  346. if (!packet_encode(m_lpOutputBuffer, c_pvData, iSize))
  347. {
  348. m_iPhase = PHASE_CLOSE;
  349. return;
  350. }
  351. }
  352. else
  353. {
  354. if (m_lpBufferedOutputBuffer)
  355. {
  356. buffer_write(m_lpBufferedOutputBuffer, c_pvData, iSize);
  357. c_pvData = buffer_read_peek(m_lpBufferedOutputBuffer);
  358. iSize = buffer_size(m_lpBufferedOutputBuffer);
  359. }
  360. // TRAFFIC_PROFILE
  361. if (g_bTrafficProfileOn)
  362. TrafficProfiler::instance().Report(TrafficProfiler::IODIR_OUTPUT, *(BYTE *) c_pvData, iSize);
  363. // END_OF_TRAFFIC_PROFILER
  364. #ifdef _IMPROVED_PACKET_ENCRYPTION_
  365. void* buf = buffer_write_peek(m_lpOutputBuffer);
  366. if (packet_encode(m_lpOutputBuffer, c_pvData, iSize))
  367. {
  368. if (cipher_.activated()) {
  369. cipher_.Encrypt(buf, iSize);
  370. }
  371. }
  372. else
  373. {
  374. m_iPhase = PHASE_CLOSE;
  375. }
  376. #else
  377. if (!m_bEncrypted)
  378. {
  379. if (!packet_encode(m_lpOutputBuffer, c_pvData, iSize))
  380. {
  381. m_iPhase = PHASE_CLOSE;
  382. }
  383. }
  384. else
  385. {
  386. if (buffer_has_space(m_lpOutputBuffer) < iSize + 8)
  387. {
  388. sys_err("desc buffer mem_size overflow. memsize(%u) write_pos(%u) iSize(%d)",
  389. m_lpOutputBuffer->mem_size, m_lpOutputBuffer->write_point_pos, iSize);
  390. m_iPhase = PHASE_CLOSE;
  391. }
  392. else
  393. {
  394. // ¾Ïȣȭ¿¡ ÇÊ¿äÇÑ ÃæºĞÇÑ ¹öÆÛ Å©±â¸¦ È®º¸ÇÑ´Ù.
  395. /* buffer_adjust_size(m_lpOutputBuffer, iSize + 8); */
  396. DWORD * pdwWritePoint = (DWORD *) buffer_write_peek(m_lpOutputBuffer);
  397. if (packet_encode(m_lpOutputBuffer, c_pvData, iSize))
  398. {
  399. int iSize2 = TEA_Encrypt(pdwWritePoint, pdwWritePoint, GetEncryptionKey(), iSize);
  400. if (iSize2 > iSize)
  401. buffer_write_proceed(m_lpOutputBuffer, iSize2 - iSize);
  402. }
  403. }
  404. }
  405. #endif // _IMPROVED_PACKET_ENCRYPTION_
  406. SAFE_BUFFER_DELETE(m_lpBufferedOutputBuffer);
  407. }
  408. //sys_log(0, "%d bytes written (first byte %d)", iSize, *(BYTE *) c_pvData);
  409. if (m_iPhase != PHASE_CLOSE)
  410. fdwatch_add_fd(m_lpFdw, m_sock, this, FDW_WRITE, true);
  411. }
  412. void DESC::LargePacket(const void * c_pvData, int iSize)
  413. {
  414. buffer_adjust_size(m_lpOutputBuffer, iSize);
  415. sys_log(0, "LargePacket Size %d", iSize, buffer_size(m_lpOutputBuffer));
  416. Packet(c_pvData, iSize);
  417. }
  418. void DESC::SetPhase(int _phase)
  419. {
  420. m_iPhase = _phase;
  421. TPacketGCPhase pack;
  422. pack.header = HEADER_GC_PHASE;
  423. pack.phase = _phase;
  424. Packet(&pack, sizeof(TPacketGCPhase));
  425. switch (m_iPhase)
  426. {
  427. case PHASE_CLOSE:
  428. // ¸Ş½ÅÀú°¡ ij¸¯ÅÍ´ÜÀ§°¡ µÇ¸é¼­ »èÁ¦
  429. //MessengerManager::instance().Logout(GetAccountTable().login);
  430. m_pInputProcessor = &m_inputClose;
  431. break;
  432. case PHASE_HANDSHAKE:
  433. m_pInputProcessor = &m_inputHandshake;
  434. break;
  435. case PHASE_SELECT:
  436. // ¸Ş½ÅÀú°¡ ij¸¯ÅÍ´ÜÀ§°¡ µÇ¸é¼­ »èÁ¦
  437. //MessengerManager::instance().Logout(GetAccountTable().login); // ÀǵµÀûÀ¸·Î break ¾È°Ë
  438. case PHASE_LOGIN:
  439. case PHASE_LOADING:
  440. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  441. m_bEncrypted = true;
  442. #endif
  443. m_pInputProcessor = &m_inputLogin;
  444. break;
  445. case PHASE_GAME:
  446. case PHASE_DEAD:
  447. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  448. m_bEncrypted = true;
  449. #endif
  450. m_pInputProcessor = &m_inputMain;
  451. break;
  452. case PHASE_AUTH:
  453. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  454. m_bEncrypted = true;
  455. #endif
  456. m_pInputProcessor = &m_inputAuth;
  457. sys_log(0, "AUTH_PHASE %p", this);
  458. break;
  459. }
  460. }
  461. void DESC::BindAccountTable(TAccountTable * pAccountTable)
  462. {
  463. assert(pAccountTable != NULL);
  464. thecore_memcpy(&m_accountTable, pAccountTable, sizeof(TAccountTable));
  465. DESC_MANAGER::instance().ConnectAccount(m_accountTable.login, this);
  466. }
  467. void DESC::UDPGrant(const struct sockaddr_in & c_rSockAddr)
  468. {
  469. m_UDPSockAddr = c_rSockAddr;
  470. TPacketGCBindUDP pack;
  471. pack.header = HEADER_GC_BINDUDP;
  472. pack.addr = m_UDPSockAddr.sin_addr.s_addr;
  473. pack.port = m_UDPSockAddr.sin_port;
  474. Packet(&pack, sizeof(TPacketGCBindUDP));
  475. }
  476. void DESC::Log(const char * format, ...)
  477. {
  478. if (!m_pLogFile)
  479. return;
  480. va_list args;
  481. time_t ct = get_global_time();
  482. struct tm tm = *localtime(&ct);
  483. fprintf(m_pLogFile,
  484. "%02d %02d %02d:%02d:%02d | ",
  485. tm.tm_mon + 1,
  486. tm.tm_mday,
  487. tm.tm_hour,
  488. tm.tm_min,
  489. tm.tm_sec);
  490. va_start(args, format);
  491. vfprintf(m_pLogFile, format, args);
  492. va_end(args);
  493. fputs("\n", m_pLogFile);
  494. fflush(m_pLogFile);
  495. }
  496. void DESC::StartHandshake(DWORD _handshake)
  497. {
  498. // Handshake
  499. m_dwHandshake = _handshake;
  500. SendHandshake(get_dword_time(), 0);
  501. m_iHandshakeRetry = 0;
  502. }
  503. void DESC::SendHandshake(DWORD dwCurTime, long lNewDelta)
  504. {
  505. TPacketGCHandshake pack;
  506. pack.bHeader = HEADER_GC_HANDSHAKE;
  507. pack.dwHandshake = m_dwHandshake;
  508. pack.dwTime = dwCurTime;
  509. pack.lDelta = lNewDelta;
  510. Packet(&pack, sizeof(TPacketGCHandshake));
  511. m_dwHandshakeSentTime = dwCurTime;
  512. m_bHandshaking = true;
  513. }
  514. bool DESC::HandshakeProcess(DWORD dwTime, long lDelta, bool bInfiniteRetry)
  515. {
  516. DWORD dwCurTime = get_dword_time();
  517. if (lDelta < 0)
  518. {
  519. sys_err("Desc::HandshakeProcess : value error (lDelta %d, ip %s)", lDelta, m_stHost.c_str());
  520. return false;
  521. }
  522. int bias = (int) (dwCurTime - (dwTime + lDelta));
  523. if (bias >= 0 && bias <= 50)
  524. {
  525. if (bInfiniteRetry)
  526. {
  527. BYTE bHeader = HEADER_GC_TIME_SYNC;
  528. Packet(&bHeader, sizeof(BYTE));
  529. }
  530. if (GetCharacter())
  531. sys_log(0, "Handshake: client_time %u server_time %u name: %s", m_dwClientTime, dwCurTime, GetCharacter()->GetName());
  532. else
  533. sys_log(0, "Handshake: client_time %u server_time %u", m_dwClientTime, dwCurTime, lDelta);
  534. m_dwClientTime = dwCurTime;
  535. m_bHandshaking = false;
  536. return true;
  537. }
  538. long lNewDelta = (long) (dwCurTime - dwTime) / 2;
  539. if (lNewDelta < 0)
  540. {
  541. sys_log(0, "Handshake: lower than zero %d", lNewDelta);
  542. lNewDelta = (dwCurTime - m_dwHandshakeSentTime) / 2;
  543. }
  544. sys_log(1, "Handshake: ServerTime %u dwTime %u lDelta %d SentTime %u lNewDelta %d", dwCurTime, dwTime, lDelta, m_dwHandshakeSentTime, lNewDelta);
  545. if (!bInfiniteRetry)
  546. if (++m_iHandshakeRetry > HANDSHAKE_RETRY_LIMIT)
  547. {
  548. sys_err("handshake retry limit reached! (limit %d character %s)",
  549. HANDSHAKE_RETRY_LIMIT, GetCharacter() ? GetCharacter()->GetName() : "!NO CHARACTER!");
  550. SetPhase(PHASE_CLOSE);
  551. return false;
  552. }
  553. SendHandshake(dwCurTime, lNewDelta);
  554. return false;
  555. }
  556. bool DESC::IsHandshaking()
  557. {
  558. return m_bHandshaking;
  559. }
  560. DWORD DESC::GetClientTime()
  561. {
  562. return m_dwClientTime;
  563. }
  564. #ifdef _IMPROVED_PACKET_ENCRYPTION_
  565. void DESC::SendKeyAgreement()
  566. {
  567. TPacketKeyAgreement packet;
  568. size_t data_length = TPacketKeyAgreement::MAX_DATA_LEN;
  569. size_t agreed_length = cipher_.Prepare(packet.data, &data_length);
  570. if (agreed_length == 0) {
  571. // Initialization failure
  572. SetPhase(PHASE_CLOSE);
  573. return;
  574. }
  575. assert(data_length <= TPacketKeyAgreement::MAX_DATA_LEN);
  576. packet.bHeader = HEADER_GC_KEY_AGREEMENT;
  577. packet.wAgreedLength = (WORD)agreed_length;
  578. packet.wDataLength = (WORD)data_length;
  579. Packet(&packet, sizeof(packet));
  580. }
  581. void DESC::SendKeyAgreementCompleted()
  582. {
  583. TPacketKeyAgreementCompleted packet;
  584. packet.bHeader = HEADER_GC_KEY_AGREEMENT_COMPLETED;
  585. Packet(&packet, sizeof(packet));
  586. }
  587. bool DESC::FinishHandshake(size_t agreed_length, const void* buffer, size_t length)
  588. {
  589. return cipher_.Activate(false, agreed_length, buffer, length);
  590. }
  591. bool DESC::IsCipherPrepared()
  592. {
  593. return cipher_.IsKeyPrepared();
  594. }
  595. #endif // #ifdef _IMPROVED_PACKET_ENCRYPTION_
  596. void DESC::SetRelay(const char * c_pszName)
  597. {
  598. m_stRelayName = c_pszName;
  599. }
  600. void DESC::BindCharacter(LPCHARACTER ch)
  601. {
  602. m_lpCharacter = ch;
  603. }
  604. void DESC::FlushOutput()
  605. {
  606. if (m_sock == INVALID_SOCKET) {
  607. return;
  608. }
  609. if (buffer_size(m_lpOutputBuffer) <= 0)
  610. return;
  611. struct timeval sleep_tv, now_tv, start_tv;
  612. int event_triggered = false;
  613. gettimeofday(&start_tv, NULL);
  614. socket_block(m_sock);
  615. sys_log(0, "FLUSH START %d", buffer_size(m_lpOutputBuffer));
  616. while (buffer_size(m_lpOutputBuffer) > 0)
  617. {
  618. gettimeofday(&now_tv, NULL);
  619. int iSecondsPassed = now_tv.tv_sec - start_tv.tv_sec;
  620. if (iSecondsPassed > 10)
  621. {
  622. if (!event_triggered || iSecondsPassed > 20)
  623. {
  624. SetPhase(PHASE_CLOSE);
  625. break;
  626. }
  627. }
  628. sleep_tv.tv_sec = 0;
  629. sleep_tv.tv_usec = 10000;
  630. int num_events = fdwatch(m_lpFdw, &sleep_tv);
  631. if (num_events < 0)
  632. {
  633. sys_err("num_events < 0 : %d", num_events);
  634. break;
  635. }
  636. int event_idx;
  637. for (event_idx = 0; event_idx < num_events; ++event_idx)
  638. {
  639. LPDESC d2 = (LPDESC) fdwatch_get_client_data(m_lpFdw, event_idx);
  640. if (d2 != this)
  641. continue;
  642. switch (fdwatch_check_event(m_lpFdw, m_sock, event_idx))
  643. {
  644. case FDW_WRITE:
  645. event_triggered = true;
  646. if (ProcessOutput() < 0)
  647. {
  648. sys_err("Cannot flush output buffer");
  649. SetPhase(PHASE_CLOSE);
  650. }
  651. break;
  652. case FDW_EOF:
  653. SetPhase(PHASE_CLOSE);
  654. break;
  655. }
  656. }
  657. if (IsPhase(PHASE_CLOSE))
  658. break;
  659. }
  660. if (buffer_size(m_lpOutputBuffer) == 0)
  661. sys_log(0, "FLUSH SUCCESS");
  662. else
  663. sys_log(0, "FLUSH FAIL");
  664. usleep(250000);
  665. }
  666. EVENTFUNC(disconnect_event)
  667. {
  668. DESC::desc_event_info* info = dynamic_cast<DESC::desc_event_info*>( event->info );
  669. if ( info == NULL )
  670. {
  671. sys_err( "disconnect_event> <Factor> Null pointer" );
  672. return 0;
  673. }
  674. LPDESC d = info->desc;
  675. d->m_pkDisconnectEvent = NULL;
  676. d->SetPhase(PHASE_CLOSE);
  677. return 0;
  678. }
  679. bool DESC::DelayedDisconnect(int iSec)
  680. {
  681. if (m_pkDisconnectEvent != NULL) {
  682. return false;
  683. }
  684. desc_event_info* info = AllocEventInfo<desc_event_info>();
  685. info->desc = this;
  686. m_pkDisconnectEvent = event_create(disconnect_event, info, PASSES_PER_SEC(iSec));
  687. return true;
  688. }
  689. void DESC::DisconnectOfSameLogin()
  690. {
  691. if (GetCharacter())
  692. {
  693. if (m_pkDisconnectEvent)
  694. return;
  695. GetCharacter()->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´Ù¸¥ ÄÄÇ»ÅÍ¿¡¼­ ·Î±×ÀÎ ÇÏ¿© Á¢¼ÓÀ» Á¾·á ÇÕ´Ï´Ù."));
  696. DelayedDisconnect(5);
  697. }
  698. else
  699. {
  700. SetPhase(PHASE_CLOSE);
  701. }
  702. }
  703. void DESC::SetAdminMode()
  704. {
  705. m_bAdminMode = true;
  706. }
  707. bool DESC::IsAdminMode()
  708. {
  709. return m_bAdminMode;
  710. }
  711. BYTE DESC::GetSequence()
  712. {
  713. return gc_abSequence[m_iCurrentSequence];
  714. }
  715. void DESC::SetNextSequence()
  716. {
  717. if (++m_iCurrentSequence == SEQUENCE_MAX_NUM)
  718. m_iCurrentSequence = 0;
  719. }
  720. void DESC::SendLoginSuccessPacket()
  721. {
  722. TAccountTable & rTable = GetAccountTable();
  723. TPacketGCLoginSuccess p;
  724. p.bHeader = HEADER_GC_LOGIN_SUCCESS_NEWSLOT;
  725. p.handle = GetHandle();
  726. p.random_key = DESC_MANAGER::instance().MakeRandomKey(GetHandle()); // FOR MARK
  727. thecore_memcpy(p.players, rTable.players, sizeof(rTable.players));
  728. for (int i = 0; i < PLAYER_PER_ACCOUNT; ++i)
  729. {
  730. CGuild* g = CGuildManager::instance().GetLinkedGuild(rTable.players[i].dwID);
  731. if (g)
  732. {
  733. p.guild_id[i] = g->GetID();
  734. strlcpy(p.guild_name[i], g->GetName(), sizeof(p.guild_name[i]));
  735. }
  736. else
  737. {
  738. p.guild_id[i] = 0;
  739. p.guild_name[i][0] = '\0';
  740. }
  741. }
  742. Packet(&p, sizeof(TPacketGCLoginSuccess));
  743. }
  744. //void DESC::SendServerStatePacket(int nIndex)
  745. //{
  746. // TPacketGCStateCheck rp;
  747. //
  748. // int iTotal;
  749. // int * paiEmpireUserCount;
  750. // int iLocal;
  751. //
  752. // DESC_MANAGER::instance().GetUserCount(iTotal, &paiEmpireUserCount, iLocal);
  753. //
  754. // rp.header = 1;
  755. // rp.key = 0;
  756. // rp.index = nIndex;
  757. //
  758. // if (g_bNoMoreClient) rp.state = 0;
  759. // else rp.state = iTotal > g_iFullUserCount ? 3 : iTotal > g_iBusyUserCount ? 2 : 1;
  760. //
  761. // this->Packet(&rp, sizeof(rp));
  762. // //printf("STATE_CHECK PACKET PROCESSED.\n");
  763. //}
  764. void DESC::SetLoginKey(DWORD dwKey)
  765. {
  766. m_dwLoginKey = dwKey;
  767. }
  768. void DESC::SetLoginKey(CLoginKey * pkKey)
  769. {
  770. m_pkLoginKey = pkKey;
  771. sys_log(0, "SetLoginKey %u", m_pkLoginKey->m_dwKey);
  772. }
  773. DWORD DESC::GetLoginKey()
  774. {
  775. if (m_pkLoginKey)
  776. return m_pkLoginKey->m_dwKey;
  777. return m_dwLoginKey;
  778. }
  779. const BYTE* GetKey_20050304Myevan()
  780. {
  781. static bool bGenerated = false;
  782. static DWORD s_adwKey[1938];
  783. if (!bGenerated)
  784. {
  785. bGenerated = true;
  786. DWORD seed = 1491971513;
  787. for (UINT i = 0; i < BYTE(seed); ++i)
  788. {
  789. seed ^= 2148941891ul;
  790. seed += 3592385981ul;
  791. s_adwKey[i] = seed;
  792. }
  793. }
  794. return (const BYTE*)s_adwKey;
  795. }
  796. #ifndef _IMPROVED_PACKET_ENCRYPTION_
  797. void DESC::SetSecurityKey(const DWORD * c_pdwKey)
  798. {
  799. const BYTE * c_pszKey = (const BYTE *) "JyTxtHljHJlVJHorRM301vf@4fvj10-v";
  800. if (g_iUseLocale && !LC_IsKorea())
  801. c_pszKey = GetKey_20050304Myevan() + 37;
  802. thecore_memcpy(&m_adwDecryptionKey, c_pdwKey, 16);
  803. TEA_Encrypt(&m_adwEncryptionKey[0], &m_adwDecryptionKey[0], (const DWORD *) c_pszKey, 16);
  804. sys_log(0, "SetSecurityKey decrypt %u %u %u %u encrypt %u %u %u %u",
  805. m_adwDecryptionKey[0], m_adwDecryptionKey[1], m_adwDecryptionKey[2], m_adwDecryptionKey[3],
  806. m_adwEncryptionKey[0], m_adwEncryptionKey[1], m_adwEncryptionKey[2], m_adwEncryptionKey[3]);
  807. }
  808. #endif // _IMPROVED_PACKET_ENCRYPTION_
  809. void DESC::AssembleCRCMagicCube(BYTE bProcPiece, BYTE bFilePiece)
  810. {
  811. static BYTE abXORTable[32] =
  812. {
  813. 102, 30, 0, 0, 0, 0, 0, 0,
  814. 188, 44, 0, 0, 0, 0, 0, 0,
  815. 39, 201, 0, 0, 0, 0, 0, 0,
  816. 43, 5, 0, 0, 0, 0, 0, 0,
  817. };
  818. bProcPiece = (bProcPiece ^ abXORTable[m_bCRCMagicCubeIdx]);
  819. bFilePiece = (bFilePiece ^ abXORTable[m_bCRCMagicCubeIdx+1]);
  820. m_dwProcCRC |= bProcPiece << m_bCRCMagicCubeIdx;
  821. m_dwFileCRC |= bFilePiece << m_bCRCMagicCubeIdx;
  822. m_bCRCMagicCubeIdx += 8;
  823. if (!(m_bCRCMagicCubeIdx & 31))
  824. {
  825. m_dwProcCRC = 0;
  826. m_dwFileCRC = 0;
  827. m_bCRCMagicCubeIdx = 0;
  828. }
  829. }
  830. void DESC::push_seq(BYTE hdr, BYTE seq)
  831. {
  832. if (m_seq_vector.size()>=20)
  833. {
  834. m_seq_vector.erase(m_seq_vector.begin());
  835. }
  836. seq_t info = { hdr, seq };
  837. m_seq_vector.push_back(info);
  838. }
  839. BYTE DESC::GetEmpire()
  840. {
  841. return m_accountTable.bEmpire;
  842. }
  843. void DESC::ChatPacket(BYTE type, const char * format, ...)
  844. {
  845. char chatbuf[CHAT_MAX_LEN + 1];
  846. va_list args;
  847. va_start(args, format);
  848. int len = vsnprintf(chatbuf, sizeof(chatbuf), format, args);
  849. va_end(args);
  850. struct packet_chat pack_chat;
  851. pack_chat.header = HEADER_GC_CHAT;
  852. pack_chat.size = sizeof(struct packet_chat) + len;
  853. pack_chat.type = type;
  854. pack_chat.id = 0;
  855. pack_chat.bEmpire = GetEmpire();
  856. TEMP_BUFFER buf;
  857. buf.write(&pack_chat, sizeof(struct packet_chat));
  858. buf.write(chatbuf, len);
  859. Packet(buf.read_peek(), buf.size());
  860. }

DESC.CPP