Guest User

desc.cpp

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