예제 #1
0
DWORD IHFAPI NewHook(const HookParam& hp, LPWSTR name, DWORD flag)
{
	int current; WCHAR str[0x80];

	current=current_available-hookman;
	if (current>=MAX_HOOK) OutputConsole(L"Too many hooks.");
	else {
		flag &= 0xFFFF;
		if ((flag & HOOK_AUXILIARY) == 0)
		{
			flag |= HOOK_ADDITIONAL;
			if (name==0 || *name == 0)
			{
				name=str;
				swprintf(name,L"UserHook%d",user_hook_count++);
			}
		}
		hookman[current].InitHook(hp,name,flag & 0xFFFF);
		if (hookman[current].InsertHook()==0)
		{
			OutputConsole(L"Additional hook inserted.");
			swprintf(str,L"Insert address 0x%.8X.",hookman[current].Address());
			OutputConsole(str);
			RequestRefreshProfile();
		}
		else OutputConsole(L"Unable to insert hook.");
	}
	return 0;
}
예제 #2
0
파일: Register.cpp 프로젝트: stjeong/Straw
void DoUnregistration()
{
    OutputConsole(L"Removing Service...\n");

    SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
    if (!scm)
    {
        OutputError(L"OpenSCManager fails! (%d)\n", GetLastError());
        return;
    }

    SC_HANDLE myService = NULL;
    BOOL success;

    do
    {
        OutputConsole(L"Opened Service Control Manager...\n");
        myService = OpenService(scm, SERVICE_NAME, SERVICE_ALL_ACCESS | DELETE);

        if (!myService)
        {
            DWORD dwResult = GetLastError();
            if (dwResult = ERROR_SERVICE_DOES_NOT_EXIST)
            {
                OutputConsole(L"Service doesn't exist!\n");
                break;
            }

            OutputError(L"OpenService fails! (%d)\n", dwResult);
            break;
        }

        if (DoStopService() == FALSE)
        {
            break;
        }

        success = DeleteService(myService);
        if (success)
        {
            OutputConsole(L"Service successfully removed.\n");
        }
        else
        {
            OutputError(L"DeleteService Fails! (%d)\n", GetLastError());
            break;
        }

    } while (false);

    if (myService != NULL)
    {
        CloseServiceHandle(myService);
    }

    if (scm != NULL)
    {
        CloseServiceHandle(scm);
    }
}
예제 #3
0
파일: Register.cpp 프로젝트: stjeong/Straw
void DoStartService()
{
    SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS | GENERIC_WRITE);
    if (!scm)
    {
        OutputError(L"OpenSCManager fails! (%d)\n", GetLastError());
        return;
    }

    SC_HANDLE myService = NULL;
    BOOL success;
    SERVICE_STATUS status;

    do
    {
        OutputConsole(L"Opened Service Control Manager...\n");
        myService = OpenService(scm, SERVICE_NAME, SERVICE_ALL_ACCESS);

        if (!myService)
        {
            OutputError(L"OpenService fails! (%d)\n", GetLastError());
            break;
        }

        success = QueryServiceStatus(myService, &status);
        if (!success)
        {
            OutputError(L"QueryServiceStatus fails! (%d)\n", GetLastError());
            break;
        }

        if (status.dwCurrentState != SERVICE_STOPPED && status.dwCurrentState != SERVICE_STOP_PENDING)
        {
            OutputError(L"Cannot start the service because it is already running\n");
            break;
        }

        success = StartService(myService, 0, NULL);
        if (!success)
        {
            OutputError(L"StartService fails! (%d)\n", GetLastError());
            break;
        }

        OutputConsole(L"Service started successfully!\n");

    } while (false);

    if (myService != NULL)
    {
        CloseServiceHandle(myService);
    }

    if (scm != NULL)
    {
        CloseServiceHandle(scm);
    }
}
DWORD IHFAPI OutputDWORD(DWORD d)
{
	WCHAR str[0x10];
	swprintf(str,L"%.8X",d);
	OutputConsole(str);
	return 0;
}
DWORD IHFAPI OutputRegister(DWORD *base)
{
	WCHAR str[0x40];
	swprintf(str,L"EAX:%.8X",base[0]);
	OutputConsole(str);
	swprintf(str,L"ECX:%.8X",base[-1]);
	OutputConsole(str);
	swprintf(str,L"EDX:%.8X",base[-2]);
	OutputConsole(str);
	swprintf(str,L"EBX:%.8X",base[-3]);
	OutputConsole(str);
	swprintf(str,L"ESP:%.8X",base[-4]);
	OutputConsole(str);
	swprintf(str,L"EBP:%.8X",base[-5]);
	OutputConsole(str);
	swprintf(str,L"ESI:%.8X",base[-6]);
	OutputConsole(str);
	swprintf(str,L"EDI:%.8X",base[-7]);
	OutputConsole(str);
	return 0;
}
예제 #6
0
void WndSelectBuild::RefreshBuildType()
{
    utility::File	file;
    SAFEDESTROY(m_pScriptBuild);
    if (!file.Open("model\\build\\build"))
    {
        OutputConsole("error: can't open build!\n");
        MessageBox(NULL,"打开[建筑]配置文件失败!","错误",MB_OK);
        PostQuitMessage(-1);
        return ;
    }

    m_pScriptBuild = new utility::Text;

    m_pScriptBuild->Create(&file);

    file.Close();

    utility::Text::Node *pBuildNode = m_pScriptBuild->GetRootNode()->GetChildNode("build");
    ASSERT(pBuildNode);

    char szTempName[_MAX_PATH];
    for(DWORD dwTypeNode = 0; dwTypeNode < pBuildNode->GetChildCount(); dwTypeNode++)
    {
        utility::Text::Node *pTypeNode = pBuildNode->GetChildNode(dwTypeNode);
        _snprintf(szTempName,_MAX_PATH,"%s(%s)",pTypeNode->GetVar("type")->GetStringValue(),pTypeNode->GetName());
        m_pTabCtl->AddLabel(szTempName);

    }


    if (m_pTabCtl->GetLabelCount() > 0)
    {
        m_pTabCtl->SetHighLightLabel(0);
        RefreshFileListBox();
    }
}
예제 #7
0
void CmdMapFillBlock::Dump()
{
	OutputConsole("Map_Fill_Block: %d %d",m_vGridIndexArray.size(),m_dwBlock);
}
예제 #8
0
void GameWorld::Create(HWND hWnd)
{
	m_hWnd = hWnd;

	//初始化BUILDLIST和CLINETRESOURCE和GameModelManager
	CHAR* strPath = new CHAR[MAX_PATH];
	string strWorpath("");
	if(::GetCurrentDirectory(MAX_PATH,strPath))
	{
		strWorpath=string(strPath);
	}
	delete []strPath;
	string strPackName("Game.pak");
	string strFilesInfo("FilesInfo.ril");
	CClientResource::InitialInstance();
	CClientResource* pClientResource = CClientResource::GetInstance();
	pClientResource->Initial(GAME_RES,strWorpath,strFilesInfo);
	if(!pClientResource->LoadEx())
	{
		//装载客户端资源信息出错
		//ASSERT(false);
		//return false;
	}
	PutDebugString("Init package file OK!");
	//检查资源装载情况

	//初始化模型管理器
	CGameModelManager::InitInstance();
	CGameModelManager::GetInstance()->Initial();
	CGameModelManager::GetInstance()->SetTextureShareFolder(Setting::GetInstance()->m_pszTextureSharFolder);

	GameBuildList::InitInstance();
	GameBuildList::GetInstance()->Initial();

	//建立控制台
	console::Manager::InitInstance();
	console::Manager::GetInstance()->Create(console::CONSOLE_ERROR | console::CONSOLE_OUTPUT | console::CONSOLE_WARRING);

	//初始其他接口
	input::Interface::InitInstance();
	ui::Manager::InitInstance();
	render::Interface::InitInstance();
	particle::Manager::InitInstance();
	Water::CManager::InitInstance();			//初始化水面管理器

	//建立
	input::Interface::GetInstance()->Create(hWnd);
	ui::Manager::GetInstance()->Create();
	//初始化显示部分
	utility::File file;
	if (!file.Open("render.config"))
	{
		OutputConsole("render.config doesn't exist.\n");
		MessageBox(NULL,"render.config","打开失败",MB_OK);
		PostQuitMessage(-1);		
	}
	int iFileLength = file.GetLength();
	char *pszTemp = new char[iFileLength + 1];			
	memcpy(pszTemp,file.GetData(),file.GetLength());
	pszTemp[iFileLength] = 0;
	render::Interface::GetInstance()->Create(hWnd,pszTemp);
	SAFEDELETE(pszTemp);
	file.Close();

	//初始化粒子管理器
	particle::Manager::GetInstance()->Create();

	CommDB::InitInstance();

	CmdMgr::InitInstance();
	
	CommUI::InitInstance();
	CommUI::GetInstance()->Create();

	TimeSystem::InitInstance();

	ui::Manager * pUIMgr = 	ui::Manager::GetInstance();
	//pUIMgr->ReadUIConfig();
}
예제 #9
0
void GameWorld::Create(HWND hWnd)
{
	m_hWnd = hWnd;

	//建立控制台
	console::Manager::InitInstance();
	console::Manager::GetInstance()->Create(console::CONSOLE_ERROR | console::CONSOLE_OUTPUT | console::CONSOLE_WARRING);

	//初始其他接口
	input::Interface::InitInstance();
	ui::Manager::InitInstance();
	render::Interface::InitInstance();
	particle::Manager::InitInstance();

	CHAR * strPath = new CHAR[MAX_PATH];
	string strWorpath("");
	if(::GetCurrentDirectory(MAX_PATH, strPath))
		strWorpath=string(strPath);
	delete []strPath;
	string strFilesInfo("FilesInfo.ril");
	CClientResource::InitialInstance();
	CClientResource * pClientResource = CClientResource::GetInstance();
	pClientResource->Initial(GAME_RES,strWorpath, strFilesInfo);
	if(!pClientResource->LoadEx())
	{
		//装载客户端资源信息出错
		//ASSERT(false);
		//return false;
	}

	CGameModelManager::InitInstance();	
	CGameModelManager::GetInstance()->SetTextureShareFolder(Setting::GetInstance()->m_pszTextureSharFolder);

	//建立
	input::Interface::GetInstance()->Create(hWnd);
	ui::Manager::GetInstance()->Create();

	//初始化显示部分
	utility::File file;
	if (!file.Open("render.config"))
	{
		OutputConsole("render.config doesn't exist.\n");
		MessageBox(NULL,"render.config","打开失败",MB_OK);
		PostQuitMessage(-1);
	}
	int iFileLength = file.GetLength();
	char * pszTemp = new char[iFileLength + 1];			
	memcpy(pszTemp, file.GetData(), file.GetLength());
	pszTemp[iFileLength] = 0;
	render::Interface::GetInstance()->Create(hWnd, pszTemp);
	SAFEDELETE(pszTemp);
	file.Close();

	//初始化粒子管理器
	particle::Manager::GetInstance()->Create();

	render::Interface * pInterface = render::Interface::GetInstance();
    
	int iWidth  = pInterface->GetWndWidth();
	int iHeight = pInterface->GetWndHeight();

	RECT rc= {0,0,iWidth,iHeight};
	
	m_pMainWnd = new WndViewer;
	m_pMainWnd->Create("test",&rc, FWS_VISIBLE | FWS_OUTLINE | FWS_SIZE | FWS_DRAG | FWS_FILLBKG ,NULL);

	//生成界面
	ui::Manager::GetInstance()->SetMainWnd(m_pMainWnd);

	// 初始化水面管理器
	Water::CManager::InitInstance();
}
예제 #10
0
파일: Log.cpp 프로젝트: J0nath4n/mxoemu
void Log::Output( LogLevel level,const string &str )
{
	OutputConsole(level,str);
	OutputFile(level,str);
}
예제 #11
0
파일: Register.cpp 프로젝트: stjeong/Straw
void DoRegistration(wstring apiKey, wstring envKey, string remoteServAddr, int port, vector<int> intervalTimes)
{
    OutputConsole(L"Installing Service...\n");

    DoUnregistration();

    SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
    if (!scm)
    {
        OutputError(L"OpenSCManager fails! (%d)\n", GetLastError());
        return;
    }

    SC_HANDLE myService = NULL;
    HKEY hkey = NULL;
    wchar_t *pBuf = nullptr;

    do
    {
        wstring filePath = g_moduleFilePath;
        wchar_t safeFilePath[MAX_PATH];
        StringCchPrintf(safeFilePath, MAX_PATH, L"\"%s\"", filePath.c_str());

        OutputConsole(L"Opened Service Control Manager...\n");
        myService = CreateService(
            scm, SERVICE_NAME, // the internal service name used by the SCM
            L"StrawAgent Service",  // the external label seen in the Service Control applet
            SERVICE_ALL_ACCESS,  // We want full access to control the service
            SERVICE_WIN32_OWN_PROCESS,  // The service is a single app and not a driver
            SERVICE_AUTO_START,  // The service will be started by us manually
            SERVICE_ERROR_NORMAL,  // If error during service start, don't misbehave.
            safeFilePath,
            0, 0, 0, 0, 0);

        if (!myService)
        {
            OutputError(L"CreateService fails! (%d)\n", GetLastError());
            break;
        }

        wchar_t szBuffer[MAX_PATH] = { 0 };

        StringBuilder sb;

        sb.push_back(L"asNTservice=1");
        sb.push_back(L"apiKey=" + apiKey);
        sb.push_back(L"envKey=" + envKey);
        sb.push_back("server=" + remoteServAddr);

        StringCchPrintf(szBuffer, MAX_PATH, L"port=%d", port);
        sb.push_back(szBuffer);

        if (g_debugMode == TRUE)
        {
            sb.push_back(L"debug=1");
        }

        if (RegOpenKey(HKEY_LOCAL_MACHINE, REG_SERVICE, &hkey) != ERROR_SUCCESS)
        {
            OutputError(L"RegOpenKey fails! (%d)\n", GetLastError());
            break;
        }

        int written = 0;
        pBuf = sb.ToStringMultiLine(&written);

        if (RegSetValueEx(hkey, L"Environment", 0, REG_MULTI_SZ, (const BYTE *)pBuf, written) != ERROR_SUCCESS)
        {
            OutputError(L"RegSetValueEx fails! (%d)\n", GetLastError());
            break;
        }

        OutputConsole(L"Service successfully installed.\n");

    } while (false);

    if (pBuf != nullptr)
    {
        delete[] pBuf;
    }

    if (hkey != NULL)
    {
        RegCloseKey(hkey);
    }

    if (myService != NULL)
    {
        CloseServiceHandle(myService);
    }

    if (scm != NULL)
    {
        CloseServiceHandle(scm);
    }
}
예제 #12
0
파일: Register.cpp 프로젝트: stjeong/Straw
void ProcessLatestUpdate()
{
    WORD majorVersion = 0;
    WORD minorVersion = 0;
    WORD buildNumber = 0;
    WORD revisionNumber = 0;

    wchar_t szTempFileName[MAX_PATH] { 0 };
    wchar_t lpTempPathBuffer[MAX_PATH] = { 0 };

    wstring thisFileName = g_moduleFilePath;
    wstring currentVersion;

    currentVersion = GetAppVersion(thisFileName.c_str(), &majorVersion, &minorVersion, &buildNumber, &revisionNumber);

    IWinHttpRequest *  pIWinHttpRequest = NULL;
    BSTR            bstrResponse = NULL;

    HRESULT hr = CoInitialize(NULL);

    do
    {
        VARIANT         varFalse;
        VARIANT         varEmpty;

        CLSID           clsid;

        VariantInit(&varFalse);
        V_VT(&varFalse) = VT_BOOL;
        V_BOOL(&varFalse) = VARIANT_FALSE;

        VariantInit(&varEmpty);
        V_VT(&varEmpty) = VT_ERROR;

        hr = CLSIDFromProgID(L"WinHttp.WinHttpRequest.5.1", &clsid);

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }
        
        hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
            IID_IWinHttpRequest, (void **)&pIWinHttpRequest);
        
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        BSTR bstrMethod = SysAllocString(L"GET");
        BSTR bstrUrl = SysAllocString(UPDATE_CHECK_URL);
        hr = pIWinHttpRequest->Open(bstrMethod, bstrUrl, varFalse);
        SysFreeString(bstrMethod);
        SysFreeString(bstrUrl);

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        hr = pIWinHttpRequest->Send(varEmpty);
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        hr = pIWinHttpRequest->get_ResponseText(&bstrResponse);

        wstring txt = bstrResponse;
        wstring newUpdateVersion = GetNewVersion(txt);
        if (newUpdateVersion.length() == 0)
        {
            break;
        }

        if (newUpdateVersion == currentVersion)
        {
            if (g_isConsoleApp == TRUE)
            {
                OutputConsole(L"This is the latest version (%s)\n", currentVersion.c_str());
            }
            break;
        }

        if (IsNewVersion(majorVersion, minorVersion, buildNumber, revisionNumber, newUpdateVersion) == FALSE)
        {
            if (g_isConsoleApp == TRUE)
            {
                OutputConsole(L"This is the latest version (%s)\n", L"1.0.0.4"); // currentVersion.c_str());
            }
            break;
        }

        // if new, update latest version.
        // if old, roll-back last stable version.

        bool is32bit = sizeof(char *) == 4;
        wstring location = GetUpdateLocation(txt, is32bit);

        VariantInit(&varEmpty);
        V_VT(&varEmpty) = VT_ERROR;

        bstrMethod = SysAllocString(L"GET");
        bstrUrl = SysAllocString(location.c_str());
        pIWinHttpRequest->Open(bstrMethod, bstrUrl, varFalse);
        SysFreeString(bstrMethod);
        SysFreeString(bstrUrl);

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        hr = pIWinHttpRequest->Send(varEmpty);
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        VARIANT varResponse;
        VariantInit(&varResponse);
        hr = pIWinHttpRequest->get_ResponseStream(&varResponse);
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        txt = pIWinHttpRequest->GetResponseHeader(L"Content-Type").operator const wchar_t *();
        if (txt.find(L"text/html") != -1)
        {
            OutputError(L"file not found: %s", location.c_str());
            break;
        }

        IStream*    pStream = NULL;
        BYTE        bBuffer[8192];
        DWORD       cb, cbRead, cbWritten;

        if (VT_UNKNOWN == V_VT(&varResponse) || VT_STREAM == V_VT(&varResponse))
        {
            hr = V_UNKNOWN(&varResponse)->QueryInterface(IID_IStream,
                reinterpret_cast<void**>(&pStream));
        }
        else
        {
            break;
        }

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        DWORD dwRetVal = GetTempPath(MAX_PATH,          // length of the buffer
            lpTempPathBuffer); // buffer for path 
        if (dwRetVal > MAX_PATH || (dwRetVal == 0))
        {
            OutputError(L"GetTempPath failed (%d)", GetLastError());
            break;
        }

        dwRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files
            L"straw",     // temp file name prefix 
            0,                // create unique name 
            szTempFileName);  // buffer for name 
        if (dwRetVal == 0)
        {
            OutputError(L"GetTempFileName failed (%d)", GetLastError());
            break;
        }

        bool succeed = true;

        HANDLE hFile = CreateFile(szTempFileName,
            GENERIC_WRITE,                // Open for writing. 
            0,                            // Do not share. 
            NULL,                         // No security. 
            CREATE_ALWAYS,                // Overwrite existing.
            FILE_ATTRIBUTE_NORMAL,        // Normal file.
            NULL);                        // No attribute template.
        if (hFile == INVALID_HANDLE_VALUE)
        {
            OutputError(L"Can't open a file: %s", szTempFileName);
            break;
        }
        else
        {
            cb = sizeof(bBuffer);
            hr = pStream->Read(bBuffer, cb, &cbRead);
            while (SUCCEEDED(hr) && 0 != cbRead)
            {
                if (!WriteFile(hFile, bBuffer,
                    cbRead, &cbWritten, NULL))
                {
                    OutputError(L"WriteFile fails with 0x%08lx\n", HRESULT_FROM_WIN32(GetLastError()));
                    succeed = false;
                    break;
                }

                hr = pStream->Read(bBuffer, cb, &cbRead);
            }
        }

        CloseHandle(hFile);
        pStream->Release();
        VariantClear(&varResponse);

        if (succeed == true)
        {
            wstring oldFileName = thisFileName;
            oldFileName += currentVersion + L".bak";

            ::DeleteFile(oldFileName.c_str());

            if (MoveFile(thisFileName.c_str(), oldFileName.c_str()) == FALSE)
            {
                OutputError(L"Backup fails (%d)", GetLastError());
                break;
            }

            if (MoveFile(szTempFileName, thisFileName.c_str()) == FALSE)
            {
                OutputError(L"Update fails (%d)", GetLastError());
                break;
            }

            FireRestartCommand();
        }

    } while (false);

    if (::PathFileExists(szTempFileName) == TRUE)
    {
        ::DeleteFile(szTempFileName);
    }

    if (pIWinHttpRequest)
    {
        pIWinHttpRequest->Release();
    }

    if (bstrResponse)
    {
        SysFreeString(bstrResponse);
    }

    CoUninitialize();
}
예제 #13
0
파일: Register.cpp 프로젝트: stjeong/Straw
BOOL DoStopService()
{
    SERVICE_STATUS_PROCESS ssp;
    DWORD dwStartTime = GetTickCount();
    DWORD dwBytesNeeded;
    DWORD dwTimeout = 30000; // 30-second time-out
    DWORD dwWaitTime;
    BOOL stopped = FALSE;

    SC_HANDLE schSCManager = OpenSCManager(
        NULL,                    // local computer
        NULL,                    // ServicesActive database 
        SC_MANAGER_ALL_ACCESS);  // full access rights 

    if (NULL == schSCManager)
    {
        OutputError(L"OpenSCManager failed (%d)\n", GetLastError());
        return FALSE;
    }

    SC_HANDLE schService = OpenService(
        schSCManager,         // SCM database 
        SERVICE_NAME,            // name of service 
        SERVICE_STOP |
        SERVICE_QUERY_STATUS |
        SERVICE_ENUMERATE_DEPENDENTS);

    do
    {
        if (schService == NULL)
        {
            OutputError(L"OpenService failed (%d)\n", GetLastError());
            break;
        }

        if (!QueryServiceStatusEx(
            schService,
            SC_STATUS_PROCESS_INFO,
            (LPBYTE)&ssp,
            sizeof(SERVICE_STATUS_PROCESS),
            &dwBytesNeeded))
        {
            OutputError(L"QueryServiceStatusEx failed (%d)\n", GetLastError());
            break;
        }

        if (ssp.dwCurrentState == SERVICE_STOPPED)
        {
            OutputConsole(L"Service is already stopped.\n");
            stopped = TRUE;
            break;
        }

        bool exitLoop = false;

        while (ssp.dwCurrentState == SERVICE_STOP_PENDING)
        {
            exitLoop = true;
            OutputConsole(L"Service stop pending...\n");

            dwWaitTime = ssp.dwWaitHint / 10;

            if (dwWaitTime < 1000)
                dwWaitTime = 1000;
            else if (dwWaitTime > 10000)
                dwWaitTime = 10000;

            Sleep(dwWaitTime);

            if (!QueryServiceStatusEx(
                schService,
                SC_STATUS_PROCESS_INFO,
                (LPBYTE)&ssp,
                sizeof(SERVICE_STATUS_PROCESS),
                &dwBytesNeeded))
            {
                OutputError(L"QueryServiceStatusEx failed (%d)\n", GetLastError());
                break;
            }

            if (ssp.dwCurrentState == SERVICE_STOPPED)
            {
                OutputConsole(L"Service stopped successfully.\n");
                stopped = TRUE;
                break;
            }

            if (GetTickCount() - dwStartTime > dwTimeout)
            {
                OutputError(L"Service stop timed out.\n");
                break;
            }
        }

        if (exitLoop == true)
        {
            break;
        }

        if (!ControlService(schService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp))
        {
            OutputError(L"ControlService failed (%d)\n", GetLastError());
            break;
        }

        while (ssp.dwCurrentState != SERVICE_STOPPED)
        {
            Sleep(ssp.dwWaitHint);
            if (!QueryServiceStatusEx(
                schService,
                SC_STATUS_PROCESS_INFO,
                (LPBYTE)&ssp,
                sizeof(SERVICE_STATUS_PROCESS),
                &dwBytesNeeded))
            {
                OutputError(L"QueryServiceStatusEx failed (%d)\n", GetLastError());
                exitLoop = true;
                break;
            }

            if (ssp.dwCurrentState == SERVICE_STOPPED)
            {
                stopped = TRUE;
                break;
            }

            if (GetTickCount() - dwStartTime > dwTimeout)
            {
                OutputError(L"Wait timed out\n");
                exitLoop = true;
                break;
            }
        }

        if (exitLoop == true)
        {
            break;
        }

        stopped = TRUE;
        OutputConsole(L"Service stopped successfully\n");

    } while (false);

    if (schService != NULL)
    {
        CloseServiceHandle(schService);
    }

    if (schSCManager != NULL)
    {
        CloseServiceHandle(schSCManager);
    }

    return stopped;
}
예제 #14
0
void CmdMapDelDoor::Dump()
{
	OutputConsole("Map_Del_Door: %d ",m_vGridIndexArray.size());
}
예제 #15
0
void CmdMapSetDoor::Dump(void)
{
	OutputConsole("Map_Set_DoorIndex: %d %d",m_dwGridIndex,m_dwDoorIndex);
}		
예제 #16
0
void BuildTree::Refresh()
{
	TreeView_DeleteAllItems(s_hWndTV);

	utility::File file;
	if (!file.Open("model\\build\\build.idx"))
	{
		MessageBox(NULL,"build Define File Do Not Found!","Error",MB_OK | MB_ICONERROR);
		OutputConsole("build Define File Do Not Found!\n");
		ASSERT(0);
	}
	
	utility::Text theText;
	theText.Create(&file);
	file.Close();

	utility::Text::Node *pRoot = theText.GetRootNode();
	ASSERT(pRoot);

	for(DWORD n = 0; n < pRoot->GetChildCount(); n++)
	{
		utility::Text::Node *pBuildNode = pRoot->GetChildNode(n);

		const char *pModelPath = pBuildNode->GetVar("model")->GetStringValue();
		int id = pBuildNode->GetVar("id")->GetIntValue();
		m_mapPath2Id[pModelPath] = id;
	}	

	TVINSERTSTRUCT tvi = {0};
	tvi.hParent = TVI_ROOT;
	tvi.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
	tvi.item.lParam = -1;
	tvi.item.iImage = ICON_FOLDER;
	tvi.item.iSelectedImage = ICON_FOLDER;
	tvi.item.pszText = "Build";

	HTREEITEM hModelItem = TreeView_InsertItem(s_hWndTV,&tvi);

	char szTempPath[_MAX_PATH]; 
	for(DWORD n = 0; n < pRoot->GetChildCount(); n++)
	{
		utility::Text::Node *pTempNode = pRoot->GetChildNode(n);

		utility::File::GetFilePath(pTempNode->GetVar("model")->GetStringValue(),szTempPath);

		HTREEITEM hItem = FindViewItem(hModelItem,szTempPath);
		if (!hItem)
			hItem = InsertViewItem(hModelItem,szTempPath);

		char *pFileName = utility::File::GetFileName(pTempNode->GetVar("model")->GetStringValue());
		
		TVINSERTSTRUCT tvi = {0};
		tvi.hParent = hItem;
		tvi.item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
		tvi.item.lParam = pTempNode->GetVar("id")->GetIntValue();
		tvi.item.iImage = ICON_FILE;
		tvi.item.iSelectedImage = ICON_FILE;
		tvi.item.pszText = pFileName;

		TreeView_InsertItem(s_hWndTV,&tvi);
	}	

	theText.Destroy();

}
예제 #17
0
DWORD ServiceExecutionThread(LPDWORD param)
{
#if _DEBUG
    ::OutputDebugString(L"ServiceExecutionThread\n");
#endif

    if (IntializeSystemInfo() == FALSE)
    {
        return IC_NO_INITIALIZE;
    }

    WORD wVersionRequested = MAKEWORD(1, 1);
    WSADATA wsaData;
    WSAStartup(wVersionRequested, &wsaData);
    SOCKET udpSocket = INVALID_SOCKET;

    int result = IC_NOERROR;
    bool showHelp = false;

    do
    {
        g_killServiceEvent = CreateEvent(0, TRUE, FALSE, 0);
        if (!g_killServiceEvent)
        {
            OutputError(L"CreateEvent fails! (%d)", GetLastError());
            result = IC_EVENT_CREATE_FAIL;
            break;
        }

        wstring apiKey;
        wstring envInfo;
        vector<int> intervalTimes;
        ConnectionInfo connection;

        g_debugMode = GetDebugMode(g_argc, g_argv);

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-h") == true
            || cmdOptionExists(g_argv, g_argv + g_argc, L"/h") == true)
        {
            showHelp = true;
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-unreg") == true)
        {
            DoUnregistration();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-start") == true)
        {
            DoStartService();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-stop") == true)
        {
            DoStopService();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-update") == true)
        {
            ProcessLatestUpdate();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-restart") == true)
        {
            RestartService();
            break;
        }

        apiKey = GetApiKey(g_argc, g_argv);
        envInfo = GetEnvInfo(g_argc, g_argv);
        intervalTimes = GetIntervalTime(g_argc, g_argv);

        if (apiKey.length() == 0)
        {
            OutputError(L"NO ApiKey\n");
            result = IC_NO_APIKEY;
            showHelp = true;
            break;
        }

        if (envInfo.length() == 0)
        {
            OutputError(L"NO AgentID Info\n");
            result = IC_NO_AGENTIDINFO;
            showHelp = true;
            break;
        }

        string address = GetHostAddress(g_argc, g_argv, connection);
        struct hostent *host = gethostbyname(address.c_str());
        if (host == nullptr)
        {
            OutputError(L"Can't resolve host address: %s\n", address.c_str());
            result = IC_NO_RESOLVE_HOSTADDR;
            break;
        }

        SetupHostPort(g_argc, g_argv, connection);

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-regservice") == true)
        {
            DoRegistration(apiKey, envInfo, address, connection.Getport(), intervalTimes);
            break;
        }

        struct sockaddr_in remoteServAddr;

        remoteServAddr.sin_family = host->h_addrtype;
        memcpy((char *)&remoteServAddr.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
        remoteServAddr.sin_port = htons((u_short)connection.Getport());

        /* socket creation */
        udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (udpSocket == INVALID_SOCKET) {
            OutputError(L"socket failed with error: %ld\n", WSAGetLastError());
            break;
        }

        wstring appVersion = GetAppVersion(g_moduleFilePath.c_str(), NULL, NULL, NULL, NULL);
        OutputConsole(L"(%s) ServiceExecutionThread - data collect thread - start\n", appVersion.c_str());

        {
            thread processCpuMemThread([apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes]()
            {
                ProcessCpuMemInfo(apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes[0]);
            });

            thread processDiskThread([apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes]()
            {
                ProcessDiskInfo(apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes[1]);
            });

            thread updateThread([]()
            {
                DWORD oneday = 1000 * 60 * 60 * 24;

                while (true)
                {
                    ProcessLatestUpdate();

                    if (::WaitForSingleObject(g_killServiceEvent, oneday) == WAIT_TIMEOUT)
                    {
                        continue;
                    }

                    break;
                }
            });

            if (g_isConsoleApp == TRUE)
            {
                printf("Press any key to exit...\n");
                getchar();
            }
            else
            {
#if _DEBUG
                ::OutputDebugString(L"Service thread - WaitForSingleObject...\n");
#endif
                WaitForSingleObject(g_killServiceEvent, INFINITE);
            }

#if _DEBUG
            ::OutputDebugString(L"Service thread waiting...\n");
            Sleep(1000);
#endif

            if (processCpuMemThread.joinable() == true)
            {
                processCpuMemThread.join();
            }

            if (processDiskThread.joinable() == true)
            {
                processDiskThread.join();
            }

            if (updateThread.joinable() == true)
            {
                updateThread.join();
            }

#if _DEBUG
            ::OutputDebugString(L"All Service-threads exited...\n");
#endif
        }

        ::SetEvent(g_killSafeExitEvent);

#if _DEBUG
        ::OutputDebugString(L"Service thread detached\n");
#endif

    } while (false);

#if _DEBUG
    ::OutputDebugString(L"ServiceExecutionThread - data collect thread - ending\n");
#endif

    if (udpSocket != INVALID_SOCKET)
    {
        closesocket(udpSocket);
    }

    if (showHelp == true)
    {
        ShowHelp();
    }

    WSACleanup();

#if _DEBUG
    ::OutputDebugString(L"ServiceExecutionThread - data collect thread - ended\n");
#endif

    return result;
}
예제 #18
0
void ShowHelp()
{
#if defined(_WIN64)
    int platformId = 64;
#else
    int platformId = 32;
#endif

    wstring appVersion = GetAppVersion(g_moduleFilePath.c_str(), NULL, NULL, NULL, NULL);

    OutputConsole(L"ic%d.exe (ver %s)\n", platformId, appVersion.c_str());
    OutputConsole(L"ic%d.exe -h\n", platformId);
    OutputConsole(L"ic%d.exe -key [apikey] -s [hostaddress] -id [agentid] -d [interval-sec,[...]]\n", platformId);
    OutputConsole(L"\n");
    OutputConsole(L"samples:\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5\n", platformId);
    OutputConsole(L"        apikey: 8CFDDE2478\n");
    OutputConsole(L"        data server: 192.168.0.5:80\n");
    OutputConsole(L"        (optional: agent id by default - machine name)\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5 -port 8282\n", platformId);
    OutputConsole(L"        apikey: 8CFDDE2478\n");
    OutputConsole(L"        data server: 192.168.0.5:8282\n");
    OutputConsole(L"        (optional: agent id by default - machine name)\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5 -id mypc100\n", platformId);
    OutputConsole(L"        apikey: 8CFDDE2478\n");
    OutputConsole(L"        data server: 192.168.0.5:80\n");
    OutputConsole(L"        id: mypc100\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5 -id mypc100  -regservice\n", platformId);
    OutputConsole(L"        Register as NT Service with this info,\n");
    OutputConsole(L"            apikey: 8CFDDE2478\n");
    OutputConsole(L"            data server: 192.168.0.5:80\n");
    OutputConsole(L"            id: mypc100\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -unreg\n", platformId);
    OutputConsole(L"        Unregister NT Service\n");
}
void CmdMapSetBuildRotationY::Dump(void)
{
	OutputConsole("Map_Set_BuildRotationY: %d %f",m_dwGridIndex,m_fBuildRotationY);
}		
DWORD WINAPI WaitForPipe(LPVOID lpThreadParameter) //Dynamic detect ITH main module status. 
{
	int i;
	TextHook *man;
	struct
	{
		DWORD pid;
		TextHook *man;
		DWORD module;
		DWORD engine;
	} u;
	HANDLE hMutex,hPipeExist;
	//swprintf(engine_event,L"ITH_ENGINE_%d",current_process_id);
	swprintf(detach_mutex,L"ITH_DETACH_%d",current_process_id);
	//swprintf(lose_event,L"ITH_LOSEPIPE_%d",current_process_id);
	//hEngine=IthCreateEvent(engine_event);
	//NtWaitForSingleObject(hEngine,0,0);
	//NtClose(hEngine);
	while (engine_base == 0) NtDelayExecution(0, &wait_time);
	//LoadEngine(L"ITH_Engine.dll");
	u.module=module_base;
	u.pid=current_process_id;
	u.man=hookman;
	u.engine=engine_base;
	hPipeExist=IthOpenEvent(exist);
	IO_STATUS_BLOCK ios;
	//hLose=IthCreateEvent(lose_event,0,0);
	if (hPipeExist!=INVALID_HANDLE_VALUE)
	while (running)
	{
		hPipe=INVALID_HANDLE_VALUE;
		hCommand=INVALID_HANDLE_VALUE;
		while (NtWaitForSingleObject(hPipeExist,0,&wait_time)==WAIT_TIMEOUT)
			if (!running) goto _release;
		hMutex=IthCreateMutex(mutex,0);
		NtWaitForSingleObject(hMutex,0,0);
		while (hPipe==INVALID_HANDLE_VALUE||
			hCommand==INVALID_HANDLE_VALUE) {
			NtDelayExecution(0,&sleep_time);
			if (hPipe==INVALID_HANDLE_VALUE)
				hPipe=IthOpenPipe(recv_pipe,GENERIC_WRITE);
			if (hCommand==INVALID_HANDLE_VALUE)
				hCommand=IthOpenPipe(command,GENERIC_READ);
		}
		//NtClearEvent(hLose);
		NtWriteFile(hPipe,0,0,0,&ios,&u,16,0,0);
		live=true;
		for (man=hookman,i=0;i<current_hook;man++)
			if (man->RecoverHook()) i++;
		OutputConsole(dll_name);
		OutputConsole(L"Pipe connected.");
		//OutputDWORD(tree->Count());
		NtReleaseMutant(hMutex,0);
		NtClose(hMutex);
		if (!hook_inserted && engine_base) 
		{
			hook_inserted=true;
			IdentifyEngine();
		}
		hDetach=IthCreateMutex(detach_mutex,1);
		while (running&&NtWaitForSingleObject(hPipeExist,0,&sleep_time)==WAIT_OBJECT_0) 
			NtDelayExecution(0,&sleep_time);
		live=false;
		for (man=hookman,i=0;i<current_hook;man++)
			if (man->RemoveHook()) i++;
		if (!running)
		{
			NtWriteFile(hPipe,0,0,0,&ios,man,4,0,0);
			IthReleaseMutex(hDetach);					
		}
		NtClose(hDetach);
		NtClose(hPipe);
	}
_release:
	//NtClose(hLose);
	NtClose(hPipeExist);
	return 0;
}
void CmdMapTerrainSetTile::Dump(void)
{
	// 输出错误数据
	OutputConsole("Map_Set_Tile error: %d, %d", m_ptProcessData->dwSelectedGridIndex, m_ptProcessData->dwSelectedVertexIndex);
}