HRESULT Service_Monitor::MonitoringService(LPCTSTR pServiceName, DWORD dwStatus, HANDLE hStopEvent)
{
    HRESULT   hr = S_OK;
    DWORD     dwError = ERROR_SUCCESS;
    DWORD     dwWaitResult;
    SC_HANDLE hService;
    SERVICE_NOTIFY sNotify;

    hr = GetServiceHandle(pServiceName, &hService);
    if(FAILED(hr))
    {
        goto Finished;
    }

    sNotify.dwVersion = SERVICE_NOTIFY_STATUS_CHANGE;
    sNotify.pfnNotifyCallback = (PFN_SC_NOTIFY_CALLBACK)NotifyCallBack;
    sNotify.pszServiceNames = (LPWSTR) pServiceName;
    sNotify.pContext = hStopEvent;

    dwError = NotifyServiceStatusChange(hService, dwStatus, &sNotify);
    if (dwError != ERROR_SUCCESS)
    {
        hr = HRESULT_FROM_WIN32(dwError);
        _tprintf(L"\nERROR: fail to register status change callback [%x]\n", hr);
        goto Finished;
    }

    dwWaitResult = WaitForSingleObjectEx(hStopEvent, INFINITE, TRUE);
    switch (dwWaitResult)
    {
        // Event object was signaled
    case WAIT_OBJECT_0:
    case WAIT_IO_COMPLETION:
        break;

        // An error occurred
    default:
        hr = HRESULT_FROM_WIN32(GetLastError());
        _tprintf(L"\nERROR: Monitoring service '%s' wait error [%x]\n", pServiceName, hr);
    }

Finished:
    if (hService != NULL)
    {
        CloseServiceHandle(hService);
    }
    return hr;
}
Exemple #2
0
DWORD UpdateService(char *NewName) {
    SC_HANDLE schService;
    DWORD res = ERROR_SUCCESS,
	  count = 0,
	  loop = 0,
	  lastCheck;
    SERVICE_STATUS status;
    res =  GetServiceHandle(&schService);
    if(res != ERROR_SUCCESS) return res;
  
    // Stop the actually running service
    if(!ControlService(schService,SERVICE_CONTROL_STOP,&status)) {
	res = GetLastError();
	CloseServiceHandle(schService);
	fprintf(stderr,"ControlService(SERVICE_CONTROL_STOP) failed (%d)\n",res);
	fflush(stderr);
	return res;
    }
    res = MoveFiles(NewName);
    QueryServiceStatus(schService,&status);
    lastCheck = status.dwCheckPoint;
    do {
	switch(status.dwCurrentState) {
	case SERVICE_STOPPED: break;
	case SERVICE_STOP_PENDING: Sleep(status.dwWaitHint); 
	                           // Fall through
	default: 
	    if(!QueryServiceStatus(schService,&status)) {
		res = GetLastError();
		status.dwCurrentState = SERVICE_STOPPED;
	    }
	    if(status.dwCurrentState != SERVICE_STOPPED && lastCheck == status.dwCheckPoint) {
	        ++loop;
	        Sleep(2000);
	    } else {
		loop = 0;
		lastCheck = status.dwCheckPoint;
	    }
	    break;
	}	
    } while(loop <=5 && status.dwCurrentState != SERVICE_STOPPED);
    
    
    if(!StartService(schService,0,NULL)) {
	res = GetLastError();
	fprintf(stderr,"StartService failed (%d)\n",res);
	fflush(stderr);
    }
    
    CloseServiceHandle(schService);

    return res;
}
Exemple #3
0
VOID Settings_Read()
{
	if (RegistryGetDWORD(UTASK_REG_BRANCH, UTASK_REG_SETTINGS_KEY, 
		L"PositionFix_AutoMode", (DWORD*) &settingIsAutoFix) != S_OK)
	{
		settingIsAutoFix = 1;
	}
	if (RegistryGetDWORD(UTASK_REG_BRANCH, UTASK_REG_SETTINGS_KEY, 
		L"PositionFix", (DWORD*) &settingPositionFixEnabled) != S_OK)
	{
		settingPositionFixEnabled = 1;
	}
	ExclusiveList_InitializeList();

	sizeStatusBar = ThemeLoader_GetStatusBarSize();
	sizeSoftkeyBar = ThemeLoader_GetSoftkeyBarSize();

	HANDLE hService = GetServiceHandle(L"UTS0:", NULL, 0);
	systemIsServiceEnabled = (hService == INVALID_HANDLE_VALUE || hService == NULL) ? FALSE : TRUE;
};
HRESULT Service_Monitor::StartServiceByName(LPCTSTR pServiceName, DWORD dwTimeOutSeconds)
{
    HRESULT hr = S_OK;
    SC_HANDLE hService = NULL;
    DWORD dwSleepTime = 0;
    DWORD dwRemainTime = dwTimeOutSeconds;

    hr = GetServiceHandle(pServiceName, &hService);

    if (SUCCEEDED(hr))
    {
        if (StartService(hService, 0, NULL) == FALSE)
        {
            DWORD dwError = GetLastError();
            if (dwError == ERROR_SERVICE_ALREADY_RUNNING)
            {
                dwError = ERROR_SUCCESS;
            }
            else
            {
                hr = HRESULT_FROM_WIN32(dwError);
            }
        }
        //
        // Query service status to make sure service is in running state
        //
        while(dwRemainTime >0)
        {
            DWORD     dwBytes = 0;
            SERVICE_STATUS_PROCESS sStatus;

            if (!QueryServiceStatusEx(hService,
                SC_STATUS_PROCESS_INFO,
                (LPBYTE)&sStatus,
                sizeof(SERVICE_STATUS_PROCESS),
                &dwBytes))
            {
                hr = HRESULT_FROM_WIN32(GetLastError());
                goto Finished;
            }

            if (sStatus.dwCurrentState == SERVICE_RUNNING)
            {
                goto Finished;
            }
            else if(sStatus.dwCurrentState == SERVICE_START_PENDING)
            {
                dwSleepTime = rand() % 10 + 1;
                dwSleepTime = dwSleepTime < dwRemainTime ? dwSleepTime : dwRemainTime;
                dwRemainTime -= dwSleepTime;
                Sleep(dwSleepTime * 1000);
            }
            else
            {
                //
                // Service fails to start 
                //
                hr = E_FAIL;
                goto Finished;
            }
        }
        //
        // Cannot start service within given time period
        //
        hr = HRESULT_FROM_WIN32(ERROR_TIMEOUT);
    }

    Finished:
    if(SUCCEEDED(hr))
    {
        _tprintf(L"\n Service '%s' started \n", pServiceName);
    }
    else
    {
        _tprintf(L"\nERROR: Failed to start or query status of service '%s' error [%x]\n", pServiceName, hr);
    }

    if (hService != NULL)
    {
        CloseServiceHandle(hService);
    }
    return hr;
}
HRESULT Service_Monitor::StopServiceByName(LPCTSTR pServiceName, DWORD dwTimeOutSeconds)
{
        HRESULT   hr = S_OK;
        SC_HANDLE hService = NULL;
        DWORD     dwBytes = 0;
        DWORD     dwSleepTime = 0;
        DWORD     dwRemainTime = dwTimeOutSeconds;
        SERVICE_STATUS_PROCESS sStatus;

        hr = GetServiceHandle(pServiceName, &hService);
        if (SUCCEEDED(hr)) 
        {
            if (!QueryServiceStatusEx(hService,
                SC_STATUS_PROCESS_INFO,
                (LPBYTE)&sStatus,
                sizeof(SERVICE_STATUS_PROCESS),
                &dwBytes))
            {
                hr = HRESULT_FROM_WIN32(GetLastError());
                goto Finished;
            }

            if (sStatus.dwCurrentState == SERVICE_STOPPED) 
            {
                //
                // Service has already been stopped, no action needed
                //
                goto Finished;
            }
            else if (sStatus.dwCurrentState != SERVICE_STOP_PENDING)
            {
                //
                // Sending stop signal
                //
                if (!ControlService(hService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&sStatus))
                {
                    hr = HRESULT_FROM_WIN32(GetLastError());
                    goto Finished;
                }
            }

            while (dwRemainTime >0)
            {
                DWORD     dwBytes = 0;

                if (!QueryServiceStatusEx(hService,
                    SC_STATUS_PROCESS_INFO,
                    (LPBYTE)&sStatus,
                    sizeof(SERVICE_STATUS_PROCESS),
                    &dwBytes))
                {
                    hr = HRESULT_FROM_WIN32(GetLastError());
                    goto Finished;
                }
                if (sStatus.dwCurrentState == SERVICE_STOPPED)
                {
                    goto Finished;
                }
                else if (sStatus.dwCurrentState == SERVICE_STOP_PENDING)
                {
                    dwSleepTime = rand() % 10 + 1;
                    dwSleepTime = dwSleepTime < dwRemainTime ? dwSleepTime : dwRemainTime;
                    dwRemainTime -= dwSleepTime;
                    Sleep(dwSleepTime * 1000);
                }
                else
                {
                    //
                    // Service fails to stop 
                    //
                    hr = E_FAIL;
                    goto Finished;
                }
            }
            //
            // cannot stop service within given time period
            //
            hr = HRESULT_FROM_WIN32(ERROR_TIMEOUT);

        }

    Finished: 
        if (SUCCEEDED(hr))
        {
            _tprintf(L"\n Service '%s' has been stopped \n", pServiceName);
        }
        else
        {
            _tprintf(L"\nERROR: Failed to stop or query status of service '%s' error [%x]\n", pServiceName, hr);
        }

        if (hService != NULL)
        {
            CloseServiceHandle(hService);
        }
        return hr;
    }
Exemple #6
0
INT _tmain(DWORD argc, LPCTSTR argv[])
{	
	FileInformation fCurrent = {0, 0, 0, 0, NULL};
	HANDLE hConfig = NULL, hParserHeap = NULL;
	ServiceSpecArray sEntries = NULL;
	LPTSTR lpFileData = NULL;
	DWORD dwRet = 0;

	if(argc == 2)
	{
		__try
		{
			hParserHeap = HeapCreate((HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS), 0, 0);
		
			sEntries = (ServiceSpecArray)HeapAlloc(hParserHeap, 
	
					 (HEAP_NO_SERIALIZE | HEAP_GENERATE_EXCEPTIONS), sizeof(ServSpec));
		}
		__except(ExceptionFilter(GetExceptionCode(), NULL))
		{
			ReportSysError(GetLastError());
			
			return 2;
		}
		
		hConfig = OpenServiceFile(argv[1]);
	
		if(hConfig)
		{
			INT32 fileSize = GetValidFileSize(hConfig);
			
			if(fileSize > 0)
			{
				lpFileData = (LPTSTR)HeapAlloc(hParserHeap, 
							 
							 (HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY), 
							 
							 (fileSize * sizeof(TCHAR)));
			
				if(ReadFileData(hConfig, lpFileData, fileSize) == 0)
				{
					dwRet = ParseData(lpFileData, &fCurrent, sEntries, hParserHeap);
				}
			}
		}
			
		if(dwRet == 0)
		{
			SC_HANDLE sControlMgr = InitSCM(SC_MANAGER_ALL_ACCESS);
			DWORD dwLine = 0;
			INT i = 0;
			
			_ftprintf(stdout, _T("\n Configuration file status:\n\n") 
			
							  _T(" Total lines: %i\n Total entries: %i\n Total comments: %i\n Total newlines: %i\n\n"),
			
					  fCurrent.dwLines, fCurrent.dwEntries, fCurrent.dwComments, fCurrent.dwNewLines);

			if(sControlMgr != NULL)
			{
				BOOL bSuccess = TRUE;
			
				for(i = 0; i < fCurrent.dwEntries; i++)
				{
					SC_HANDLE sService = GetServiceHandle(sControlMgr, sEntries[i]->tServiceName);
					
					if(sService != NULL)
					{
						if(dwRet = SetServiceConfig(sService, sEntries[i]->tServiceAction))
						{
							dwLine = fCurrent.eCurrent.dwEntryLine[i];
						
							bSuccess = FALSE;
						
							break;
						}
						
						StopServiceHandle(sService);
					}
					else
					{
						dwLine = fCurrent.eCurrent.dwEntryLine[i];
					
						bSuccess = FALSE;
					
						break;
					}
				}
				
				if(bSuccess)
				{
					_ftprintf(stdout, _T("\n [STATUS:Success] The configuration has been set on the current system!\n\n"));
				}
				else
				{
					_ftprintf(stderr, _T(" [LINE:%i]: The error above was toggled while trying to set the given entry.\n\n"), dwLine);
				}
				
				StopServiceHandle(sControlMgr);
			}
		}
		else
		{
			_ftprintf(stderr, _T("\n One or more syntax errors have been found.\n")
			
							  _T(" Please look over your configuration file.\n\n"), dwRet);
		}
			
		HeapDestroy(hParserHeap);
		
		CloseHandle(hConfig);
	}