Advertisement
Guest User

Untitled

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