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