LosaDev source snapshot 2019

This commit is contained in:
LosaDev committed 2026-11-07 13:30:45 +07:00
commit c198676e97
20588 files changed
+8812878

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LS_controller", "LS_controller\LS_controller.vcxproj", "{C24427A8-F74F-4662-B8E4-2AB751B66B59}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C24427A8-F74F-4662-B8E4-2AB751B66B59}.Debug|Win32.ActiveCfg = Debug|Win32
{C24427A8-F74F-4662-B8E4-2AB751B66B59}.Debug|Win32.Build.0 = Debug|Win32
{C24427A8-F74F-4662-B8E4-2AB751B66B59}.Release|Win32.ActiveCfg = Release|Win32
{C24427A8-F74F-4662-B8E4-2AB751B66B59}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,709 @@
#include "StdAfx.h"
#include "cFile.h"
#include "MD5.h"
#include "cDemonLauncher.h"
#include "SessionProc.h"
#include "GameCommand.h"
#include "Utility.h"
#include "../include/IIocpContext.h"
#include <io.h>
#include <shlwapi.h>
extern void Tokenize(const std::tstring& str, TOKENS& tokens, const std::tstring& delimiters);
extern BOOL GetServices(STRINGS& services, STRINGS& files, STRINGS& scripts);
extern BOOL IsService(const TCHAR* serviceName);
extern BOOL CreateFolder(const TCHAR* path);
extern BOOL CreateConsole(const TCHAR* title, TCHAR* command, TCHAR* arguments);
void CPing::Run(IIocpContext* context)
{
scPing packet;
packet.code = rand();
SessionProc::SendPacket(
context,
S_PING,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
void CServices::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CServices::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CServices::Begin(IIocpContext* context)
{
if(GetServices(m_services, m_files, m_scripts))
{
Debug(_T("Service count :: %lu\n"), m_services.size());
scServices packet;
packet.count = m_services.size();
cSerialize::Reset();
cSerialize::Write(reinterpret_cast<uint8*>(&packet), sizeof(packet));
Service temp;
std::tstring service, file, script;
for(uint32 n = 0 ; n < packet.count ; n++)
{
service = m_services[n];
file = m_files[n];
script = m_scripts[n];
ZeroMemory(&temp, sizeof(temp));
BOOL result = GetRunning(service.c_str(), temp.running, temp.console);
if(result)
{
Debug(_T("Running :: %s\n"), service.c_str());
}
else
{
Debug(_T("Not Running :: %s\n"), service.c_str());
}
CopyMemory(temp.service, service.c_str(), sizeof(temp.service));
cSerialize::Write(reinterpret_cast<uint8*>(&temp), sizeof(temp));
}
SessionProc::SendPacket(
context,
S_SERVICES,
cSerialize::GetBuffer(),
cSerialize::GetLength());
}
else
{
Debug(_T("Service count :: 0\n"));
scServices packet;
packet.count = 0;
SessionProc::SendPacket(
context,
S_SERVICES,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
}
BOOL CServices::GetRunning(const TCHAR* service, BOOL& running, BOOL& console)
{
running = g_demonLauncher.IsRunningService(service);
if(running)
{
console = FALSE;
return TRUE;
}
running = g_demonLauncher.IsRunningConsole(service);
if(running)
{
//PID = g_demonLauncher.GetPID(service);
console = TRUE;
return TRUE;
}
return FALSE;
}
void CTransfer::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CTransfer::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CTransfer::Begin(IIocpContext* context)
{
BOOL result = FALSE;
switch(m_packet->type)
{
case TRANSFER_BEGIN :
result = TransferBegin();
break;
case TRANSFER_DO :
result = TransferDo();
break;
case TRANSFER_END :
result = TransferEnd();
break;
}
if(result)
{
scTransfer packet;
packet.result = result;
packet.type = m_packet->type;
packet.index = m_packet->index;
SessionProc::SendPacket(
context,
S_TRANSFER,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
else
{
scTransferFail packet;
packet.result = result;
packet.type = m_packet->type;
packet.index = m_packet->index;
CopyMemory(packet.file, m_session->GetFile(), sizeof(packet.file));
SessionProc::SendPacket(
context,
S_TRANSFER,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
m_session->TransferEnd();
}
}
BOOL CTransfer::TransferBegin()
{
if(m_session->DoingTransfer())
return FALSE;
TCHAR path[512];
_stprintf_s(path, _countof(path), _T("%s\\%s"), m_begin->folder, m_begin->file);
if(UpdateFile(path, m_begin->length, m_begin->digest))
{
// 파일이 존재하지 않거나 다른 버젼이므로 복사한다
CreateFolder(m_begin->folder);
CreateBuffer(path, m_begin->length);
return TRUE;
}
// 파일이 존재하고 같은 버젼의 파일이다
return FALSE;
}
BOOL CTransfer::TransferDo()
{
if(m_session->TransferDo(m_buffer, m_length))
{
// 추가 성공
if(m_session->GetLength() >= G_MAXFILESIZE)
{
cFileWriter file;
if(!file.Open(m_session->GetFile(), OPEN_ALWAYS))
{
// 파일생성 실패
Debug(_T("CTransfer - 파일생성 실패\n"));
return FALSE;
}
file.Move(FILE_END, 0);
if(!file.Write(m_session->GetBuffer(), m_session->GetLength()))
{
// 파일 쓰기 실패
file.Close();
Debug(_T("CTransfer - 파일쓰기 실패(%lu Bytes)\n"), m_session->GetLength());
return FALSE;
}
// 종료
file.Close();
// 버퍼정리
m_session->TransferWrite();
}
return TRUE;
}
// 실패
Debug(_T("CTransfer - 데이타 전송실패\n"));
return FALSE;
}
BOOL CTransfer::TransferEnd()
{
if(!m_session->DoingTransfer())
return FALSE;
if(m_end->length == m_session->GetTransferLength())
{
// 미리 저장된 파일인지 확인
if(m_session->GetTransferLength() == m_session->GetLength())
{
// 저장된 적이 없으면 기존 파일을 지운다
DeleteFile(m_session->GetFile());
}
BOOL result = TRUE;
cFileWriter file;
if(!file.Open(m_session->GetFile(), OPEN_ALWAYS))
{
// 파일생성 실패
result = FALSE;
DWORD error = GetLastError();
m_session->TransferEnd();
Debug(_T("CTransfer - 파일생성 실패\n"));
return FALSE;
}
file.Move(FILE_END, 0);
if(!file.Write(m_session->GetBuffer(), m_session->GetLength()))
{
// 파일 쓰기 실패
file.Close();
result = FALSE;
m_session->TransferEnd();
Debug(_T("CTransfer - 파일쓰기 실패(%lu Bytes)\n"), m_session->GetLength());
return FALSE;
}
// 종료
file.Close();
m_session->TransferEnd();
Debug(_T("CTransfer - 파일 전송완료 (%0.1lfKB)\n"), m_end->length / 1024.0);
return result;
}
// 실패
m_session->TransferEnd();
Debug(_T("CTransfer - 파일 전송실패\n"));
return FALSE;
}
BOOL CTransfer::UpdateFile(const TCHAR* fileName, const uint32 fileLength, const BYTE* source)
{
cFileReader file;
BOOL result = file.Open(fileName);
if(result)
{
if(file.GetFileSize() == fileLength)
{
m_temp.Erase();
m_temp.Resize(fileLength);
if(!file.Read(m_temp.GetBuffer(), fileLength))
{
file.Close();
return TRUE;
}
m_temp.SetLength(fileLength);
CMD5 MD5;
MD5.Generate(m_temp.GetBuffer(), fileLength);
BYTE digest[16];
CopyMemory(digest, MD5.GetDigest(), sizeof(digest));
for(uint32 n = 0 ; n < 16 ; n++)
{
if(digest[n] != source[n])
{
file.Close();
return TRUE;
}
}
file.Close();
return FALSE;
}
else
{
file.Close();
return TRUE;
}
}
return TRUE;
}
BOOL CTransfer::CreateBuffer(const TCHAR* fileName, const uint32 length)
{
m_session->TransferBegin(fileName, length);
DeleteFile(m_session->GetFile());
return TRUE;
}
void CRemove::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CRemove::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CRemove::Begin(IIocpContext* context)
{
BOOL result = RemoveFolder();
scRemove packet;
packet.result = result;
SessionProc::SendPacket(
context,
S_REMOVE,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
BOOL CRemove::RemoveFolder()
{
SHFILEOPSTRUCT fileop = {0};
fileop.hwnd = NULL;
fileop.wFunc = FO_DELETE; // 삭제 속성 설정
fileop.pFrom = m_packet->folder;
fileop.pTo = NULL;
fileop.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI;
fileop.fAnyOperationsAborted = FALSE;
fileop.hNameMappings = NULL;
fileop.lpszProgressTitle = NULL;
int result = SHFileOperation(&fileop);
return (0 == result) ? TRUE : FALSE;
}
void CInstall::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CInstall::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CInstall::Begin(IIocpContext* context)
{
BOOL result = FALSE;
if(m_packet->install)
{
result = DoInstall(m_install->service, m_install->file, m_install->script);
}
else
{
result = DoUninstall(m_uninstall->service);
if(result)
{
Remove(m_uninstall->clear);
}
}
scInstall packet;
packet.result = result;
SessionProc::SendPacket(
context,
S_INSTALL,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
BOOL CInstall::DoInstall(const TCHAR* service, const TCHAR* file, const TCHAR* script)
{
if(CreateRegistry(service, file, script))
{
TCHAR command[512];
_stprintf_s(command, _countof(command), _T("/c \"%s -i %s %s\""), file, service, service);
ShellExecute(NULL , NULL, _T("cmd.exe") , command, NULL, SW_HIDE);
return IsService(service);
}
return FALSE;
}
BOOL CInstall::DoUninstall(const TCHAR* service)
{
if(DeleteRegistry(service))
{
TCHAR command[512];
_stprintf_s(command, _countof(command), _T("/c \"sc delete %s\""), service);
ShellExecute(NULL , NULL, _T("cmd.exe") , command, NULL, SW_HIDE);
return !IsService(service);
}
return FALSE;
}
void CInstall::Remove(const BOOL b)
{
if(b)
{
// 파일을 모두 지운다
}
}
BOOL CInstall::CreateRegistry(const TCHAR* service, const TCHAR* file, const TCHAR* script)
{
TCHAR regKey[512];
_stprintf_s(regKey, _countof(regKey), _T("software\\LostSaga\\%s"), service);
HKEY key;
DWORD disp = 0;
LONG ret = RegCreateKeyEx(HKEY_CURRENT_USER, regKey,
0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &disp);
if(ret != ERROR_SUCCESS) return FALSE;
uint32 length = _tcsclen(service);
length = length*sizeof(TCHAR);
RegSetValueEx(key, _T("service"), 0, REG_SZ, (LPBYTE)service, length);
length = _tcsclen(file);
length = length*sizeof(TCHAR);
RegSetValueEx(key, _T("file"), 0, REG_SZ, (LPBYTE)file, length);
length = _tcsclen(script);
length = length*sizeof(TCHAR);
RegSetValueEx(key, _T("script"), 0, REG_SZ, (LPBYTE)script, length);
RegCloseKey(key);
return TRUE;
}
BOOL CInstall::DeleteRegistry(const TCHAR* service)
{
TCHAR regKey[512];
_stprintf_s(regKey, _countof(regKey), _T("software\\LostSaga\\%s"), service);
DWORD disp = 0;
LONG ret = SHDeleteKey(HKEY_CURRENT_USER, regKey);
if(ret != ERROR_SUCCESS) return FALSE;
return TRUE;
}
void CPlay::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CPlay::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CPlay::Begin(IIocpContext* context)
{
BOOL result = FALSE;
if(m_packet->play)
{
result = g_demonLauncher.Play(m_packet->service, m_packet->isDemon);
}
else
{
result = g_demonLauncher.Stop(m_packet->service, m_packet->isDemon);
}
scPlay packet;
packet.result = result;
SessionProc::SendPacket(
context,
S_PLAY,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
void CBackup::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CBackup::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CBackup::Begin(IIocpContext* context)
{
BOOL result = DoBackup(m_packet->source, m_packet->target);
scBackup packet;
packet.result = result;
SessionProc::SendPacket(
context,
S_BACKUP,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
BOOL CBackup::DoBackup(const TCHAR* source, const TCHAR* target)
{
SYSTEMTIME systemTime;
GetLocalTime(&systemTime);
TCHAR backup[512];
ZeroMemory(backup, _countof(backup));
_stprintf_s(backup, _countof(backup),
_T("%s\\%04d%02d%02d-%02d%02d"),
target,
systemTime.wYear,
systemTime.wMonth,
systemTime.wDay,
systemTime.wHour,
systemTime.wMinute);
if(!CreateFolder(backup))
return FALSE;
SHFILEOPSTRUCT fileop = {0};
fileop.hwnd = NULL;
fileop.wFunc = FO_COPY; // 삭제 속성 설정
fileop.pFrom = source;
fileop.pTo = backup;
fileop.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI;
fileop.fAnyOperationsAborted = FALSE;
fileop.hNameMappings = NULL;
fileop.lpszProgressTitle = NULL;
int result = SHFileOperation(&fileop);
return (0 == result) ? TRUE : FALSE;
}
void CReboot::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CReboot::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CReboot::Begin(IIocpContext* context)
{
BOOL result = DoReboot(m_packet->option);
scReboot packet;
packet.result = result;
SessionProc::SendPacket(
context,
S_REBOOT,
reinterpret_cast<uint8*>(&packet),
sizeof(packet));
}
BOOL CReboot::DoReboot(const uint32 option)
{
TCHAR command[512];
_stprintf_s(command, _countof(command), _T("/c \"shutdown.exe /f /r /t %lu\""), option);
ShellExecute(NULL , NULL, _T("cmd.exe") , command, NULL, SW_HIDE);
return TRUE;
}
void CResource::Run(IIocpContext* context)
{
if(!Ready(context))
return;
Begin(context);
}
BOOL CResource::Ready(IIocpContext* context)
{
m_session = SessionProc::GetSession(context->GetEntity());
if(!m_session) return FALSE;
return TRUE;
}
void CResource::Begin(IIocpContext* context)
{
UNITS cpus, mems, diskC, diskD, networks;
DWORD error;
m_perfomance.GetCPU(cpus, error);
m_perfomance.GetMemory(mems, error);
m_perfomance.GetDisk(_T("c:"), diskC, error);
m_perfomance.GetDisk(_T("d:"), diskD, error);
m_perfomance.GetNetwork(networks, error);
scResource packet;
packet.result = TRUE;
packet.cpu = cpus.size();
packet.memory = mems.size();
packet.disk = diskC.size() + diskD.size();
packet.network = networks.size();
cSerialize::Reset();
cSerialize::Write(reinterpret_cast<uint8*>(&packet), sizeof(packet));
for(unsigned int i = 0 ; i < cpus.size() ; i++)
{
cSerialize::Write(static_cast<uint32>(cpus[i]));
}
for(unsigned int i = 0 ; i < mems.size() ; i++)
{
cSerialize::Write(static_cast<uint32>(mems[i]));
}
for(unsigned int i = 0 ; i < diskC.size() ; i++)
{
cSerialize::Write(static_cast<uint32>(diskC[i]));
}
for(unsigned int i = 0 ; i < diskD.size() ; i++)
{
cSerialize::Write(static_cast<uint32>(diskD[i]));
}
for(unsigned int i = 0 ; i < networks.size() ; i++)
{
cSerialize::Write(static_cast<uint32>(networks[i]));
}
SessionProc::SendPacket(
context,
S_RESOURCE,
cSerialize::GetBuffer(),
cSerialize::GetLength());
}
@@ -0,0 +1,348 @@
#pragma once
#include "cCommand.h"
#include "cBuffer.h"
#include "cSession.h"
#include "cSerialize.h"
#include "Utility.h"
#include "PerfMon.h"
#include "../common/internal.h"
#include <vector>
class CPing : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length != 0)
return FALSE;
m_packet = reinterpret_cast<csPing*>(buffer);
return TRUE;
}
virtual void Self()
{
Debug(_T("C_PING\n"));
}
virtual void Run(IIocpContext* context);
protected:
csPing* m_packet;
};
class CServices : public cCommand, public cSerialize
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
m_services.clear();
m_files.clear();
m_scripts.clear();
return TRUE;
}
virtual void Self()
{
Debug(_T("C_SERVICES\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
BOOL GetRunning(const TCHAR* service, BOOL& running, BOOL& console);
protected:
cSession* m_session;
STRINGS m_services, m_files, m_scripts;
};
class CTransfer : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length < sizeof(csTransfer))
return FALSE;
m_packet = reinterpret_cast<csTransfer*>(buffer);
m_buffer = NULL;
m_length = 0;
m_temp.Erase();
switch(m_packet->type)
{
case TRANSFER_BEGIN :
if(length < sizeof(csTransferBegin))
return FALSE;
m_begin = reinterpret_cast<csTransferBegin*>(buffer);
break;
case TRANSFER_DO :
{
if(length < sizeof(csTransferDo))
return FALSE;
m_do = reinterpret_cast<csTransferDo*>(buffer);
m_buffer = (buffer + sizeof(csTransferDo));
if(length != (m_do->length + sizeof(csTransferDo)))
return FALSE;
m_length = m_do->length;
}
break;
case TRANSFER_END :
if(length < sizeof(csTransferEnd))
return FALSE;
m_end = reinterpret_cast<csTransferEnd*>(buffer);
break;
}
return TRUE;
}
virtual void Self()
{
Debug(_T("C_TRANSFER\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
BOOL TransferBegin();
BOOL TransferDo();
BOOL TransferEnd();
BOOL UpdateFile(const TCHAR* fileName, const uint32 fileLength, const BYTE* source);
BOOL CreateBuffer(const TCHAR* fileName, const uint32 length);
protected:
cSession* m_session;
csTransfer* m_packet;
csTransferBegin* m_begin;
csTransferDo* m_do;
csTransferEnd* m_end;
uint8* m_buffer;
uint32 m_length;
cBuffer m_temp;
};
class CRemove : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length < sizeof(csRemove))
return FALSE;
m_packet = reinterpret_cast<csRemove*>(buffer);
return TRUE;
}
virtual void Self()
{
Debug(_T("C_REMOVE\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
BOOL RemoveFolder();
protected:
cSession* m_session;
csRemove* m_packet;
};
class CInstall : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length < sizeof(Install))
return FALSE;
m_packet = reinterpret_cast<Install*>(buffer);
if(m_packet->install)
{
if(length < sizeof(csInstall))
return FALSE;
m_install = reinterpret_cast<csInstall*>(buffer);
}
else
{
if(length < sizeof(csUninstall))
return FALSE;
m_uninstall = reinterpret_cast<csUninstall*>(buffer);
}
return TRUE;
}
virtual void Self()
{
Debug(_T("C_INSTALL\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
BOOL DoInstall(const TCHAR* service, const TCHAR* file, const TCHAR* script);
BOOL DoUninstall(const TCHAR* service);
void Remove(const BOOL b);
BOOL CreateRegistry(const TCHAR* service, const TCHAR* file, const TCHAR* script);
BOOL DeleteRegistry(const TCHAR* service);
protected:
cSession* m_session;
Install* m_packet;
csInstall* m_install;
csUninstall* m_uninstall;
};
class CPlay : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length < sizeof(Play))
return FALSE;
m_packet = reinterpret_cast<Play*>(buffer);
if(m_packet->play)
{
if(length < sizeof(csPlay))
return FALSE;
m_play = reinterpret_cast<csPlay*>(buffer);
}
else
{
if(length < sizeof(csStop))
return FALSE;
m_stop = reinterpret_cast<csStop*>(buffer);
}
return TRUE;
}
virtual void Self()
{
Debug(_T("C_PLAY\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
BOOL DoPlay(const TCHAR* service, const BOOL isDemon, DWORD &PID);
BOOL DoStop(const TCHAR* service, const BOOL isDemon);
protected:
cSession* m_session;
Play* m_packet;
csPlay* m_play;
csStop* m_stop;
};
class CBackup : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length < sizeof(csBackup))
return FALSE;
m_packet = reinterpret_cast<csBackup*>(buffer);
return TRUE;
}
virtual void Self()
{
Debug(_T("C_BACKUP\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
BOOL DoBackup(const TCHAR* source, const TCHAR* target);
protected:
cSession* m_session;
csBackup* m_packet;
};
class CReboot : public cCommand
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
if(length < sizeof(csReboot))
return FALSE;
m_packet = reinterpret_cast<csReboot*>(buffer);
return TRUE;
}
virtual void Self()
{
Debug(_T("C_REBOOT\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
BOOL DoReboot(const uint32 option);
protected:
cSession* m_session;
csReboot* m_packet;
};
class CResource : public cCommand, public cSerialize
{
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length)
{
return TRUE;
}
virtual void Self()
{
Debug(_T("C_RESOURCE\n"));
}
virtual void Run(IIocpContext* context);
protected:
BOOL Ready(IIocpContext* context);
void Begin(IIocpContext* context);
protected:
cSession* m_session;
PerfMon m_perfomance;
};
@@ -0,0 +1,47 @@
#include "StdAfx.h"
#include "cEnvironment.h"
#include "cSessionTable.h"
#include "SessionProc.h"
#include "InternalCommand.h"
#include "../include/IIocpContext.h"
#include "../include/INetwork.h"
#include "../include/cSingleton.h"
#include "../common/Internal.h"
void IConnect::Run(IIocpContext* context)
{
Debug(_T("Connected\n"));
// 세션추가
if(!SessionProc::AddSession(context))
{
// 접속 중이던 세션이므로 종료가 필요함
SessionProc::DeleteSession(context);
}
}
void IClose::Run(IIocpContext* context)
{
Debug(_T("Closed\n"));
// 세션삭제
SessionProc::DeleteSession(context);
}
void IPing::Run(const uint32 serverId)
{
// 접속된 모든 클라이언트 소켓들에게 PING을 보낸다
//Debug("@Ping\n");
SessionProc::Broadcast(S_PING, NULL, 0);
}
void IFlush::Run(const uint32 serverId)
{
//Debug("@Flush\n");
cSession* session = SessionProc::GetFirstSession();
while(session)
{
cSingleton<INetwork>::GetInstance()->Flush(session->GetContext());
session = SessionProc::GetNextSession();
}
}
@@ -0,0 +1,76 @@
#pragma once
#include "cCommand.h"
// 서버에 접속됐을때 자동으로 호출되는 명령
class IConnect : public cCommand
{
protected:
virtual void Self()
{
Debug(_T("I_CONNECT\n"));
}
virtual void Run(IIocpContext* context);
};
// 서버와 연결이 종료되었을때 자동으로 호출되는 명령
class IClose : public cCommand
{
protected:
virtual void Self()
{
Debug(_T("I_CLOSE\n"));
}
virtual void Run(IIocpContext* context);
};
// Ping을 처리해야될 타이머 메세지
class IPing : public cCommand
{
public:
IPing() : m_sequence(0)
{}
protected:
virtual void Self()
{
Debug(_T("I_PING\n"));
}
virtual void Run(const uint32 serverId);
protected:
uint32 m_sequence;
};
// send buffer flush
class IFlush : public cCommand
{
public:
IFlush()
{}
protected:
virtual void Self()
{
Debug(_T("I_FLUSH\n"));
}
virtual void Run(const uint32 serverId);
};
// 접속한 서버에서 주는 신호
class SPing : public cCommand
{
protected:
virtual void Self()
{
Debug(_T("S_PING\n"));
}
};
@@ -0,0 +1,224 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{C24427A8-F74F-4662-B8E4-2AB751B66B59}</ProjectGuid>
<RootNamespace>LS_controller</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">C:\Program Files %28x86%29\Microsoft SDKs\Windows\v7.0A\Include;C:\Program Files %28x86%29\boost\boost_1_47;$(IncludePath)</IncludePath>
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">C:\Program Files %28x86%29\Microsoft SDKs\Windows\v7.0A\Lib;C:\Program Files %28x86%29\boost\boost_1_47\lib;$(LibraryPath)</LibraryPath>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ProjectName)D</TargetName>
<IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">C:\Program Files %28x86%29\boost\boost_1_47;$(IncludePath)</IncludePath>
<LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">C:\Program Files %28x86%29\boost\boost_1_47;$(LibraryPath)</LibraryPath>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(ProjectName)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Midl>
<TypeLibraryName>$(SolutionDir)$(Configuration)/LS-controller.tlb</TypeLibraryName>
<HeaderFileName>
</HeaderFileName>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);../../../src/include</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>
</AssemblerListingLocation>
<ObjectFileName>$(IntDir)</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)ls_controllerD.pdb</ProgramDataBaseFileName>
<WarningLevel>Level3</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Link>
<AdditionalDependencies>perfmonD.lib;pdh.lib;Userenv.lib;Wtsapi32.lib;Shlwapi.lib;../lib/networkD.lib;ws2_32.lib;odbc32.lib;winmm.lib;odbccp32.lib;Mswsock.lib;comsuppw.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>..\Bin\$(ProjectName)D.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
<AdditionalLibraryDirectories>../../../lib</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>
</IgnoreSpecificDefaultLibraries>
</Link>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(SolutionDir)$(Configuration)/LS-controller.bsc</OutputFile>
</Bscmake>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<BuildLog>
<Path>Release\BuildLog.htm</Path>
</BuildLog>
<Midl>
<TypeLibraryName>Release/$(Configuration)/LS-controller.tlb</TypeLibraryName>
<HeaderFileName>
</HeaderFileName>
</Midl>
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);../../../src/include</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeaderOutputFile>$(TargetName).pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>
</AssemblerListingLocation>
<ObjectFileName>Release\</ObjectFileName>
<ProgramDataBaseFileName>Release\LS-controller.pdb</ProgramDataBaseFileName>
<XMLDocumentationFileName>Release\</XMLDocumentationFileName>
<WarningLevel>Level3</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Link>
<AdditionalDependencies>perfmon.lib;pdh.lib;Userenv.lib;Wtsapi32.lib;Shlwapi.lib;../lib/Lua_U.lib;../lib/network.lib;ws2_32.lib;odbc32.lib;winmm.lib;odbccp32.lib;Mswsock.lib;comsuppw.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>..\Bin\$(ProjectName).exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<ManifestFile>Release\$(TargetFileName).intermediate.manifest</ManifestFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
<AdditionalLibraryDirectories>../../../lib</AdditionalLibraryDirectories>
</Link>
<Manifest>
<OutputManifestFile>$(TargetFileName).embed.manifest</OutputManifestFile>
</Manifest>
<ManifestResourceCompile>
<ResourceOutputFileName>$(TargetFileName).embed.manifest.res</ResourceOutputFileName>
</ManifestResourceCompile>
<Xdcmake>
<OutputFile>Release\$(TargetName).xml</OutputFile>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(SolutionDir)\LS_controller\$(Configuration)\LS-controller.bsc</OutputFile>
</Bscmake>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="cBuffer.cpp" />
<ClCompile Include="cDemonLauncher.cpp" />
<ClCompile Include="cFile.cpp" />
<ClCompile Include="cServiceLS.cpp" />
<ClCompile Include="Utility.cpp" />
<ClCompile Include="GameCommand.cpp" />
<ClCompile Include="InternalCommand.cpp" />
<ClCompile Include="cCommand.cpp" />
<ClCompile Include="SessionProc.cpp" />
<ClCompile Include="cCommandHandler.cpp">
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ClCompile Include="cProcessor.cpp">
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ClCompile Include="cSession.cpp" />
<ClCompile Include="cSessionTable.cpp" />
<ClCompile Include="cManager.cpp" />
<ClCompile Include="main.cpp">
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ClCompile Include="cMiniDump.cpp" />
<ClCompile Include="cScheduler.cpp" />
<ClCompile Include="cEnvironment.cpp">
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ClCompile Include="cService.cpp" />
<ClCompile Include="MD5.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="cBuffer.h" />
<ClInclude Include="cDemonLauncher.h" />
<ClInclude Include="cFile.h" />
<ClInclude Include="cServiceLS.h" />
<ClInclude Include="Utility.h" />
<ClInclude Include="GameCommand.h" />
<ClInclude Include="InternalCommand.h" />
<ClInclude Include="cCommand.h" />
<ClInclude Include="cSerialize.h" />
<ClInclude Include="SessionProc.h" />
<ClInclude Include="cCommandHandler.h" />
<ClInclude Include="cProcessor.h" />
<ClInclude Include="cSession.h" />
<ClInclude Include="cSessionTable.h" />
<ClInclude Include="..\common\Internal.h" />
<ClInclude Include="..\common\Protocol.h" />
<ClInclude Include="cManager.h" />
<ClInclude Include="cMiniDump.h" />
<ClInclude Include="cScheduler.h" />
<ClInclude Include="cEnvironment.h" />
<ClInclude Include="cService.h" />
<ClInclude Include="MD5.h" />
<ClInclude Include="StdAfx.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,177 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="cProcessor.cpp">
<Filter>App\Processor</Filter>
</ClCompile>
<ClCompile Include="cScheduler.cpp">
<Filter>App\Scheduler</Filter>
</ClCompile>
<ClCompile Include="cMiniDump.cpp">
<Filter>Etc\Minidump</Filter>
</ClCompile>
<ClCompile Include="cService.cpp">
<Filter>Etc\Service</Filter>
</ClCompile>
<ClCompile Include="cServiceLS.cpp">
<Filter>Etc\Service</Filter>
</ClCompile>
<ClCompile Include="cCommand.cpp">
<Filter>App\Handler</Filter>
</ClCompile>
<ClCompile Include="cCommandHandler.cpp">
<Filter>App\Handler</Filter>
</ClCompile>
<ClCompile Include="GameCommand.cpp">
<Filter>App\Command</Filter>
</ClCompile>
<ClCompile Include="InternalCommand.cpp">
<Filter>App\Command</Filter>
</ClCompile>
<ClCompile Include="cSession.cpp">
<Filter>App\Session</Filter>
</ClCompile>
<ClCompile Include="cSessionTable.cpp">
<Filter>App\Session</Filter>
</ClCompile>
<ClCompile Include="cManager.cpp">
<Filter>Etc\Manager</Filter>
</ClCompile>
<ClCompile Include="cEnvironment.cpp">
<Filter>Etc</Filter>
</ClCompile>
<ClCompile Include="cBuffer.cpp">
<Filter>Etc\Utility</Filter>
</ClCompile>
<ClCompile Include="cFile.cpp">
<Filter>Etc\Utility</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>Etc</Filter>
</ClCompile>
<ClCompile Include="SessionProc.cpp">
<Filter>App\Command\Proc</Filter>
</ClCompile>
<ClCompile Include="Utility.cpp">
<Filter>Etc\Utility</Filter>
</ClCompile>
<ClCompile Include="MD5.cpp">
<Filter>Etc\Utility</Filter>
</ClCompile>
<ClCompile Include="cDemonLauncher.cpp">
<Filter>App</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="cProcessor.h">
<Filter>App\Processor</Filter>
</ClInclude>
<ClInclude Include="cScheduler.h">
<Filter>App\Scheduler</Filter>
</ClInclude>
<ClInclude Include="cMiniDump.h">
<Filter>Etc\Minidump</Filter>
</ClInclude>
<ClInclude Include="cServiceLS.h">
<Filter>Etc\Service</Filter>
</ClInclude>
<ClInclude Include="cService.h">
<Filter>Etc\Service</Filter>
</ClInclude>
<ClInclude Include="cCommandHandler.h">
<Filter>App\Handler</Filter>
</ClInclude>
<ClInclude Include="cCommand.h">
<Filter>App\Handler</Filter>
</ClInclude>
<ClInclude Include="GameCommand.h">
<Filter>App\Command</Filter>
</ClInclude>
<ClInclude Include="InternalCommand.h">
<Filter>App\Command</Filter>
</ClInclude>
<ClInclude Include="cSessionTable.h">
<Filter>App\Session</Filter>
</ClInclude>
<ClInclude Include="cSession.h">
<Filter>App\Session</Filter>
</ClInclude>
<ClInclude Include="cManager.h">
<Filter>Etc\Manager</Filter>
</ClInclude>
<ClInclude Include="cEnvironment.h">
<Filter>Etc</Filter>
</ClInclude>
<ClInclude Include="cSerialize.h">
<Filter>Etc\Utility</Filter>
</ClInclude>
<ClInclude Include="cBuffer.h">
<Filter>Etc\Utility</Filter>
</ClInclude>
<ClInclude Include="cFile.h">
<Filter>Etc\Utility</Filter>
</ClInclude>
<ClInclude Include="..\common\Internal.h">
<Filter>define</Filter>
</ClInclude>
<ClInclude Include="SessionProc.h">
<Filter>App\Command\Proc</Filter>
</ClInclude>
<ClInclude Include="..\common\Protocol.h">
<Filter>define</Filter>
</ClInclude>
<ClInclude Include="StdAfx.h">
<Filter>Etc</Filter>
</ClInclude>
<ClInclude Include="Utility.h">
<Filter>Etc\Utility</Filter>
</ClInclude>
<ClInclude Include="MD5.h">
<Filter>Etc\Utility</Filter>
</ClInclude>
<ClInclude Include="cDemonLauncher.h">
<Filter>App</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Filter Include="App">
<UniqueIdentifier>{a14f78a2-5208-4e30-9757-97cd0d76b073}</UniqueIdentifier>
</Filter>
<Filter Include="App\Command">
<UniqueIdentifier>{27561b4e-9633-4501-a45c-0cb6891051c6}</UniqueIdentifier>
</Filter>
<Filter Include="App\Scheduler">
<UniqueIdentifier>{5fb8afa9-7529-4f38-93a9-2f592f8b56d0}</UniqueIdentifier>
</Filter>
<Filter Include="Etc">
<UniqueIdentifier>{1c3ae19c-fde1-4221-904e-2ae5bd198b23}</UniqueIdentifier>
</Filter>
<Filter Include="Etc\Minidump">
<UniqueIdentifier>{004c8b2a-6f16-4394-b6a2-4b81b46f9b5d}</UniqueIdentifier>
</Filter>
<Filter Include="Etc\Service">
<UniqueIdentifier>{bbb9b669-1f79-4c89-ab62-02a2c16d3f48}</UniqueIdentifier>
</Filter>
<Filter Include="App\Handler">
<UniqueIdentifier>{9af97764-8639-4f8f-8481-9d48566c6111}</UniqueIdentifier>
</Filter>
<Filter Include="App\Processor">
<UniqueIdentifier>{20def935-1e29-43b6-a6a8-474641fafebf}</UniqueIdentifier>
</Filter>
<Filter Include="App\Session">
<UniqueIdentifier>{1f5c2150-0abc-48b1-846c-fd5303d190cd}</UniqueIdentifier>
</Filter>
<Filter Include="Etc\Manager">
<UniqueIdentifier>{b3967eb2-cc3a-40aa-a128-99eaf7ecd1bb}</UniqueIdentifier>
</Filter>
<Filter Include="Etc\Utility">
<UniqueIdentifier>{6d017d3a-5b14-47ae-9fa6-93bfdb4ab6fc}</UniqueIdentifier>
</Filter>
<Filter Include="define">
<UniqueIdentifier>{522d4564-a3c4-4e70-9912-251110e03ea8}</UniqueIdentifier>
</Filter>
<Filter Include="App\Command\Proc">
<UniqueIdentifier>{d093448e-5c6b-46ce-a5b0-002d776dd24a}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>
+288
View File
@@ -0,0 +1,288 @@
// MD5.cpp: implementation of the CMD5 class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MD5.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
static BYTE PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
static void MD5Transform (UINT state[4], BYTE block[64]);
static void Encode(BYTE* output, UINT* input, UINT len);
static void Decode (UINT* output, BYTE* input, UINT len);
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMD5::CMD5()
{
}
CMD5::~CMD5()
{
}
/*
CString CMD5::GetString(CString str)
{
MD5_CTX context;
BYTE digest[16];
UINT len = str.GetLength();
MD5Init (&context);
MD5Update (&context, (BYTE*)(LPTSTR)(LPCTSTR)str, len);
MD5Final (digest, &context);
CString temp;
CString ret = _T("");
for (int i=0; i<16; i++)
{
temp.Format("%02X", digest[i]);
ret += temp;
}
return ret;
}
*/
void CMD5::Generate(BYTE* file, UINT length)
{
ZeroMemory(m_digest, sizeof(m_digest));
MD5_CTX context;
MD5Init(&context);
MD5Update(&context, file, length);
MD5Final(m_digest, &context);
}
void CMD5::MD5Init(MD5_CTX* context)
{
context->count[0] = context->count[1] = 0;
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
void CMD5::MD5Update (MD5_CTX* context, BYTE* input, UINT inputLen)
{
UINT i, index, partLen;
index = (UINT)((context->count[0] >> 3) & 0x3F);
if ((context->count[0] += ((UINT)inputLen << 3)) < ((UINT)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT)inputLen >> 29);
partLen = 64 - index;
if (inputLen >= partLen)
{
memcpy(&context->buffer[index], input, partLen);
MD5Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
memcpy(&context->buffer[index], &input[i], inputLen-i);
}
void CMD5::MD5Final (BYTE* digest, MD5_CTX* context)
{
BYTE bits[8];
UINT index, padLen;
Encode (bits, context->count, 8);
index = (UINT)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD5Update (context, PADDING, padLen);
MD5Update (context, bits, 8);
Encode (digest, context->state, 16);
memset (context, 0, sizeof (*context));
}
static void MD5Transform (UINT state[4], BYTE block[64])
{
UINT a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information. */
memset (x, 0, sizeof (x));
}
static void Encode(BYTE* output, UINT* input, UINT len)
{
UINT i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (BYTE)(input[i] & 0xff);
output[j+1] = (BYTE)((input[i] >> 8) & 0xff);
output[j+2] = (BYTE)((input[i] >> 16) & 0xff);
output[j+3] = (BYTE)((input[i] >> 24) & 0xff);
}
}
static void Decode (UINT* output, BYTE* input, UINT len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT)input[j]) | (((UINT)input[j+1]) << 8) |
(((UINT)input[j+2]) << 16) | (((UINT)input[j+3]) << 24);
}
+32
View File
@@ -0,0 +1,32 @@
// MD5.h: interface for the CMD5 class.
//
//////////////////////////////////////////////////////////////////////
#pragma once
class CMD5
{
public:
CMD5();
~CMD5();
public:
void Generate(BYTE* file, UINT length);
BYTE* GetDigest() { return m_digest; }
protected:
BYTE m_digest[16];
protected:
typedef struct
{
UINT state[4]; /* state (ABCD) */
UINT count[2]; /* number of bits, modulo 2^64 (lsb first) */
BYTE buffer[64]; /* input buffer */
} MD5_CTX;
void MD5Init(MD5_CTX* ctx);
void MD5Update(MD5_CTX* ctx, BYTE* input, UINT inputlen);
void MD5Final(BYTE* digest, MD5_CTX* ctx);
};
@@ -0,0 +1,88 @@
#include "StdAfx.h"
#include "SessionProc.h"
#include "SessionProc.h"
#include "../include/IIocpContext.h"
#include "../include/INetwork.h"
#include "../include/cSingleton.h"
void SessionProc::SendPacket(
IIocpContext* context,
const uint32 command,
const uint8* packet,
const uint32 length)
{
if(context)
{
cSingleton<INetwork>::GetInstance()->Send(
context,
static_cast<uint16>(command),
packet,
static_cast<uint16>(length),
FALSE);
}
}
void SessionProc::Broadcast(
const uint32 command,
const uint8* packet,
const uint32 length)
{
cSession* session = SessionProc::GetFirstSession();
while(session)
{
SendPacket(
session->GetContext(),
command,
packet,
length);
session = SessionProc::GetNextSession();
}
}
BOOL SessionProc::AddSession(IIocpContext* context)
{
cSession* session = g_sessionTable.Get(context->GetEntity());
if(session) return FALSE;
// 세션정보 추가
return g_sessionTable.Insert(context->GetEntity(), context);
}
BOOL SessionProc::DeleteSession(IIocpContext* context)
{
cSession* session = g_sessionTable.Get(context->GetEntity());
if(session)
{
// 세션 종료시의 처리
session->OnDisconnect();
// 세션 정보 삭제
g_sessionTable.Remove(context->GetEntity());
}
// 접속종료
context->Disconnect();
return TRUE;
}
uint32 SessionProc::GetSessionCount()
{
return g_sessionTable.GetCount();
}
cSession* SessionProc::GetSession(const uint32 entity)
{
return g_sessionTable.Get(entity);
}
cSession* SessionProc::GetFirstSession()
{
return g_sessionTable.GetFirst();
}
cSession* SessionProc::GetNextSession()
{
return g_sessionTable.GetNext();
}
@@ -0,0 +1,32 @@
#pragma once
#include "cSessionTable.h"
class IIocpContext;
class SessionProc
{
public:
static void SendPacket(
IIocpContext* context,
const uint32 command,
const uint8* packet,
const uint32 length);
static void Broadcast(
const uint32 command,
const uint8* packet,
const uint32 length);
public:
static BOOL AddSession(IIocpContext* context);
static BOOL DeleteSession(IIocpContext* context);
public:
static uint32 GetSessionCount();
static cSession* GetSession(const uint32 entity);
static cSession* GetFirstSession();
static cSession* GetNextSession();
};
+21
View File
@@ -0,0 +1,21 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include <SDKDDKVer.h>
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <string>
#include "../include/common.h"
extern void Trace( const TCHAR *format, ... );
extern void Debug( const TCHAR *format, ... );
extern void Information( const TCHAR *format, ... );
extern void Debug();
namespace std { typedef std::basic_string<TCHAR> tstring; }
+320
View File
@@ -0,0 +1,320 @@
#include "StdAfx.h"
#include "cService.h"
#include "Utility.h"
#include <iostream>
#include <wtsapi32.h>
#include <userenv.h>
#include <tlhelp32.h>
using namespace std;
BOOL FindUserWindow(const TCHAR* title, DWORD& PID);
// trace
void Trace( const TCHAR *format, ... )
{
#ifdef _DEBUG
TCHAR buffer[2048];
va_list marker;
va_start( marker, format );
_vstprintf_s( buffer, _countof(buffer), format, marker );
va_end( marker );
OutputDebugString( buffer );
#endif
}
// console
void Debug( const TCHAR *format, ... )
{
#ifdef _DEBUG
static TCHAR buffer[2048];
va_list marker;
va_start(marker, format);
_vstprintf_s(buffer, _countof(buffer), format, marker);
va_end(marker);
cService::_serviceMainClass->Debug(buffer);
//wcout << buffer;
#endif
}
// console
void Information( const TCHAR *format, ... )
{
static TCHAR buffer[2048];
va_list marker;
va_start( marker, format );
_vstprintf_s( buffer, _countof(buffer), format, marker );
va_end( marker );
cService::_serviceMainClass->Debug(buffer);
}
// last error
void Debug()
{
DWORD dwError = WSAGetLastError();
LPTSTR lpMsgBuf = NULL;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
0, // Default language
(LPTSTR)&lpMsgBuf,
0,
NULL );
#ifdef _UNICODE
wcout << _T("WSAGetLastError[") << dwError << _T("] : ") << lpMsgBuf << endl << flush;
#else
cout << _T("WSAGetLastError[") << dwError << _T("] : ") << lpMsgBuf << endl << flush;
#endif
// Free the buffer.
LocalFree( lpMsgBuf );
}
void Tokenize(const std::tstring& str, TOKENS& tokens, const std::tstring& delimiters)
{
tokens.clear();
// 맨 첫 글자가 구분자인 경우 무시
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// 구분자가 아닌 첫 글자를 찾는다
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// token을 찾았으니 vector에 추가한다
tokens.push_back(str.substr(lastPos, pos - lastPos));
// 구분자를 뛰어넘는다. "not_of"에 주의하라
lastPos = str.find_first_not_of(delimiters, pos);
// 다음 구분자가 아닌 글자를 찾는다
pos = str.find_first_of(delimiters, lastPos);
}
}
BOOL GetService(std::tstring& service, std::tstring& file, std::tstring& script)
{
HKEY key;
LONG ret = RegOpenKeyEx(HKEY_CURRENT_USER, _T("software\\LostSaga"), 0, KEY_ALL_ACCESS, &key);
if(ERROR_SUCCESS != ret) return FALSE;
DWORD size;
FILETIME fileTime;
TCHAR group[256], regFile[512], regScript[512];
for(DWORD i = 0 ; i < 1000 ; i++)
{
size = _countof(group);
ret = RegEnumKeyEx(key, i, group, &size, NULL, NULL, NULL, &fileTime);
if(ERROR_SUCCESS != ret) break;
if(service == group)
{
HKEY subkey;
ret = RegOpenKeyEx(key, group, 0, KEY_ALL_ACCESS, &subkey);
if(ERROR_SUCCESS != ret) break;
size = sizeof(regFile);
if(RegQueryValueEx(subkey, _T("file"), NULL, NULL, (LPBYTE)regFile, &size) != ERROR_SUCCESS)
{
RegCloseKey(subkey);
RegCloseKey(key);
return FALSE;
}
size = sizeof(regScript);
if(RegQueryValueEx(subkey, _T("script"), NULL, NULL, (LPBYTE)regScript, &size) != ERROR_SUCCESS)
{
RegCloseKey(subkey);
RegCloseKey(key);
return FALSE;
}
file = regFile;
script = regScript;
RegCloseKey(subkey);
return TRUE;
}
}
RegCloseKey(key);
return FALSE;
}
BOOL GetServices(STRINGS& services, STRINGS& files, STRINGS& scripts)
{
services.clear();
files.clear();
scripts.clear();
HKEY key;
LONG ret = RegOpenKeyEx(HKEY_CURRENT_USER, _T("software\\LostSaga"), 0, KEY_ALL_ACCESS, &key);
if(ERROR_SUCCESS != ret)
{
DWORD error = GetLastError();
return FALSE;
}
DWORD size;
FILETIME fileTime;
TCHAR group[256], service[256], file[512], script[512];
for(DWORD i = 0 ; i < 1000 ; i++)
{
size = _countof(group);
ret = RegEnumKeyEx(key, i, group, &size, NULL, NULL, NULL, &fileTime);
if(ERROR_SUCCESS != ret) break;
//_stprintf_s(folder, sizeof(folder), "software\\LostSaga\\%s", group);
HKEY subkey;
ret = RegOpenKeyEx(key, group, 0, KEY_ALL_ACCESS, &subkey);
if(ERROR_SUCCESS != ret) break;
size = _countof(service);
if(RegQueryValueEx(subkey, _T("service"), NULL, NULL, (LPBYTE)service, &size) != ERROR_SUCCESS)
{
RegCloseKey(subkey);
RegCloseKey(key);
return TRUE;
}
size = _countof(file);
if(RegQueryValueEx(subkey, _T("file"), NULL, NULL, (LPBYTE)file, &size) != ERROR_SUCCESS)
{
RegCloseKey(subkey);
RegCloseKey(key);
return FALSE;
}
size = _countof(script);
if(RegQueryValueEx(subkey, _T("script"), NULL, NULL, (LPBYTE)script, &size) != ERROR_SUCCESS)
{
RegCloseKey(subkey);
RegCloseKey(key);
return FALSE;
}
services.push_back(service);
files.push_back(file);
scripts.push_back(script);
RegCloseKey(subkey);
}
RegCloseKey(key);
return TRUE;
}
BOOL IsService(const TCHAR* serviceName)
{
// 서비스 관리자 얻기
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(0 == schSCManager) return FALSE;
// 서비스 핸들 얻기
SC_HANDLE schService = OpenService(schSCManager, serviceName, GENERIC_ALL);
if(0 == schService) return FALSE;
// 서비스 상태얻기
SERVICE_STATUS_PROCESS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
DWORD bytesNeeded;
BOOL result = QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)(&status),
sizeof(status),
&bytesNeeded);
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return result;
}
BOOL CreateFolder(const TCHAR* path)
{
std::tstring folder = path;
TOKENS folders;
Tokenize(folder, folders, _T("\\"));
if(folders.size() > 1 )
{
std::tstring temp = folders[0];
for(uint32 i = 1; i < folders.size(); i++)
{
temp = temp + _T("\\") + folders[i];
::CreateDirectory(temp.c_str(), NULL);
}
}
return TRUE;
}
BOOL FindUserWindow(const TCHAR* title, DWORD& PID)
{
TCHAR text[512] = {0};
HANDLE hProcessSnap;
PROCESSENTRY32 pe32; //프로세스정보를 저장할 구조체
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
Process32First( hProcessSnap, &pe32 );
printf( "\n Process ID = 0x%08X", pe32.th32ProcessID );
printf( "\n Thread count = %d", pe32.cntThreads );
printf( "\n Parent process ID = 0x%08X", pe32.th32ParentProcessID );
printf( "\n Priority base = %d", pe32.pcPriClassBase );
while(Process32Next( hProcessSnap, &pe32 ))
{
HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, pe32.th32ProcessID);
if(hProcess != NULL)
{
GetWindowText((HWND)hProcess, text, _countof(text));
wcout << "title : " << text << endl;;
if(0 == _tcscmp(title, text))
{
PID = pe32.th32ProcessID;
return TRUE;
}
}
}
return FALSE;
//HWINSTA hWinsta = OpenWindowStation(_T("winsta0"), FALSE, WINSTA_ALL_ACCESS);
//// 데몬 서버 상태 얻기
//HWND hWnd = FindWindow(NULL, title);
//if(hWnd)
//{
// DWORD ret = GetWindowThreadProcessId(hWnd, &PID);
// CloseWindowStation(hWinsta);
// return (ret != 0) ? TRUE : FALSE;
//}
//CloseWindowStation(hWinsta);
//return FALSE;
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <string>
#include <vector>
namespace std { typedef std::basic_string<TCHAR> tstring; }
typedef std::vector<std::tstring> TOKENS;
typedef std::vector<std::tstring> STRINGS;
+184
View File
@@ -0,0 +1,184 @@
// cBuffer.cpp: implementation of the cBuffer class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "cBuffer.h"
#include <iostream>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cBuffer::cBuffer()
{
Init();
}
cBuffer::cBuffer( uint32 uBuffLen )
{
Init();
Create( uBuffLen );
}
cBuffer::~cBuffer()
{
Destroy();
}
void cBuffer::Init()
{
m_pDT = NULL;
m_unLen = 0;
m_unMax = 0;
}
void cBuffer::Destroy()
{
if( m_pDT )
delete []m_pDT;
m_pDT = NULL;
m_unLen = 0;
m_unMax = 0;
}
//////////////////////////////////////////////////////////////////////
// Create/Erase
//////////////////////////////////////////////////////////////////////
bool cBuffer::Create( uint32 uBuffLen )
{
if( m_pDT )
Destroy();
m_pDT = new uint8[ uBuffLen ];
if( m_pDT )
{
m_unLen = 0;
m_unMax = uBuffLen;
Erase();
return true;
}
return false;
}
bool cBuffer::Erase()
{
if( m_pDT )
{
ZeroMemory( m_pDT, m_unLen );
m_unLen = 0;
return true;
}
return false;
}
void cBuffer::Resize( uint32 uBuffLen )
{
if(m_unMax < uBuffLen)
{
Create(uBuffLen);
}
}
//////////////////////////////////////////////////////////////////////
// Copy/Append
//////////////////////////////////////////////////////////////////////
bool cBuffer::Copy( const TCHAR* pDT )
{
if( m_pDT )
{
uint32 unLen = _tcslen( pDT ) + 1;
if( unLen <= m_unMax )
{
Erase();
m_unLen = unLen;
CopyMemory( m_pDT, pDT, m_unLen );
return true;
}
}
return false;
}
bool cBuffer::Copy( uint32 unDst, const TCHAR* pDT )
{
if( m_pDT )
{
uint32 unLen = _tcslen( pDT ) + 1;
if( (unDst+unLen) <= m_unMax )
{
CopyMemory( m_pDT+unDst, pDT, unLen );
m_unLen = unDst + unLen;
return true;
}
}
return false;
}
bool cBuffer::Copy( const uint8* pDT, uint32 unLen )
{
if( m_pDT )
{
if( unLen <= m_unMax )
{
Erase();
m_unLen = unLen;
CopyMemory( m_pDT, pDT, m_unLen );
return true;
}
}
return false;
}
bool cBuffer::Copy( uint32 unDst, const uint8* pDT, uint32 unLen )
{
if( m_pDT )
{
if( (unDst+unLen) <= m_unMax )
{
CopyMemory( m_pDT + unDst, pDT, unLen );
m_unLen = unDst + unLen;
return true;
}
}
return false;
}
bool cBuffer::Append( const TCHAR* pDT )
{
if( m_pDT )
{
uint32 unLen = _tcslen( pDT ) + 1;
if( (unLen+m_unLen) <= m_unMax )
{
CopyMemory( m_pDT+m_unLen, pDT, unLen );
m_unLen += unLen;
return true;
}
}
return false;
}
bool cBuffer::Append( const uint8* pDT, uint32 unLen )
{
if( m_pDT )
{
if( (unLen+m_unLen) <= m_unMax )
{
CopyMemory( m_pDT + m_unLen, pDT, unLen );
m_unLen += unLen;
return true;
}
}
return false;
}
+56
View File
@@ -0,0 +1,56 @@
// cBuffer.h: interface for the cBuffer class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CBUFFER_H__ECE7A49E_767B_4F38_91CE_A4795B0F4535__INCLUDED_)
#define AFX_CBUFFER_H__ECE7A49E_767B_4F38_91CE_A4795B0F4535__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class cBuffer
{
public:
cBuffer();
cBuffer( uint32 uBuffLen );
virtual ~cBuffer();
void Init();
void Destroy();
public:
bool Create( uint32 uBuffLen );
bool Erase();
void Resize( uint32 uBuffLen );
public:
void SetLength( uint32 unLen ) { m_unLen = unLen; }
uint32 GetMaxLength() { return m_unMax; }
uint32 GetLength() { return m_unLen; }
uint8* GetBuffer() const { return m_pDT; }
TCHAR* GetString() const { return reinterpret_cast<TCHAR*>(m_pDT); }
uint8* GetBuffer( uint32 unLen ) const { return (m_pDT+unLen); }
bool Copy( const TCHAR* pDT );
bool Copy( uint32 unDst, const TCHAR* pDT );
bool Copy( const uint8* pDT, uint32 unLen );
bool Copy( uint32 unDst, const uint8* pDT, uint32 unLen );
bool Append( const TCHAR* pDT );
bool Append( const uint8* pDT, uint32 unLen );
protected:
uint8* m_pDT;
uint32 m_unLen;
uint32 m_unMax;
};
#endif // !defined(AFX_CBUFFER_H__ECE7A49E_767B_4F38_91CE_A4795B0F4535__INCLUDED_)
@@ -0,0 +1,35 @@
#include "StdAfx.h"
#include "../include/IIocpContext.h"
#include "cCommand.h"
//////////////////////////////////////////////////////////////////////
// Operation
//////////////////////////////////////////////////////////////////////
BOOL cCommand::Run(IIocpContext* context, const uint8* buffer, const uint32 payload)
{
// 자신의 정보를 출력
//Self();
if(Verify(context, const_cast<uint8*>(buffer), payload))
{
// 명령처리
Run(context);
return TRUE;
}
return FALSE;
}
BOOL cCommand::Run(const uint32 serverId, const uint8* buffer, const uint32 payload)
{
// 자신의 정보를 출력
//Self();
if(Verify(const_cast<uint8*>(buffer), payload))
{
// 명령처리
Run(serverId);
return TRUE;
}
return FALSE;
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
class IIocpContext;
class cCommand
{
public:
cCommand(void) {}
~cCommand(void) {}
public:
BOOL Run(IIocpContext* context, const uint8* buffer, const uint32 payload);
BOOL Run(const uint32 serverId, const uint8* buffer, const uint32 payload);
protected:
virtual BOOL Verify(IIocpContext* pContext, uint8* buffer, const uint32 length) { return TRUE; }
virtual BOOL Verify(uint8* buffer, const uint32 length) { return TRUE; }
virtual void Self() {}
virtual void Run(IIocpContext* context) {}
virtual void Run(const uint32 serverId) {}
};
@@ -0,0 +1,72 @@
// cCommandHandler.cpp
#include "stdafx.h"
#include "GameCommand.h"
#include "InternalCommand.h"
#include "cCommandHandler.h"
#include "../common/Protocol.h"
#include "../common/Internal.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cCommandHandler::cCommandHandler()
{
Init();
}
cCommandHandler::~cCommandHandler()
{
Destroy();
}
void cCommandHandler::Init()
{
m_commandTable.resize(0xFFFF, NULL);
LoadCommand();
}
void cCommandHandler::Destroy()
{
COMMMANDTABLE::iterator it;
for(it = m_commandTable.begin() ; it != m_commandTable.end() ; ++it)
{
delete *it;
}
m_commandTable.clear();
}
//////////////////////////////////////////////////////////////////////
// operation
//////////////////////////////////////////////////////////////////////
void cCommandHandler::LoadCommand()
{
InsertCommand(I_CONNECT, new IConnect);
InsertCommand(I_CLOSE, new IClose);
InsertCommand(I_PING, new IPing);
InsertCommand(I_FLUSH, new IFlush);
InsertCommand(C_PING, new CPing);
InsertCommand(C_SERVICES, new CServices);
InsertCommand(C_TRANSFER, new CTransfer);
InsertCommand(C_REMOVE, new CRemove);
InsertCommand(C_INSTALL, new CInstall);
InsertCommand(C_PLAY, new CPlay);
InsertCommand(C_BACKUP, new CBackup);
InsertCommand(C_REBOOT, new CReboot);
InsertCommand(C_RESOURCE, new CResource);
}
void cCommandHandler::InsertCommand(const uint32 commandId, cCommand* command)
{
COMMMANDTABLE::pointer ptr = &m_commandTable[commandId];
*ptr = command;
}
cCommand* cCommandHandler::Get(const uint32 commandId)
{
return (commandId < 0xFFFF) ? m_commandTable[commandId] : NULL;
}
@@ -0,0 +1,26 @@
#pragma once
#include <vector>
class cCommand;
class cCommandHandler
{
public:
cCommandHandler();
virtual ~cCommandHandler();
void Init();
void Destroy();
protected:
void LoadCommand();
void InsertCommand(const uint32 commandId, cCommand* command);
public:
cCommand* Get(const uint32 commandId);
protected:
typedef std::vector<cCommand*> COMMMANDTABLE;
COMMMANDTABLE m_commandTable;
};
@@ -0,0 +1,256 @@
#include "StdAfx.h"
#include "cDemonLauncher.h"
#include <wtsapi32.h>
#include <userenv.h>
extern BOOL GetService(std::tstring& service, std::tstring& file, std::tstring& script);
cDemonLauncher g_demonLauncher;
cDemonLauncher::cDemonLauncher(void)
{
}
cDemonLauncher::~cDemonLauncher(void)
{
}
BOOL cDemonLauncher::Play(const TCHAR* service, const BOOL console)
{
// 실행중인지 확인
if(IsRunningService(service)) return FALSE;
if(IsRunningConsole(service)) return FALSE;
std::tstring key = service;
std::tstring m_file;
std::tstring m_script;
if(GetService(key, m_file, m_script))
{
if(console == FALSE)
{
TCHAR command[512];
_stprintf_s(command, _countof(command), _T("/c \"sc start %s %s %s.txt\""), service, m_script.c_str(), service);
ShellExecute(NULL , NULL, _T("cmd.exe") , command, NULL, SW_HIDE);
Debug(_T("@Play : %s\r\n"), command);
return TRUE;
}
else
{
//TCHAR command[512];
//TCHAR path[512]={0};
//TCHAR tempPath[512]={0};
//TCHAR drive[512]={0};
//TCHAR exeFile[512]={0};
//TCHAR tempExeFile[512]={0};
//TCHAR luaFile[512]={0};
//TCHAR tempLuaFile[512]={0};
//TCHAR ext1[512]={0};
//TCHAR ext2[512]={0};
//TCHAR arguments[512]={0};
//_tsplitpath_s(m_file.c_str(), drive, tempPath, tempExeFile, ext1);
////_tsplitpath_s(m_script.c_str(), drive, tempPath, tempLuaFile, ext2);
//_stprintf_s(path, _countof(path), _T("%s%s"), drive, tempPath);
//_stprintf_s(exeFile, _countof(exeFile), _T("%s%s"), tempExeFile, ext1);
////_stprintf_s(luaFile, _countof(luaFile), _T("%s%s"), tempLuaFile, ext2);
////_stprintf_s(command, _countof(command), _T("/c \"start \"%s\" /D%s %s -c %s\""), service, path, exeFile, luaFile);
////ShellExecute(NULL , NULL, _T("cmd.exe") , command, path, SW_SHOW);
//_stprintf_s(command, _countof(command), _T("%s\\%s"), path, exeFile);
//_stprintf_s(arguments, _countof(arguments), _T(" -c"));
////_stprintf_s(arguments, _countof(arguments), _T(" -c %s"), luaFile);
//CreateConsole(service, command, arguments);
return TRUE;
}
}
return FALSE;
}
BOOL cDemonLauncher::Stop(const TCHAR* service, const BOOL console)
{
TCHAR command[512];
//uint32 PID = GetPID(service);
HANDLE hProcess = GetHandle(service);
if( hProcess != 0 )
{
if(TerminateProcess(hProcess, 0))
{
RemovePI(service);
}
//_stprintf_s(command, _countof(command), _T("/c \"taskkill /PID %d\""), PID);
//ShellExecute(NULL , NULL, _T("cmd.exe") , command, NULL, SW_HIDE);
return TRUE;
}
else
{
_stprintf_s(command, _countof(command), _T("/c \"sc stop %s\""), service);
ShellExecute(NULL , NULL, _T("cmd.exe") , command, NULL, SW_HIDE);
return TRUE;
}
return FALSE;
}
BOOL cDemonLauncher::CreateConsole(const TCHAR* title, TCHAR* command, TCHAR* arguments)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
//
HANDLE hTokenNew = NULL, hTokenDup = NULL;
WTSQueryUserToken(WTSGetActiveConsoleSessionId(), &hTokenNew);
DuplicateTokenEx(hTokenNew,MAXIMUM_ALLOWED,NULL,SecurityIdentification,TokenPrimary,&hTokenDup);
LPVOID pEnv = NULL;
if(!CreateEnvironmentBlock(&pEnv, hTokenDup, FALSE))
{
return FALSE;
}
//
ZeroMemory( &si, sizeof( STARTUPINFO ) );
si.cb = sizeof( STARTUPINFO );
si.lpDesktop = TEXT("winsta0\\default");
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW ;
si.lpTitle = const_cast<TCHAR*>(title); // (LPWSTR)
if(CreateProcessAsUser(hTokenDup, command, arguments, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT |NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, pEnv, NULL, &si, &pi))
{
SetPI(title, pi);
}
else
{
DWORD error = GetLastError();
}
RevertToSelf();
return TRUE;
}
void cDemonLauncher::SetPI(const TCHAR* service, PROCESS_INFORMATION& pi)
{
if(!IsRunningConsole(service))
{
m_demons[service] = pi;
}
}
void cDemonLauncher::RemovePI(const TCHAR* service)
{
PROCESS_TABLE::iterator it = m_demons.find(service);
if(it != m_demons.end())
{
m_demons.erase(it);
}
}
uint32 cDemonLauncher::GetPID(const TCHAR* service)
{
PROCESS_TABLE::iterator it = m_demons.find(service);
if(it != m_demons.end())
{
PROCESS_INFORMATION pi = it->second;
return pi.dwProcessId;
}
return 0;
}
HANDLE cDemonLauncher::GetHandle(const TCHAR* service)
{
PROCESS_TABLE::iterator it = m_demons.find(service);
if(it != m_demons.end())
{
PROCESS_INFORMATION pi = it->second;
return pi.hProcess;
}
return 0;
}
BOOL cDemonLauncher::IsRunningConsole(const TCHAR* service)
{
PROCESS_TABLE::const_iterator it = m_demons.find(service);
if(it != m_demons.end())
{
return TRUE;
}
return FALSE;
}
BOOL cDemonLauncher::IsRunningService(const TCHAR* service)
{
// 서비스 관리자 얻기
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(0 == schSCManager)
{
Debug(_T("IsRunning :: failed(%s)\n"), service);
return FALSE;
}
// 서비스 핸들 얻기
SC_HANDLE schService = OpenService(schSCManager, service, GENERIC_ALL);
if(0 == schService)
{
Debug(_T("IsRunning :: failed(%s)\n"), service);
return FALSE;
}
// 서비스 상태얻기
SERVICE_STATUS_PROCESS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
DWORD bytesNeeded;
BOOL result = QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)(&status),
sizeof(status),
&bytesNeeded);
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
if(result)
{
switch(status.dwCurrentState)
{
case SERVICE_CONTINUE_PENDING :
return FALSE;
case SERVICE_PAUSE_PENDING :
return FALSE;
case SERVICE_PAUSED :
return FALSE;
case SERVICE_RUNNING :
return TRUE;
case SERVICE_START_PENDING :
return TRUE;
case SERVICE_STOP_PENDING :
return FALSE;
case SERVICE_STOPPED :
return FALSE;
}
}
return FALSE;
}
@@ -0,0 +1,34 @@
#pragma once
#include <map>
#include <string>
class cDemonLauncher
{
public:
cDemonLauncher(void);
~cDemonLauncher(void);
public:
BOOL Play(const TCHAR* service, const BOOL console);
BOOL Stop(const TCHAR* service, const BOOL console);
BOOL CreateConsole(const TCHAR* title, TCHAR* command, TCHAR* arguments);
public:
void SetPI(const TCHAR* service, PROCESS_INFORMATION& pi);
void RemovePI(const TCHAR* service);
uint32 GetPID(const TCHAR* service);
HANDLE GetHandle(const TCHAR* service);
BOOL IsRunningConsole(const TCHAR* service);
BOOL IsRunningService(const TCHAR* service);
protected:
typedef std::map<std::tstring,PROCESS_INFORMATION> PROCESS_TABLE;
PROCESS_TABLE m_demons;
};
extern cDemonLauncher g_demonLauncher;
@@ -0,0 +1,22 @@
// cEnvironment.cpp: implementation of the cEnvironment class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "cEnvironment.h"
#include "../include/cSingleton.h"
#include <iostream>
cEnvironment g_environment;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cEnvironment::cEnvironment() :
m_maxSession(0),
m_flushTime(0)
{
}
@@ -0,0 +1,35 @@
// cEnvironment.h: interface for the cEnvironment class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CENVIRONMENT_H__299EC96C_7762_41C7_997D_35C16F4E94A9__INCLUDED_)
#define AFX_CENVIRONMENT_H__299EC96C_7762_41C7_997D_35C16F4E94A9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
const int PATH_MAXSIZE = 250;
class cEnvironment
{
public :
cEnvironment();
public:
const uint32 GetMaxSession() { return m_maxSession; }
const uint32 GetFlushTime() { return m_flushTime; }
void SetMaxSession( uint32 sessionCount ) { m_maxSession = sessionCount; }
void SetFlushTime( uint32 flushTime ) { m_flushTime = flushTime; }
private:
uint32 m_maxSession;
uint32 m_flushTime;
};
extern cEnvironment g_environment;
#endif // !defined(AFX_CENVIRONMENT_H__299EC96C_7762_41C7_997D_35C16F4E94A9__INCLUDED_)
+274
View File
@@ -0,0 +1,274 @@
// cFile.cpp: implementation of the cFile class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "cFile.h"
#include <stdio.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cFile::cFile() : m_hFile(INVALID_HANDLE_VALUE), m_dwSizeLow(0), m_dwSizeHigh(0)
{
}
cFile::cFile(LPCTSTR fileName, DWORD dwMode, DWORD dwShareMode, DWORD dwCreationDisposition) : m_hFile(INVALID_HANDLE_VALUE), m_dwSizeLow(0), m_dwSizeHigh(0)
{
Open(fileName, dwMode, dwShareMode, dwCreationDisposition);
}
cFile::~cFile()
{
Close();
}
//////////////////////////////////////////////////////////////////////
// operation
//////////////////////////////////////////////////////////////////////
BOOL cFile::Open(const TCHAR* fileName, DWORD dwMode, DWORD dwShareMode, DWORD dwCreationDisposition)
{
Close();
m_hFile = CreateFile( reinterpret_cast<LPCTSTR>(fileName),
dwMode,
dwShareMode,
NULL,
dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(m_hFile == INVALID_HANDLE_VALUE) return FALSE;
return (m_hFile == INVALID_HANDLE_VALUE) ? FALSE : TRUE;
}
void cFile::Close()
{
if(m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
m_hFile = NULL;
}
m_dwSizeLow = 0;
m_dwSizeHigh = 0;
}
BOOL cFile::Move(DWORD dwOrigin, LONG lOffset)
{
if(m_hFile != INVALID_HANDLE_VALUE)
{
DWORD dwResult = SetFilePointer( m_hFile,
lOffset,
NULL,
dwOrigin);
return (dwResult == 0xFFFFFFFF) ? FALSE : TRUE;
}
return FALSE;
}
DWORD cFile::GetFileSize()
{
if(m_dwSizeLow != 0)
return m_dwSizeLow;
DWORD dwError = 0;
if(m_hFile != INVALID_HANDLE_VALUE)
{
m_dwSizeLow = ::GetFileSize(m_hFile, &m_dwSizeHigh);
if((INVALID_FILE_SIZE == m_dwSizeLow) &&
((dwError = GetLastError()) != NO_ERROR))
return 0;
}
return m_dwSizeLow;
}
//////////////////////////////////////////////////////////////////////
// cFileReader class
//////////////////////////////////////////////////////////////////////
cFileReader::cFileReader(const TCHAR* fileName) : m_nReadType(-1)
{
if(fileName != NULL)
{
Open(fileName);
}
}
BOOL cFileReader::Open(const TCHAR* fileName)
{
if(cFile::Open(fileName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING))
{
return (GetBOM() > 0) ? TRUE : FALSE;
}
return FALSE;
}
BOOL cFileReader::Read(BYTE* buffer, const DWORD dwLength)
{
DWORD dwWritten = 0;
if(m_hFile == INVALID_HANDLE_VALUE) return FALSE;
if(ReadFile( m_hFile,
buffer,
dwLength,
&dwWritten,
NULL))
{
if(dwLength == dwWritten) return TRUE;
}
return FALSE;
}
BOOL cFileReader::Convert(const BYTE* bufferA, const int lengthA, BYTE* bufferB, const int lengthB)
{
switch(m_nReadType)
{
case FILEFORMAT_ANSI :
CopyMemory(bufferB, bufferA, (lengthA > lengthB) ? lengthB : lengthA);
return TRUE;
case FILEFORMAT_UNICODE_UTF8 :
CopyMemory(bufferB, bufferA, (lengthA > lengthB) ? lengthB : lengthA);
return TRUE;
case FILEFORMAT_UNICODE_LE :
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)bufferA, lengthA, (LPSTR)bufferB, lengthB, NULL, NULL);
return TRUE;
case FILEFORMAT_UNICODE_BE :
return TRUE;
}
return FALSE;
}
int cFileReader::GetBOM()
{
if((-1) == m_nReadType)
{
Move(FILE_BEGIN, 0);
WORD BOM = 0;
if(Read(reinterpret_cast<BYTE*>(&BOM), sizeof(WORD)))
{
switch(BOM)
{
case 0xFEFF :
m_nReadType = FILEFORMAT_UNICODE_LE;
break;
case 0xFFFE :
m_nReadType = 0; //FILEFORMAT_UNICODE_BE; not supported
break;
case 0xBBEF :
m_nReadType = FILEFORMAT_UNICODE_UTF8;
Move(FILE_BEGIN, 3);
break;
default:
m_nReadType = FILEFORMAT_ANSI;
Move(FILE_BEGIN, 0);
break;
}
return m_nReadType;
}
return 0;
}
return m_nReadType;
}
DWORD cFileReader::GetFileSize()
{
if(0 == m_dwSizeLow)
{
cFile::GetFileSize();
switch(m_nReadType)
{
case FILEFORMAT_UNICODE_LE :
case FILEFORMAT_UNICODE_BE :
m_dwSizeLow -= (2);
break;
case FILEFORMAT_UNICODE_UTF8 :
m_dwSizeLow -= (3);
break;
default:
break;
}
}
return m_dwSizeLow;
}
//////////////////////////////////////////////////////////////////////
// cFileWriter class
//////////////////////////////////////////////////////////////////////
cFileWriter::cFileWriter(const TCHAR* fileName)
{
if(fileName != NULL)
{
Open(fileName);
}
}
BOOL cFileWriter::Open(const TCHAR* fileName, DWORD diposition)
{
if(0 == diposition)
{
diposition = CREATE_NEW;
}
if(cFile::Open(fileName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, diposition))
{
//WriteHeader();
return TRUE;
}
return FALSE;
}
BOOL cFileWriter::Write(const BYTE* buffer, const DWORD dwLength)
{
if(dwLength == 0)
return TRUE;
DWORD dwBytes = 0;
if(WriteFile( m_hFile,
buffer,
dwLength,
&dwBytes,
NULL))
{
return (dwBytes == dwLength) ? TRUE : FALSE;
}
return FALSE;
}
BOOL cFileWriter::WriteFormat(const TCHAR* format, ...)
{
TCHAR buffer[4096];
va_list marker;
va_start(marker, format);
_vstprintf_s(buffer, _countof(buffer), format, marker);
va_end(marker);
return Write(reinterpret_cast<BYTE*>(buffer), (DWORD)(_tcslen(buffer)*sizeof(TCHAR)));
}
void cFileWriter::WriteHeader()
{
#ifdef _UNICODE
Move(FILE_BEGIN, 0);
WORD BOM = 0xFEFF;
Write(reinterpret_cast<BYTE*>(&BOM), sizeof(BOM));
#endif
}
+66
View File
@@ -0,0 +1,66 @@
#pragma once
// cFile
class cFile
{
public:
cFile();
cFile(LPCTSTR fileName, DWORD dwMode, DWORD dwShareMode, DWORD dwCreationDisposition);
virtual ~cFile();
public:
BOOL Open(const TCHAR* fileName, DWORD dwMode, DWORD dwShareMode, DWORD dwCreationDisposition);
void Close();
BOOL Move(DWORD dwOrigin, LONG lOffset);
virtual DWORD GetFileSize();
protected:
enum SaveFileFormat
{
FILEFORMAT_ANSI = 1,
FILEFORMAT_UNICODE_UTF8,
FILEFORMAT_UNICODE_LE,
FILEFORMAT_UNICODE_BE,
};
HANDLE m_hFile;
DWORD m_dwSizeLow, m_dwSizeHigh;
};
// cFileReader
class cFileReader : public cFile
{
public:
cFileReader(const TCHAR* fileName=NULL);
public:
BOOL Open(const TCHAR* fileName);
BOOL Read(BYTE* buffer, const DWORD dwLength);
BOOL Convert(const BYTE* bufferA, const int lengthA, BYTE* bufferB, const int lengthB);
int GetBOM();
virtual DWORD GetFileSize();
private:
int m_nReadType;
};
// cFileWriter
class cFileWriter : public cFile
{
public:
cFileWriter(const TCHAR* fileName=NULL);
public:
BOOL Open(const TCHAR* fileName, DWORD diposition=0);
BOOL Write(const BYTE* buffer, const DWORD dwLength);
BOOL WriteFormat(const TCHAR* format, ...);
void WriteHeader();
};
@@ -0,0 +1,82 @@
#include "stdafx.h"
#include "cProcessor.h"
#include "cEnvironment.h"
#include "cScheduler.h"
#include "cManager.h"
#include "../include/Constant.h"
#include "../include/ISystem.h"
#include "../include/cSingleton.h"
#include "../common/Internal.h"
cManager::cManager(void)
{
}
cManager::~cManager(void)
{
}
BOOL cManager::Init(const uint32 maxSession, const uint32 flush)
{
g_environment.SetMaxSession(maxSession);
g_environment.SetFlushTime(flush);
cSingleton<ISystem>::GetInstance()->SetProcessor(cSingleton<cProcessor>::GetInstance());
cSingleton<ISystem>::GetInstance()->SetEvent(I_CONNECT, I_CLOSE);
if(!cSingleton<ISystem>::GetInstance()->Startup(maxSession, 1024*51, 1000, 0))
{
return FALSE;
}
return TRUE;
}
BOOL cManager::Listen(const uint16 port, const uint32 backlog)
{
if(!cSingleton<ISystem>::GetInstance()->Listen(port, backlog))
{
return FALSE;
}
return TRUE;
}
BOOL cManager::Start(const uint32 worker, const uint32 commander)
{
if(!cSingleton<ISystem>::GetInstance()->Start(worker, commander, 0))
{
return FALSE;
}
return TRUE;
}
BOOL cManager::Timer()
{
// sets the minimum timer resolution for an application or device driver.
timeBeginPeriod(1);
g_scheduler.AddSchedule(I_PING, NULL, 0, 100000); // ping ÀÔ·Â
g_scheduler.AddSchedule(I_FLUSH, NULL, 0, g_environment.GetFlushTime()); // flush out
cSchedule* schedule = NULL;
while(TRUE)
{
if(g_scheduler.Begin())
{
while((schedule = g_scheduler.GetSchedule()))
{
cSingleton<ISystem>::GetInstance()->Call(
schedule->GetCommand(),
NULL,
0);
}
g_scheduler.End();
}
Sleep(33);
}
// clears a previously set minimum timer resolution.
timeEndPeriod(1);
return TRUE;
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
class cManager
{
public:
cManager();
~cManager();
public:
BOOL Init(const uint32 maxSession, const uint32 flush);
BOOL Listen(const uint16 port, const uint32 backlog);
BOOL Start(const uint32 worker, const uint32 commander);
BOOL Timer();
};
@@ -0,0 +1,110 @@
#include "stdafx.h"
#include "cMiniDump.h"
#include <TCHAR.h>
#include <DBGHELP.h>
TCHAR cMiniDump::m_filename[MAX_PATH];
TCHAR cMiniDump::m_folername[MAX_PATH];
typedef BOOL (WINAPI *MINIDUMPWRITEDUMP)(
HANDLE hProcess,
DWORD dwPid,
HANDLE hFile,
MINIDUMP_TYPE DumpType,
CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
LPTOP_LEVEL_EXCEPTION_FILTER PreviousExceptionFilter = NULL;
LONG WINAPI UnHandledExceptionFilter(struct _EXCEPTION_POINTERS *exceptionInfo)
{
HMODULE DllHandle = NULL;
// Windows 2000 이전에는 따로 DBGHELP를 배포해서 설정해 주어야 한다.
DllHandle = LoadLibrary(_T("DBGHELP.DLL"));
if (DllHandle)
{
MINIDUMPWRITEDUMP MiniDumpWriteDump = reinterpret_cast<MINIDUMPWRITEDUMP>(GetProcAddress(DllHandle, "MiniDumpWriteDump"));
if (MiniDumpWriteDump)
{
TCHAR DumpPath[MAX_PATH] = {0};
SYSTEMTIME SystemTime;
GetLocalTime(&SystemTime);
_stprintf_s(
DumpPath,
MAX_PATH-1,
_T("%s\\%s(%04d%02d%02d-%02d%02d%02d).dmp"),
cMiniDump::m_folername,
cMiniDump::m_filename,
SystemTime.wYear,
SystemTime.wMonth,
SystemTime.wDay,
SystemTime.wHour,
SystemTime.wMinute,
SystemTime.wSecond);
HANDLE hDumpFile = CreateFile(
DumpPath,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hDumpFile != INVALID_HANDLE_VALUE)
{
_MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
ExceptionInfo.ThreadId = GetCurrentThreadId();
ExceptionInfo.ExceptionPointers = exceptionInfo;
ExceptionInfo.ClientPointers = NULL;
BOOL bSuccess = MiniDumpWriteDump(
GetCurrentProcess(),
GetCurrentProcessId(),
hDumpFile,
MiniDumpNormal,
&ExceptionInfo,
NULL,
NULL);
if (bSuccess)
{
CloseHandle(hDumpFile);
return EXCEPTION_EXECUTE_HANDLER;
}
CloseHandle(hDumpFile);
}
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
BOOL cMiniDump::Begin(const TCHAR* filename)
{
SetErrorMode(SEM_FAILCRITICALERRORS);
TCHAR temp[512];
GetCurrentDirectory(_countof(temp), temp);
_sntprintf_s(m_folername, sizeof(m_folername), _T("%s\\dump"), temp);
CreateDirectory(m_folername, NULL);
_tcscpy_s(m_filename, 260, filename);
PreviousExceptionFilter = SetUnhandledExceptionFilter(UnHandledExceptionFilter);
return TRUE;
}
BOOL cMiniDump::End(VOID)
{
SetUnhandledExceptionFilter(PreviousExceptionFilter);
return TRUE;
}
@@ -0,0 +1,12 @@
#pragma once
class cMiniDump
{
public:
static BOOL Begin(const TCHAR* filename);
static BOOL End(VOID);
public:
static TCHAR m_filename[MAX_PATH];
static TCHAR m_folername[MAX_PATH];
};
@@ -0,0 +1,121 @@
// cProcessor.cpp: implementation of the cProcessor class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "cCommand.h"
#include "cCommandHandler.h"
#include "SessionProc.h"
#include "cProcessor.h"
#include "../include/cSingleton.h"
#include "../include/IIocpContext.h"
#include "../include/INetwork.h"
#include "../common/Internal.h"
//#define _USE_TRYEXCEPT 1
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cProcessor::cProcessor()
{
Init();
}
cProcessor::~cProcessor()
{
Destroy();
}
void cProcessor::Init()
{
m_commandHandler = new cCommandHandler;
}
void cProcessor::Destroy()
{
if(m_commandHandler)
{
delete m_commandHandler;
m_commandHandler = NULL;
}
}
//////////////////////////////////////////////////////////////////////
// operation
//////////////////////////////////////////////////////////////////////
void cProcessor::Timeout()
{
cSession* session = SessionProc::GetFirstSession();
while(session)
{
Flush(session->GetContext());
session = SessionProc::GetNextSession();
}
}
void cProcessor::Process(IIocpContext* context, const uint32 commandId, const uint8* data, const uint32 length)
{
#ifdef _USE_TRYEXCEPT
__try
{
#endif
if(context && !context->IsActive())
{
return;
}
cCommand* pCommand = m_commandHandler->Get(commandId);
if(pCommand)
{
pCommand->Run(context, data, length);
//Flush(context);
}
else
{
pCommand = m_commandHandler->Get(I_CLOSE);
if(pCommand)
{
pCommand->Run(context, data, length);
}
}
#ifdef _USE_TRYEXCEPT
}
__except(1)
{
cout << _T("오류발생 클라이언트 Command :: ") << commandId << endl << flush;
}
#endif
}
void cProcessor::Process(const uint32 serverId, const uint32 commandId, const uint8* data, const uint32 length)
{
#ifdef _USE_TRYEXCEPT
__try
{
#endif
cCommand* pCommand = m_commandHandler->Get(commandId);
if(pCommand)
{
pCommand->Run(serverId, data, length);
}
else
{
Debug(_T("-----> 내부 프로토콜 검색 실패 : ServerID(%lu), Command(%lu)!!"), serverId, commandId);
}
#ifdef _USE_TRYEXCEPT
}
__except(1)
{
cout << _T("오류발생 내부 Command :: ") << commandId << endl << flush;
}
#endif
}
void cProcessor::Flush(IIocpContext* context)
{
cSingleton<INetwork>::GetInstance()->Flush(context);
}
@@ -0,0 +1,44 @@
// cProcessor.h: interface for the cProcessor class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CPROCESSOR_H__99EAE6C9_7E44_4B41_AD66_73D633AE4EA2__INCLUDED_)
#define AFX_CPROCESSOR_H__99EAE6C9_7E44_4B41_AD66_73D633AE4EA2__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "../include/IProcessor.h"
class cCommandHandler;
class cProcessor : public IProcessor
{
public:
cProcessor();
virtual ~cProcessor();
void Init();
void Destroy();
public:
virtual void Timeout();
virtual void Process(IIocpContext* context, const uint32 commandId, const uint8* data, const uint32 length);
virtual void Process(const uint32 serverId, const uint32 commandId, const uint8* data, const uint32 length);
private:
void Flush(IIocpContext* context);
private:
cCommandHandler* m_commandHandler;
};
#endif // !defined(AFX_CPROCESSOR_H__99EAE6C9_7E44_4B41_AD66_73D633AE4EA2__INCLUDED_)
@@ -0,0 +1,71 @@
#include "StdAfx.h"
#include "cScheduler.h"
cScheduler g_scheduler;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cScheduler::cScheduler() : m_current(0)
{
Init();
}
cScheduler::~cScheduler(void)
{
Destroy();
}
void cScheduler::Init()
{
}
void cScheduler::Destroy()
{
SCHEDULES::iterator it;
for(it = m_schedules.begin() ; it != m_schedules.end() ; ++it)
{
delete (*it);
}
m_schedules.clear();
}
//////////////////////////////////////////////////////////////////////
// Operation
//////////////////////////////////////////////////////////////////////
BOOL cScheduler::Begin()
{
m_iterator = m_schedules.begin();
m_current = GetTickCount();
return TRUE;
}
void cScheduler::End()
{
//Debug("cScheduler::End() ÃÑ ¼Ò¿ä½Ã°£ : %lu\n", GetTickCount()-m_current);
}
BOOL cScheduler::AddSchedule(const uint32 command, const uint32 data, const uint32 size, const uint32 tick)
{
m_schedules.push_back(new cSchedule(command,data,size,tick));
return TRUE;
}
cSchedule* cScheduler::GetSchedule()
{
cSchedule* schedule = NULL;
while(m_iterator != m_schedules.end())
{
schedule = (*m_iterator);
++m_iterator;
if(schedule->IsTimeup(m_current))
{
return schedule;
}
}
return NULL;
}
@@ -0,0 +1,67 @@
#pragma once
#include <map>
#include <list>
class cCommand;
class cSchedule
{
public:
cSchedule(const uint32 command, const uint32 data, const uint32 size, const uint32 tick)
: m_command(command), m_data(data), m_size(size), m_tick(tick), m_last(0)
{}
BOOL IsTimeup(uint32 current)
{
if(m_tick == 0)
return TRUE;
if((m_last == 0) || ((current - m_last) > m_tick))
{
m_last = current;
return TRUE;
}
return FALSE;
}
uint32 GetCommand() { return m_command; }
uint32 GetData() { return m_data; }
uint32 GetSize() { return m_size; }
private:
uint32 m_command;
uint32 m_data;
uint32 m_size;
uint32 m_tick;
uint32 m_last;
};
class cScheduler
{
public:
cScheduler(void);
~cScheduler(void);
void Init();
void Destroy();
public:
BOOL Begin();
void End();
BOOL AddSchedule(const uint32 command, const uint32 data, const uint32 size, const uint32 tick);
cSchedule* GetSchedule();
private:
typedef std::list<cSchedule*> SCHEDULES;
SCHEDULES m_schedules;
SCHEDULES::iterator m_iterator;
uint32 m_current;
};
extern cScheduler g_scheduler;
+158
View File
@@ -0,0 +1,158 @@
#pragma once
#include <list>
#include <vector>
#include "cBuffer.h"
// ÃÖ´ë¹öÆÛ±æÀÌ
const uint32 G_MAXSTORAGELENGTH = 1024 * 16;
class cSerialize
{
public:
cSerialize(void)
{
m_storage.Create(G_MAXSTORAGELENGTH);
}
public:
void Reset()
{
m_storage.Erase();
}
uint8* GetBuffer() { return m_storage.GetBuffer(); }
uint32 GetLength() { return m_storage.GetLength(); }
public:
void operator<<(const uint8 value) { m_storage.Append(reinterpret_cast<const uint8*>(&value), sizeof(value)); }
void operator<<(const uint16 value) { m_storage.Append(reinterpret_cast<const uint8*>(&value), sizeof(value)); }
void operator<<(const uint32 value) { m_storage.Append(reinterpret_cast<const uint8*>(&value), sizeof(value)); }
void operator<<(const uint64 value) { m_storage.Append(reinterpret_cast<const uint8*>(&value), sizeof(value)); }
void operator<<(const float value) { m_storage.Append(reinterpret_cast<const uint8*>(&value), sizeof(value)); }
public:
void Write( const uint8 value ) { m_storage.Append( reinterpret_cast<const uint8*>(&value), sizeof(value) ); }
void Write( const uint16 value ){ m_storage.Append( reinterpret_cast<const uint8*>(&value), sizeof(value) ); }
void Write( const uint32 value ){ m_storage.Append( reinterpret_cast<const uint8*>(&value), sizeof(value) ); }
void Write( const uint64 value ){ m_storage.Append( reinterpret_cast<const uint8*>(&value), sizeof(value) ); }
void Write( const float value ) { m_storage.Append( reinterpret_cast<const uint8*>(&value), sizeof(value) ); }
void Write( const uint8* value, uint32 length, BOOL saveLength = FALSE )
{
if( saveLength )
Write( static_cast<uint16>(length) );
m_storage.Append( value, length );
}
template<typename TD>
void Write( std::vector<TD>& vcList, BOOL saveLength = TRUE )
{
if( saveLength )
Write( static_cast<uint32>(vcList.size()) );
for( std::vector<TD>::iterator it = vcList.begin() ; it != vcList.end() ; ++it )
{
Write( *it );
}
}
template<typename TD>
void Write( std::list<TD>& vcList, BOOL saveLength = TRUE )
{
if( saveLength )
Write( static_cast<uint32>(vcList.size()) );
for( std::list<TD>::iterator it = vcList.begin() ; it != vcList.end() ; ++it )
{
Write( *it );
}
}
template<typename TD>
void Read( const uint8* pBuffer, std::vector<TD>& vcList )
{
uint32 nLength = 0;
CopyMemory( &nLength, pBuffer, sizeof(nLength) );
vcList.clear();
vcList.reserve( nLength );
TD data;
pBuffer += sizeof(nLength);
for( uint32 i = 0 ; i < nLength ; i++ )
{
CopyMemory( &data, pBuffer+sizeof(TD)*i, sizeof(TD) );
vcList.push_back( data );
}
}
public:
void SetBuffer( uint8* pBuffer, uint32 maxLength )
{
m_temporary = pBuffer;
m_maxLength = maxLength;
m_offset = 0;
}
BOOL GetStringLength(uint16& length)
{
CopyMemory( &length, m_temporary+m_offset, sizeof(length) );
m_offset += sizeof(uint16);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
BOOL GetUInt(uint8& data)
{
CopyMemory( &data, m_temporary+m_offset, sizeof(data) );
m_offset += sizeof(data);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
BOOL GetUInt(uint16& data)
{
CopyMemory( &data, m_temporary+m_offset, sizeof(data) );
m_offset += sizeof(data);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
BOOL GetUInt(uint32& data)
{
CopyMemory( &data, m_temporary+m_offset, sizeof(data) );
m_offset += sizeof(data);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
BOOL GetUInt(uint64& data)
{
CopyMemory( &data, m_temporary+m_offset, sizeof(data) );
m_offset += sizeof(data);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
BOOL GetFloat(float& data)
{
CopyMemory( &data, m_temporary+m_offset, sizeof(data) );
m_offset += sizeof(data);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
BOOL GetString(const uint32 length, TCHAR* buffer, const uint32 size)
{
if( length < size )
{
CopyMemory( buffer, m_temporary+m_offset, length );
buffer[length] = NULL;
m_offset += length;
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
return FALSE;
}
/*
const BOOL operator>>(uint8& data)
{
CopyMemory( &data, m_temporary+m_offset, sizeof(data) );
m_offset += sizeof(data);
return (m_offset <= m_maxLength) ? TRUE : FALSE;
}
*/
const uint8* GetExtra() { return (m_offset <= m_maxLength) ? (m_temporary + m_offset) : NULL; }
const uint32 GetExtraLength() { return (m_offset <= m_maxLength) ? (m_maxLength - m_offset) : 0; }
private:
uint8* m_temporary;
uint32 m_offset, m_maxLength;
cBuffer m_storage;
};
+291
View File
@@ -0,0 +1,291 @@
#include "stdafx.h"
#include "cService.h"
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cService* cService::_serviceMainClass = NULL;
cService::cService(int argc, TCHAR **argv)
{
_serviceMainClass = this;
m_serviceName = _T("");
m_displayName = _T("");
m_arguments.clear();
m_arguments.reserve(argc + 1);
for(int i = 1 ; i < argc ; i++)
{
m_arguments.push_back(argv[i]);
}
}
cService::~cService()
{
}
void cService::ServiceMainProc()
{
if(m_arguments.size() > 0)
{
if(m_arguments[0] == _T("-i"))
{
if(m_arguments.size() < 3) return;
// -i serviceName displayName
Debug(_T("service : install\n"));
m_serviceName = m_arguments[1];
m_displayName = m_arguments[2];
if(Install(m_serviceName.c_str(), m_displayName.c_str()))
{
Debug(_T("service installed\n"));
}
else
{
Debug(_T("service install failed\n"));
}
}
else if(m_arguments[0] == _T("-u"))
{
if(m_arguments.size() < 2) return;
// -u serviceName
Debug(_T("service : uninstall\n"));
m_serviceName = m_arguments[1];
if(Uninstall(m_serviceName.c_str()))
{
Debug(_T("service uninstalled\n"));
}
else
{
Debug(_T("service uninstall failed\n"));
}
}
else if(m_arguments[0] == _T("-c"))
{
if(m_arguments.size() < 1) return;
// -c
Debug(_T("service : console\n"));
ServiceStart();
}
else
{
Debug(_T("USAGE : \n"));
Debug(_T(" -i [service name] [display name]\n"));
Debug(_T(" -u [service name]\n"));
Debug(_T(" -c [lua file]\n"));
Debug(_T(" [lua file] [log file]\n\n"));
Debug(_T(" i------------Creates a service\n"));
Debug(_T(" u------------Deletes a service\n"));
Debug(_T(" c------------Run as console\n"));
Debug(_T(" ------------Run as service\n"));
Debug(_T("EXAMPLE : \n"));
Debug(_T(" -i rod-service \"R.O.D game service\"\n"));
Debug(_T(" -c lua-file.lua\n"));
}
}
else
{
_ExecuteProcess();
}
}
void WINAPI cService::_ServiceMain(int argc, TCHAR **argv)
{
if (_serviceMainClass != NULL)
{
_serviceMainClass->ServiceMain(argc, argv);
}
}
void cService::ServiceMain(int argc, TCHAR **argv)
{
m_hServiceStatusHandle = RegisterServiceCtrlHandler(m_serviceName.c_str(), _ServiceHandler);
if(0 == m_hServiceStatusHandle)
{
return;
}
m_arguments.clear();
m_arguments.reserve(argc + 1);
m_arguments.push_back(_T(""));
for(int i = 1 ; i < argc ; i++)
{
m_arguments.push_back(argv[i]);
}
// Initialization complete - report running status
m_serviceStatus.dwServiceType = SERVICE_WIN32;
m_serviceStatus.dwCurrentState = SERVICE_START_PENDING;
m_serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
m_serviceStatus.dwWin32ExitCode = NO_ERROR;
m_serviceStatus.dwServiceSpecificExitCode = 0;
m_serviceStatus.dwCheckPoint = 0;
m_serviceStatus.dwWaitHint = 0;
m_serviceStatus.dwCheckPoint = 0;
m_serviceStatus.dwWaitHint = 0;
m_serviceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(m_hServiceStatusHandle, &m_serviceStatus);
if(!ServiceStart())
{
m_serviceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(m_hServiceStatusHandle, &m_serviceStatus);
}
}
BOOL cService::Install(const TCHAR* serviceName, const TCHAR* displayName)
{
// 실행 파일 경로
TCHAR serviceDemon[MAX_PATH+1];
DWORD size = GetModuleFileName(NULL, serviceDemon, MAX_PATH);
serviceDemon[size] = 0;
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if(0 == schSCManager) return FALSE;
SC_HANDLE schService = CreateService(
schSCManager,
serviceName,
displayName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
serviceDemon,
NULL,
NULL,
NULL,
NULL,
NULL);
if(0 == schService) return FALSE;
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return TRUE;
}
BOOL cService::Uninstall(const TCHAR* serviceName)
{
// 서비스 관리자 얻기
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(0 == schSCManager) return FALSE;
// 서비스 핸들 얻기
SC_HANDLE schService = OpenService(schSCManager, serviceName, DELETE);
if(0 == schService) return FALSE;
// 서비스 삭제
if(!DeleteService(schService))
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return FALSE;
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return TRUE;
}
BOOL cService::KillService(const TCHAR* serviceName)
{
// 서비스 관리자 얻기
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(0 == schSCManager) return FALSE;
// 서비스 핸들 얻기
SC_HANDLE schService = OpenService(schSCManager, serviceName, SERVICE_STOP);
if(0 == schService) return FALSE;
// 서비스 중지
SERVICE_STATUS status;
if(!ControlService(schService, SERVICE_CONTROL_STOP, &status))
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return FALSE;
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return TRUE;
}
BOOL cService::RunService(const TCHAR* serviceName)
{
// 서비스 관리자 얻기
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(0 == schSCManager) return FALSE;
// 서비스 핸들 얻기
SC_HANDLE schService = OpenService(schSCManager, serviceName, SERVICE_START);
if(0 == schService) return FALSE;
// 서비스 시작
if(!StartService(schService, 0, 0))
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return FALSE;
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return TRUE;
}
void WINAPI cService::_ServiceHandler(DWORD fdwControl)
{
if(_serviceMainClass != NULL)
{
_serviceMainClass->ServiceHandler(fdwControl);
}
}
void cService::ServiceHandler(DWORD fdwControl)
{
switch(fdwControl)
{
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
m_serviceStatus.dwWin32ExitCode = 0;
m_serviceStatus.dwCurrentState = SERVICE_STOPPED;
m_serviceStatus.dwCheckPoint = 0;
m_serviceStatus.dwWaitHint = 0;
ServiceStop();
break;
case SERVICE_CONTROL_PAUSE:
m_serviceStatus.dwCurrentState = SERVICE_PAUSED;
break;
default:
m_serviceStatus.dwCurrentState = SERVICE_RUNNING;
};
SetServiceStatus(m_hServiceStatusHandle, &m_serviceStatus);
}
BOOL cService::_ExecuteProcess()
{
SERVICE_TABLE_ENTRY dipatchTable[] =
{
{const_cast<LPTSTR>(m_serviceName.c_str()), reinterpret_cast<LPSERVICE_MAIN_FUNCTION>(_ServiceMain)},
{NULL , NULL}
};
StartServiceCtrlDispatcher(dipatchTable);
return TRUE;
}
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include <vector>
#include <string>
class cService
{
public:
cService(int argc, TCHAR **argv);
virtual ~cService();
public:
void ServiceMainProc(); // 서비스 실행 메인 함수
static cService* _serviceMainClass;
static void WINAPI _ServiceMain(int argc, TCHAR **argv); // 서비스 메인 함수(ServiceMain()함수를 호출)
static void WINAPI _ServiceHandler(DWORD fdwControl); // 서비스 제어 메인 함수(ServiceHandler()함수를 호출)
void ServiceMain(int argc, TCHAR **argv); // 서비스 메인의 구현부
void ServiceHandler(DWORD fdwControl); // 서비스 제어의 구현부
public:
virtual BOOL ExecuteProcess() = 0; // 서비스 실행시에 호출되는 함수
virtual BOOL ServiceStart() = 0; // 서비스 실행(START)시에 호출됨
virtual void ServiceStop() = 0; // 서비스 중지(STOP)시에 호출됨
virtual void Debug(const TCHAR *message) = 0; // 디버깅용 메세지 출력
protected:
BOOL _ExecuteProcess(); // 서비스의 실행시 호출됨
// Service Control
BOOL Install(const TCHAR* serviceName, const TCHAR* displayName); // 서비스 등록
BOOL Uninstall(const TCHAR* serviceName); // 서비스 제거
BOOL RunService(const TCHAR* serviceName); // 서비스 실행(START)
BOOL KillService(const TCHAR* serviceName); // 서비스 중지(STOP)
protected:
std::vector<std::tstring> m_arguments;
std::tstring m_serviceName;
std::tstring m_displayName;
SERVICE_STATUS_HANDLE m_hServiceStatusHandle;
SERVICE_STATUS m_serviceStatus;
};
@@ -0,0 +1,174 @@
#include "stdafx.h"
#include "cFile.h"
#include "cManager.h"
#include "cMiniDump.h"
#include "cServiceLS.h"
#include "../include/cSingleton.h"
#include <iostream>
using namespace std;
void DisplayHeapInfo(HANDLE heap)
{
ULONG heapInfo;
SIZE_T size;
if(HeapQueryInformation(
heap,
HeapCompatibilityInformation,
&heapInfo,
sizeof(heapInfo),
&size) == FALSE)
{
Debug();
}
else
{
//Information(_T("Handle: %X, HeapInfo: %d\n", heap, heapInfo);
}
}
void SetHeapInformation()
{
HANDLE heaps[1025];
BOOL results[1025];
ZeroMemory(heaps, sizeof(heaps));
ZeroMemory(results, sizeof(results));
ULONG HeapFragValue = 2;
DWORD count = GetProcessHeaps(1024, heaps);
for(DWORD i = 0; i < count; i++)
{
results[i] = HeapSetInformation(
heaps[i],
HeapCompatibilityInformation,
&HeapFragValue,
sizeof(HeapFragValue));
if(!results[i])
{
DisplayHeapInfo(heaps[i]);
}
}
}
void SetCurrentModulePath()
{
TCHAR temp[MAX_PATH+1];
GetModuleFileName(NULL, temp, MAX_PATH);
TCHAR* token = _tcsrchr(temp, _T('\\'));
*(token+1) = _T('\0');
SetCurrentDirectory(temp);
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cServiceLS::cServiceLS(int argc, TCHAR **argv) : cService(argc, argv)
{
}
cServiceLS::~cServiceLS()
{
}
BOOL cServiceLS::ExecuteProcess()
{
return TRUE;
}
void cServiceLS::ServiceStop()
{
Debug(_T("service stopped\r\n"));
cMiniDump::End();
}
BOOL cServiceLS::ServiceStart()
{
ConfigureSystem();
cMiniDump::Begin(_T("lostsaga-controller"));
m_logFile = _T("lostsaga-controller.txt");
Debug(_T("----------------------------------------------------\r\n"));
Debug(_T("-- start lostsaga-controller\r\n"));
Debug(_T("----------------------------------------------------\r\n"));
if(!cSingleton<cManager>::GetInstance()->Init(10, 80))
{
TCHAR error[512];
wsprintf( error, _T("ls_controller Init failed(%lu)\r\n"), GetLastError());
Debug(error);
return FALSE;
}
if(!cSingleton<cManager>::GetInstance()->Listen(24444, 10))
{
TCHAR error[512];
wsprintf( error, _T("ls_controller Listen failed(%lu)\r\n"), GetLastError());
Debug(error);
return FALSE;
}
if(!cSingleton<cManager>::GetInstance()->Start(2, 1))
{
TCHAR error[512];
wsprintf( error, _T("ls_controller Start failed(%lu)\r\n"), GetLastError());
Debug(error);
return FALSE;
}
Debug(_T("service start - success\r\n"));
cSingleton<cManager>::GetInstance()->Timer();
return TRUE;
}
void cServiceLS::Debug(const TCHAR *message)
{
if(0 == m_logFile.size())
{
#ifdef _UNICODE
wcout << message;
#else
cout << message;
#endif
}
else
{
/*
SYSTEMTIME systime;
GetLocalTime(&systime);
TCHAR currentTime[256];
_stprintf_s(
currentTime,
sizeof(currentTime),
"[%04d-%02d-%02d %02d:%02d:%02d]",
systime.wYear,
systime.wMonth,
systime.wDay,
systime.wHour,
systime.wMinute,
systime.wSecond);
*/
cFileWriter file;
if(file.Open(GetLogFile(), OPEN_ALWAYS))
{
uint32 length = (_tcslen(message))*sizeof(TCHAR);
file.Move(FILE_BEGIN, file.GetFileSize());
file.Write(reinterpret_cast<const BYTE*>(message), length);
file.Close();
}
}
}
void cServiceLS::ConfigureSystem()
{
SetHeapInformation();
SetCurrentModulePath();
}
@@ -0,0 +1,27 @@
#pragma once
#include "cService.h"
class cServiceLS : public cService
{
public:
cServiceLS(int argc, TCHAR **argv);
virtual ~cServiceLS();
public:
virtual BOOL ExecuteProcess(); // 서비스 실행시에 호출되는 함수(사용자 정의)
virtual BOOL ServiceStart(); // 서비스 실행(START)시에 호출됨
virtual void ServiceStop(); // 서비스 중지(STOP)시에 호출됨
virtual void Debug(const TCHAR *message); // 디버깅용 메세지 출력
protected:
void ConfigureSystem();
const TCHAR* GetLogFile() { return m_logFile.c_str(); } // 서비스 로그가 남을 파일
protected:
std::tstring m_luaFile;
std::tstring m_logFile;
};
@@ -0,0 +1,80 @@
#include "stdafx.h"
#include "cSession.h"
#include "../include/IIocpContext.h"
void tinet_ntoa(uint32 IP, TCHAR* buffer)
{
SOCKADDR_IN sockAddr;
sockAddr.sin_addr.s_addr = IP;
#ifdef UNICODE
char szIP[16];
strcpy_s(szIP, sizeof(szIP), inet_ntoa(sockAddr.sin_addr));
uint32 length = MultiByteToWideChar(CP_ACP, 0, szIP, sizeof(szIP)-1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, szIP, sizeof(szIP)-1, buffer, length);
buffer[length] = NULL;
#else
strcpy_s(buffer, sizeof(buffer), inet_ntoa(sockAddr.sin_addr));
#endif
}
void cSession::OnConnect()
{
TCHAR szIP[64];
tinet_ntoa(GetContext()->GetIP(), szIP);
TransferEnd();
Debug(_T("@¼ÒÄÏ Á¢¼Ó(%s)\n"), szIP);
}
void cSession::OnDisconnect()
{
TransferEnd();
Debug(_T("@¼ÒÄÏ Á¢¼ÓÇØÁ¦\n"));
}
BOOL cSession::TransferBegin(const TCHAR* file, const uint32 length)
{
if(!m_transfer)
{
m_transfer = TRUE;
if(length > G_MAXFILESIZE)
m_buffer.Resize(G_MAXFILESIZE*2);
else
m_buffer.Resize(length);
m_transferLength = 0;
ZeroMemory(m_file, sizeof(m_file));
CopyMemory(m_file, file, sizeof(m_file));
return TRUE;
}
return FALSE;
}
BOOL cSession::TransferDo(const uint8* buffer, const uint32 length)
{
if(m_transfer)
{
m_transferLength += length;
return m_buffer.Append(buffer, length);
}
return FALSE;
}
void cSession::TransferWrite()
{
if(m_transfer)
{
m_buffer.Erase();
}
}
void cSession::TransferEnd()
{
m_transfer = FALSE;
m_buffer.Erase();
ZeroMemory(m_file, sizeof(m_file));
}
+75
View File
@@ -0,0 +1,75 @@
#pragma once
#include "cBuffer.h"
#include "../common/Protocol.h"
#include "../include/BoostPooler.h"
class IIocpContext;
// 技记鸥涝
enum SessionTypes
{
SESSION_NORMAL = 0,
SESSION_LOGIN,
SESSION_PLAYER,
SESSION_SERVER,
SESSION_OPERATOR,
};
// 技记牢磐其捞胶
class ISession
{
public:
ISession(void) : m_sessionType(SESSION_NORMAL), m_context(NULL)
{}
public:
void SetType(const SessionTypes type) { m_sessionType = type; }
void SetContext(IIocpContext* context) { m_context = context; }
SessionTypes GetType() { return m_sessionType; }
IIocpContext* GetContext() { return m_context; }
public:
BOOL IsNormal() { return (SESSION_NORMAL == m_sessionType) ? TRUE : FALSE; }
BOOL IsWaiter() { return (SESSION_LOGIN == m_sessionType) ? TRUE : FALSE; }
BOOL IsPlayer() { return (SESSION_PLAYER == m_sessionType) ? TRUE : FALSE; }
BOOL IsServer() { return (SESSION_SERVER == m_sessionType) ? TRUE : FALSE; }
public:
virtual void OnConnect() {};
virtual void OnDisconnect() {};
protected:
SessionTypes m_sessionType;
IIocpContext* m_context;
};
// 扁夯技记
class cSession : public ISession, public BoostPooler<cSession>
{
public:
cSession(void) {}
public:
virtual void OnConnect();
virtual void OnDisconnect();
public:
BOOL TransferBegin(const TCHAR* file, const uint32 length);
BOOL TransferDo(const uint8* buffer, const uint32 length);
void TransferWrite();
void TransferEnd();
BOOL DoingTransfer() { return m_transfer; }
const TCHAR* GetFile() { return m_file; }
const uint8* GetBuffer() { return m_buffer.GetBuffer(); }
const uint32 GetLength() { return m_buffer.GetLength(); }
const uint32 GetTransferLength() { return m_transferLength; }
public:
BOOL m_transfer;
TCHAR m_file[512];
uint32 m_transferLength;
cBuffer m_buffer;
};
@@ -0,0 +1,90 @@
#include "stdafx.h"
#include "cSessionTable.h"
cSessionTable g_sessionTable;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cSessionTable::cSessionTable(void)
{
Init();
}
cSessionTable::~cSessionTable(void)
{
Destroy();
}
void cSessionTable::Init()
{
}
void cSessionTable::Destroy()
{
m_sessions.clear();
}
//////////////////////////////////////////////////////////////////////
// Operation
//////////////////////////////////////////////////////////////////////
BOOL cSessionTable::Insert(const uint32 entity, IIocpContext* context)
{
cSession* session = Get(entity);
if(!session)
{
session = new cSession;
session->SetContext(context);
session->OnConnect();
m_sessions[entity] = session;
return TRUE;
}
return FALSE;
}
void cSessionTable::Remove(const uint32 entity)
{
cSession* session = Get(entity);
if(!session) return;
SESSION_TABLE::iterator it = m_sessions.find(entity);
if(it != m_sessions.end())
{
m_sessions.erase(it);
}
switch(session->GetType())
{
case SESSION_LOGIN :
case SESSION_PLAYER :
case SESSION_SERVER :
default :
{
delete session;
}
break;
}
}
cSession* cSessionTable::Get(const uint32 entity)
{
SESSION_TABLE::iterator it = m_sessions.find(entity);
return (it != m_sessions.end()) ? it->second : NULL;
}
cSession* cSessionTable::GetFirst()
{
m_iterator = m_sessions.begin();
return (m_iterator != m_sessions.end()) ? m_iterator->second : NULL;
}
cSession* cSessionTable::GetNext()
{
++m_iterator;
return (m_iterator != m_sessions.end()) ? m_iterator->second : NULL;
}
@@ -0,0 +1,35 @@
#pragma once
#include <map>
#include <vector>
#include "cSession.h"
// ¼¼¼ÇÀ» °ü¸®ÇÏ´Â Å×À̺í
class cSessionTable
{
public:
cSessionTable(void);
~cSessionTable(void);
void Init();
void Destroy();
public:
BOOL Insert(const uint32 entity, IIocpContext* context);
void Remove(const uint32 entity);
uint32 GetCount() { return m_sessions.size(); }
cSession* Get(const uint32 entity);
cSession* GetFirst();
cSession* GetNext();
private:
typedef std::map<uint32,cSession*> SESSION_TABLE;
SESSION_TABLE::iterator m_iterator;
SESSION_TABLE m_sessions;
};
extern cSessionTable g_sessionTable;
+20
View File
@@ -0,0 +1,20 @@
#include "stdafx.h"
#include "cServiceLS.h"
#include <iostream>
using namespace std;
int _tmain(int argc, TCHAR **argv)
{
// 한글 OS가 설치되지 않은 곳에서 실행되지 않으므로 삭제. 2013-01-14 신영욱
//#ifdef _UNICODE
// wcin.imbue( locale("korean") );
// wcout.imbue(locale("korean"));
//#endif
cServiceLS *service = new cServiceLS(argc, argv);
service->ServiceMainProc();
delete service;
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LS_launcher", "LS_launcher\LS_launcher.vcxproj", "{C247F5AA-04DD-45B9-85E7-FD2537686BE3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C247F5AA-04DD-45B9-85E7-FD2537686BE3}.Debug|Win32.ActiveCfg = Debug|Win32
{C247F5AA-04DD-45B9-85E7-FD2537686BE3}.Debug|Win32.Build.0 = Debug|Win32
{C247F5AA-04DD-45B9-85E7-FD2537686BE3}.Release|Win32.ActiveCfg = Release|Win32
{C247F5AA-04DD-45B9-85E7-FD2537686BE3}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,74 @@
// AddIPDialog.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "AddIPDialog.h"
#include "WinMessage.h"
// CAddIPDialog 대화 상자입니다.
IMPLEMENT_DYNAMIC(CAddIPDialog, CDialog)
CAddIPDialog::CAddIPDialog(CWnd* pParent /*=NULL*/)
: CDialog(CAddIPDialog::IDD, pParent)
, m_tapName(_T(""))
, m_port(0)
, m_ip(_T(""))
{
}
CAddIPDialog::~CAddIPDialog()
{
}
void CAddIPDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_TAP_NAME_EDIT, m_tapName);
DDX_Text(pDX, IDC_PORT_EDIT, m_port);
DDX_Text(pDX, IDC_ADDIP_EDIT, m_ip);
}
BEGIN_MESSAGE_MAP(CAddIPDialog, CDialog)
ON_BN_CLICKED(IDC_ADD_IP_OK_BUTTON, &CAddIPDialog::OnBnClickedAddIpOkButton)
ON_BN_CLICKED(IDC_ADD_IP_CANCEL_BUTTON, &CAddIPDialog::OnBnClickedAddIpCancelButton)
ON_WM_TIMER()
END_MESSAGE_MAP()
// CAddIPDialog 메시지 처리기입니다.
void CAddIPDialog::OnBnClickedAddIpOkButton()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
UpdateData(TRUE);
OnOK();
}
void CAddIPDialog::OnBnClickedAddIpCancelButton()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
OnCancel();
}
void CAddIPDialog::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
switch(nIDEvent)
{
case ECOMMAND::WATCHDOG:
{
}
break;
}
CDialog::OnTimer(nIDEvent);
}
@@ -0,0 +1,35 @@
#pragma once
// CAddIPDialog 대화 상자입니다.
class CAddIPDialog : public CDialog
{
DECLARE_DYNAMIC(CAddIPDialog)
public:
CAddIPDialog(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~CAddIPDialog();
// 대화 상자 데이터입니다.
enum { IDD = IDD_ADD_IP_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedAddIpOkButton();
afx_msg void OnBnClickedAddIpCancelButton();
CString GetTapName() { return m_tapName; }
UINT GetPort() { return m_port; }
CString GetIP() { return m_ip; }
protected:
CString m_tapName;
UINT m_port;
CString m_ip;
public:
afx_msg void OnTimer(UINT_PTR nIDEvent);
};
@@ -0,0 +1,88 @@
// BackupDialog.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "BackupDialog.h"
extern BOOL SelectFolder(HWND hWnd, CString &folder);
// CBackupDialog 대화 상자입니다.
IMPLEMENT_DYNAMIC(CBackupDialog, CDialog)
CBackupDialog::CBackupDialog(CWnd* pParent /*=NULL*/)
: CDialog(CBackupDialog::IDD, pParent)
{
}
CBackupDialog::~CBackupDialog()
{
}
void CBackupDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_SOURCE, m_sourcePath);
DDX_Control(pDX, IDC_STATIC_TARGET, m_targetPath);
}
BEGIN_MESSAGE_MAP(CBackupDialog, CDialog)
ON_BN_CLICKED(IDC_BUTTON_SOURCE, &CBackupDialog::OnBnClickedButtonSource)
ON_BN_CLICKED(IDC_BUTTON_TARGET, &CBackupDialog::OnBnClickedButtonTarget)
ON_BN_CLICKED(IDC_BUTTON_BACKUPOK, &CBackupDialog::OnBnClickedButtonBackupOK)
ON_BN_CLICKED(IDC_BUTTON_BACKUPCANCEL, &CBackupDialog::OnBnClickedButtonBackupCancel)
END_MESSAGE_MAP()
// CBackupDialog 메시지 처리기입니다.
void CBackupDialog::OnBnClickedButtonSource()
{
// 소스폴더 선택
m_source = _T("");
if(SelectFolder(this->GetSafeHwnd(), m_source))
{
m_sourcePath.SetWindowText(m_source);
}
else
{
m_sourcePath.SetWindowText(_T(""));
}
}
void CBackupDialog::OnBnClickedButtonTarget()
{
// 타겟폴더 선택
m_target = _T("");
if(SelectFolder(this->GetSafeHwnd(), m_target))
{
m_targetPath.SetWindowText(m_target);
}
else
{
m_targetPath.SetWindowText(_T(""));
}
}
BOOL CBackupDialog::GetBackupPath(CString& source, CString& target)
{
if(m_source.IsEmpty()) return FALSE;
if(m_target.IsEmpty()) return FALSE;
source = m_source;
target = m_target;
return TRUE;
}
void CBackupDialog::OnBnClickedButtonBackupOK()
{
CDialog::EndDialog(IDOK);
}
void CBackupDialog::OnBnClickedButtonBackupCancel()
{
CDialog::EndDialog(IDCANCEL);
}
@@ -0,0 +1,36 @@
#pragma once
#include "afxwin.h"
// CBackupDialog 대화 상자입니다.
class CBackupDialog : public CDialog
{
DECLARE_DYNAMIC(CBackupDialog)
public:
CBackupDialog(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~CBackupDialog();
// 대화 상자 데이터입니다.
enum { IDD = IDD_BACKUP_DIALOG };
public:
BOOL GetBackupPath(CString& source, CString& target);
protected:
CString m_source;
CString m_target;
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButtonSource();
afx_msg void OnBnClickedButtonTarget();
CStatic m_sourcePath;
CStatic m_targetPath;
afx_msg void OnBnClickedButtonBackupOK();
afx_msg void OnBnClickedButtonBackupCancel();
};
@@ -0,0 +1,230 @@
#include "StdAfx.h"
#include "BaseCommand.h"
#include "../resource.h"
#include "../LS_launcherDlg.h"
#include "../LauncherTabCtrl.h"
BaseCommand::BaseCommand(DWORD type) : m_commandType(type)
{
Init();
}
BaseCommand::~BaseCommand(void)
{
Destroy();
}
void BaseCommand::Init()
{
m_launcher = NULL;
m_isServiceAll = FALSE;
m_isApplyAll = FALSE;
m_state = CST_BEFORE_EXCUTE;
m_error = CET_NOERROR;
}
void BaseCommand::Destroy()
{
}
BOOL BaseCommand::Execute()
{
if( NULL == m_launcher )
{
m_error = CET_WRONG_NO_LAUNCHER;
return FALSE;
}
if( m_isApplyAll )
{
if( m_isServiceAll )
{
for( int i = 0 ; i < GetDialogCount() ; i++ )
{
CServerDialog* dialog = GetDialog(i);
if( !ExecuteServiceAll( dialog ) )
return FALSE;
}
}
else
{
for( int i = 0 ; i < GetDialogCount() ; i++ )
{
CServerDialog* dialog = GetDialog(i);
if( !ExecuteServiceOne( dialog ) )
return FALSE;
}
}
}
else
{
if( m_isServiceAll )
{
for( UINT i = 0 ; i < m_tabIndexes.size() ; i++ )
{
CServerDialog* dialog = GetDialog(m_tabIndexes[i]);
if( !ExecuteServiceAll(dialog) )
return FALSE;
}
}
else
{
for( UINT i = 0 ; i < m_tabIndexes.size() ; i++ )
{
CServerDialog* dialog = GetDialog(m_tabIndexes[i]);
if( !ExecuteServiceOne(dialog) )
return FALSE;
}
}
}
if( m_isWait && m_state != CST_ALREADY_EXCUTE )
{
m_state = CST_WAITING;
m_launcher->BatchWait();
return FALSE;
}
m_state = CST_EXCUTE_DONE;
return TRUE;
}
BOOL BaseCommand::CheckContinue()
{
if( NULL == m_launcher )
{
m_error = CET_WRONG_NO_LAUNCHER;
return FALSE;
}
if( m_state != CST_WAITING )
return FALSE;
if( m_isApplyAll )
{
if( m_isServiceAll )
{
for( int i = 0 ; i < GetDialogCount() ; i++ )
{
CServerDialog* dialog = GetDialog(i);
if( !CheckContinueServiceAll(dialog) )
{
return FALSE;
}
}
}
else
{
for( int i = 0 ; i < GetDialogCount() ; i++ )
{
CServerDialog* dialog = GetDialog(i);
if( !CheckContinueServiceOne(dialog) )
{
return FALSE;
}
}
}
}
else
{
if( m_isServiceAll )
{
for( UINT i = 0 ; i < m_tabIndexes.size() ; i++ )
{
CServerDialog* dialog = GetDialog(m_tabIndexes[i]);
if( !CheckContinueServiceAll(dialog) )
return FALSE;
}
}
else
{
for( UINT i = 0 ; i < m_tabIndexes.size() ; i++ )
{
CServerDialog* dialog = GetDialog(m_tabIndexes[i]);
if( !CheckContinueServiceOne(dialog) )
return FALSE;
}
}
}
m_state = CST_EXCUTE_DONE;
return TRUE;
}
BOOL BaseCommand::IsValid()
{
// 전체적으로 체크할 오류?..
if( !m_launcher )
return FALSE;
// Apply All 처리 - TabIndex가 있으면 ApplyAll이 아니다
if( m_tabIndexes.empty() )
{
m_isApplyAll = TRUE;
}
else
{
m_isApplyAll = FALSE;
}
return IsValidDetail();
}
void BaseCommand::SetOption( DWORD optionBit )
{
m_isWait = FALSE;
if( BITCHK(optionBit, BOT_SERVICE_WAIT) )
{
m_isWait = TRUE;
}
m_isServiceAll = FALSE;
if( BITCHK(optionBit, BOT_ALL_SERVICE) )
{
m_isServiceAll = TRUE;
}
}
void BaseCommand::SetCommandText(const char* commandLine)
{
TCHAR tcommandLine[_MAX_FNAME];
#ifdef UNICODE
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, commandLine, strlen(commandLine)+1, tcommandLine, _MAX_FNAME-1 );
#else
strcpy_s( tstring, string );
#endif
m_commandText.Format( _T("%s"), tcommandLine );
}
void BaseCommand::AddString( const char* string, int len )
{
TCHAR tstring[_MAX_FNAME];
CString temp;
#ifdef UNICODE
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, string, len, tstring, _MAX_FNAME-1 );
tstring[len] = 0;
#else
strcpy_s( tstring, string );
#endif
temp.Format( _T("%s"), tstring );
m_strings.push_back( temp );
}
CServerDialog* BaseCommand::GetDialog(int index)
{
CServerDialog* dlg = m_launcher->GetTabDialog(index);
if(dlg)
{
m_launcher->m_serverTabs.UserFocus(index);
}
return dlg;
}
int BaseCommand::GetDialogCount()
{
return m_launcher->GetTabDialogCount();
}
@@ -0,0 +1,66 @@
#pragma once
#include <vector>
#include "BatchCompileDefine.h"
class CLS_launcherDlg;
class CServerDialog;
class BaseCommand
{
public:
BaseCommand(DWORD type);
virtual ~BaseCommand(void);
private:
void Init();
void Destroy();
public:
BOOL Execute();
BOOL CheckContinue();
BOOL IsValid();
void SetOption( DWORD optionBit );
void SetCommandText(const char* commandLine);
protected:
virtual BOOL ExecuteServiceAll(CServerDialog* dialog) = 0;
virtual BOOL ExecuteServiceOne(CServerDialog* dialog) = 0;
virtual BOOL CheckContinueServiceAll(CServerDialog* dialog) = 0;
virtual BOOL CheckContinueServiceOne(CServerDialog* dialog) = 0;
virtual BOOL IsValidDetail() = 0;
public:
DWORD GetType() { return m_commandType; }
void SetLauncher( CLS_launcherDlg* launcher ) { m_launcher = launcher; }
void AddIndex( int index ) { m_tabIndexes.push_back( index ); }
void AddString( const char* string, int len );
CServerDialog* GetDialog(int index);
int GetDialogCount();
DWORD GetState() { return m_state; }
DWORD GetError() { return m_error; }
CString GetCommand() { return m_commandText; }
protected:
const DWORD m_commandType;
CString m_commandText;
CLS_launcherDlg* m_launcher;
VECINT m_tabIndexes;
VECCSTRING m_strings;
BOOL m_isWait;
BOOL m_isServiceAll;
BOOL m_isApplyAll;
DWORD m_state;
DWORD m_error;
};
@@ -0,0 +1,130 @@
#include "stdafx.h"
#include "Batch.h"
#include "BatchManager.h"
#include "BatchScanner.h"
Batch::Batch(void)
{
Init();
}
Batch::~Batch(void)
{
Destroy();
}
void Batch::Init()
{
m_commands.reserve( 32 );
m_currentIndex = 0;
}
void Batch::Destroy()
{
for( unsigned i = 0 ; i < m_commands.size() ; i++ )
{
if( m_commands[i] )
{
delete m_commands[i];
}
}
m_commands.clear();
}
BOOL Batch::OpenFile( TCHAR* fileName )
{
return m_file.OpenFile( fileName );
}
BOOL Batch::ScanProcess( BatchScanner* scanner, CLS_launcherDlg* launcher )
{
if( NULL == scanner )
return FALSE;
char line[_MAX_FNAME];
while( true )
{
if( !m_file.GetLine( line, _MAX_FNAME ) )
{
break;
}
BaseCommand* command = scanner->Scanner(line);
if( !command )
{
Destroy();
return FALSE;
}
command->SetLauncher( launcher );
if( !command->IsValid() )
{
delete command;
command = NULL;
Destroy();
return FALSE;
}
m_commands.push_back( command );
}
if( m_commands.empty() )
return FALSE;
return TRUE;
}
BOOL Batch::Execute(CBatchManager* batchManager)
{
if( m_commands.empty() )
return FALSE;
for( m_currentIndex ; m_currentIndex < m_commands.size() ; m_currentIndex++ )
{
BaseCommand* command = m_commands[m_currentIndex];
if( !command ) continue;
int index = 0;
batchManager->BeginProgress(command->GetCommand(), 0, _T("..."));
if(batchManager->IsConsoleMode())
_tprintf(command->GetCommand());
if( !command->Execute() )
{
return FALSE;
}
batchManager->EndProgress( 100, _T("completed"),FALSE);
}
return TRUE;
}
BOOL Batch::CheckContinue()
{
if( m_commands.empty() )
return FALSE;
if( m_currentIndex >= m_commands.size() )
return FALSE;
return m_commands[m_currentIndex]->CheckContinue();
}
BOOL Batch::Next()
{
m_currentIndex++;
if( m_currentIndex >= m_commands.size() )
return FALSE;
return TRUE;
}
DWORD Batch::GetCurrentState()
{
if( m_currentIndex >= m_commands.size() )
return CST_UNKNOWN_COMMAND;
return m_commands[m_currentIndex]->GetState();
}
@@ -0,0 +1,44 @@
#pragma once
#include <vector>
#include "BatchCompileDefine.h"
#include "FileReader.h"
class BatchScanner;
class CLS_launcherDlg;
class BaseCommand;
class CBatchManager;
using namespace std;
class Batch
{
public:
typedef vector<BaseCommand*> VECCOMMANDS;
public:
Batch(void);
~Batch(void);
private:
void Init();
void Destroy();
public:
BOOL OpenFile( TCHAR* fileName );
BOOL ScanProcess( BatchScanner* scanner, CLS_launcherDlg* launcher );
BOOL Execute(CBatchManager* batchManager);
BOOL CheckContinue();
BOOL Next();
public:
void ResetExecute() { m_currentIndex = 0; }
DWORD GetCurrentState();
private:
FileReader m_file;
VECCOMMANDS m_commands;
UINT m_currentIndex;
};
@@ -0,0 +1,79 @@
#pragma once
#define MAX_TOKEN_BUFFER_SIZE 32
#define TOKEN_SPLIT_CHAR _T(' ')
enum BatchCommandType
{
BCT_NONE = -1,
BCT_PLAY = 0,
BCT_STOP,
BCT_SYNC,
BCT_INSTALL,
BCT_UNINSTALL,
BCT_BACKUP,
BCT_REMOVE,
BCT_WAIT,
BCT_QUIT,
BCT_END,
};
enum BatchOptionType
{
BOT_SERVICE_WAIT = 0,
BOT_ALL_SERVICE,
//BOT_WATCHDOG,
//BOT_APPLYALL,
//BOT_RECURSIVE,
// 여기까지 비트처리 옵션들
//====================
// 여기부터 기타 옵션들
BOT_TABINDEX,
BOT_END,
};
enum CommandStateType
{
CST_NONE = 0,
CST_BEFORE_EXCUTE,
CST_WAITING,
CST_EXCUTE_DONE,
CST_FAIL,
CST_SYNC_CHECK,
CST_ALREADY_EXCUTE,
CST_UNKNOWN_COMMAND, // 나와선 안될 오류
CST_END,
};
enum CommandErrorType
{
CET_NONE = 0,
CET_NOERROR,
CET_WRONG_COMMAND_LINE, // 명령어 잘못됨
CET_WRONG_NO_LAUNCHER, // 런쳐 없음 - 나와선 안될 오류
// common Error
CET_ERROR_NO_COMMAND, // 커맨드 없음
CET_ERROR_NO_SERVICENAME, // 서비스 이름 없음
CET_ERROR_WRONG_COMMAND, // 잘못된 명령어
CET_ERROR_WRONG_SERVICENAME, // 잘못된 서비스 이름
CET_ERROR_WRONG_TABINDEX, // 잘못된 탭인덱스
CET_ERROR_NO_NEED_SERVICENAME, // '/a' 옵션과 서비스 이름 중첩
// Play Error
// Stop Error
// Uninstall Error
// Install Error
CET_ERROR_INSTALL_NO_INIFILE,
CET_ERROR_INSTALL_NO_EXEFILE,
// Sync Error
CET_END
};
#define BITON(x, y) ( x |= (1 << y) )
#define BITOFF(x, y) ( x &= !(1 << y ) )
#define BITCHK(x, y) ( x & (1 << y) )
typedef std::vector<int> VECINT;
typedef std::vector<CString> VECCSTRING;
@@ -0,0 +1,231 @@
#include "StdAfx.h"
#include "Batch.h"
#include "../resource.h"
#include "../BatchDialog.h"
#include "BatchManager.h"
CBatchManager::CBatchManager(void) : m_currentIndex(0), m_batchDlg(NULL), m_current(0), m_elapse(0), m_beginTime(0)
{
Init();
}
CBatchManager::~CBatchManager(void)
{
Destroy();
}
void CBatchManager::Init()
{
m_batchs.reserve( 32 );
if(!m_batchDlg)
{
m_batchDlg = new CBatchDialog();
m_batchDlg->Create(IDD_BATCH_DIALOG, NULL);
m_batchDlg->SetWindowPos(&m_batchDlg->wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
m_consoleMode = FALSE;
}
}
void CBatchManager::Destroy()
{
for( unsigned i = 0 ; i < m_batchs.size() ; i++ )
{
if( m_batchs[i] )
{
delete m_batchs[i];
}
}
m_batchs.clear();
}
void CBatchManager::ShowDialog()
{
if(m_batchDlg)
{
CString log;
log.Format(_T("Elapsed : %lu s"), 0);
m_batchDlg->UpdateBatchResult(log);
m_batchDlg->CenterWindow();
m_batchDlg->ShowWindow(SW_SHOW);
}
}
void CBatchManager::End()
{
}
BOOL CBatchManager::AddBatchFile( TCHAR* batchFileName, CLS_launcherDlg* launcher )
{
CString checkNull = batchFileName;
if(checkNull.IsEmpty())
return FALSE;
Batch* batch = new Batch;
if( !batch->OpenFile( batchFileName ) )
{
delete batch;
Error(_T("File open"), _T("failed"), TRUE);
return FALSE;
}
if( !batch->ScanProcess( &m_Scanner, launcher ) )
{
delete batch;
Error(_T("Command parsing"), _T("failed"));
return FALSE;
}
m_batchs.push_back( batch );
return TRUE;
}
BOOL CBatchManager::Execute()
{
if( m_batchs.empty() )
return FALSE;
if( m_currentIndex >= m_batchs.size() )
return TRUE;
for( m_currentIndex ; m_currentIndex < m_batchs.size() ; m_currentIndex++ )
{
Batch *batch = m_batchs[m_currentIndex];
if( !batch ) continue;
if( !batch->Execute(this) )
{
return FALSE;
}
}
return TRUE;
}
BOOL CBatchManager::CheckContinue()
{
if( m_batchs.empty() )
return FALSE;
if( m_currentIndex >= m_batchs.size() )
return FALSE;
return m_batchs[m_currentIndex]->CheckContinue();
}
BOOL CBatchManager::Next()
{
if( m_currentIndex >= m_batchs.size() )
return FALSE;
if( !m_batchs[m_currentIndex]->Next() )
{
m_currentIndex++;
if( m_currentIndex >= m_batchs.size() )
return FALSE;
}
return TRUE;
}
BOOL CBatchManager::HaveBaches()
{
if(m_batchs.size() > 0) return TRUE;
return FALSE;
}
int CBatchManager::BeginProgress(const TCHAR* title, const int progress, const TCHAR* result)
{
m_beginTime = GetTickCount();
m_batchDlg->BeginProgress(title, progress, result, m_current);
return m_current;
}
void CBatchManager::DoingProgress(const int progress)
{
m_batchDlg->DoingProgress(m_current, progress);
}
void CBatchManager::ShowExecuteResult(const TCHAR* result, BOOL quit)
{
if(IsConsoleMode())
{
_tprintf(_T("\t\t %s \n"), result);
}
}
void CBatchManager::EndProgress(const int progress, const TCHAR* result, BOOL quit)
{
DWORD elapse = GetTickCount() - m_beginTime;
m_elapse += elapse;
CString log;
log.Format(_T("Elapsed : %0.2lf s"), (double)m_elapse / 1000.0);
m_batchDlg->EndProgress(m_current, progress, result);
m_batchDlg->UpdateBatchResult(log);
ShowExecuteResult(result, quit);
}
void CBatchManager::EndProgress(const int progress, const TCHAR* result)
{
DWORD elapse = GetTickCount() - m_beginTime;
m_elapse += elapse;
CString log;
log.Format(_T("Elapsed : %0.2lf s"), (double)m_elapse / 1000.0);
m_batchDlg->EndProgress(m_current, progress, result);
m_batchDlg->UpdateBatchResult(log);
}
void CBatchManager::Error(const TCHAR* title, const TCHAR* result, BOOL quit)
{
BeginProgress(title, 0, result);
EndProgress(0, result);
if(IsConsoleMode())
{
_tprintf(_T("%s %s \n"), title, result);
}
else
ShowDialog();
}
void CBatchManager::ResetExecute()
{
for( UINT i = 0 ; i < m_batchs.size() ; i ++ )
{
Batch* batch = m_batchs[i];
if( !batch ) continue;
batch->ResetExecute();
}
m_currentIndex = 0;
}
DWORD CBatchManager::GetCurrentState()
{
if( m_currentIndex >= m_batchs.size() )
return CST_UNKNOWN_COMMAND;
return m_batchs[m_currentIndex]->GetCurrentState();
}
void CBatchManager::SetConsoleMode(BOOL mode)
{
m_consoleMode = mode;
}
BOOL CBatchManager::IsConsoleMode()
{
return m_consoleMode;
}
@@ -0,0 +1,61 @@
#pragma once
#include "BatchScanner.h"
class Batch;
class CLS_launcherDlg;
class CBatchDialog;
using namespace std;
class CBatchManager
{
public:
typedef vector<Batch*> BATCHES;
public:
CBatchManager(void);
~CBatchManager(void);
private:
void Init();
void Destroy();
public:
void ShowDialog();
void End();
public:
BOOL AddBatchFile( TCHAR* batchFileName, CLS_launcherDlg* launcher );
BOOL Execute();
BOOL CheckContinue();
BOOL Next();
BOOL HaveBaches();
public:
int BeginProgress(const TCHAR* title, const int progress, const TCHAR* result);
void DoingProgress(const int progress);
void EndProgress(const int progress, const TCHAR* result);
void EndProgress(const int progress, const TCHAR* result, BOOL quit);
void Error(const TCHAR* title, const TCHAR* result, BOOL quit=NULL);
public:
void ResetExecute();
DWORD GetCurrentState();
void SetConsoleMode(BOOL mode);
BOOL IsConsoleMode();
void ShowExecuteResult(const TCHAR* result, BOOL quit);
protected:
BatchScanner m_Scanner;
BATCHES m_batchs;
UINT m_currentIndex;
CBatchDialog* m_batchDlg;
int m_current;
int m_elapse;
DWORD m_beginTime;
BOOL m_consoleMode;
};
@@ -0,0 +1,370 @@
#include "StdAfx.h"
#include "BatchScanner.h"
#include "PlayCommand.h"
#include "StopCommand.h"
#include "SyncCommand.h"
#include "QuitCommand.h"
#include "InstallCommand.h"
#include "UninstallCommand.h"
BatchScanner::BatchScanner(void)
{
Init();
}
BatchScanner::~BatchScanner(void)
{
Destroy();
}
void BatchScanner::Init()
{
InitCommand();
InitOption();
}
void BatchScanner::Destroy()
{
}
void BatchScanner::InitCommand()
{
strcpy_s(m_commandTokens[BCT_PLAY], "play" );
strcpy_s(m_commandTokens[BCT_STOP], "stop");
strcpy_s(m_commandTokens[BCT_SYNC], "sync");
strcpy_s(m_commandTokens[BCT_INSTALL], "install");
strcpy_s(m_commandTokens[BCT_UNINSTALL],"uninstall");
strcpy_s(m_commandTokens[BCT_BACKUP], "backup");
strcpy_s(m_commandTokens[BCT_REMOVE], "remove");
strcpy_s(m_commandTokens[BCT_WAIT], "wait");
strcpy_s(m_commandTokens[BCT_QUIT], "quit");
}
void BatchScanner::InitOption()
{
strcpy_s(m_optionTokens[BOT_SERVICE_WAIT], "/w");
strcpy_s(m_optionTokens[BOT_ALL_SERVICE], "/a");
strcpy_s(m_optionTokens[BOT_TABINDEX], "/t");
}
BaseCommand* BatchScanner::Scanner( const char* commandLine )
{
if( !commandLine )
return NULL;
int commandLen = strlen(commandLine);
if( 0 == commandLen ) return NULL;
VECCHARTOKEN tokens;
if( SplitToken( commandLine, commandLen, tokens ) )
{
return MakeCommand( tokens );
}
return NULL;
}
BOOL BatchScanner::SplitToken( const char* commandLine, int commandLen, VECCHARTOKEN& tokens )
{
if( !commandLine || strlen(commandLine) == 0 )
{
return FALSE;
}
int index = -1;
do
{
JumpSplitChar( commandLine, commandLen, index ); //공백을 제외한 첫글자 위치를 index에 넣어줌.
if( commandLine[index] == NULL)
{
break;
}
tokens.push_back( &commandLine[index] ); //첫 문자열을 집어넣음.
FindSplitChar(commandLine, commandLen, index ); //공백을 만날때 까지 index ++;
}while(commandLine[index] != NULL); //배치 파일의 글자 시작 index를 VECCHARTOKEN에 push
if( tokens.size() < 1 )
{
return FALSE;
}
return TRUE;
}
void BatchScanner::JumpSplitChar( const char* commandLine, int commandLen, int& index )
{
while( (TOKEN_SPLIT_CHAR == commandLine[++index]) && (commandLen >= index) )
{
}
}
void BatchScanner::FindSplitChar( const char* commandLine, int commandLen, int& index )
{
while( (TOKEN_SPLIT_CHAR != commandLine[++index]) && (commandLen >= index ) )
{
if( NULL == commandLine[index] )
break;
}
}
BaseCommand* BatchScanner::MakeCommand( VECCHARTOKEN& tokens )
{
if( tokens.size() < 1 )
return NULL;
DWORD commandType = BCT_NONE; //CommandState()를 통해 play,stop 같은 커멘트 타입이 정해짐.
DWORD optionBit = 0;
SETINDEXES tabIndexes;
SETINDEXES stringIndexes;
int index = 0;
CommandStateType state = CS_COMMAND; //배치파일 처음은 play stop 같은 commend임,
while( (CS_DONE != state) && (CS_FAIL != state) )
{
if( (unsigned int)index >= tokens.size() )
{
state = CS_DONE;
}
switch(state)
{
case CS_COMMAND:
{
state = CommandState( tokens[index], commandType );
index++;
}
break;
case CS_OPTION:
{
state = OptionState( tokens[index], optionBit );
if( CS_STRING != state ) // 서비스네임이라면 인덱스 증가 시키면 안됨
{
index++;
}
}
break;
case CS_TABINDEX:
{
state = TabIndexState( tokens[index], tabIndexes );
if( CS_TABINDEX == state )
{
index++;
}
}
break;
case CS_STRING:
{
stringIndexes.insert( index );
state = CS_OPTION;
index++;
}
break;
case CS_DONE:
{
}
break;
default:
break;
}
}
if( CS_FAIL == state )
{
return NULL;
}
//분리한 각 코맨드 및 문자들 처리./////////////////
BaseCommand* command = GetCommand( commandType );
command->SetCommandText( tokens[0] );
command->SetOption( optionBit );
for( INDEXESITER it = tabIndexes.begin() ; it != tabIndexes.end() ; ++it )
{
int tabIndex = *it;
command->AddIndex( tabIndex );
}
for( INDEXESITER it = stringIndexes.begin() ; it != stringIndexes.end() ; ++it )
{
int stringIndex = *it;
command->AddString( tokens[stringIndex], GetServiceNameLen( tokens[stringIndex] ) );
}
return command; //batchCommand;
}
BaseCommand* BatchScanner::GetCommand( DWORD type )
{
BaseCommand* command = NULL;
switch( type )
{
case BCT_PLAY:
command = new PlayCommand;
break;
case BCT_STOP:
command = new StopCommand;
break;
case BCT_SYNC:
command = new SyncCommand;
break;
case BCT_INSTALL:
command = new InstallCommand;
break;
case BCT_UNINSTALL:
command = new UninstallCommand;
break;
case BCT_QUIT:
command = new QuitCommand;
break;
case BCT_BACKUP:
case BCT_REMOVE:
case BCT_WAIT:
default:
break;
}
return command;
}
BatchScanner::CommandStateType BatchScanner::CommandState( const char* command, DWORD& commandType )
{
commandType = GetCommandType( command );
if( BCT_END == commandType )
{
return CS_FAIL;
}
else
{
return CS_OPTION;
}
}
BatchScanner::CommandStateType BatchScanner::OptionState( const char* command, DWORD& optionBit )
{
DWORD option = GetOptionType( command );
if( BOT_END == option )
{
return CS_STRING;
}
else if( BOT_TABINDEX == option )
{
return CS_TABINDEX;
}
else
{
if( BITCHK( optionBit, option ) )
{
return CS_FAIL;
}
else
{
BITON( optionBit, option ); // /w (optionBit == 1), /a (potionBit == 5)
return CS_OPTION;
}
}
}
BatchScanner::CommandStateType BatchScanner::TabIndexState( const char* command, SETINDEXES& tabIndexes )
{
DWORD digit;
if( GetDigit( command, digit ) )
{
tabIndexes.insert( digit );
return CS_TABINDEX;
}
return CS_OPTION;
}
int BatchScanner::GetCommandType( const char* command )
{
int type = 0;
for( type ; type < BCT_END ; type++ )
{
if( TokenCompare( m_commandTokens[type], command ) )
{
break;
}
}
return type;
}
int BatchScanner::GetOptionType( const char* command )
{
unsigned int type = 0;
for( type ; type < BOT_END ; type++ )
{
if( TokenCompare( m_optionTokens[type], command ) )
{
break;
}
}
return type;
}
BOOL BatchScanner::GetDigit( const char* command, DWORD& digit )
{
digit = 0;
char ch = 0;
while( true )
{
ch = *command;
if( IsDigit( ch ) )
{
digit = digit*10 + ( ch - '0' );
command++;
}
else
{
break;
}
}
if( (TOKEN_SPLIT_CHAR == ch) || (NULL == ch) )
{
return TRUE;
}
return FALSE;
}
BOOL BatchScanner::TokenCompare( const char* token, const char* command )
{
//미리 저장해둔 명령어 비교.
unsigned int tokenLen = strlen(token);
if( strlen(command) < tokenLen )
{
return FALSE;
}
if( strncmp( token, command, tokenLen ) == 0)
{
if( (TOKEN_SPLIT_CHAR == command[tokenLen]) ||
(NULL == command[tokenLen]) )
{
return TRUE;
}
}
return FALSE;
}
int BatchScanner::GetServiceNameLen( const char* serviceName )
{
int len = 0;
while(true)
{
if( (TOKEN_SPLIT_CHAR == serviceName[len]) ||
(NULL == serviceName[len]) )
{
break;
}
len++;
}
return len;
}
@@ -0,0 +1,66 @@
#pragma once
#include <vector>
#include <set>
#include "BatchCompileDefine.h"
#include "BaseCommand.h"
class BatchScanner
{
public:
typedef std::vector<const char*> VECCHARTOKEN;
typedef std::set<int> SETINDEXES;
typedef SETINDEXES::iterator INDEXESITER;
enum CommandStateType
{
CS_COMMAND,
CS_OPTION,
CS_TABINDEX,
CS_STRING,
CS_DONE,
CS_FAIL,
CS_END
};
public:
BatchScanner(void);
~BatchScanner(void);
private:
void Init();
void Destroy();
void InitCommand();
void InitOption();
public:
// virtual ??
BaseCommand* Scanner( const char* commandLine );
private:
BOOL SplitToken( const char* commandLine, int commandLen, VECCHARTOKEN& tokens );
void JumpSplitChar( const char* commandLine, int commandLen, int& index );
void FindSplitChar( const char* commandLine, int commandLen, int& index );
private:
BaseCommand* MakeCommand( VECCHARTOKEN& tokens );
BaseCommand* GetCommand( DWORD type );
CommandStateType CommandState( const char* command, DWORD& commandType );
CommandStateType OptionState( const char* command, DWORD& optionBit );
CommandStateType TabIndexState( const char* command, SETINDEXES& tabIndexes );
int GetCommandType( const char* command );
int GetOptionType( const char* command );
BOOL GetDigit( const char* command, DWORD& digit );
BOOL IsDigit( const char ch ) { return ( ('0' <= ch) && ( ch <= '9') ); }
BOOL TokenCompare( const char* token, const char* command );
int GetServiceNameLen( const char* serviceName );
private:
char m_commandTokens[BCT_END][MAX_TOKEN_BUFFER_SIZE];
char m_optionTokens[BOT_END][MAX_TOKEN_BUFFER_SIZE];
};
@@ -0,0 +1,150 @@
#ifndef _MEMDC_H_
#define _MEMDC_H_
#include <afxwin.h>
////////////////////////////////////////////////////////////////////////////////
// CUserMemDC - memory DC
//
// Author: Keith Rule
// Email: [email protected]
// Copyright 1996-2002, Keith Rule
//
// You may freely use or modify this code provided this
// copyright is included in all derived versions.
//
// History - 10/03/97 Fixed scrolling bug.
// Added print support. - KR
//
// 11/03/99 Fixed most common complaint. Added
// background color fill. - KR
//
// 11/03/99 Added support for mapping modes other than
// MM_TEXT as suggested by Lee Sang Hun. - KR
//
// 02/11/02 Added support for CScrollView as supplied
// by Gary Kirkham. - KR
//
// 04/19/06 Modified background fill to try and use
// correct background brush/color - AGB
//
// This class implements a memory device context which allows
// flicker free drawing.
////////////////////////////////////////////////////////////////////////////////
class CUserMemDC : public CDC
{
private:
BOOL m_bMemDC; // TRUE if not printing
CBitmap m_MemBitmap; // offscreen bitmap
CBitmap* m_pOldBitmap; // original bitmap
CDC* m_pDC; // saves CDC passed in constructor
CRect m_rect; // rectangle of drawing area
public:
// constructor sets up the memory DC
CUserMemDC(CDC* pDC, const CRect* pRect = NULL) : CDC()
{
// make sure the call provided a valid device context
ASSERT(pDC != NULL);
// save the original device context for later BitBlt()
m_pDC = pDC;
// check whether we're printing
m_bMemDC = !pDC->IsPrinting();
// get the output rectangle
if (pRect == NULL)
pDC->GetClipBox(&m_rect);
else
m_rect = *pRect;
if (m_bMemDC)
{
// do the memory DC stuff if not printing
// create a memory DC
CreateCompatibleDC(pDC);
// create new bitmap and save old bitmap
pDC->LPtoDP(&m_rect);
m_MemBitmap.CreateCompatibleBitmap(pDC, m_rect.Width(), m_rect.Height());
m_pOldBitmap = SelectObject(&m_MemBitmap);
SetMapMode(pDC->GetMapMode());
SetWindowExt(pDC->GetWindowExt());
SetViewportExt(pDC->GetViewportExt());
pDC->DPtoLP(&m_rect);
// set window origin
SetWindowOrg(m_rect.left, m_rect.top);
}
else
{
// make a copy of the relevant parts of the original DC for printing
m_bPrinting = pDC->m_bPrinting;
m_hDC = pDC->m_hDC;
m_hAttribDC = pDC->m_hAttribDC;
}
// fill background
CWnd* pWnd = pDC->GetWindow();
HWND hWnd = NULL;
if (pWnd != NULL)
{
hWnd = pWnd->m_hWnd;
if (hWnd != NULL)
{
if (GetClassLongPtr(hWnd, GCW_ATOM) == 32770)
{
// if window is a dialog box, use dialog background color
FillSolidRect(m_rect, GetSysColor(COLOR_BTNFACE));
}
else
{
// try to get background brush for window class
ULONG_PTR ulpBrush = GetClassLongPtr(hWnd, GCLP_HBRBACKGROUND);
if (ulpBrush)
{
// fill with class background brush
FillRect(m_rect, CBrush::FromHandle((HBRUSH)ulpBrush));
}
else
hWnd = NULL;
}
}
}
if (hWnd == NULL)
FillSolidRect(m_rect, pDC->GetBkColor());
}
// destructor copies the contents of the memory DC to the original DC
~CUserMemDC()
{
if (m_bMemDC)
{
// copy the offscreen bitmap onto the screen
m_pDC->BitBlt(m_rect.left, m_rect.top, m_rect.Width(), m_rect.Height(),
this, m_rect.left, m_rect.top, SRCCOPY);
// restore the original bitmap
m_pDC->SelectObject(m_pOldBitmap);
}
else
{
// all we need to do is replace the DC with an illegal value,
// this keeps us from accidently deleting the handles associated
// with the CDC that was passed to the constructor
m_hDC = m_hAttribDC = NULL;
}
}
// allow usage as a pointer
CUserMemDC* operator->() { return this; }
// allow usage as a pointer
operator CUserMemDC*() { return this; }
};
#endif //#ifndef _MEMDC_H_
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,75 @@
#include "StdAfx.h"
#include "FileReader.h"
FileReader::FileReader(void)
{
Init();
}
FileReader::~FileReader(void)
{
Destroy();
}
void FileReader::Init()
{
m_readFile.clear();
}
void FileReader::Destroy()
{
if( m_readFile.is_open() )
{
m_readFile.close();
}
}
BOOL FileReader::OpenFile( TCHAR* fileName )
{
if( _tcslen( fileName ) >= _MAX_FNAME )
{
return FALSE;
}
#ifdef UNICODE
char _fileName[_MAX_FNAME];
int ret = WideCharToMultiByte( CP_ACP, 0, fileName, _tcslen( fileName ), _fileName, sizeof(_fileName), NULL, NULL );
_fileName[ret] = 0;
m_readFile.open( _fileName, ios::in );
#else
m_readFile.open( fileName, ios::in );
#endif
if( !m_readFile.is_open() )
{
return FALSE;
}
return TRUE;
}
BOOL FileReader::GetLine( char* line, int len )
{
/*if( !m_readFile.is_open() || m_readFile.eof() )
{
return FALSE;
}*/
m_readFile.getline( line, len );
if( 0 == strlen(line ) )
{
if( m_readFile.eof() )
{
return FALSE;
}
else
{
return GetLine( line, len );
}
}
return TRUE;
}
@@ -0,0 +1,25 @@
#pragma once
#include <fstream>
using namespace std;
class FileReader
{
public:
FileReader(void);
~FileReader(void);
private:
void Init();
void Destroy();
public:
BOOL OpenFile( TCHAR* fileName );
BOOL GetLine( char* line, int len );
private:
TCHAR m_fileName[_MAX_FNAME];
ifstream m_readFile;
};
@@ -0,0 +1,81 @@
#include "StdAfx.h"
#include "InstallCommand.h"
#include "../resource.h"
#include "../LS_launcherDlg.h"
#include "../ServerDialog.h"
#include "../cFile.h"
InstallCommand::InstallCommand(): BaseCommand(BCT_INSTALL)
{
}
InstallCommand::~InstallCommand()
{
}
BOOL InstallCommand::ExecuteServiceAll(CServerDialog* dialog)
{
return ExecuteServiceOne(dialog);
}
BOOL InstallCommand::ExecuteServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
// ÀÌ¹Ì ¼³Ä¡µÆ´Ù¸é?
if( CheckContinueServiceOne( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandInstall( m_strings[0], m_strings[1], m_strings[2] ) )
{
return FALSE;
}
return TRUE;
}
BOOL InstallCommand::CheckContinueServiceAll(CServerDialog* dialog)
{
return CheckContinueServiceOne(dialog);
}
BOOL InstallCommand::CheckContinueServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
int index = dialog->FindServiceIndex( m_strings[0] );
if( index == -1 )
{
return FALSE;
}
return TRUE;
}
BOOL InstallCommand::IsValidDetail()
{
if( m_strings.size() != 3 )
return FALSE;
cFileReader exeFile;
if( !exeFile.Open( m_strings[1].GetBuffer() ) )
{
return FALSE;
}
exeFile.Close();
cFileReader iniFile;
if( !iniFile.Open( m_strings[2].GetBuffer() ) )
{
return FALSE;
}
iniFile.Close();
return TRUE;
}
@@ -0,0 +1,19 @@
#pragma once
#include "BaseCommand.h"
class InstallCommand
: public BaseCommand
{
public:
InstallCommand();
~InstallCommand();
public:
BOOL ExecuteServiceAll(CServerDialog* dialog);
BOOL ExecuteServiceOne(CServerDialog* dialog);
BOOL CheckContinueServiceAll(CServerDialog* dialog);
BOOL CheckContinueServiceOne(CServerDialog* dialog);
BOOL IsValidDetail();
};
@@ -0,0 +1,173 @@
// ListCtrlEx.cpp : implementation file
//
#include "stdafx.h"
#include "ListCtrlEx.h"
#include <tchar.h>
// CListCtrlEx
IMPLEMENT_DYNAMIC(CListCtrlEx, CListCtrl)
CListCtrlEx::CListCtrlEx() : m_ProgressColumn(0)
{
m_progress = NULL;
}
CListCtrlEx::~CListCtrlEx()
{
}
BEGIN_MESSAGE_MAP(CListCtrlEx, CListCtrl)
ON_WM_PAINT()
ON_WM_SETFOCUS()
ON_WM_KILLFOCUS()
END_MESSAGE_MAP()
// CListCtrlEx message handlers
void CListCtrlEx::OnPaint()
{
// TODO: Add your message handler code here
// Do not call CListCtrl::OnPaint() for painting messages
int Top=GetTopIndex();
int Total=GetItemCount();
int PerPage=GetCountPerPage();
int LastItem=((Top+PerPage)>Total)?Total:Top+PerPage;
CHeaderCtrl* pHeader=GetHeaderCtrl();
POSITION pos = m_ProgressList.GetHeadPosition();
for(int i=Top;i<LastItem;i++)
{
if(pos != NULL)
{
CTextProgressCtrl* progress = m_ProgressList.GetAt(pos);
CRect ColRt;
pHeader->GetItemRect(m_ProgressColumn,&ColRt);
// get the rect
CString Data=GetItemText(i,m_ProgressColumn);
//SetItemText(i,m_ProgressColumn,_T(""));
CRect rt;
GetItemRect(i,&rt,LVIR_BOUNDS);
rt.top+=1;
rt.bottom-=1;
rt.right -= 10;
rt.left+=ColRt.left;
int Width=ColRt.Width() ;
rt.right=rt.left+Width-4;
int Percent=_ttoi(Data.GetBuffer());
// set the position on the control
progress->MoveWindow(rt);
progress->SetPos(Percent);
progress->ShowWindow(SW_SHOWNORMAL);
m_ProgressList.GetNext(pos);
}
}
CListCtrl::OnPaint();
}
void CListCtrlEx::InitProgressColumn(int ColNum/*=0*/)
{
m_ProgressColumn=ColNum;
// create the progress control and set their position
}
int CListCtrlEx::InsertItem( _In_ const LVITEM* pItem )
{
m_ProgressList.AddTail(CreateProgress());
return CListCtrl::InsertItem(pItem);
}
int CListCtrlEx::InsertItem( _In_ int nItem, _In_z_ LPCTSTR lpszItem )
{
m_ProgressList.AddTail(CreateProgress());
return CListCtrl::InsertItem(nItem,lpszItem);
}
int CListCtrlEx::InsertItem( _In_ int nItem, _In_z_ LPCTSTR lpszItem, _In_ int nImage )
{
m_ProgressList.AddTail(CreateProgress());
return CListCtrl::InsertItem(nItem,lpszItem,nImage);
}
BOOL CListCtrlEx::SetItemText( _In_ int nItem, _In_ int nSubItem, _In_z_ LPCTSTR lpszText )
{
return CListCtrl::SetItemText(nItem,nSubItem,lpszText);
}
BOOL CListCtrlEx::DeleteItem( _In_ int nItem )
{
CTextProgressCtrl* progress = m_ProgressList.RemoveTail();
delete progress;
return CListCtrl::DeleteItem(nItem);
}
BOOL CListCtrlEx::DeleteAllItems()
{
POSITION pos = m_ProgressList.GetHeadPosition();
while(pos)
{
CTextProgressCtrl* progress = m_ProgressList.GetAt(pos);
delete progress;
m_ProgressList.GetNext(pos);
}
m_ProgressList.RemoveAll();
return CListCtrl::DeleteAllItems();
}
CTextProgressCtrl* CListCtrlEx::CreateProgress()
{
CTextProgressCtrl* pControl=new CTextProgressCtrl();
CRect rt;
pControl->Create(NULL,rt,this,IDC_PROGRESS_LIST+ m_ProgressList.GetCount());
pControl->ShowWindow(SW_HIDE);
return pControl;
}
#if 0
void CListCtrlEx::SetProgressRange( int progressIndex, int min, int max )
{
if(m_ProgressList.GetSize() < progressIndex)
{
CProgressCtrl* progress = m_ProgressList.GetAt(progressIndex);
}
}
#endif
void CListCtrlEx::OnSetFocus(CWnd* pOldWnd)
{
CListCtrl::OnSetFocus(pOldWnd);
// TODO: 여기에 메시지 처리기 코드를 추가합니다.
}
void CListCtrlEx::OnKillFocus(CWnd* pNewWnd)
{
CListCtrl::OnKillFocus(pNewWnd);
// TODO: 여기에 메시지 처리기 코드를 추가합니다.
}
@@ -0,0 +1,47 @@
#pragma once
#include "TextProgressCtrl.h"
#include <atlcoll.h>
// CListCtrlEx
#define IDC_PROGRESS_LIST WM_USER
class CListCtrlEx : public CListCtrl
{
DECLARE_DYNAMIC(CListCtrlEx)
// the array of the Progress Controls in the list control
ATL::CAtlList<CTextProgressCtrl*> m_ProgressList;
// the column which should contain the progress bars
int m_ProgressColumn;
public:
CListCtrlEx();
virtual ~CListCtrlEx();
public:
// initialize the column containing the bars
void InitProgressColumn(int ColNum=0);
//void SetProgressRange( int progressIndex, int min, int max ); NotWorking
public:
int InsertItem(_In_ const LVITEM* pItem);
int InsertItem(_In_ int nItem, _In_z_ LPCTSTR lpszItem);
int InsertItem(_In_ int nItem, _In_z_ LPCTSTR lpszItem, _In_ int nImage);
BOOL SetItemText(_In_ int nItem, _In_ int nSubItem, _In_z_ LPCTSTR lpszText);
BOOL DeleteItem(_In_ int nItem);
BOOL DeleteAllItems();
protected:
CTextProgressCtrl* CreateProgress();
protected:
CTextProgressCtrl* m_progress;
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnPaint();
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnKillFocus(CWnd* pNewWnd);
};
@@ -0,0 +1,99 @@
#include "StdAfx.h"
#include "PlayCommand.h"
#include "../resource.h"
#include "../LS_launcherDlg.h"
#include "../ServerDialog.h"
PlayCommand::PlayCommand() : BaseCommand(BCT_PLAY)
{
}
PlayCommand::~PlayCommand()
{
}
BOOL PlayCommand::ExecuteServiceAll(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckContinueServiceAll( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandPlayAll() )
{
return FALSE;
}
return TRUE;
}
BOOL PlayCommand::ExecuteServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckContinueServiceOne( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandPlay( m_strings[0] ) )
{
return FALSE;
}
return TRUE;
}
BOOL PlayCommand::CheckContinueServiceAll(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
int serviceCount = dialog->GetServiceCount();
for( int index = 0; index < serviceCount ; index ++ )
{
if( !dialog->IsServiceOn(index) )
{
return FALSE;
}
}
return TRUE;
}
BOOL PlayCommand::CheckContinueServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( !dialog->IsServiceOn(m_strings[0]) )
{
return FALSE;
}
return TRUE;
}
BOOL PlayCommand::IsValidDetail()
{
if( m_isServiceAll )
{
if( !m_strings.empty() )
return FALSE;
}
else
{
if( m_strings.size() != 1 )
return FALSE;
}
return TRUE;
}
@@ -0,0 +1,18 @@
#pragma once
#include "BaseCommand.h"
class PlayCommand : public BaseCommand
{
public:
PlayCommand();
~PlayCommand();
public:
BOOL ExecuteServiceAll(CServerDialog* dialog);
BOOL ExecuteServiceOne(CServerDialog* dialog);
BOOL CheckContinueServiceAll(CServerDialog* dialog);
BOOL CheckContinueServiceOne(CServerDialog* dialog);
BOOL IsValidDetail();
};
@@ -0,0 +1,40 @@
#include "StdAfx.h"
#include "QuitCommand.h"
#include "../resource.h"
#include "../ServerDialog.h"
QuitCommand::QuitCommand(): BaseCommand(BCT_QUIT)
{
}
QuitCommand::~QuitCommand()
{
}
BOOL QuitCommand::ExecuteServiceAll(CServerDialog* dialog)
{
AfxGetMainWnd()->SendMessage(WM_CLOSE);
return TRUE;
}
BOOL QuitCommand::ExecuteServiceOne(CServerDialog* dialog)
{
AfxGetMainWnd()->SendMessage(WM_CLOSE);
return TRUE;
}
BOOL QuitCommand::CheckContinueServiceAll(CServerDialog* dialog)
{
return TRUE;
}
BOOL QuitCommand::CheckContinueServiceOne(CServerDialog* dialog)
{
return TRUE;
}
BOOL QuitCommand::IsValidDetail()
{
return TRUE;
}
@@ -0,0 +1,20 @@
#pragma once
#include "BaseCommand.h"
class QuitCommand : public BaseCommand
{
public:
QuitCommand(void);
~QuitCommand(void);
public:
BOOL ExecuteServiceAll(CServerDialog* dialog);
BOOL ExecuteServiceOne(CServerDialog* dialog);
BOOL CheckContinueServiceAll(CServerDialog* dialog);
BOOL CheckContinueServiceOne(CServerDialog* dialog);
BOOL IsValidDetail();
};
@@ -0,0 +1,98 @@
#include "StdAfx.h"
#include "StopCommand.h"
#include "../resource.h"
#include "../ServerDialog.h"
StopCommand::StopCommand() : BaseCommand(BCT_STOP)
{
}
StopCommand::~StopCommand()
{
}
BOOL StopCommand::ExecuteServiceAll(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckContinueServiceAll( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandStopAll() )
{
return FALSE;
}
return TRUE;
}
BOOL StopCommand::ExecuteServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckContinueServiceOne( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandStop( m_strings[0] ) )
{
return FALSE;
}
return TRUE;
}
BOOL StopCommand::CheckContinueServiceAll(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
int serviceCount = dialog->GetServiceCount();
for( int index = 0; index < serviceCount ; index ++ )
{
if( dialog->IsServiceOn(index) )
{
return FALSE;
}
}
return TRUE;
}
BOOL StopCommand::CheckContinueServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( dialog->IsServiceOn(m_strings[0]) )
{
return FALSE;
}
return TRUE;
}
BOOL StopCommand::IsValidDetail()
{
if( m_isServiceAll )
{
if( !m_strings.empty() )
return FALSE;
}
else
{
if( m_strings.size() != 1 )
return FALSE;
}
return TRUE;
}
@@ -0,0 +1,19 @@
#pragma once
#include "BaseCommand.h"
class StopCommand : public BaseCommand
{
public:
StopCommand();
~StopCommand();
public:
BOOL ExecuteServiceAll(CServerDialog* dialog);
BOOL ExecuteServiceOne(CServerDialog* dialog);
BOOL CheckContinueServiceAll(CServerDialog* dialog);
BOOL CheckContinueServiceOne(CServerDialog* dialog);
BOOL IsValidDetail();
};
@@ -0,0 +1,129 @@
#include "StdAfx.h"
#include "SyncCommand.h"
#include "../resource.h"
#include "../LS_launcherDlg.h"
#include "../ServerDialog.h"
#include <direct.h>
SyncCommand::SyncCommand() : BaseCommand(BCT_SYNC)
{
}
SyncCommand::~SyncCommand()
{
}
BOOL SyncCommand::ExecuteServiceAll(CServerDialog* dialog)
{
return ExecuteServiceOne(dialog);
}
BOOL SyncCommand::ExecuteServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckCompleteDialogs( m_syncCommandDialogs, dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( m_syncCommandDialogs.size() != m_syncComplteDialogs.size() )
{
return TRUE;
}
if( !dialog->CommandFileSync( m_strings[0] ) )
{
return FALSE;
}
PushCompleteDialogs( m_syncCommandDialogs, dialog );
return TRUE;
}
BOOL SyncCommand::CheckContinueServiceAll(CServerDialog* dialog)
{
return CheckContinueServiceOne(dialog);
}
BOOL SyncCommand::CheckContinueServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( !dialog->IsSyncComplete() )
{
return FALSE;
}
if( CheckCompleteDialogs( m_syncComplteDialogs, dialog ) )
{
return TRUE;
}
PushCompleteDialogs( m_syncComplteDialogs, dialog );
if( m_syncComplteDialogs.size() == m_totalSyncTabCount )
return TRUE;
return BaseCommand::Execute();
}
BOOL SyncCommand::IsValidDetail()
{
if( m_strings.size() != 1 )
{
return FALSE;
}
TCHAR tPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, tPath);
if( _tchdir(m_strings[0].GetBuffer()) == -1 )
{
return FALSE;
}
_tchdir( tPath );
GetCurrentDirectory(MAX_PATH, tPath);
// FileSync´Â ¹«Á¶°Ç WaitMode·Î ÇÑ´Ù
m_isWait = TRUE;
if( m_isApplyAll )
{
m_totalSyncTabCount = GetDialogCount();
}
else
{
m_totalSyncTabCount = m_tabIndexes.size();
}
m_syncComplteDialogs.clear();
return TRUE;
}
void SyncCommand::PushCompleteDialogs( SETDIALOGS& dialogs, CServerDialog* dialog )
{
DIALOGSITER it = dialogs.find( dialog );
if( it == dialogs.end() )
{
dialogs.insert( dialog );
}
}
BOOL SyncCommand::CheckCompleteDialogs( SETDIALOGS& dialogs, CServerDialog* dialog )
{
DIALOGSITER it = dialogs.find( dialog );
if( it != dialogs.end() )
{
return TRUE;
}
return FALSE;
}
@@ -0,0 +1,32 @@
#pragma once
#include <set>
#include "BaseCommand.h"
class SyncCommand : public BaseCommand
{
public:
SyncCommand();
~SyncCommand();
public:
BOOL ExecuteServiceAll(CServerDialog* dialog);
BOOL ExecuteServiceOne(CServerDialog* dialog);
BOOL CheckContinueServiceAll(CServerDialog* dialog);
BOOL CheckContinueServiceOne(CServerDialog* dialog);
BOOL IsValidDetail();
private:
typedef std::set<CServerDialog*> SETDIALOGS;
typedef SETDIALOGS::iterator DIALOGSITER;
void PushCompleteDialogs( SETDIALOGS& dialogs, CServerDialog* dialog );
BOOL CheckCompleteDialogs( SETDIALOGS& dialogs, CServerDialog* dialog );
private:
UINT m_totalSyncTabCount;
SETDIALOGS m_syncCommandDialogs;
SETDIALOGS m_syncComplteDialogs;
};
@@ -0,0 +1,615 @@
// TextProgressCtrl.cpp : implementation file
//
// Written by Chris Maunder ([email protected])
// Copyright 1998-2005.
//
// TextProgressCtrl is a drop-in replacement for the standard
// CProgressCtrl that displays text in a progress control.
//
// Homepage: http://www.codeproject.com/miscctrl/text_progressctrl.asp
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed by any means PROVIDING it is not sold for
// profit without the author's written consent, and providing that this
// notice and the author's name is included. If the source code in
// this file is used in any commercial application then an email to
// me would be nice.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to your
// computer or anything else vaguely within its vicinity.
//
// Expect bugs.
//
// Please use and enjoy. Please let me know of any bugs/mods/improvements
// that you have found/implemented and I will fix/incorporate them into this
// file.
////////////////////////////////////////////////////////////////////////////////
// Revision History - by PJ Arends ([email protected])
// July 1, 2001 - added functionality to set font to parent windows font
// July 15, 2001 - added SetTextColor() and GetTextColor() functions
// August 2, 2001 - Added functionality where the control now responds to
// PBM_* progress bar messages. Now the control can be
// controlled by sending messages to its HWND.
// - added PBM_SETTEXTCOLOR and PBM_SETSHOWTEXT messages
// - added the ability to call GetPos() via OnGetPos()
// January 3, 2005 - By Kriz: Added two basic methods some other changes to
// allow the user to switch between the three alignment
// styles LEFT, CENTER and RIGHT - even on the fly if that's
// needed. Methods: AlignText and AlignTextInvalidate
// - By C Maunder: updated the code so it compiles in VC7
// March 6, 2006 - By A. Bommarito: changed to allow text in vertical
// progress bars; added method to change text background
// color; added capability to independently control display
// of text and percentage complete; added marquee mode;
// changed to exclusively use messaging interface
// February 22, 2007 - By A. Bommarito: changed to fix problem where progress bar
// border didn't display on XP and above when a manifest file
// specified use of Version 6 of the Common Controls; fixed
// problem with AppendFormat method being used without an
// _T() around the format string - caused compile error when
// using Unicode (message from dev75040); added complete turn
// off of Marquee style (message from Robert Pickford)
//
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "TextProgressCtrl.h"
//#include "CUserMemDC.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
////////////////////////////////////////////////////////////////////////////////
// CTextProgressCtrl
#define IDT_MARQUEE 1 // timer used to update marquee style progress bar
#define EDGE_SPACE 2 // number of pixels to space text away from edge of progress bar
CTextProgressCtrl::CTextProgressCtrl()
{
// default range
m_nMin = 0;
m_nMax = 100;
// default step size
m_nStepSize = 10;
// initial starting position
m_nPos = 0;
// default colors
m_crBarClr = CLR_DEFAULT;
m_crBarBkClr = CLR_DEFAULT;
m_crTextClr = CLR_DEFAULT;
m_crTextBkClr = CLR_DEFAULT;
// default to show percent complete, all text centered
m_bShowPercent = TRUE;
m_dwTextStyle = DT_CENTER;
// default marquee bar size of 20% of full progress bar
m_nMarqueeSize = 20;
}
CTextProgressCtrl::~CTextProgressCtrl()
{
// delete vertical font if needed
if (m_VerticalFont.m_hObject)
m_VerticalFont.DeleteObject();
}
BEGIN_MESSAGE_MAP(CTextProgressCtrl, CProgressCtrl)
//{{AFX_MSG_MAP(CTextProgressCtrl)
ON_WM_ERASEBKGND()
ON_WM_PAINT()
ON_WM_TIMER()
//}}AFX_MSG_MAP
ON_MESSAGE(PBM_SETRANGE, OnSetRange)
ON_MESSAGE(PBM_SETPOS, OnSetPos)
ON_MESSAGE(PBM_DELTAPOS, OnOffsetPos)
ON_MESSAGE(PBM_SETSTEP, OnSetStep)
ON_MESSAGE(PBM_STEPIT, OnStepIt)
ON_MESSAGE(PBM_SETRANGE32, OnSetRange32)
ON_MESSAGE(PBM_GETRANGE, OnGetRange)
ON_MESSAGE(PBM_GETPOS, OnGetPos)
ON_MESSAGE(PBM_SETBARCOLOR, OnSetBarColor)
ON_MESSAGE(PBM_SETBKCOLOR, OnSetBarBkColor)
ON_MESSAGE(PBM_USERGETBARCOLOR, OnGetBarColor)
ON_MESSAGE(PBM_USERGETBKCOLOR, OnGetBarBkColor)
ON_MESSAGE(PBM_SETTEXTCOLOR, OnSetTextColor)
ON_MESSAGE(PBM_GETTEXTCOLOR, OnGetTextColor)
ON_MESSAGE(PBM_SETTEXTBKCOLOR, OnSetTextBkColor)
ON_MESSAGE(PBM_GETTEXTBKCOLOR, OnGetTextBkColor)
ON_MESSAGE(PBM_SETSHOWPERCENT, OnSetShowPercent)
ON_MESSAGE(PBM_ALIGNTEXT, OnAlignText)
ON_MESSAGE(PBM_SETMARQUEE, OnSetMarquee)
ON_MESSAGE(PBM_SETMARQUEEOPTIONS, OnSetMarqueeOptions)
END_MESSAGE_MAP()
////////////////////////////////////////////////////////////////////////////////
// CTextProgressCtrl message handlers
BOOL CTextProgressCtrl::OnEraseBkgnd(CDC* /*pDC*/)
{
return TRUE;
}
void CTextProgressCtrl::OnPaint()
{
if (m_nMin >= m_nMax)
return;
CPaintDC PaintDC(this); // device context for painting
CUserMemDC dc(&PaintDC); // memory device context
// get colors to use
COLORREF crBarColor = (COLORREF)OnGetBarColor(0, 0);
COLORREF crBarBkColor = (COLORREF)OnGetBarBkColor(0, 0);
COLORREF crTextColor = (COLORREF)OnGetTextColor(0, 0);
COLORREF crTextBkColor = (COLORREF)OnGetTextBkColor(0, 0);;
// select progress bar font if there is one, else select parent font
if (GetFont())
dc.SelectObject(GetFont());
else
dc.SelectObject(GetParent()->GetFont());
// get bar dimensions and draw bar outline
BOOL bLeft = true, bMiddle = true, bRight = true;
CRect LeftRect, MiddleRect, RightRect, ClientRect;
GetClientRect(&ClientRect);
DrawEdge(dc, ClientRect, EDGE_SUNKEN, BF_ADJUST | BF_RECT | BF_FLAT);
LeftRect = MiddleRect = RightRect = ClientRect;
// compute the fractional position
double dFraction = (double)(m_nPos - m_nMin) / ((double)(m_nMax - m_nMin));
// get the control style
DWORD dwStyle = GetStyle();
// create a vertical font if needed
if ((dwStyle & PBS_VERTICAL) && (!m_VerticalFont.m_hObject))
CreateVerticalFont();
if (dwStyle & PBS_MARQUEE)
{
if (dwStyle & PBS_VERTICAL)
{
MiddleRect.top = MiddleRect.bottom - (int)((MiddleRect.Height()) * dFraction);
MiddleRect.bottom = MiddleRect.top + (((LeftRect.Height() * m_nMarqueeSize) + 50) / 100);
if (MiddleRect.bottom >= LeftRect.bottom)
{
bLeft = false;
MiddleRect.bottom = LeftRect.bottom;
}
else
LeftRect.top = MiddleRect.bottom;
if (MiddleRect.top <= RightRect.top)
{
bRight = false;
MiddleRect.top = RightRect.top;
}
else
RightRect.bottom = MiddleRect.top;
}
else
{
MiddleRect.right = MiddleRect.left + (int)((MiddleRect.Width()) * dFraction);
MiddleRect.left = MiddleRect.right - (((LeftRect.Width() * m_nMarqueeSize) + 50) / 100);
if (MiddleRect.left <= LeftRect.left)
{
bLeft = false;
MiddleRect.left = LeftRect.left;
}
else
LeftRect.right = MiddleRect.left;
if (MiddleRect.right >= RightRect.right)
{
bRight = false;
MiddleRect.right = RightRect.right;
}
else
RightRect.left = MiddleRect.right;
}
}
else
{
bLeft = false;
if (dwStyle & PBS_VERTICAL)
{
MiddleRect.top = MiddleRect.bottom - (int)((MiddleRect.Height()) * dFraction);
RightRect.bottom = MiddleRect.top;
}
else
{
MiddleRect.right = MiddleRect.left + (int)((MiddleRect.Width()) * dFraction);
RightRect.left = MiddleRect.right;
}
}
if (bLeft)
dc.FillSolidRect(LeftRect, crBarBkColor);
if (bMiddle)
dc.FillSolidRect(MiddleRect, crBarColor);
if (bRight)
dc.FillSolidRect(RightRect, crBarBkColor);
// draw text if needed
CString str;
GetWindowText(str);
if (m_bShowPercent)
str.AppendFormat(_T("%d%%"), (int)((dFraction * 100.0) + 0.5));
if (str.GetLength())
{
CFont *pOldFont = NULL;
CPoint ptStart;
CSize szText;
if (dwStyle & PBS_VERTICAL)
{
pOldFont = (CFont*)dc.SelectObject(&m_VerticalFont);
szText = dc.GetOutputTextExtent(str);
switch (m_dwTextStyle)
{
case DT_LEFT:
ptStart.y = ClientRect.bottom - 1 - EDGE_SPACE;
break;
case DT_RIGHT:
ptStart.y = ClientRect.top + szText.cx + EDGE_SPACE;
break;
case DT_CENTER:
default:
ptStart.y = ClientRect.top + szText.cx + (ClientRect.Height() - szText.cx) / 2;
break;
}
ptStart.x = ClientRect.left + ((ClientRect.Width() - szText.cy) / 2);
}
else
{
szText = dc.GetOutputTextExtent(str);
switch (m_dwTextStyle)
{
case DT_LEFT:
ptStart.x = ClientRect.left + EDGE_SPACE;
break;
case DT_RIGHT:
ptStart.x = ClientRect.right - szText.cx - 1 - EDGE_SPACE;
break;
case DT_CENTER:
default:
ptStart.x = ClientRect.left + ((ClientRect.Width() - szText.cx) / 2);
break;
}
ptStart.y = ClientRect.top + ((ClientRect.Height() - szText.cy) / 2);
}
dc.SetBkMode(TRANSPARENT);
CRgn rgn;
if (bLeft)
{
rgn.CreateRectRgn(LeftRect.left, LeftRect.top, LeftRect.right, LeftRect.bottom);
dc.SelectClipRgn(&rgn);
dc.SetTextColor(crTextColor);
dc.ExtTextOut(ptStart.x, ptStart.y, ETO_CLIPPED, &ClientRect, str, NULL);
rgn.DeleteObject();
}
if (bMiddle)
{
rgn.CreateRectRgn(MiddleRect.left, MiddleRect.top, MiddleRect.right, MiddleRect.bottom);
dc.SelectClipRgn(&rgn);
dc.SetTextColor(crTextBkColor);
dc.ExtTextOut(ptStart.x, ptStart.y, ETO_CLIPPED, &ClientRect, str, NULL);
rgn.DeleteObject();
}
if (bRight)
{
rgn.CreateRectRgn(RightRect.left, RightRect.top, RightRect.right, RightRect.bottom);
dc.SelectClipRgn(&rgn);
dc.SetTextColor(crTextColor);
dc.ExtTextOut(ptStart.x, ptStart.y, ETO_CLIPPED, &ClientRect, str, NULL);
rgn.DeleteObject();
}
if (pOldFont)
dc.SelectObject(pOldFont);
}
}
void CTextProgressCtrl::OnTimer(UINT_PTR nIDEvent)
{
static int nDirection = +1;
if (nIDEvent == IDT_MARQUEE)
{
int nPosition = GetPos();
int nMax = (int)((((double)(100 + m_nMarqueeSize) * (double)m_nMax) + 0.5) / 100.0);
if ((nDirection == 1) && (nPosition >= nMax))
nDirection = -1;
else if ((nDirection == -1) && (nPosition <= m_nMin))
nDirection = +1;
SetPos(nPosition + nDirection);
}
}
LRESULT CTextProgressCtrl::OnSetRange(WPARAM, LPARAM lparamRange)
{
// set new 16-bit range, returning old one
return (OnSetRange32(LOWORD(lparamRange), HIWORD(lparamRange)));
}
LRESULT CTextProgressCtrl::OnSetPos(WPARAM nNewPos, LPARAM)
{
// save old position for return
int nOldPos = m_nPos;
// set new position
m_nPos = (int)nNewPos;
// limit position to inside of range
DWORD dwStyle = GetStyle();
if (m_nPos < m_nMin)
m_nPos = m_nMin;
if (dwStyle & PBS_MARQUEE)
{
int nMax = (int)((((double)(100 + m_nMarqueeSize) * (double)m_nMax) + 0.5) / 100.0);
if (m_nPos > nMax)
m_nPos = nMax;
}
else if (m_nPos > m_nMax)
m_nPos = m_nMax;
// call a common routine to redraw window
CommonPaint();
// return old position
return ((LRESULT)nOldPos);
}
LRESULT CTextProgressCtrl::OnOffsetPos(WPARAM nIncrement, LPARAM)
{
// set new position, returning old one
return (OnSetPos((WPARAM)(m_nPos + (int)nIncrement), 0));
}
LRESULT CTextProgressCtrl::OnSetStep(WPARAM nStepInc, LPARAM)
{
// save old step size for return
int nOldStep = m_nStepSize;
// set new step size
m_nStepSize = (int)nStepInc;
// return old step size
return ((LRESULT)nOldStep);
}
LRESULT CTextProgressCtrl::OnStepIt(WPARAM, LPARAM)
{
// compute new position, wrapping if needed
int nPos = m_nPos + m_nStepSize;
if (nPos < m_nMin)
nPos = m_nMax - abs(m_nMin - nPos);
else if (nPos > m_nMax)
nPos = m_nMin + abs(nPos - m_nMax);
// set new position, returning old one
return ((LRESULT)OnSetPos((WPARAM)nPos, 0));
}
LRESULT CTextProgressCtrl::OnSetRange32(WPARAM nLowLim, LPARAM nHighLim)
{
// save old range for return
int nOldMin = m_nMin;
int nOldMax = m_nMax;
// set new range
m_nMin = (int)nLowLim;
m_nMax = (int)nHighLim;
// return old range (16 bit only)
return (MAKELRESULT(LOWORD(nOldMin), LOWORD(nOldMax)));
}
LRESULT CTextProgressCtrl::OnGetRange(WPARAM bWhichLimit, LPARAM pPBRange)
{
// get arguments into proper types
BOOL bType = (BOOL)bWhichLimit;
PPBRANGE pRange = (PPBRANGE)pPBRange;
// return both range limits if a pointer was provided
if (pRange)
{
pRange->iLow = m_nMin;
pRange->iHigh = m_nMax;
}
// return selected range limit
return ((LRESULT)(bType ? m_nMin : m_nMax));
}
LRESULT CTextProgressCtrl::OnGetPos(WPARAM, LPARAM)
{
// return current position
return ((LRESULT)m_nPos);
}
LRESULT CTextProgressCtrl::OnSetBarColor(WPARAM, LPARAM crBar)
{
// call a common routine to redraw window
CommonPaint();
// set new bar color, returning old one
COLORREF crOldBarClr = m_crBarClr;
m_crBarClr = (COLORREF)crBar;
return ((LRESULT)crOldBarClr);
}
LRESULT CTextProgressCtrl::OnSetBarBkColor(WPARAM, LPARAM crBarBk)
{
// call a common routine to redraw window
CommonPaint();
// set new bar background color, returning old one
COLORREF crOldBarBkClr = m_crBarBkClr;
m_crBarBkClr = (COLORREF)crBarBk;
return ((LRESULT)crOldBarBkClr);
}
LRESULT CTextProgressCtrl::OnGetBarColor(WPARAM, LPARAM)
{
// return current bar color
return ((LRESULT)((m_crBarClr == CLR_DEFAULT)? ::GetSysColor(COLOR_HIGHLIGHT) : m_crBarClr));
}
LRESULT CTextProgressCtrl::OnGetBarBkColor(WPARAM, LPARAM)
{
// return current bar background color
return ((LRESULT)((m_crBarBkClr == CLR_DEFAULT)? ::GetSysColor(COLOR_BTNFACE) : m_crBarBkClr));
}
LRESULT CTextProgressCtrl::OnSetTextColor(WPARAM, LPARAM crText)
{
// call a common routine to redraw window
CommonPaint();
// set new text color, returning old one
COLORREF crOldTextClr = m_crTextClr;
m_crTextClr = (COLORREF)crText;
return ((LRESULT)crOldTextClr);
}
LRESULT CTextProgressCtrl::OnGetTextColor(WPARAM, LPARAM)
{
// return current text color
return ((LRESULT)((m_crTextClr == CLR_DEFAULT ? ::GetSysColor(COLOR_WINDOWTEXT) : m_crTextClr)));
}
LRESULT CTextProgressCtrl::OnSetTextBkColor(WPARAM, LPARAM crTextBkClr)
{
// call a common routine to redraw window
CommonPaint();
// set new text background color, returning old one
COLORREF crOldTextBkClr = m_crTextBkClr;
m_crTextBkClr = (COLORREF)crTextBkClr;
return ((LRESULT)crOldTextBkClr);
}
LRESULT CTextProgressCtrl::OnGetTextBkColor(WPARAM, LPARAM)
{
// return current text background color
return ((LRESULT)((m_crTextBkClr == CLR_DEFAULT ? ::GetSysColor(COLOR_WINDOW) : m_crTextBkClr)));
}
LRESULT CTextProgressCtrl::OnSetShowPercent(WPARAM bShow, LPARAM)
{
// call a common routine to redraw window
CommonPaint();
// set new percent completed display state, returning old one
BOOL bOldShow = m_bShowPercent;
m_bShowPercent = (BOOL)bShow;
return ((LRESULT)bOldShow);
}
LRESULT CTextProgressCtrl::OnAlignText(WPARAM dwAlignment, LPARAM)
{
// get argument into proper type
DWORD dwAlign = (DWORD)dwAlignment;
// check input
ASSERT((dwAlign == DT_LEFT) || (dwAlign == DT_RIGHT) || (dwAlign == DT_CENTER));
// call a common routine to redraw window
CommonPaint();
// set new text alignment mode, returning old one
DWORD dwOldTextStyle = m_dwTextStyle;
m_dwTextStyle = dwAlign;
return ((LRESULT)dwOldTextStyle);
}
LRESULT CTextProgressCtrl::OnSetMarquee(WPARAM bShow, LPARAM uMsecBetweenUpdate)
{
// call a common routine to redraw window
CommonPaint();
// can't have percent complete for this style
m_bShowPercent = false;
// turn marquee mode on or off
if ((BOOL)bShow)
{
ModifyStyle(0, PBS_MARQUEE);
SetTimer(IDT_MARQUEE, (UINT)uMsecBetweenUpdate, NULL);
}
else
{
KillTimer(IDT_MARQUEE);
ModifyStyle(PBS_MARQUEE, 0);
}
// return current marquee mode
return ((LRESULT)bShow);
}
LRESULT CTextProgressCtrl::OnSetMarqueeOptions(WPARAM nBarSize, LPARAM)
{
// get argument into proper type
int nBar = (int)nBarSize;
// call a common routine to redraw window
CommonPaint();
// set new marquee bar size
m_nMarqueeSize = nBar;
// return bar size (have to return something from a message)
return ((LRESULT)nBar);
}
////////////////////////////////////////////////////////////////////////////////
// CTextProgressCtrl helper functions
void CTextProgressCtrl::CreateVerticalFont()
{
// delete old font if it exists
if (m_VerticalFont.m_hObject)
m_VerticalFont.DeleteObject();
// create a new vertical font based on the current font
LOGFONT lf;
GetFont()->GetLogFont(&lf);
lf.lfEscapement = lf.lfOrientation = 900;
m_VerticalFont.CreateFontIndirect(&lf);
}
void CTextProgressCtrl::CommonPaint()
{
//
// common place to mess with redraw options
//
// note that Invalidate() by itself won't cause
// a repaint when this control is used in a modeless
// dialog box
//
// also note that the marquee timer won't work in a modeless
// dialog - to use marquee mode in a modeless dialog the code
// that is running will have to pump Windows messages
//
RedrawWindow();
}
@@ -0,0 +1,293 @@
#ifndef _TEXTPROGRESSCTRL_H_
#define _TEXTPROGRESSCTRL_H_
#include "CUserMemDC.h"
//
// TextProgressCtrl.h : header file for CTextProgressCtrl class
//
// Written by Chris Maunder ([email protected])
// Copyright 1998-2005.
//
// TextProgressCtrl is a drop-in replacement for the standard
// CProgressCtrl that displays text in a progress control.
//
// Homepage: http://www.codeproject.com/miscctrl/text_progressctrl.asp
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed by any means PROVIDING it is not sold for
// profit without the author's written consent, and providing that this
// notice and the author's name is included. If the source code in
// this file is used in any commercial application then an email to
// me would be nice.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to your
// computer, causes your pet cat to fall ill, increases baldness or
// makes you car start emitting strange noises when you start it up.
//
// Expect bugs.
//
// Please use and enjoy. Please let me know of any bugs/mods/improvements
// that you have found/implemented and I will fix/incorporate them into this
// file.
//
// See file TextProgressCtrl.cpp for modification history.
//
////////////////////////////////////////////////////////////////////////////////
//
// To set the range (16 bit):
// call SetRange(WORD wLower, WORD wUpper)
// or SendMessage(PBM_SETRANGE, 0, MAKELPARAM(wLower, wUpper))
// or ::SendMessage(m_hWnd, PBM_SETRANGE, 0, MAKELPARAM(wLower, wUpper))
//
// To set the position:
// call SetPos(int nNewPos)
// or SendMessage(PBM_SETPOS, (WPARAM)nNewPos, 0)
// or ::SendMessage(m_hWnd, PBM_SETPOS, (WPARAM)nNewPos, 0)
//
// To set the position using a delta value:
// call OffsetPos(int nIncrement)
// or SendMessage(PBM_DELTAPOS, (WPARAM)nIncrement, 0)
// or ::SendMessage(m_hWnd, PBM_DELTAPOS, (WPARAM)nIncrement, 0)
//
// To set the step increment size:
// call SetStep(int nStepInc)
// or SendMessage(PBM_SETSTEP, (WPARAM)nStepInc, 0)
// or ::SendMessage(m_hWnd, PBM_SETSTEP, (WPARAM)nStepInc, 0)
//
// To step the position by the step increment size:
// call StepIt()
// or SendMessage(PBM_STEPIT, 0, 0)
// or ::SendMessage(m_hWnd, PBM_STEPIT, 0, 0)
//
// To set the range (32 bit):
// call SetRange32(int nLowLim, int nHighLim)
// or SendMessage(PBM_SETRANGE32, (WPARAM)nLowLim, (LPARAM)nHighLim)
// or ::SendMessage(m_hWnd, PBM_SETRANGE32, (WPARAM)nLowLim, (LPARAM)nHighLim)
//
// To get the current range:
// call GetRange(BOOL bWhichLimit, PBRANGE* pPBRange)
// or SendMessage(PBM_GETRANGE, (WPARAM)bWhichLimit, (LPARAM)pBBRange)
// or ::SendMessage(m_hWnd, PBM_GETRANGE, (WPARAM)bWhichLimit, (LPARAM)pBBRange)
//
// To get the current position:
// call GetPos()
// or SendMessage(PBM_GETPOS, 0, 0)
// or ::SendMessage(m_hWnd, PBM_GETPOS, 0, 0)
//
// To set the bar color:
// call SetBarColor(COLORREF crBar)
// or SendMessage (PBM_SETBARCOLOR, 0, (LPARAM)crBar)
// or ::SendMessage (m_hwnd, PBM_SETBARCOLOR, 0, (LPARAM)crBar)
//
// To get the bar color:
// call GetBarColor()
// or SendMessage (PBM_USERGETBARCOLOR, 0, 0)
// or ::SendMessage (m_hwnd, PBM_USERGETBARCOLOR, 0, 0)
//
// To set the bar background color:
// call SetBkColor(COLORREF crBarBk)
// or SetBarBkColor(COLORREF crBarBk)
// or SendMessage (PBM_SETBARBKCOLOR, 0, (LPARAM)crBarBk)
// or ::SendMessage (m_hwnd, PBM_SETBARBKCOLOR, 0, (LPARAM)crBarBk)
//
// To get the bar background color:
// call GetBarBkColor()
// or SendMessage (PBM_GETBARBKCOLOR, 0, 0)
// or ::SendMessage (m_hwnd, PBM_GETBARBKCOLOR, 0, 0)
//
// To operate on the bar text:
// use any of the normal CWnd window text functions, such as
// SetWindowText, GetWindowText, GetWindowTextLength, SetFont and GetFont
//
// To set the text color:
// call SetTextColor(COLORREF crTextClr)
// or SendMessage (PBM_SETTEXTCOLOR, 0, (LPARAM)crTextClr)
// or ::SendMessage (m_hwnd, PBM_SETTEXTCOLOR, 0, (LPARAM)crTextClr)
// To get the text color:
// call GetTextColor()
// or SendMessage (PBM_GETTEXTCOLOR, 0, 0)
// or ::SendMessage (m_hwnd, PBM_GETTEXTCOLOR, 0, 0)
//
// To set the text background color:
// call SetTextBkColor(COLORREF crTextBkClr)
// or SendMessage (PBM_SETTEXTBKCOLOR, 0, (LPARAM)crTextBkClr)
// or ::SendMessage (m_hwnd, PBM_SETTEXTBKCOLOR, 0, (LPARAM)crTextBkClr)
//
// To get the text background color:
// call GetTextBkColor()
// or SendMessage (PBM_GETTEXTBKCOLOR, 0, 0)
// or ::SendMessage (m_hwnd, PBM_GETTEXTBKCOLOR, 0, 0)
//
// To show or hide percentage complete:
// call SetShowPercent(BOOL bShow)
// or SendMessage(PBM_SETSHOWPERCENT, (WPARAM)bShow, 0)
// or ::SendMessage(m_hWnd, PBM_SETSHOWPERCENT, (WPARAM)bShow, 0)
//
// To set the text alignment mode:
// call AlignText(DWORD dwAlignment), where dwAlignment = DT_LEFT, DT_RIGHT or DT_CENTER
// or SendMessage(PBM_ALIGNTEXT, (WPARAM)dwAlignment, 0)
// or SendMessage(m_hWnd, PBM_ALIGNTEXT, (WPARAM)dwAlignment, 0)
//
// To turn on/off marquee mode
// call SetMarquee(BOOL bOn, int nMsecBetweenUpdate)
// or SendMessage(PBM_SETMARQUEE, (WPARAM)bOn, (LPARAM)nMsecBetweenUpdate)
// or ::SendMessage(m_hWnd, PBM_SETMARQUEE, (WPARAM)bOn, (LPARAM)nMsecBetweenUpdate)
//
// To set marquee options
// call SetMarqueeOptions(int nBarSize)
// or SendMessage(PBM_SETMARQUEEOPTIONS, (WPARAM)nBarSize, 0)
// or ::SendMessage(m_hWnd, PBM_SETMARQUEEOPTIONS, (WPARAM)nBarSize, 0)
//
////////////////////////////////////////////////////////////////////////////////
// setup aliases using "Colour" instead of "Color"
#define SetBarColour SetBarColor
#define GetBarColour GetBarColor
#define SetBgColour SetBarBkColor
#define GetBgColour GetBarBkColor
#define SetTextColour SetTextColor
#define GetTextColour GetTextColor
// define progress bar stuff that may not be elsewhere defined (if needed)
#ifndef PBS_SMOOTH
#define PBS_SMOOTH 0x01
#endif
#ifndef PBS_VERTICAL
#define PBS_VERTICAL 0x04
#endif
#ifndef PBS_MARQUEE
#define PBS_MARQUEE 0x08
#endif
#ifndef PBM_SETRANGE32
#define PBM_SETRANGE32 (WM_USER+6)
typedef struct
{
int iLow;
int iHigh;
} PBRANGE, *PPBRANGE;
#endif
#ifndef PBM_GETRANGE
#define PBM_GETRANGE (WM_USER+7)
#endif
#ifndef PBM_GETPOS
#define PBM_GETPOS (WM_USER+8)
#endif
#ifndef PBM_SETBARCOLOR
#define PBM_SETBARCOLOR (WM_USER+9)
#endif
#ifndef PBM_SETBKCOLOR
#define PBM_SETBKCOLOR CCM_SETBKCOLOR
#endif
#ifndef PBM_SETMARQUEE
#define PBM_SETMARQUEE (WM_USER+10)
#endif
// setup message codes for new messages
#define PBM_USERGETBARCOLOR (WM_USER+100)
#define PBM_USERGETBKCOLOR (WM_USER+101)
#define PBM_SETTEXTCOLOR (WM_USER+102)
#define PBM_GETTEXTCOLOR (WM_USER+103)
#define PBM_SETTEXTBKCOLOR (WM_USER+104)
#define PBM_GETTEXTBKCOLOR (WM_USER+105)
#define PBM_SETSHOWPERCENT (WM_USER+106)
#define PBM_ALIGNTEXT (WM_USER+107)
#define PBM_SETMARQUEEOPTIONS (WM_USER+108)
////////////////////////////////////////////////////////////////////////////////
// CTextProgressCtrl class
class CTextProgressCtrl : public CProgressCtrl
{
// Constructor / Destructor
public:
CTextProgressCtrl();
virtual ~CTextProgressCtrl();
// Operations
public:
inline COLORREF SetBarColor(COLORREF crBarClr = CLR_DEFAULT)
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_SETBARCOLOR, 0, (LPARAM)crBarClr)); }
inline COLORREF GetBarColor() const
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_USERGETBARCOLOR, 0, 0)); }
inline COLORREF SetBarBkColor(COLORREF crBarBkClr = CLR_DEFAULT)
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_SETBKCOLOR, 0, (LPARAM)crBarBkClr)); }
inline COLORREF GetBarBkColor() const
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_USERGETBKCOLOR, 0, 0)); }
inline COLORREF SetTextColor(COLORREF crTextClr = CLR_DEFAULT)
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_SETTEXTCOLOR, 0, (LPARAM)crTextClr)); }
inline COLORREF GetTextColor() const
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_GETTEXTCOLOR, 0, 0)); }
inline COLORREF SetTextBkColor(COLORREF crTextBkClr = CLR_DEFAULT)
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_SETTEXTBKCOLOR, 0, (LPARAM)crTextBkClr)); }
inline COLORREF GetTextBkColor() const
{ ASSERT(::IsWindow(m_hWnd)); return ((COLORREF) ::SendMessage(m_hWnd, PBM_GETTEXTBKCOLOR, 0, 0)); }
inline BOOL SetShowPercent(BOOL bShow)
{ ASSERT(::IsWindow(m_hWnd)); return ((BOOL) ::SendMessage(m_hWnd, PBM_SETSHOWPERCENT, (WPARAM)bShow, 0)); }
inline DWORD AlignText(DWORD dwAlignment = DT_CENTER)
{ ASSERT(::IsWindow(m_hWnd)); return ((DWORD) ::SendMessage(m_hWnd, PBM_ALIGNTEXT, (WPARAM)dwAlignment, 0)); }
inline BOOL SetMarquee(BOOL bOn, UINT uMsecBetweenUpdate)
{ ASSERT(::IsWindow(m_hWnd)); return ((BOOL) ::SendMessage(m_hWnd, PBM_SETMARQUEE, (WPARAM)bOn, (LPARAM)uMsecBetweenUpdate)); }
inline int SetMarqueeOptions(int nBarSize)
{ ASSERT(::IsWindow(m_hWnd)); return ((BOOL) ::SendMessage(m_hWnd, PBM_SETMARQUEEOPTIONS, (WPARAM)nBarSize, 0)); }
// Generated message map functions
protected:
//{{AFX_MSG(CTextProgressCtrl)
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg void OnTimer(UINT_PTR nIDEvent);
//}}AFX_MSG
// handlers for shell progress control standard messages
afx_msg LRESULT OnSetRange(WPARAM, LPARAM lparamRange);
afx_msg LRESULT OnSetPos(WPARAM nNewPos, LPARAM);
afx_msg LRESULT OnOffsetPos(WPARAM nIncrement, LPARAM);
afx_msg LRESULT OnSetStep(WPARAM nStepInc, LPARAM);
afx_msg LRESULT OnStepIt(WPARAM, LPARAM);
afx_msg LRESULT OnSetRange32(WPARAM nLowLim, LPARAM nHighLim);
afx_msg LRESULT OnGetRange(WPARAM bWhichLimit, LPARAM pPBRange);
afx_msg LRESULT OnGetPos(WPARAM, LPARAM);
afx_msg LRESULT OnSetBarColor(WPARAM, LPARAM crBar);
afx_msg LRESULT OnSetBarBkColor(WPARAM, LPARAM crBarBk);
// new handlers added by this class
afx_msg LRESULT OnGetBarColor(WPARAM, LPARAM);
afx_msg LRESULT OnGetBarBkColor(WPARAM, LPARAM);
afx_msg LRESULT OnSetTextColor(WPARAM, LPARAM crText);
afx_msg LRESULT OnGetTextColor(WPARAM, LPARAM);
afx_msg LRESULT OnSetTextBkColor(WPARAM, LPARAM crTextBk);
afx_msg LRESULT OnGetTextBkColor(WPARAM, LPARAM);
afx_msg LRESULT OnSetShowPercent(WPARAM bShow, LPARAM);
afx_msg LRESULT OnAlignText(WPARAM dwAlignment, LPARAM);
afx_msg LRESULT OnSetMarquee(WPARAM bOn, LPARAM nMsecBetweenUpdate);
afx_msg LRESULT OnSetMarqueeOptions(WPARAM nBarSize, LPARAM);
// helper functions
void CreateVerticalFont();
void CommonPaint();
DECLARE_MESSAGE_MAP()
// variables for class
BOOL m_bShowPercent; // true to show percent complete as text
CFont m_VerticalFont; // font for vertical progress bars
COLORREF m_crBarClr, m_crBarBkClr; // bar colors
COLORREF m_crTextClr, m_crTextBkClr; // text colors
DWORD m_dwTextStyle; // alignment style for text
int m_nPos; // current position within range
int m_nStepSize; // current step size
int m_nMin, m_nMax; // minimum and maximum values of range
int m_nMarqueeSize; // size of sliding marquee bar in percent (0 - 100)
};
////////////////////////////////////////////////////////////////////////////////
#endif //#ifndef _TEXTPROGRESSCTRL_H_
@@ -0,0 +1,95 @@
#include "StdAfx.h"
#include "UninstallCommand.h"
#include "../resource.h"
#include "../LS_launcherDlg.h"
#include "../ServerDialog.h"
UninstallCommand::UninstallCommand() : BaseCommand(BCT_UNINSTALL)
{
}
UninstallCommand::~UninstallCommand()
{
}
BOOL UninstallCommand::ExecuteServiceAll(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckContinueServiceAll( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandUninstallAll() )
{
return FALSE;
}
return TRUE;
}
BOOL UninstallCommand::ExecuteServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
if( CheckContinueServiceOne( dialog ) )
{
m_state = CST_ALREADY_EXCUTE;
return TRUE;
}
m_state = CST_BEFORE_EXCUTE;
if( !dialog->CommandUninstall( m_strings[0] ) )
{
return FALSE;
}
return TRUE;
}
BOOL UninstallCommand::CheckContinueServiceAll(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
int serviceCount = dialog->GetServiceCount();
if( serviceCount != 0 )
return FALSE;
return TRUE;
}
BOOL UninstallCommand::CheckContinueServiceOne(CServerDialog* dialog)
{
if( !dialog )
return FALSE;
int index = dialog->FindServiceIndex( m_strings[0] );
if( index != -1 )
{
return FALSE;
}
return TRUE;
}
BOOL UninstallCommand::IsValidDetail()
{
if( m_isServiceAll )
{
if( !m_strings.empty() )
return FALSE;
}
else
{
if( m_strings.size() != 1 )
return FALSE;
}
return TRUE;
}
@@ -0,0 +1,18 @@
#pragma once
#include "BaseCommand.h"
class UninstallCommand : public BaseCommand
{
public:
UninstallCommand();
~UninstallCommand();
public:
BOOL ExecuteServiceAll(CServerDialog* dialog);
BOOL ExecuteServiceOne(CServerDialog* dialog);
BOOL CheckContinueServiceAll(CServerDialog* dialog);
BOOL CheckContinueServiceOne(CServerDialog* dialog);
BOOL IsValidDetail();
};
@@ -0,0 +1,94 @@
// BatchDialog.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "BatchDialog.h"
#include "afxdialogex.h"
// CBatchDialog 대화 상자입니다.
IMPLEMENT_DYNAMIC(CBatchDialog, CDialogEx)
CBatchDialog::CBatchDialog(CWnd* pParent /*=NULL*/)
: CDialogEx(CBatchDialog::IDD, pParent)
{
}
CBatchDialog::~CBatchDialog()
{
}
void CBatchDialog::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_BATCH, m_batchList);
DDX_Control(pDX, IDC_STATIC_BATCHRESULT, m_batchResult);
}
BEGIN_MESSAGE_MAP(CBatchDialog, CDialogEx)
END_MESSAGE_MAP()
// CBatchDialog 메시지 처리기입니다.
BOOL CBatchDialog::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 여기에 추가 초기화 작업을 추가합니다.
m_batchList.DeleteAllItems();
m_batchList.InitProgressColumn(1);
m_batchList.InsertColumn(0, _T("Command"), LVCFMT_LEFT, 200);
m_batchList.InsertColumn(1, _T("Progress"), LVCFMT_LEFT, 200);
m_batchList.InsertColumn(2, _T("Result"), LVCFMT_LEFT, 100);
return TRUE; // return TRUE unless you set the focus to a control
// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
void CBatchDialog::BeginProgress(const TCHAR* title, const int progress, const TCHAR* result, int& index)
{
index = m_batchList.GetItemCount();
CString ratio;
ratio.Format(_T("%d"), progress);
m_batchList.InsertItem(index, _T(""), 0);
m_batchList.SetItemText(index, 0, title);
m_batchList.SetItemText(index, 1, ratio);
m_batchList.SetItemText(index, 2, result);
TRACE(_T("insert :: [%d] - %d\n"), index, progress);
}
void CBatchDialog::DoingProgress(const int index, const int progress)
{
TRACE(_T("set [%d] - %d\n"), index, progress);
CString ratio;
ratio.Format(_T("%d"), progress);
m_batchList.SetItemText(index, 1, ratio);
}
void CBatchDialog::EndProgress(const int index, const int progress, const TCHAR* result)
{
CString ratio;
ratio.Format(_T("%d"), progress);
m_batchList.SetItemText(index, 1, ratio);
m_batchList.SetItemText(index, 2, result);
}
void CBatchDialog::UpdateBatchResult(CString result)
{
//_tprintf(result.GetBuffer());
m_batchResult.SetWindowText( result );
}
@@ -0,0 +1,38 @@
#pragma once
#include "resource.h"
#include "afxcmn.h"
#include "Batch/ListCtrlEx.h"
#include "afxwin.h"
// CBatchDialog 대화 상자입니다.
class CBatchDialog : public CDialogEx
{
DECLARE_DYNAMIC(CBatchDialog)
public:
CBatchDialog(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~CBatchDialog();
// 대화 상자 데이터입니다.
enum { IDD = IDD_BATCH_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
void BeginProgress(const TCHAR* title, const int progress, const TCHAR* result, int& index);
void DoingProgress(const int index, const int progress);
void EndProgress(const int index, const int progress, const TCHAR* result);
void UpdateBatchResult(CString result);
public:
CListCtrlEx m_batchList;
virtual BOOL OnInitDialog();
CStatic m_batchResult;
};
@@ -0,0 +1,164 @@
// ClientSocket.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "ClientSocket.h"
#include "cHeader.h"
#include "WinMessage.h"
// CClientSocket
CClientSocket::CClientSocket(HWND hwnd, CString& IP, UINT port) : m_connected(FALSE)
{
m_hwnd = hwnd;
m_IP = IP;
m_port = port;
m_storage.Create(PACKET_BUFFER*3);
m_temporage.Create(PACKET_BUFFER*3);
}
CClientSocket::~CClientSocket()
{
}
// CClientSocket 멤버 함수
void CClientSocket::OnReceive(int nErrorCode)
{
//TRACE("OnReceive\n");
if(0 == nErrorCode)
{
int bytes = Receive(m_receive, sizeof(m_receive));
if(0 != bytes)
{
m_temporage.Copy(m_storage.GetBuffer(), m_storage.GetLength());
m_temporage.Append(m_receive, bytes);
}
// 패킷 파싱
if(Parse(m_temporage.GetBuffer(), m_temporage.GetLength()))
{
m_storage.Erase();
}
m_temporage.Erase();
}
}
BOOL CClientSocket::Parse(BYTE* buffer, UINT length)
{
// 패킷의 헤더길이 검사
if(length < sizeof(cHeader))
{
// 헤더보다 작은 패킷이 들어왔을 경우 저장하고 끝난다
m_storage.Copy(buffer, length);
return FALSE;
}
// 헤더로 페이로드 길이 확인
cHeader* header = reinterpret_cast<cHeader*>(buffer);
//if(!header->IsPerfect())
//{
// // 잘못된 헤더가 들어왔을때 패킷을 drop한다
// TRACE("[%lu]invalid packet : %lu\n", GetCurrentThreadId());
// return FALSE;
//}
if(header->GetPayload() > PACKET_BUFFER)
{
TRACE("[%lu]too large payload : %lu\n", GetCurrentThreadId(), header->GetPayload());
return TRUE;
}
// 패킷 헤더에 따른 길이 검사
UINT packetLength = sizeof(cHeader) + header->GetPayload();
if(length < packetLength) // 패킷길이가 잘려서 들어왔다
{
TRACE("[%lu]short than payload : %lu\n", GetCurrentThreadId(), packetLength);
m_storage.Copy(buffer, length);
return FALSE;
}
else if(length == packetLength) // 패킷길이가 정확하게 들어왔다
{
Push(
header->GetCommand(),
buffer+sizeof(cHeader),
packetLength);
return TRUE;
}
else if(length > packetLength) // 패킷길이가 붙어서 들어왔다
{
Push(
header->GetCommand(),
buffer+sizeof(cHeader),
packetLength);
// 다시 한번 패킷 검사
return Parse(buffer+packetLength, length-packetLength);
}
return TRUE;
}
void CClientSocket::Push(UINT nCommand, BYTE* buffer, UINT length)
{
SendMessage(m_hwnd, IDC_RECEIVE, (WPARAM)nCommand, (LPARAM)buffer);
}
void CClientSocket::OnSend(int nErrorCode)
{
//TRACE("OnSend\n");
}
void CClientSocket::OnConnect(int nErrorCode)
{
//TRACE("OnConnect\n");
if(0 == nErrorCode)
{
m_connected = TRUE;
SendMessage(m_hwnd, IDC_CONNECT, (WPARAM)0, (LPARAM)0);
}
else
{
SendMessage(m_hwnd, IDC_DISCONNECT, (WPARAM)0, (LPARAM)0);
}
}
void CClientSocket::OnClose(int nErrorCode)
{
//TRACE("OnClose\n");
m_connected = FALSE;
CAsyncSocket::Close();
CAsyncSocket::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE);
SendMessage(m_hwnd, IDC_DISCONNECT, (WPARAM)0, (LPARAM)0);
}
BOOL CClientSocket::Create()
{
CAsyncSocket::Close();
return CAsyncSocket::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE);
}
BOOL CClientSocket::Connect()
{
if(m_connected)
return TRUE;
return CAsyncSocket::Connect(m_IP, m_port);
}
BOOL CClientSocket::Reconnect()
{
if(!Create())
{
return FALSE;
}
return Connect();
}
@@ -0,0 +1,46 @@
#pragma once
#include <afxsock.h>
#include <string>
#include "cBuffer.h"
const uint32 PACKET_BUFFER = 1024*4;
// CClientSocket ¸í·É ´ë»óÀÔ´Ï´Ù.
class CClientSocket : public CAsyncSocket
{
public:
CClientSocket(HWND hwnd, CString& IP, UINT port);
virtual ~CClientSocket();
public:
BOOL Create();
BOOL Connect();
BOOL Reconnect();
BOOL IsConnected() { return m_connected; }
protected:
virtual void OnReceive(int nErrorCode);
virtual void OnSend(int nErrorCode);
virtual void OnConnect(int nErrorCode);
virtual void OnClose(int nErrorCode);
BOOL Parse(BYTE* buffer, UINT length);
void Push(UINT command, BYTE* buffer, UINT length);
protected:
HWND m_hwnd;
CString m_IP;
UINT m_port;
BOOL m_connected;
BYTE m_receive[PACKET_BUFFER];
cBuffer m_storage, m_temporage;
};
+21
View File
@@ -0,0 +1,21 @@
#pragma once // AP_SERVER
#ifndef _AP_BASIC_TYPES_
#define _AP_BASIC_TYPES_
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned long ulong;
typedef unsigned long uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef unsigned __int64 uint64;
typedef char int8;
typedef short int16;
typedef long int32;
typedef __int64 int64;
typedef uint64 uniq;
typedef uint32 unit;
#endif
@@ -0,0 +1,84 @@
// InstallDialog.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "InstallDialog.h"
// CInstallDialog 대화 상자입니다.
IMPLEMENT_DYNAMIC(CInstallDialog, CDialog)
CInstallDialog::CInstallDialog(const CString folder, CWnd* pParent /*=NULL*/)
: CDialog(CInstallDialog::IDD, pParent)
{
m_folder = folder;
}
CInstallDialog::~CInstallDialog()
{
}
void CInstallDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_SELECTDEMON, m_selectedDemon);
DDX_Control(pDX, IDC_STATIC_SELECTSCRIPT, m_selectedScript);
DDX_Control(pDX, IDC_EDIT_SERVICENAME, m_serviceName);
}
BEGIN_MESSAGE_MAP(CInstallDialog, CDialog)
ON_BN_CLICKED(IDC_BUTTON_SELECTDEMON, &CInstallDialog::OnBnClickedButtonSelectDemon)
ON_BN_CLICKED(IDC_BUTTON_SELECTSCRIPT, &CInstallDialog::OnBnClickedButtonSelectScript)
ON_BN_CLICKED(IDC_BUTTON_INSTALLCANCEL, &CInstallDialog::OnBnClickedButtonInstallCancel)
ON_BN_CLICKED(IDC_BUTTON_INSTALLOK, &CInstallDialog::OnBnClickedButtonInstallOK)
END_MESSAGE_MAP()
// CInstallDialog 메시지 처리기입니다.
void CInstallDialog::OnBnClickedButtonSelectDemon()
{
TCHAR name[512] = _T("exe Files (*.exe)|*.exe|All Files (*.*)|*.*||");
CFileDialog fileInfo(TRUE, _T("exe"), _T("*.exe"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, name, NULL);
fileInfo.m_ofn.nFilterIndex = 1;
fileInfo.m_ofn.lpstrInitialDir = m_folder;
if(fileInfo.DoModal() == IDOK)
{
m_demon = fileInfo.GetPathName();
m_selectedDemon.SetWindowText(fileInfo.GetFileName());
}
}
void CInstallDialog::OnBnClickedButtonSelectScript()
{
//TCHAR name[512] = _T("lua script Files (*.lua)|*.lua|All Files (*.*)|*.*||");
TCHAR name[512] = _T("ini Files (*.ini)|*.ini|All Files (*.*)|*.*||");
CFileDialog fileInfo(TRUE, _T("ini"), _T("*.ini"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, name, NULL);
fileInfo.m_ofn.nFilterIndex = 1;
fileInfo.m_ofn.lpstrInitialDir = m_folder;
if(fileInfo.DoModal() == IDOK)
{
m_script = fileInfo.GetPathName();
m_selectedScript.SetWindowText(fileInfo.GetFileName());
}
}
void CInstallDialog::OnBnClickedButtonInstallOK()
{
m_serviceName.GetWindowText(m_service);
CDialog::EndDialog(IDOK);
}
void CInstallDialog::OnBnClickedButtonInstallCancel()
{
CDialog::EndDialog(IDCANCEL);
}
@@ -0,0 +1,39 @@
#pragma once
#include "afxwin.h"
// CInstallDialog 대화 상자입니다.
class CInstallDialog : public CDialog
{
DECLARE_DYNAMIC(CInstallDialog)
public:
CInstallDialog(const CString folder, CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~CInstallDialog();
// 대화 상자 데이터입니다.
enum { IDD = IDD_INSTALL_DIALOG };
public:
CString GetService() { return m_service; }
CString GetDemon() { return m_demon; }
CString GetScript() { return m_script; }
protected:
CString m_folder, m_demon, m_script;
CString m_service;
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButtonSelectDemon();
afx_msg void OnBnClickedButtonSelectScript();
CStatic m_selectedDemon;
CStatic m_selectedScript;
afx_msg void OnBnClickedButtonInstallCancel();
afx_msg void OnBnClickedButtonInstallOK();
CEdit m_serviceName;
};
@@ -0,0 +1,96 @@
// LS_launcher.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "LS_launcherDlg.h"
#include <string>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLS_LauncherApp
BEGIN_MESSAGE_MAP(CLS_LauncherApp, CWinApp)
//ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CLS_LauncherApp construction
CLS_LauncherApp::CLS_LauncherApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CLS_LauncherApp object
CLS_LauncherApp theApp;
// CLS_LauncherApp initialization
BOOL CLS_LauncherApp::InitInstance()
{
MiniDump::Begin(_T("Lostsaga Luncher"));
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
if (!AfxSocketInit())
{
MessageBox(NULL, _T("AfxSocketInit failed"), _T("Error"), MB_OK);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
//server, batch read
//_fgetts(m_lpCmdLine,MAX_PATH,stdin);
//m_lpCmdLine[_tcslen(m_lpCmdLine)-1] = NULL;
CLS_launcherDlg dlg(m_lpCmdLine);
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
int CLS_LauncherApp::ExitInstance()
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
MiniDump::End();
return CWinApp::ExitInstance();
}
@@ -0,0 +1,31 @@
// LS_launcher.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CLS_LauncherApp:
// See LS_launcher.cpp for the implementation of this class
//
class CLS_LauncherApp : public CWinApp
{
public:
CLS_LauncherApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
virtual int ExitInstance();
};
extern CLS_LauncherApp theApp;
+323
View File
@@ -0,0 +1,323 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// 한국어(대한민국) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_KOR)
LANGUAGE LANG_KOREAN, SUBLANG_DEFAULT
#pragma code_page(949)
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"#define _AFX_NO_SPLITTER_RESOURCES\r\n"
"#define _AFX_NO_OLE_RESOURCES\r\n"
"#define _AFX_NO_TRACKER_RESOURCES\r\n"
"#define _AFX_NO_PROPERTY_RESOURCES\r\n"
"\r\n"
"#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_KOR)\r\n"
"LANGUAGE 18, 1\r\n"
"#pragma code_page(949)\r\n"
"#include ""res\\LS_launcher.rc2"" // non-Microsoft Visual C++ edited resources\r\n"
"#include ""afxres.rc"" // Standard components\r\n"
"#endif\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDR_MAINFRAME ICON "res\\LS_launcher.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_SERVICELAUNCHER_DIALOG DIALOGEX 0, 0, 371, 307
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_ACCEPTFILES | WS_EX_APPWINDOW
CAPTION "LS_launcher"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
CONTROL "",IDC_TAB_SERVERS,"SysTabControl32",WS_TABSTOP,7,7,295,293
CONTROL "WatchDog",IDC_CHECK_WATCHDOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,316,46,49,10
GROUPBOX "Global",IDC_STATIC,307,16,59,53
CONTROL "Apply All",IDC_CHECK_APPLYALL,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,316,31,45,11
CONTROL "Console",IDC_CHECK_CONSOLE,"Button",BS_AUTOCHECKBOX | NOT WS_VISIBLE | WS_TABSTOP,316,116,42,13
CONTROL "Recursive",IDC_CHECK_RECURSIVE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,316,99,44,15
CONTROL "Monitor",IDC_CHECK_Monitor,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,316,86,40,10
GROUPBOX "Option",IDC_STATIC,308,72,58,59
END
IDD_SERVERINFO_DIALOG DIALOGEX 0, 0, 295, 273
STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
LTEXT "Static",IDC_STATIC_NAME,37,24,99,11
CONTROL "",IDC_STATIC_STATUS,"Static",SS_BITMAP | WS_BORDER,15,22,16,14
GROUPBOX "Status",IDC_STATIC,10,8,184,36
LTEXT "Done",IDC_STATIC_LOG,9,245,275,8
GROUPBOX "Service",IDC_STATIC,9,47,184,193
CONTROL "",IDC_LIST_SERVICE,"SysListView32",LVS_REPORT | LVS_ALIGNLEFT | LVS_NOCOLUMNHEADER | WS_BORDER | WS_TABSTOP,20,57,162,177
EDITTEXT IDC_EDIT_ROOT,207,23,69,13,ES_AUTOHSCROLL
CONTROL "",IDC_PROGRESS_TRANSFER,"msctls_progress32",PBS_SMOOTH,18,258,270,10
GROUPBOX "Target",IDC_STATIC,202,8,86,37
CONTROL "",IDC_STATIC_CPU,"Static",SS_BLACKFRAME,214,66,32,46
CONTROL "",IDC_STATIC_RAM,"Static",SS_BLACKFRAME,247,66,32,46
CONTROL "",IDC_STATIC_UPLOAD,"Static",SS_BLACKFRAME,214,184,32,46
CONTROL "",IDC_STATIC_DOWNLOAD,"Static",SS_BLACKFRAME,247,184,32,46
GROUPBOX "Resource",IDC_STATIC,201,47,87,193
CONTROL "",IDC_STATIC_DISK,"Static",SS_BLACKFRAME,214,123,32,46
CONTROL "",IDC_STATIC_DISK2,"Static",SS_BLACKFRAME,247,123,32,46
LTEXT "CPU",IDC_STATIC,223,56,14,8
LTEXT "RAM",IDC_STATIC,250,56,16,8
LTEXT "C",IDC_STATIC,227,115,8,8
LTEXT "D",IDC_STATIC,259,115,8,8
LTEXT "UP",IDC_STATIC,225,175,9,8
LTEXT "Down",IDC_STATIC,254,175,19,8
END
IDD_INSTALL_DIALOG DIALOGEX 0, 0, 178, 95
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Service Install"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
PUSHBUTTON "Demon",IDC_BUTTON_SELECTDEMON,123,44,48,17
LTEXT "",IDC_STATIC_SELECTDEMON,19,48,95,10
PUSHBUTTON "INI",IDC_BUTTON_SELECTSCRIPT,123,24,48,17
LTEXT "",IDC_STATIC_SELECTSCRIPT,19,30,95,10
PUSHBUTTON "OK",IDC_BUTTON_INSTALLOK,39,75,66,16
PUSHBUTTON "Cancel",IDC_BUTTON_INSTALLCANCEL,107,75,66,16
EDITTEXT IDC_EDIT_SERVICENAME,41,6,100,12,ES_AUTOHSCROLL
LTEXT "Service",IDC_STATIC_SERVICENAME,10,7,25,9
END
IDD_BACKUP_DIALOG DIALOGEX 0, 0, 334, 76
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Dialog"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
PUSHBUTTON "Source",IDC_BUTTON_SOURCE,5,10,57,17
PUSHBUTTON "Target",IDC_BUTTON_TARGET,5,30,57,17
LTEXT "",IDC_STATIC_SOURCE,68,16,244,10
LTEXT "",IDC_STATIC_TARGET,68,34,244,10
PUSHBUTTON "OK",IDC_BUTTON_BACKUPOK,157,55,78,18
PUSHBUTTON "Cancel",IDC_BUTTON_BACKUPCANCEL,239,55,78,18
END
IDD_ADD_IP_DIALOG DIALOGEX 0, 0, 186, 90
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Dialog"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
PUSHBUTTON "OK",IDC_ADD_IP_OK_BUTTON,71,69,50,14
PUSHBUTTON "CANCEL",IDC_ADD_IP_CANCEL_BUTTON,129,69,50,14
EDITTEXT IDC_TAP_NAME_EDIT,68,7,102,17,ES_AUTOHSCROLL
EDITTEXT IDC_PORT_EDIT,122,40,49,14,ES_AUTOHSCROLL | ES_NUMBER
LTEXT "Tap Name : ",IDC_TAP_NAME_STATIC,17,7,43,17
LTEXT "IP :",IDC_IP_STATIC,18,30,43,8
LTEXT "Port :",IDC_PORT_STATIC,124,31,34,8
EDITTEXT IDC_ADDIP_EDIT,16,40,90,14,ES_AUTOHSCROLL
END
IDD_PERFMONDLG DIALOGEX 0, 0, 142, 101
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Resource Monitor"
FONT 9, "MS Shell Dlg", 0, 0, 0x0
BEGIN
CONTROL "",IDC_PROGRESS_MONCPU,"msctls_progress32",PBS_SMOOTH | PBS_VERTICAL | WS_BORDER,19,23,15,44
CONTROL "",IDC_PROGRESS_MONRAM,"msctls_progress32",PBS_SMOOTH | PBS_VERTICAL | WS_BORDER,61,23,15,44
CONTROL "",IDC_PROGRESS_MONNETWORK,"msctls_progress32",PBS_SMOOTH | PBS_VERTICAL | WS_BORDER,104,23,15,44
GROUPBOX "CPU",IDC_STATIC,7,9,38,78
GROUPBOX "Memory",IDC_STATIC,49,9,38,78
GROUPBOX "Network",IDC_STATIC,92,9,38,78
CTEXT "0%",IDC_STATIC_MONCPU,14,71,27,13
CTEXT "0%",IDC_STATIC_MONMEM,57,71,27,13
CTEXT "0%",IDC_STATIC_MONNET,103,71,22,10
END
IDD_BATCH_DIALOG DIALOGEX 0, 0, 355, 205
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Batch progress"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
CONTROL "",IDC_LIST_BATCH,"SysListView32",LVS_REPORT | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,7,7,336,177
LTEXT "0",IDC_STATIC_BATCHRESULT,9,188,334,12
END
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "TODO: <Company name>"
VALUE "FileDescription", "TODO: <File description>"
VALUE "FileVersion", "1.0.0.1"
VALUE "InternalName", "LS_launcher.exe"
VALUE "LegalCopyright", "TODO: (c) <Company name>. All rights reserved."
VALUE "OriginalFilename", "LS_launcher.exe"
VALUE "ProductName", "TODO: <Product name>"
VALUE "ProductVersion", "1.0.0.1"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_SERVICELAUNCHER_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 364
TOPMARGIN, 7
BOTTOMMARGIN, 300
END
IDD_SERVERINFO_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 288
TOPMARGIN, 7
BOTTOMMARGIN, 266
END
IDD_INSTALL_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 171
TOPMARGIN, 7
BOTTOMMARGIN, 88
END
IDD_BACKUP_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 327
TOPMARGIN, 7
BOTTOMMARGIN, 69
END
IDD_ADD_IP_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 179
TOPMARGIN, 7
BOTTOMMARGIN, 83
END
IDD_PERFMONDLG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 135
TOPMARGIN, 7
BOTTOMMARGIN, 94
END
IDD_BATCH_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 348
TOPMARGIN, 7
BOTTOMMARGIN, 198
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Bitmap
//
IDB_BITMAP_OFF BITMAP "res\\off.bmp"
IDB_BITMAP_ON BITMAP "res\\on.bmp"
IDB_BITMAP_ALL BITMAP "res\\bitmap1.bmp"
#endif // 한국어(대한민국) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_KOR)
LANGUAGE 18, 1
#pragma code_page(949)
#include "res\LS_launcher.rc2" // non-Microsoft Visual C++ edited resources
#include "afxres.rc" // Standard components
#endif
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
@@ -0,0 +1,236 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Template|Win32">
<Configuration>Template</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{C247F5AA-04DD-45B9-85E7-FD2537686BE3}</ProjectGuid>
<RootNamespace>LS_launcher</RootNamespace>
<Keyword>MFCProj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseOfMfc>Static</UseOfMfc>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseOfMfc>Static</UseOfMfc>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<EmbedManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</EmbedManifest>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\bin\</OutDir>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ProjectName)D</TargetName>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\Bin\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Midl>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>false</ValidateAllParameters>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>C:\Program Files (x86)\boost\boost_1_47</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0409</Culture>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<OutputFile>..\Bin\$(ProjectName)D.exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
<AdditionalDependencies>dbghelp.lib;Psapi.lib</AdditionalDependencies>
<AdditionalLibraryDirectories>C:\Program Files (x86)\boost\boost_1_47\lib</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Midl>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>false</ValidateAllParameters>
</Midl>
<ClCompile>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>C:\Program Files (x86)\boost\boost_1_50</AdditionalIncludeDirectories>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0409</Culture>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<OutputFile>..\Bin\$(ProjectName).exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
<AdditionalDependencies>dbghelp.lib;Psapi.lib</AdditionalDependencies>
<AdditionalLibraryDirectories>C:\Program Files (x86)\boost\boost_1_50\lib</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Template|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>C:\Program Files (x86)\boost\boost_1_47</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>C:\Program Files (x86)\boost\boost_1_47\lib</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="BatchDialog.h" />
<ClInclude Include="Batch\BaseCommand.h" />
<ClInclude Include="Batch\Batch.h" />
<ClInclude Include="Batch\BatchCompileDefine.h" />
<ClInclude Include="Batch\BatchManager.h" />
<ClInclude Include="Batch\BatchScanner.h" />
<ClInclude Include="Batch\FileReader.h" />
<ClInclude Include="Batch\InstallCommand.h" />
<ClInclude Include="Batch\ListCtrlEx.h" />
<ClInclude Include="Batch\PlayCommand.h" />
<ClInclude Include="Batch\QuitCommand.h" />
<ClInclude Include="Batch\StopCommand.h" />
<ClInclude Include="Batch\SyncCommand.h" />
<ClInclude Include="Batch\TextProgressCtrl.h" />
<ClInclude Include="Batch\UninstallCommand.h" />
<ClInclude Include="cHeader.h" />
<ClInclude Include="LauncherListCtrl.h" />
<ClInclude Include="LauncherTabCtrl.h" />
<ClInclude Include="Minidump\File.h" />
<ClInclude Include="Minidump\MiniDump.h" />
<ClInclude Include="MonitorCtrl.h" />
<ClInclude Include="MsgBox.h" />
<ClInclude Include="OptionManager.h" />
<ClInclude Include="PerfMonDlg.h" />
<ClInclude Include="ProcessCtrl.h" />
<ClInclude Include="Server.h" />
<ClInclude Include="Singleton.h" />
<ClInclude Include="Timer.h" />
<ClInclude Include="UserDefine.h" />
<ClInclude Include="Utility.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="cBuffer.h" />
<ClInclude Include="cEncrypt.h" />
<ClInclude Include="cFile.h" />
<ClInclude Include="ClientSocket.h" />
<ClInclude Include="cPacket.h" />
<ClInclude Include="..\common\Protocol.h" />
<ClInclude Include="WinMessage.h" />
<ClInclude Include="LS_launcherDlg.h" />
<ClInclude Include="AddIPDialog.h" />
<ClInclude Include="BackupDialog.h" />
<ClInclude Include="InstallDialog.h" />
<ClInclude Include="ServerDialog.h" />
<ClInclude Include="MD5.h" />
<ClInclude Include="LS_launcher.h" />
<ClInclude Include="stdafx.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="BatchDialog.cpp" />
<ClCompile Include="Batch\BaseCommand.cpp" />
<ClCompile Include="Batch\Batch.cpp" />
<ClCompile Include="Batch\BatchManager.cpp" />
<ClCompile Include="Batch\BatchScanner.cpp" />
<ClCompile Include="Batch\FileReader.cpp" />
<ClCompile Include="Batch\InstallCommand.cpp" />
<ClCompile Include="Batch\ListCtrlEx.cpp" />
<ClCompile Include="Batch\PlayCommand.cpp" />
<ClCompile Include="Batch\QuitCommand.cpp" />
<ClCompile Include="Batch\StopCommand.cpp" />
<ClCompile Include="Batch\SyncCommand.cpp" />
<ClCompile Include="Batch\TextProgressCtrl.cpp" />
<ClCompile Include="Batch\UninstallCommand.cpp" />
<ClCompile Include="LauncherListCtrl.cpp" />
<ClCompile Include="LauncherTabCtrl.cpp" />
<ClCompile Include="Minidump\File.cpp" />
<ClCompile Include="Minidump\MiniDump.cpp" />
<ClCompile Include="MonitorCtrl.cpp" />
<ClCompile Include="MsgBox.cpp" />
<ClCompile Include="OptionManager.cpp" />
<ClCompile Include="PerfMonDlg.cpp" />
<ClCompile Include="ProcessCtrl.cpp" />
<ClCompile Include="Utility.cpp" />
<ClCompile Include="cBuffer.cpp" />
<ClCompile Include="cEncrypt.cpp" />
<ClCompile Include="cFile.cpp" />
<ClCompile Include="ClientSocket.cpp" />
<ClCompile Include="cPacket.cpp" />
<ClCompile Include="LS_launcherDlg.cpp" />
<ClCompile Include="AddIPDialog.cpp" />
<ClCompile Include="BackupDialog.cpp" />
<ClCompile Include="InstallDialog.cpp" />
<ClCompile Include="ServerDialog.cpp" />
<ClCompile Include="MD5.cpp" />
<ClCompile Include="LS_launcher.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="res\bitmap1.bmp" />
<None Include="res\demonOn.bmp" />
<None Include="res\off.bmp" />
<None Include="res\on.bmp" />
<None Include="res\LS_launcher.ico" />
<None Include="res\LS_launcher.rc2" />
<None Include="res\serviceOn.bmp" />
<None Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="LS_launcher.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
<ProjectExtensions>
<VisualStudio>
<UserProperties RESOURCE_FILE="LS_launcher.rc" />
</VisualStudio>
</ProjectExtensions>
</Project>
@@ -0,0 +1,307 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="LS_launcher.cpp" />
<ClCompile Include="stdafx.cpp" />
<ClCompile Include="AddIPDialog.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="BackupDialog.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="cEncrypt.cpp">
<Filter>Network</Filter>
</ClCompile>
<ClCompile Include="ClientSocket.cpp">
<Filter>Network</Filter>
</ClCompile>
<ClCompile Include="cPacket.cpp">
<Filter>Network</Filter>
</ClCompile>
<ClCompile Include="InstallDialog.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="LauncherListCtrl.cpp">
<Filter>UI\Controls</Filter>
</ClCompile>
<ClCompile Include="LauncherTabCtrl.cpp">
<Filter>UI\Controls</Filter>
</ClCompile>
<ClCompile Include="cBuffer.cpp">
<Filter>Utility</Filter>
</ClCompile>
<ClCompile Include="cFile.cpp">
<Filter>Utility</Filter>
</ClCompile>
<ClCompile Include="MD5.cpp">
<Filter>Utility</Filter>
</ClCompile>
<ClCompile Include="ServerDialog.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="LS_launcherDlg.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="Utility.cpp">
<Filter>Utility</Filter>
</ClCompile>
<ClCompile Include="MsgBox.cpp" />
<ClCompile Include="Minidump\File.cpp">
<Filter>Minidump</Filter>
</ClCompile>
<ClCompile Include="Minidump\MiniDump.cpp">
<Filter>Minidump</Filter>
</ClCompile>
<ClCompile Include="PerfMonDlg.cpp">
<Filter>UI\Monitor</Filter>
</ClCompile>
<ClCompile Include="MonitorCtrl.cpp">
<Filter>UI\Monitor</Filter>
</ClCompile>
<ClCompile Include="ProcessCtrl.cpp">
<Filter>UI\Monitor</Filter>
</ClCompile>
<ClCompile Include="Batch\Batch.cpp">
<Filter>Batch</Filter>
</ClCompile>
<ClCompile Include="Batch\BatchManager.cpp">
<Filter>Batch</Filter>
</ClCompile>
<ClCompile Include="Batch\BatchScanner.cpp">
<Filter>Batch\Scanner</Filter>
</ClCompile>
<ClCompile Include="Batch\FileReader.cpp">
<Filter>Batch\File</Filter>
</ClCompile>
<ClCompile Include="Batch\PlayCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="Batch\StopCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="Batch\SyncCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="Batch\UninstallCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="Batch\InstallCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="OptionManager.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="Batch\QuitCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="Batch\BaseCommand.cpp">
<Filter>Batch\Command</Filter>
</ClCompile>
<ClCompile Include="BatchDialog.cpp">
<Filter>UI</Filter>
</ClCompile>
<ClCompile Include="Batch\ListCtrlEx.cpp">
<Filter>UI\Controls</Filter>
</ClCompile>
<ClCompile Include="Batch\TextProgressCtrl.cpp">
<Filter>UI\Controls</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="LS_launcher.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="BackupDialog.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="AddIPDialog.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="cEncrypt.h">
<Filter>Network</Filter>
</ClInclude>
<ClInclude Include="ClientSocket.h">
<Filter>Network</Filter>
</ClInclude>
<ClInclude Include="cPacket.h">
<Filter>Network</Filter>
</ClInclude>
<ClInclude Include="InstallDialog.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="LauncherTabCtrl.h">
<Filter>UI\Controls</Filter>
</ClInclude>
<ClInclude Include="LauncherListCtrl.h">
<Filter>UI\Controls</Filter>
</ClInclude>
<ClInclude Include="cFile.h">
<Filter>Utility</Filter>
</ClInclude>
<ClInclude Include="cBuffer.h">
<Filter>Utility</Filter>
</ClInclude>
<ClInclude Include="MD5.h">
<Filter>Utility</Filter>
</ClInclude>
<ClInclude Include="ServerDialog.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="LS_launcherDlg.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="..\common\Protocol.h">
<Filter>Include</Filter>
</ClInclude>
<ClInclude Include="Server.h">
<Filter>Include</Filter>
</ClInclude>
<ClInclude Include="Resource.h">
<Filter>UI\Resource</Filter>
</ClInclude>
<ClInclude Include="Utility.h">
<Filter>Utility</Filter>
</ClInclude>
<ClInclude Include="WinMessage.h">
<Filter>Include</Filter>
</ClInclude>
<ClInclude Include="cHeader.h">
<Filter>Network</Filter>
</ClInclude>
<ClInclude Include="MsgBox.h" />
<ClInclude Include="Minidump\File.h">
<Filter>Minidump</Filter>
</ClInclude>
<ClInclude Include="Minidump\MiniDump.h">
<Filter>Minidump</Filter>
</ClInclude>
<ClInclude Include="Singleton.h" />
<ClInclude Include="UserDefine.h" />
<ClInclude Include="Timer.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="PerfMonDlg.h">
<Filter>UI\Monitor</Filter>
</ClInclude>
<ClInclude Include="MonitorCtrl.h">
<Filter>UI\Monitor</Filter>
</ClInclude>
<ClInclude Include="ProcessCtrl.h">
<Filter>UI\Monitor</Filter>
</ClInclude>
<ClInclude Include="Batch\Batch.h">
<Filter>Batch</Filter>
</ClInclude>
<ClInclude Include="Batch\BatchCompileDefine.h">
<Filter>Batch</Filter>
</ClInclude>
<ClInclude Include="Batch\BatchManager.h">
<Filter>Batch</Filter>
</ClInclude>
<ClInclude Include="Batch\BatchScanner.h">
<Filter>Batch\Scanner</Filter>
</ClInclude>
<ClInclude Include="Batch\FileReader.h">
<Filter>Batch\File</Filter>
</ClInclude>
<ClInclude Include="Batch\PlayCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="Batch\InstallCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="Batch\StopCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="Batch\SyncCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="Batch\UninstallCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="OptionManager.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="Batch\QuitCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="Batch\BaseCommand.h">
<Filter>Batch\Command</Filter>
</ClInclude>
<ClInclude Include="BatchDialog.h">
<Filter>UI</Filter>
</ClInclude>
<ClInclude Include="Batch\ListCtrlEx.h">
<Filter>UI\Controls</Filter>
</ClInclude>
<ClInclude Include="Batch\TextProgressCtrl.h">
<Filter>UI\Controls</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
<None Include="res\bitmap1.bmp">
<Filter>UI\Resource</Filter>
</None>
<None Include="res\demonOn.bmp">
<Filter>UI\Resource</Filter>
</None>
<None Include="res\off.bmp">
<Filter>UI\Resource</Filter>
</None>
<None Include="res\on.bmp">
<Filter>UI\Resource</Filter>
</None>
<None Include="res\serviceOn.bmp">
<Filter>UI\Resource</Filter>
</None>
<None Include="res\LS_launcher.rc2">
<Filter>UI\Resource</Filter>
</None>
<None Include="res\LS_launcher.ico">
<Filter>UI\Resource</Filter>
</None>
</ItemGroup>
<ItemGroup>
<Filter Include="UI">
<UniqueIdentifier>{5f961548-3b59-4c72-bb9e-5b1c5ee20d43}</UniqueIdentifier>
</Filter>
<Filter Include="UI\Resource">
<UniqueIdentifier>{3d73a0c1-09c9-463c-8cf5-c850b395bec4}</UniqueIdentifier>
</Filter>
<Filter Include="Network">
<UniqueIdentifier>{d6c719ce-3903-445a-bbab-63ea93fec6f7}</UniqueIdentifier>
</Filter>
<Filter Include="Utility">
<UniqueIdentifier>{e4960be1-81e8-40ac-9ba5-9c96aa2080e4}</UniqueIdentifier>
</Filter>
<Filter Include="Include">
<UniqueIdentifier>{84f5aa68-0ad8-4a07-afe3-1ec04691124f}</UniqueIdentifier>
</Filter>
<Filter Include="UI\Monitor">
<UniqueIdentifier>{627426c3-1126-4fcb-8484-1c3ea221b07c}</UniqueIdentifier>
</Filter>
<Filter Include="Minidump">
<UniqueIdentifier>{e765722a-2bc1-435b-8c53-97b855c77e9b}</UniqueIdentifier>
</Filter>
<Filter Include="UI\Controls">
<UniqueIdentifier>{69dbf32e-5656-4ade-a02f-bbdebfe9fe37}</UniqueIdentifier>
</Filter>
<Filter Include="Batch">
<UniqueIdentifier>{34a07e64-53ce-48eb-9740-f48b2c0f30de}</UniqueIdentifier>
</Filter>
<Filter Include="Batch\Scanner">
<UniqueIdentifier>{0d4623b9-2c89-4492-8d88-e2a1a329be84}</UniqueIdentifier>
</Filter>
<Filter Include="Batch\Command">
<UniqueIdentifier>{61fa37ec-6f71-498d-9eab-3c8be376d3cc}</UniqueIdentifier>
</Filter>
<Filter Include="Batch\File">
<UniqueIdentifier>{a093ba4d-c323-4b33-83d6-12de248650d0}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="LS_launcher.rc">
<Filter>UI\Resource</Filter>
</ResourceCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,786 @@
// LS_launcherDlg.cpp : implementation file
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "LS_launcherDlg.h"
#include "AddIPDialog.h"
#include "WinMessage.h"
#include "Timer.h"
#include "cFile.h"
#include <string>
const int TIME_MONITOR = 1000 * 2;
const int TIME_WATCHDOG = 1000 * 30;
const int TIME_REFRESH = 2000;
const int TIME_BATCH_WAIT = 1000;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLS_launcherDlg dialog
extern void Tokenize(const CString& str, TOKENS& tokens, const CString& delimiters);
BOOL g_spread = FALSE;
std::vector<CLS_launcherDlg*> g_launchers;
CLS_launcherDlg::CLS_launcherDlg(const TCHAR* parameter, CWnd* pParent /*=NULL*/)
: CDialog(CLS_launcherDlg::IDD, pParent), m_loaded(FALSE), m_tabCurFocus(0), m_fileName(_T("")), m_batchName(_T(""))
{
m_parameter = parameter;
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CLS_launcherDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TAB_SERVERS, m_serverTabs);
DDX_Control(pDX, IDC_CHECK_WATCHDOG, m_chk_watchdog);
DDX_Control(pDX, IDC_CHECK_APPLYALL, m_chk_applyall);
DDX_Control(pDX, IDC_CHECK_RECURSIVE, m_chk_recusive);
DDX_Control(pDX, IDC_CHECK_CONSOLE, m_chk_console);
DDX_Control(pDX, IDC_CHECK_Monitor, m_chk_monitor);
}
BEGIN_MESSAGE_MAP(CLS_launcherDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_WM_DROPFILES()
ON_MESSAGE(IDC_SERVICE_ADD_IP, OnAddIP)
ON_MESSAGE(IDC_SERVICE_DELETE_IP, OnDeleteIP)
ON_MESSAGE(IDC_SERVICE_SPREAD, OnSpread)
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB_SERVERS, &CLS_launcherDlg::OnTcnSelchangeTabServers)
ON_BN_CLICKED(IDC_CHECK_WATCHDOG, &CLS_launcherDlg::OnBnClickedCheckWatchdog)
ON_BN_CLICKED(IDC_CHECK_APPLYALL, &CLS_launcherDlg::OnBnClickedCheckApplyall)
ON_WM_TIMER()
ON_BN_CLICKED(IDC_CHECK_RECURSIVE, &CLS_launcherDlg::OnBnClickedCheckRecursive)
ON_BN_CLICKED(IDC_CHECK_CONSOLE, &CLS_launcherDlg::OnBnClickedCheckConsole)
ON_BN_CLICKED(IDC_CHECK_Monitor, &CLS_launcherDlg::OnBnClickedCheckMonitor)
ON_WM_WINDOWPOSCHANGING()
END_MESSAGE_MAP()
// CLS_launcherDlg message handlers
BOOL CLS_launcherDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
if(m_parameter.GetLength() > 2)
{
Load(m_parameter);
}
m_serverTabs.CreatePopup();
LoadOption();
BeginBatches();
SetTimer(TIMER_REFRESH, TIME_REFRESH, 0);
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CLS_launcherDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
BOOL IsAvailable(const int limitCount, const int currentCount)
{
if(currentCount < limitCount)
return FALSE;
else
return TRUE;
}
void CLS_launcherDlg::ConsoleStart()
{
AllocConsole();
freopen("CONOUT$", "wt", stdout);
}
void CLS_launcherDlg::ConsoleStop()
{
if(m_batchManager.IsConsoleMode())
FreeConsole();
}
BOOL CLS_launcherDlg::ParseToken(TOKENS &tokens)
{
//BatchManager.h memeber m_batchType true == consoleType
int tokenCount = tokens.size();
int limitCount = 1;
int tokenIndex =0;
if(_tcscmp(tokens[tokenIndex].GetBuffer(0), _T("-c")) == 0)
{
ConsoleStart();
m_batchManager.SetConsoleMode(TRUE);
++tokenIndex;
++limitCount;
}
if(!IsAvailable(limitCount, tokenCount))
return FALSE;
else
{
m_fileName = tokens[tokenIndex++];
if(limitCount == tokenCount)
return TRUE;
}
m_batchName = tokens[tokenIndex];
return TRUE;
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CLS_launcherDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
BOOL CLS_launcherDlg::Load(const TCHAR* filePath)
{
// TODO: Add extra initialization here
CString temp = filePath;
TOKENS tokens;
int tokenNum = 0;
Tokenize(temp, tokens, _T(" "));
if(tokens.empty())
return FALSE;
if(!ParseToken(tokens))
return FALSE;
if(!ReadFile(m_fileName.GetBuffer()))
return FALSE;
if(!ParseServer())
return FALSE; //서버 연결.
InitTab();
if( !m_batchName.IsEmpty() )
{
if(!m_batchManager.AddBatchFile(m_batchName.GetBuffer(), this ) )
return FALSE;
}
m_loaded = TRUE;
return TRUE;
}
BOOL CLS_launcherDlg::LoadOption()
{
OPTION()->LoadOptions();
if(OPTION()->GetOption(OPTION_MONITOR))
{
m_chk_monitor.SetCheck(1);
SetTimer(TIMER_MONITOR, TIME_MONITOR, 0);
}
if(OPTION()->GetOption(OPTION_RECURSIVE))
{
m_chk_recusive.SetCheck(1);
}
if(OPTION()->GetOption(OPTION_CONSOLE))
{
m_chk_console.SetCheck(1);
}
return TRUE;
}
BOOL CLS_launcherDlg::ReadFile(const TCHAR* filePath)
{
cFileReader file;
if(file.Open(filePath))
{
DWORD length = file.GetFileSize();
BYTE* buffer = new BYTE[length+1];
file.Read(buffer, length);
buffer[length] = NULL;
file.Close();
switch(file.GetBOM())
{
case cFile::FILEFORMAT_ANSI :
m_buffer = (char*)buffer;
break;
case cFile::FILEFORMAT_UNICODE_LE :
m_buffer = (TCHAR*)buffer;
break;
default :
break;
}
delete []buffer;
_tprintf(_T("fileName : %s\n\n"), m_fileName);
return TRUE;
}
if(m_batchManager.IsConsoleMode())
{
_tprintf(_T("Batch type error('-c' is only possible) or Ip Text fail\n"));
}
return FALSE;
}
BOOL CLS_launcherDlg::SaveFile()
{
cFileWriter file;
if(file.Open(m_fileName))
{
CString szServerInfo = GetServerInfo();
file.WriteFormat(_T("%s\r\n"), szServerInfo);
file.Close();
return TRUE;
}
return FALSE;
}
CString CLS_launcherDlg::GetServerInfo()
{
CString szServerInfo;
CString name, ip, port;
CServerInfo* serverInfo = NULL;
SERVERINFO_LIST::iterator it;
for(it = m_serverInfos.begin() ; it != m_serverInfos.end() ; ++it)
{
serverInfo = *it;
if(serverInfo)
{
TCHAR tempPort[100] = {0};
name.SetString(serverInfo->m_name);
ip.SetString(serverInfo->m_IP);
_itot_s(serverInfo->m_port, tempPort, 10);
port.SetString(tempPort);
szServerInfo.Append(name);
szServerInfo.Append(_T(", "));
szServerInfo.Append(ip);
szServerInfo.Append(_T(", "));
szServerInfo.Append(port);
szServerInfo.Append(_T("\r\n"));
}
}
return szServerInfo;
}
int CLS_launcherDlg::GetTabDialogCount()
{
return m_serverTabs.GetCount();
}
CServerDialog* CLS_launcherDlg::GetTabDialog(int index)
{
return m_serverTabs.GetDialog(index);
}
BOOL CLS_launcherDlg::ParseServer()
{
CString buffer = m_buffer;
TOKENS lines;
Tokenize(buffer, lines, _T("\r\n"));
if(lines.size() == 0)
return FALSE;
m_serverInfos.clear();
TOKENS tokens;
CString name, IP;
for(UINT i = 0 ; i < lines.size() ; i++)
{
tokens.clear();
Tokenize(lines[i], tokens, _T(","));
if(tokens.size() != 3)
return TRUE;
name = tokens[0];
IP = tokens[1];
name.Trim();
IP.Trim();
if(g_spread && (g_launchers.size() != i))
{
continue;
}
CServerInfo* serverInfo = new CServerInfo;
serverInfo->m_name = name;
serverInfo->m_IP = IP;
serverInfo->m_port = _tstoi(tokens[2]);
m_serverInfos.push_back(serverInfo);
}
return TRUE;
}
BOOL CLS_launcherDlg::InitTab()
{
CServerInfo* serverInfo = NULL;
SERVERINFO_LIST::iterator it;
for(it = m_serverInfos.begin() ; it != m_serverInfos.end() ; ++it)
{
serverInfo = *it;
if(serverInfo)
m_serverTabs.AddTab(serverInfo->m_name, serverInfo->m_IP, serverInfo->m_port);
}
// 포커스 초기화 0으로..
m_serverTabs.ShowTab(m_serverInfos.size() -1, FALSE);
m_serverTabs.ShowTab(0, TRUE);
return TRUE;
}
void CLS_launcherDlg::DeleteServerInfo(CString name)
{
CServerInfo* serverInfo = NULL;
SERVERINFO_LIST::iterator it;
for(it = m_serverInfos.begin(); it != m_serverInfos.end(); ++it)
{
serverInfo = *it;
if(serverInfo)
{
if(serverInfo->m_name == name)
{
m_serverInfos.remove(serverInfo);
delete serverInfo;
serverInfo = NULL;
break;
}
}
}
}
void CLS_launcherDlg::Quit()
{
if(m_batchManager.IsConsoleMode())
{
CWnd* wnd=AfxGetMainWnd();
if(wnd)
{
wnd->PostMessageW(WM_CLOSE);
}
}
}
BOOL CLS_launcherDlg::PreTranslateMessage(MSG* pMsg)
{
switch(pMsg->message)
{
case WM_KEYDOWN :
{
if(VK_RETURN == pMsg->wParam) return FALSE;
if(VK_ESCAPE == pMsg->wParam) return FALSE;
if(VK_F5 == pMsg->wParam)
{
TRACE(_T("global F5\n"));
PostMessageToAll(NULL, ECOMMAND::REFRESH);
return FALSE;
}
break;
}
}
return CDialog::PreTranslateMessage(pMsg);
}
void CLS_launcherDlg::OnDropFiles(HDROP hDropInfo)
{
if(!m_loaded)
{
TCHAR pathName[512];
int files = DragQueryFile(hDropInfo, 0xFFFFFFFF, pathName, _countof(pathName));
if(files > 0)
{
DragQueryFile(hDropInfo, 0, pathName, _countof(pathName));
}
m_parameter = pathName;
if(!Load(m_parameter))
{
MessageBox(_T("file error"), _T("error"), MB_OK);
return;
}
CDialog::OnDropFiles(hDropInfo);
}
}
LRESULT CLS_launcherDlg::OnAddIP(WPARAM wParam, LPARAM lParam)
{
CAddIPDialog dlg;
if(IDOK == dlg.DoModal())
{
CString name = dlg.GetTapName().GetBuffer();
CString ip = dlg.GetIP().GetBuffer();
m_serverTabs.AddTab( name, ip, dlg.GetPort() );
AddServerInfo(name, ip, dlg.GetPort());
// 파일 저장.
SaveFile();
}
return 0;
}
LRESULT CLS_launcherDlg::OnDeleteIP(WPARAM wParam, LPARAM lParam)
{
// 해당 탭 삭제.
m_serverTabs.DeleteTab(m_tabCurFocus);
SaveFile();
return 0;
}
LRESULT CLS_launcherDlg::OnSpread(WPARAM wParam, LPARAM lParam)
{
if(g_spread)
{
// 모으다
g_spread = FALSE;
int count = g_launchers.size();
for(std::vector<CLS_launcherDlg*>::iterator it = g_launchers.begin() ; it != g_launchers.end() ; ++it)
{
CLS_launcherDlg* dlg = *it;
if(dlg)
{
dlg->ShowWindow(SW_HIDE);
}
}
ShowMainDlg(SW_SHOW);
}
else
{
// 퍼트리다
g_spread = TRUE;
int cx = 0;
int cy = 0;
CRect rect;
GetWindowRect(rect);
int cxIcon = GetSystemMetrics(SM_CXFULLSCREEN);
int cyIcon = GetSystemMetrics(SM_CYFULLSCREEN);
if(g_launchers.size() == 0)
{
for(uint32 i = 0 ; i < m_serverInfos.size() ; i++)
{
CLS_launcherDlg* dlg = new CLS_launcherDlg(m_parameter);
dlg->Create(IDD_SERVICELAUNCHER_DIALOG, this);
dlg->m_chk_applyall.SetCheck(this->m_chk_applyall.GetCheck());
dlg->m_chk_console.SetCheck(this->m_chk_console.GetCheck());
dlg->m_chk_recusive.SetCheck(this->m_chk_recusive.GetCheck());
dlg->m_chk_watchdog.SetCheck(this->m_chk_watchdog.GetCheck());
UINT style = GetWindowLong(m_hWnd, GWL_STYLE);
style = style | WS_OVERLAPPEDWINDOW;
style = style & ~WS_CHILD;
SetWindowLong(m_hWnd, GWL_STYLE, style);
g_launchers.push_back(dlg);
}
}
ShowMainDlg(SW_HIDE);
for(std::vector<CLS_launcherDlg*>::iterator it = g_launchers.begin() ; it != g_launchers.end() ; ++it)
{
CLS_launcherDlg* dlg = *it;
if(dlg)
{
dlg->SetWindowPos(&CWnd::wndBottom, cx, cy, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
dlg->ShowWindow(SW_SHOW);
//cx += rect.Width();
cx += 90;
if((cx+rect.Width()) > cxIcon)
{
cx = 0;
//cy += rect.Height();
cy += 70;
if((cy+rect.Height()) > cyIcon)
{
cx = 90;
cy = 70;
}
}
}
}
}
return 0;
}
void CLS_launcherDlg::AddServerInfo(CString title, CString IP, UINT port)
{
CServerInfo* serverInfo = new CServerInfo;
serverInfo->m_name = title;
serverInfo->m_IP = IP;
serverInfo->m_port = port;
m_serverInfos.push_back(serverInfo);
}
void CLS_launcherDlg::ShowMainDlg(int nCmdShow)
{
CLS_launcherDlg* dlg = static_cast<CLS_launcherDlg*>( AfxGetMainWnd() );
if(dlg)
{
dlg->ShowWindow(nCmdShow);
}
}
void CLS_launcherDlg::PostMessageToAll(WPARAM wParam, LPARAM lParam)
{
for(unsigned int i = 0 ; i < m_serverTabs.m_dialogs.size() ; ++i)
{
m_serverTabs.m_dialogs[i]->PostMessage(WM_AUTOMATIC, wParam, lParam);
}
}
void CLS_launcherDlg::BeginBatches()
{
if(!m_batchManager.IsConsoleMode() && !m_batchName.IsEmpty() && m_batchManager.HaveBaches())
{
m_batchManager.ShowDialog();
}
SetTimer( TIMER_BATCHSTARTCHECK, TIME_BATCH_WAIT, 0 );
}
void CLS_launcherDlg::EndBatches()
{
KillTimer( TIMER_BATCHSTARTCHECK );
KillTimer( TIMER_BATCHCONTINUECHECK );
m_batchManager.End();
}
void CLS_launcherDlg::BatchStartCheck()
{
// 타이머 먼저 죽이고
if( m_serverTabs.IsAllReady() )
{
KillTimer( TIMER_BATCHSTARTCHECK );
m_batchManager.ResetExecute();
if( m_batchManager.Execute() )
{
// 모두 성공
m_batchManager.EndProgress(100, _T("completed"), TRUE);
}
else
{
if( m_batchManager.GetCurrentState() != CST_WAITING )
{
m_batchManager.EndProgress(0, _T("failed"), TRUE);
}
}
}
//else
//{
// m_batchManager.Error(_T("Server connect"), _T("failed"));
//}
}
void CLS_launcherDlg::BatchContinueCheck()
{
if( m_batchManager.CheckContinue() )
{
KillTimer( TIMER_BATCHCONTINUECHECK );
m_batchManager.EndProgress(100, _T("completed"),FALSE);
m_batchManager.Next();
if( m_batchManager.Execute() )
{
// 모두 성공
m_batchManager.EndProgress(100, _T("completed"), TRUE);
return;
}
}
if( m_batchManager.GetCurrentState() != CST_WAITING )
{
// error
m_batchManager.EndProgress(0, _T("failed"), FALSE);
}
}
void CLS_launcherDlg::BatchWait()
{
KillTimer( TIMER_BATCHCONTINUECHECK );
SetTimer( TIMER_BATCHCONTINUECHECK, TIME_BATCH_WAIT, 0 );
}
void CLS_launcherDlg::BatchProgress(int progress)
{
m_batchManager.DoingProgress( progress );
}
void CLS_launcherDlg::OnTcnSelchangeTabServers(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
*pResult = 0;
}
void CLS_launcherDlg::OnBnClickedCheckWatchdog()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
OPTION()->SetOption(OPTION_WATCHDOG, m_chk_watchdog.GetCheck());
if(OPTION()->GetOption(OPTION_WATCHDOG))
{
SetTimer(TIMER_WATCHDOG, TIME_WATCHDOG, 0);
}
else
{
KillTimer(TIMER_WATCHDOG);
}
}
void CLS_launcherDlg::OnBnClickedCheckMonitor()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
OPTION()->SetOption(OPTION_MONITOR, m_chk_monitor.GetCheck());
if(OPTION()->GetOption(OPTION_MONITOR))
{
SetTimer(TIMER_MONITOR, TIME_MONITOR, 0);
}
else
{
KillTimer(TIMER_MONITOR);
}
}
void CLS_launcherDlg::OnBnClickedCheckApplyall()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
if(m_chk_applyall.GetCheck() == TRUE)
{
if(TRUE == MessageBox(_T("Are you sure? Check ApplyAll"), _T("Warning"), MB_OKCANCEL))
{
OPTION()->SetOption(OPTION_APPLYALL, TRUE);
}
else
{
OPTION()->SetOption(OPTION_APPLYALL, FALSE);
m_chk_applyall.SetCheck(FALSE);
}
}
else
OPTION()->SetOption(OPTION_APPLYALL, FALSE);
}
void CLS_launcherDlg::OnBnClickedCheckRecursive()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
OPTION()->SetOption(OPTION_RECURSIVE, m_chk_recusive.GetCheck());
}
void CLS_launcherDlg::OnBnClickedCheckConsole()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
OPTION()->SetOption(OPTION_CONSOLE, m_chk_console.GetCheck());
}
void CLS_launcherDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
switch(nIDEvent)
{
case TIMER_REFRESH :
{
PostMessageToAll(NULL, ECOMMAND::REFRESH);
}
break;
case TIMER_WATCHDOG :
{
PostMessageToAll(OPTION()->GetOption(OPTION_WATCHDOG), ECOMMAND::WATCHDOG);
}
break;
case TIMER_MONITOR :
{
PostMessageToAll(OPTION()->GetOption(OPTION_MONITOR), ECOMMAND::MONITOR);
}
break;
case TIMER_BATCHSTARTCHECK:
{
BatchStartCheck();
}
break;
case TIMER_BATCHCONTINUECHECK:
{
BatchContinueCheck();
}
break;
}
CDialog::OnTimer(nIDEvent);
}
void CLS_launcherDlg::OnWindowPosChanging(WINDOWPOS* lpwndpos)
{
CDialog::OnWindowPosChanging(lpwndpos);
// TODO: 여기에 메시지 처리기 코드를 추가합니다.
if(m_batchManager.IsConsoleMode())
{
lpwndpos->flags &= ~SWP_SHOWWINDOW;
}
else
{
lpwndpos->flags |= SWP_SHOWWINDOW;
}
}
@@ -0,0 +1,122 @@
// LS_launcherDlg.h : header file
//
#pragma once
#include <list>
#include <vector>
#include "afxcmn.h"
#include "LauncherTabCtrl.h"
#include "Server.h"
#include "afxwin.h"
#include "Utility.h"
#include "Batch/BatchManager.h"
class CServerDialog;
// CLS_launcherDlg dialog
class CLS_launcherDlg : public CDialog
{
// Construction
public:
CLS_launcherDlg(const TCHAR* parameter, CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_SERVICELAUNCHER_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
public:
UINT GetTabCurFocus() { return m_tabCurFocus; }
void SetTabCurFocus( UINT focus) { m_tabCurFocus = focus; }
void SetLoaded(BOOL b) { m_loaded = b;}
void DeleteServerInfo(CString name);
CString GetServerInfo();
CBatchManager* GetBatchManager() { return &m_batchManager;}
int GetTabDialogCount();
CServerDialog* GetTabDialog(int index);
protected:
BOOL Load(const TCHAR* filePath);
BOOL LoadOption();
BOOL ReadFile(const TCHAR* filePath);
BOOL SaveFile();
BOOL ParseServer();
BOOL ParseToken(TOKENS &tokens);
BOOL InitTab();
void AddServerInfo(CString title, CString IP, UINT port);
void ShowMainDlg(int nCmdShow);
void PostMessageToAll(WPARAM wParam, LPARAM lParam);
protected:
void BeginBatches();
void EndBatches();
void BatchStartCheck();
void BatchContinueCheck();
public:
void BatchWait();
void BatchProgress(int progress);
void ConsoleStart();
void ConsoleStop();
void Quit();
protected:
BOOL m_loaded;
CString m_buffer;
UINT m_tabCurFocus;
CString m_parameter;
CString m_fileName;
CString m_batchName;
typedef std::list<CServerInfo*> SERVERINFO_LIST;
SERVERINFO_LIST m_serverInfos;
CBatchManager m_batchManager;
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CLauncherTabCtrl m_serverTabs;
CButton m_chk_watchdog;
CButton m_chk_applyall;
CButton m_chk_monitor;
CButton m_chk_recusive;
CButton m_chk_console;
virtual BOOL PreTranslateMessage(MSG* pMsg);
afx_msg void OnDropFiles(HDROP hDropInfo);
afx_msg void OnTcnSelchangeTabServers(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedCheckWatchdog();
afx_msg void OnBnClickedCheckApplyall();
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnBnClickedCheckRecursive();
afx_msg void OnBnClickedCheckConsole();
afx_msg LRESULT OnAddIP(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnDeleteIP(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnSpread(WPARAM wParam, LPARAM lParam);
afx_msg void OnBnClickedCheckMonitor();
afx_msg void OnWindowPosChanging(WINDOWPOS* lpwndpos);
};
@@ -0,0 +1,164 @@
// LauncherListCtrl.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "LauncherListCtrl.h"
#include "WinMessage.h"
// CLauncherListCtrl
IMPLEMENT_DYNAMIC(CLauncherListCtrl, CListCtrl)
CLauncherListCtrl::CLauncherListCtrl()
{
}
CLauncherListCtrl::~CLauncherListCtrl()
{
}
BEGIN_MESSAGE_MAP(CLauncherListCtrl, CListCtrl)
ON_NOTIFY_REFLECT(NM_RCLICK, &CLauncherListCtrl::OnNMRClick)
END_MESSAGE_MAP()
// CLauncherListCtrl 메시지 처리기입니다.
void CLauncherListCtrl::CreatePopup()
{
// 팝업메뉴
m_menu.CreatePopupMenu();
CString menu;
menu = _T("Play Service(A)");
m_menu.AppendMenu(MF_STRING, IDC_SERVICE_PLAY, (LPCTSTR)menu);
menu = _T("Stop Service(A)");
m_menu.AppendMenu(MF_STRING, IDC_SERVICE_STOP, (LPCTSTR)menu);
//m_menu.AppendMenu(MF_SEPARATOR);
//menu = _T("Play Console");
//m_menu.AppendMenu(MF_STRING, IDC_SERVICE_PLAY_CONSOLE, (LPCTSTR)menu);
//menu = _T("Stop Console");
//m_menu.AppendMenu(MF_STRING, IDC_SERVICE_STOP_CONSOLE, (LPCTSTR)menu);
m_menu.AppendMenu(MF_SEPARATOR);
menu = _T("Uninstall");
m_menu.AppendMenu(MF_STRING, IDC_SERVICE_UNINSTALL, (LPCTSTR)menu);
}
int CLauncherListCtrl::GetSelectedIndex()
{
int index = -1;
for(int i = 0; i < GetItemCount(); i++)
{
if(LVIS_SELECTED == GetItemState(i, LVIS_SELECTED))
{
index = i;
break;
}
}
return index;
}
void CLauncherListCtrl::Save()
{
int index = -1;
for(int i = 0; i < GetItemCount(); i++)
{
if(LVIS_SELECTED == GetItemState(i, LVIS_SELECTED))
{
m_currentIndex = i;
break;
}
}
m_topIndex = GetTopIndex();
}
void CLauncherListCtrl::Restore()
{
if(0 != m_topIndex)
{
EnsureVisible(GetItemCount()-1, FALSE);
EnsureVisible(m_topIndex, FALSE);
}
if(-1 != m_currentIndex)
{
if(m_currentIndex < GetItemCount())
{
SetItemState(m_currentIndex, LVIS_SELECTED, LVIS_SELECTED );
}
}
}
void CLauncherListCtrl::OnNMRClick(NMHDR *pNMHDR, LRESULT *pResult)
{
CPoint pos;
GetCursorPos(&pos);
int index = GetSelectedIndex();
if(index != -1)
{
// 마우스 위치에 팝업메뉴를 출력한다.
m_menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pos.x, pos.y, this);
}
*pResult = 0;
}
BOOL CLauncherListCtrl::OnCommand(WPARAM wParam, LPARAM lParam)
{
int index = -1;
for(int i = 0; i < GetItemCount(); i++)
{
if(LVIS_SELECTED == GetItemState(i, LVIS_SELECTED))
{
index = i;
break;
}
}
switch(wParam)
{
case IDC_SERVICE_MONITOR :
GetParent()->SendMessage(IDC_SERVICE_MONITOR, index, 0);
break;
case IDC_SERVICE_PLAY :
GetParent()->SendMessage(IDC_SERVICE_PLAY, index, 0);
break;
case IDC_SERVICE_STOP :
GetParent()->SendMessage(IDC_SERVICE_STOP, index, 0);
break;
case IDC_SERVICE_PLAY_CONSOLE :
GetParent()->SendMessage(IDC_SERVICE_PLAY_CONSOLE, index, 0);
break;
case IDC_SERVICE_STOP_CONSOLE :
GetParent()->SendMessage(IDC_SERVICE_STOP_CONSOLE, index, 0);
break;
case IDC_SERVICE_UNINSTALL :
GetParent()->SendMessage(IDC_SERVICE_UNINSTALL, index, 0);
break;
}
return CListCtrl::OnCommand(wParam, lParam);
}
@@ -0,0 +1,38 @@
#pragma once
// CLauncherListCtrl
class CLauncherListCtrl : public CListCtrl
{
DECLARE_DYNAMIC(CLauncherListCtrl)
public:
CLauncherListCtrl();
virtual ~CLauncherListCtrl();
public:
void CreatePopup();
int GetSelectedIndex();
void Save();
void Restore();
protected:
CMenu m_menu;
int m_topIndex;
int m_currentIndex;
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnNMRClick(NMHDR *pNMHDR, LRESULT *pResult);
protected:
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
};
@@ -0,0 +1,330 @@
// LauncherTabCtrl.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "LS_launcher.h"
#include "LauncherTabCtrl.h"
#include "WinMessage.h"
#include "LS_launcherDlg.h"
// CLauncherTabCtrl
IMPLEMENT_DYNAMIC(CLauncherTabCtrl, CTabCtrl)
CLauncherTabCtrl::CLauncherTabCtrl()
{
m_tabIndex = 0;
}
CLauncherTabCtrl::~CLauncherTabCtrl()
{
}
BEGIN_MESSAGE_MAP(CLauncherTabCtrl, CTabCtrl)
ON_WM_LBUTTONUP()
ON_WM_RBUTTONUP()
END_MESSAGE_MAP()
// CLauncherTabCtrl 메시지 처리기입니다.
void CLauncherTabCtrl::Init()
{
m_tabIndex = 0;
CServerDialog* dlg;
int tapCount = 0;
for(SERVER_DIALOGS::iterator it = m_dialogs.begin() ; it != m_dialogs.end() ; ++it)
{
dlg = it->second;
delete dlg;
this->DeleteItem(tapCount++);
}
m_dialogs.clear();
for(SERVER_DIALOGS::iterator it = m_dialogs.begin() ; it != m_dialogs.end() ; ++it)
{
dlg = it->second;
delete dlg;
this->DeleteItem(tapCount++);
}
m_dialogs.clear();
// 이작업을 해주어야 다시 로드(탭추가)를 할 수 있다.
CLS_launcherDlg* dlg2 = static_cast<CLS_launcherDlg*>( AfxGetMainWnd() );
dlg2->SetLoaded(FALSE);
SetMinTabWidth(100);
}
void CLauncherTabCtrl::AddTab(CString& title, CString& IP, UINT port)
{
this->InsertItem(GetItemCount(), title);
// 다이얼로그 처리
if(GetItemCount() == 1) // 최초 한번만 실행
{
CRect tabRect, itemRect;
GetClientRect(&tabRect);
GetItemRect(0, &itemRect);
m_x = itemRect.left;
m_y = itemRect.bottom+1;
m_width = tabRect.right - itemRect.left-1;
m_height = tabRect.bottom - m_y -1;
}
CServerDialog* dlg = new CServerDialog(this);
dlg->Create(IDD_SERVERINFO_DIALOG, this);
dlg->SetWindowPos(&wndTop, m_x, m_y, m_width, m_height, SWP_HIDEWINDOW);
UINT index = GetItemCount() - 1;
RECT rect;
this->GetItemRect(index, &rect);
dlg->Init(title, IP, port, rect);
m_dialogs[index] = dlg;
// 포커스 초기화 0으로..
SetCurSel(index);
SetFocus(index);
}
void CLauncherTabCtrl::DeleteTab(const UINT focus)
{
CServerDialog* dlg = GetDialog(focus);
if(!dlg) return;
this->DeleteItem(focus);
// 탭Item값에 맞추어서 리스트 재조정.
TapRenewal(focus);
// 서버 정보(m_serverInfos) 삭제
DeleteServerInfo(dlg->GetTitle());
delete dlg;
dlg = NULL;
}
void CLauncherTabCtrl::DeleteServerInfo(CString name)
{
CLS_launcherDlg* dlg = static_cast<CLS_launcherDlg*>( AfxGetMainWnd() );
dlg->DeleteServerInfo(name);
}
void CLauncherTabCtrl::TapRenewal( UINT focus )
{
SERVER_DIALOGS::iterator it = m_dialogs.find(focus);
if(it != m_dialogs.end())
{
m_dialogs.erase(it);
}
// 탭Item값에 맞추어서 리스트 재조정.
UINT count=0;
UINT index = 0;
RECT rect;
CServerDialog* dlg = NULL;
SERVER_DIALOGS dialogs;
for(it = m_dialogs.begin() ; it != m_dialogs.end() ; ++it)
{
index = count++;
dlg = dialogs[index] = it->second;
if(dlg)
{ // 탭 위치 재조정
GetItemRect(index, &rect);
dlg->SetTabRect(rect);
}
}
m_dialogs.clear();
m_dialogs = dialogs;
// 포커스 초기화 0으로..
SetCurSel(0);
SetFocus(0);
// 탭이 다 지워졌다면 초기화를 해준다.
if(m_dialogs.empty()) Init();
}
void CLauncherTabCtrl::SetFocus(const UINT index)
{
if(GetTabIndex() != index)
{
ShowTab(GetTabIndex(), FALSE);
ShowTab(GetCurFocus(), TRUE);
}
else
{
ShowTab(GetTabIndex(), TRUE);
}
}
void CLauncherTabCtrl::UserFocus(const UINT index)
{
if(GetTabIndex() != index)
{
ShowTab(GetTabIndex(), FALSE);
ShowTab(index, TRUE);
}
else
{
ShowTab(GetTabIndex(), TRUE);
}
}
void CLauncherTabCtrl::ShowTab(const UINT index, const BOOL show)
{
CServerDialog* dlg = GetDialog(index);
if(!dlg) return;
if(show)
{
dlg->ShowWindow(SW_SHOW);
dlg->SetFocus();
SetCurSel(index);
m_tabIndex = index;
TCHAR buffer[256] = {0};
TCITEM item;
item.mask = TCIF_TEXT;
item.pszText = buffer;
item.cchTextMax = sizeof(buffer);
this->GetItem(m_tabIndex, &item);
CLS_launcherDlg* parentDlg = (CLS_launcherDlg*)(this->GetParent());
parentDlg->SetWindowText(buffer);
}
else
{
dlg->ShowWindow(SW_HIDE);
}
}
CServerDialog* CLauncherTabCtrl::GetDialog(const int index)
{
SERVER_DIALOGS::iterator it = m_dialogs.find(index);
if(it != m_dialogs.end())
{
return it->second;
}
return NULL;
}
void CLauncherTabCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
SetFocus(GetCurFocus());
CTabCtrl::OnLButtonUp(nFlags, point);
}
void CLauncherTabCtrl::OnRButtonUp(UINT nFlags, CPoint point)
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
UINT choiceTabindex = GetTabFocus(point.x, point.y);
SetCurSel(choiceTabindex);
SetFocus(choiceTabindex);
CLS_launcherDlg* dlg = static_cast<CLS_launcherDlg*>( AfxGetMainWnd() );
dlg->SetTabCurFocus(choiceTabindex);
CPoint pos;
GetCursorPos(&pos);
// 마우스 위치에 팝업메뉴를 출력한다.
m_menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pos.x, pos.y, this);
CTabCtrl::OnRButtonUp(nFlags, point);
}
void CLauncherTabCtrl::CreatePopup()
{
// 팝업메뉴
m_menu.CreatePopupMenu();
CString menu;
menu = _T("Add IP");
m_menu.AppendMenu(MF_STRING, IDC_SERVICE_ADD_IP, (LPCTSTR)menu);
menu = _T("Delete IP");
m_menu.AppendMenu(MF_STRING, IDC_SERVICE_DELETE_IP, (LPCTSTR)menu);
//m_menu.AppendMenu(MF_SEPARATOR);
//menu = _T("Spread");
//m_menu.AppendMenu(MF_STRING, IDC_SERVICE_SPREAD, (LPCTSTR)menu);
}
BOOL CLauncherTabCtrl::OnCommand(WPARAM wParam, LPARAM lParam)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
int index = -1;
for(int i = 0; i < GetItemCount(); i++)
{
if(LVIS_SELECTED == GetItemState(i, LVIS_SELECTED))
{
index = i;
break;
}
}
switch(wParam)
{
case IDC_SERVICE_ADD_IP :
GetParent()->SendMessage(IDC_SERVICE_ADD_IP, index, 0);
break;
case IDC_SERVICE_DELETE_IP :
GetParent()->SendMessage(IDC_SERVICE_DELETE_IP, index, 0);
break;
case IDC_SERVICE_SPREAD :
GetParent()->SendMessage(IDC_SERVICE_SPREAD, index, 0);
break;
}
return CTabCtrl::OnCommand(wParam, lParam);
}
UINT CLauncherTabCtrl::GetTabFocus(LONG x, LONG y)
{
CServerDialog* dlg = NULL;
for(SERVER_DIALOGS::iterator it = m_dialogs.begin() ; it != m_dialogs.end() ; ++it)
{
dlg = it->second;
if(!dlg) continue;
if( dlg->IsMouseOverTab(x, y) )
{
return it->first;
}
}
return -1;
}
BOOL CLauncherTabCtrl::IsAllReady()
{
if( m_dialogs.empty() )
return FALSE;
for(SERVER_DIALOGS::iterator it = m_dialogs.begin() ; it != m_dialogs.end() ; ++it)
{
CServerDialog* dlg = it->second;
if(!dlg) continue;
if( !dlg->IsReady() )
{
return FALSE;
}
}
return TRUE;
}
@@ -0,0 +1,62 @@
#pragma once
#include <vector>
#include <map>
#include "ServerDialog.h"
// CLauncherTabCtrl
class CLauncherTabCtrl : public CTabCtrl
{
DECLARE_DYNAMIC(CLauncherTabCtrl)
public:
CLauncherTabCtrl();
virtual ~CLauncherTabCtrl();
public:
void Init();
void AddTab(CString& title, CString& IP, UINT port);
void DeleteTab(const UINT focus);
void SetFocus(const UINT index);
void UserFocus(const UINT index);
void CreatePopup();
UINT GetTabFocus(LONG x, LONG y);
public:
BOOL IsAllReady();
public:
const UINT GetTabIndex() { return m_tabIndex; }
const UINT GetCount() { return m_dialogs.size(); }
void ShowTab(const UINT index, const BOOL show = TRUE);
public:
CServerDialog* GetDialog(const int index);
private:
void TapRenewal(const UINT focus);
void DeleteServerInfo(CString name);
public:
typedef std::map<UINT, CServerDialog*> SERVER_DIALOGS;
SERVER_DIALOGS m_dialogs;
protected:
UINT m_tabIndex;
CMenu m_menu;
int m_x, m_y, m_width, m_height;
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
protected:
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
};
+288
View File
@@ -0,0 +1,288 @@
// MD5.cpp: implementation of the CMD5 class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MD5.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
static BYTE PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UINT)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
static void MD5Transform (UINT state[4], BYTE block[64]);
static void Encode(BYTE* output, UINT* input, UINT len);
static void Decode (UINT* output, BYTE* input, UINT len);
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMD5::CMD5()
{
}
CMD5::~CMD5()
{
}
/*
CString CMD5::GetString(CString str)
{
MD5_CTX context;
BYTE digest[16];
UINT len = str.GetLength();
MD5Init (&context);
MD5Update (&context, (BYTE*)(LPTSTR)(LPCTSTR)str, len);
MD5Final (digest, &context);
CString temp;
CString ret = _T("");
for (int i=0; i<16; i++)
{
temp.Format("%02X", digest[i]);
ret += temp;
}
return ret;
}
*/
void CMD5::Generate(BYTE* file, UINT length)
{
ZeroMemory(m_digest, sizeof(m_digest));
MD5_CTX context;
MD5Init(&context);
MD5Update(&context, file, length);
MD5Final(m_digest, &context);
}
void CMD5::MD5Init(MD5_CTX* context)
{
context->count[0] = context->count[1] = 0;
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
void CMD5::MD5Update (MD5_CTX* context, BYTE* input, UINT inputLen)
{
UINT i, index, partLen;
index = (UINT)((context->count[0] >> 3) & 0x3F);
if ((context->count[0] += ((UINT)inputLen << 3)) < ((UINT)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT)inputLen >> 29);
partLen = 64 - index;
if (inputLen >= partLen)
{
memcpy(&context->buffer[index], input, partLen);
MD5Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
memcpy(&context->buffer[index], &input[i], inputLen-i);
}
void CMD5::MD5Final (BYTE* digest, MD5_CTX* context)
{
BYTE bits[8];
UINT index, padLen;
Encode (bits, context->count, 8);
index = (UINT)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD5Update (context, PADDING, padLen);
MD5Update (context, bits, 8);
Encode (digest, context->state, 16);
memset (context, 0, sizeof (*context));
}
static void MD5Transform (UINT state[4], BYTE block[64])
{
UINT a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information. */
memset (x, 0, sizeof (x));
}
static void Encode(BYTE* output, UINT* input, UINT len)
{
UINT i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (BYTE)(input[i] & 0xff);
output[j+1] = (BYTE)((input[i] >> 8) & 0xff);
output[j+2] = (BYTE)((input[i] >> 16) & 0xff);
output[j+3] = (BYTE)((input[i] >> 24) & 0xff);
}
}
static void Decode (UINT* output, BYTE* input, UINT len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT)input[j]) | (((UINT)input[j+1]) << 8) |
(((UINT)input[j+2]) << 16) | (((UINT)input[j+3]) << 24);
}
+32
View File
@@ -0,0 +1,32 @@
// MD5.h: interface for the CMD5 class.
//
//////////////////////////////////////////////////////////////////////
#pragma once
class CMD5
{
public:
CMD5();
~CMD5();
public:
void Generate(BYTE* file, UINT length);
BYTE* GetDigest() { return m_digest; }
protected:
BYTE m_digest[16];
protected:
typedef struct
{
UINT state[4]; /* state (ABCD) */
UINT count[2]; /* number of bits, modulo 2^64 (lsb first) */
BYTE buffer[64]; /* input buffer */
} MD5_CTX;
void MD5Init(MD5_CTX* ctx);
void MD5Update(MD5_CTX* ctx, BYTE* input, UINT inputlen);
void MD5Final(BYTE* digest, MD5_CTX* ctx);
};
@@ -0,0 +1,275 @@
// File.cpp: implementation of the File class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "File.h"
#include <stdio.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
File::File() : m_hFile(INVALID_HANDLE_VALUE), m_dwSizeLow(0), m_dwSizeHigh(0)
{
}
File::File(LPCTSTR fileName, DWORD dwMode, DWORD dwShareMode, DWORD dwCreationDisposition) : m_hFile(INVALID_HANDLE_VALUE), m_dwSizeLow(0), m_dwSizeHigh(0)
{
Open(fileName, dwMode, dwShareMode, dwCreationDisposition);
}
File::~File()
{
Close();
}
//////////////////////////////////////////////////////////////////////
// operation
//////////////////////////////////////////////////////////////////////
BOOL File::Open(const TCHAR* fileName, DWORD dwMode, DWORD dwShareMode, DWORD dwCreationDisposition)
{
Close();
m_hFile = CreateFile(
reinterpret_cast<LPCTSTR>(fileName),
dwMode,
dwShareMode,
NULL,
dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(m_hFile == INVALID_HANDLE_VALUE) return FALSE;
return (m_hFile == INVALID_HANDLE_VALUE) ? FALSE : TRUE;
}
void File::Close()
{
if(m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
m_hFile = NULL;
}
m_dwSizeLow = 0;
m_dwSizeHigh = 0;
}
BOOL File::Move(DWORD dwOrigin, LONG lOffset)
{
if(m_hFile != INVALID_HANDLE_VALUE)
{
DWORD dwResult = SetFilePointer( m_hFile,
lOffset,
NULL,
dwOrigin);
return (dwResult == 0xFFFFFFFF) ? FALSE : TRUE;
}
return FALSE;
}
DWORD File::GetFileSize()
{
if(m_dwSizeLow != 0)
return m_dwSizeLow;
DWORD dwError = 0;
if(m_hFile != INVALID_HANDLE_VALUE)
{
m_dwSizeLow = ::GetFileSize(m_hFile, &m_dwSizeHigh);
if((INVALID_FILE_SIZE == m_dwSizeLow) &&
((dwError = GetLastError()) != NO_ERROR))
return 0;
}
return m_dwSizeLow;
}
//////////////////////////////////////////////////////////////////////
// FileReader class
//////////////////////////////////////////////////////////////////////
FileReader::FileReader(const TCHAR* fileName) : m_nReadType(-1)
{
if(fileName != NULL)
{
Open(fileName);
}
}
BOOL FileReader::Open(const TCHAR* fileName)
{
if(File::Open(fileName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING))
{
return (GetBOM() > 0) ? TRUE : FALSE;
}
return FALSE;
}
BOOL FileReader::Read(BYTE* buffer, const DWORD dwLength)
{
DWORD dwWritten = 0;
if(m_hFile == INVALID_HANDLE_VALUE) return FALSE;
if(ReadFile( m_hFile,
buffer,
dwLength,
&dwWritten,
NULL))
{
if(dwLength == dwWritten) return TRUE;
}
return FALSE;
}
BOOL FileReader::Convert(const BYTE* bufferA, const int lengthA, BYTE* bufferB, const int lengthB)
{
switch(m_nReadType)
{
case FILEFORMAT_ANSI :
CopyMemory(bufferB, bufferA, (lengthA > lengthB) ? lengthB : lengthA);
return TRUE;
case FILEFORMAT_UNICODE_UTF8 :
CopyMemory(bufferB, bufferA, (lengthA > lengthB) ? lengthB : lengthA);
return TRUE;
case FILEFORMAT_UNICODE_LE :
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)bufferA, lengthA, (LPSTR)bufferB, lengthB, NULL, NULL);
return TRUE;
case FILEFORMAT_UNICODE_BE :
return TRUE;
}
return FALSE;
}
int FileReader::GetBOM()
{
if((-1) == m_nReadType)
{
Move(FILE_BEGIN, 0);
WORD BOM = 0;
if(Read(reinterpret_cast<BYTE*>(&BOM), sizeof(WORD)))
{
switch(BOM)
{
case 0xFEFF :
m_nReadType = FILEFORMAT_UNICODE_LE;
break;
case 0xFFFE :
m_nReadType = 0; //FILEFORMAT_UNICODE_BE; not supported
break;
case 0xBBEF :
m_nReadType = FILEFORMAT_UNICODE_UTF8;
Move(FILE_BEGIN, 3);
break;
default:
m_nReadType = FILEFORMAT_ANSI;
Move(FILE_BEGIN, 0);
break;
}
return m_nReadType;
}
return 0;
}
return m_nReadType;
}
DWORD FileReader::GetFileSize()
{
if(0 == m_dwSizeLow)
{
File::GetFileSize();
switch(m_nReadType)
{
case FILEFORMAT_UNICODE_LE :
case FILEFORMAT_UNICODE_BE :
m_dwSizeLow -= (2);
break;
case FILEFORMAT_UNICODE_UTF8 :
m_dwSizeLow -= (3);
break;
default:
break;
}
}
return m_dwSizeLow;
}
//////////////////////////////////////////////////////////////////////
// FileWriter class
//////////////////////////////////////////////////////////////////////
FileWriter::FileWriter(const TCHAR* fileName)
{
if(fileName != NULL)
{
Open(fileName);
}
}
BOOL FileWriter::Open(const TCHAR* fileName, DWORD diposition)
{
if(0 == diposition)
{
diposition = CREATE_NEW;
}
if(File::Open(fileName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, diposition))
{
WriteHeader();
return TRUE;
}
return FALSE;
}
BOOL FileWriter::Write(const BYTE* buffer, const DWORD dwLength)
{
if(dwLength == 0)
return TRUE;
DWORD dwBytes = 0;
if(WriteFile( m_hFile,
buffer,
dwLength,
&dwBytes,
NULL))
{
return (dwBytes == dwLength) ? TRUE : FALSE;
}
return FALSE;
}
BOOL FileWriter::WriteFormat(const TCHAR* format, ...)
{
TCHAR buffer[4096];
va_list marker;
va_start(marker, format);
_vstprintf_s(buffer, _countof(buffer), format, marker);
va_end(marker);
return Write(reinterpret_cast<BYTE*>(buffer), (DWORD)(_tcslen(buffer)*sizeof(TCHAR)));
}
void FileWriter::WriteHeader()
{
#ifdef _UNICODE
Move(FILE_BEGIN, 0);
WORD BOM = 0xFEFF;
Write(reinterpret_cast<BYTE*>(&BOM), sizeof(BOM));
#endif
}
Loaded 100 of 20588 files, more files were not shown because too many files have changed in this diff. Show more