//开始服务 bool CCenterService::StartService() { //停止服务 ASSERT(m_ServiceStatus!=ServiceStatus_Service); if (m_ServiceStatus==ServiceStatus_Service) return false; //终止服务 StopService(); //加载参数 m_InitParamter.LoadInitParamter(); //创建组件//OMA 获取接口失败并且创建接口失败,返回false if ((m_DataBaseEngine.GetInterface()==NULL)&&(m_DataBaseEngine.CreateInstance()==false)) return false; if ((m_AttemperEngine.GetInterface()==NULL)&&(m_AttemperEngine.CreateInstance()==false)) return false; if ((m_TCPNetworkEngine.GetInterface()==NULL)&&(m_TCPNetworkEngine.CreateInstance()==false)) return false; //组件接口 IUnknownEx * pIAttemperEngine=m_AttemperEngine.GetInterface(); IUnknownEx * pITCPNetworkEngine=m_TCPNetworkEngine.GetInterface(); //回调接口 IUnknownEx * pIDataBaseEngineSink=QUERY_OBJECT_INTERFACE(m_DataBaseEngineSink,IUnknownEx); IUnknownEx * pIAttemperEngineSink=QUERY_OBJECT_INTERFACE(m_AttemperEngineSink,IUnknownEx); //绑定接口 if (m_AttemperEngine->SetAttemperEngineSink(pIAttemperEngineSink)==false) return false; if (m_DataBaseEngine->SetDataBaseEngineSink(pIDataBaseEngineSink)==false) return false; //内核组件 if (m_AttemperEngine->SetNetworkEngine(pITCPNetworkEngine)==false) return false; if (m_TCPNetworkEngine->SetTCPNetworkEngineEvent(pIAttemperEngine)==false) return false; //调度回调 m_AttemperEngineSink.m_pInitParamter=&m_InitParamter; m_AttemperEngineSink.m_pIDataBaseEngine=m_DataBaseEngine.GetInterface(); m_AttemperEngineSink.m_pITCPNetworkEngine=m_TCPNetworkEngine.GetInterface(); //数据库回调 m_DataBaseEngineSink.m_pInitParamter=&m_InitParamter; m_DataBaseEngineSink.m_pIDataBaseEngineEvent=QUERY_OBJECT_PTR_INTERFACE(pIAttemperEngine,IDataBaseEngineEvent); //配置网络 WORD wMaxConnect=m_InitParamter.m_wMaxConnect; WORD wServicePort=m_InitParamter.m_wListenPort; if (m_TCPNetworkEngine->SetServiceParameter(wServicePort,wMaxConnect)==false) return false; //调度引擎 if (m_AttemperEngine->StartService()==false) { ASSERT(FALSE); return false; } //数据引擎 if (m_DataBaseEngine->StartService()==false) { ASSERT(FALSE); return false; } //网络引擎 if (m_TCPNetworkEngine->StartService()==false) { ASSERT(FALSE); return false; } //设置变量 m_ServiceStatus=ServiceStatus_Service; return true; }
/** * Installs or upgrades the SVC_NAME service. * If an existing service is already installed, we replace it with the * currently running process. * * @param action The action to perform. * @return TRUE if the service was installed/upgraded */ BOOL SvcInstall(SvcInstallAction action) { // Get a handle to the local computer SCM database with full access rights. nsAutoServiceHandle schSCManager(OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)); if (!schSCManager) { LOG(("Could not open service manager. (%d)\n", GetLastError())); return FALSE; } WCHAR newServiceBinaryPath[MAX_PATH + 1]; if (!GetModuleFileNameW(NULL, newServiceBinaryPath, sizeof(newServiceBinaryPath) / sizeof(newServiceBinaryPath[0]))) { LOG(("Could not obtain module filename when attempting to " "install service. (%d)\n", GetLastError())); return FALSE; } // Check if we already have the service installed. nsAutoServiceHandle schService(OpenServiceW(schSCManager, SVC_NAME, SERVICE_ALL_ACCESS)); DWORD lastError = GetLastError(); if (!schService && ERROR_SERVICE_DOES_NOT_EXIST != lastError) { // The service exists but we couldn't open it LOG(("Could not open service. (%d)\n", GetLastError())); return FALSE; } if (schService) { // The service exists but it may not have the correct permissions. // This could happen if the permissions were not set correctly originally // or have been changed after the installation. This will reset the // permissions back to allow limited user accounts. if (!SetUserAccessServiceDACL(schService)) { LOG(("Could not reset security ACE on service handle. It might not be " "possible to start the service. This error should never " "happen. (%d)\n", GetLastError())); } // The service exists and we opened it DWORD bytesNeeded; if (!QueryServiceConfigW(schService, NULL, 0, &bytesNeeded) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { LOG(("Could not determine buffer size for query service config. (%d)\n", GetLastError())); return FALSE; } // Get the service config information, in particular we want the binary // path of the service. nsAutoArrayPtr<char> serviceConfigBuffer = new char[bytesNeeded]; if (!QueryServiceConfigW(schService, reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()), bytesNeeded, &bytesNeeded)) { LOG(("Could open service but could not query service config. (%d)\n", GetLastError())); return FALSE; } QUERY_SERVICE_CONFIGW &serviceConfig = *reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()); // Ensure the service path is not quoted. We own this memory and know it to // be large enough for the quoted path, so it is large enough for the // unquoted path. This function cannot fail. PathUnquoteSpacesW(serviceConfig.lpBinaryPathName); // Obtain the existing maintenanceservice file's version number and // the new file's version number. Versions are in the format of // A.B.C.D. DWORD existingA, existingB, existingC, existingD; DWORD newA, newB, newC, newD; BOOL obtainedExistingVersionInfo = GetVersionNumberFromPath(serviceConfig.lpBinaryPathName, existingA, existingB, existingC, existingD); if (!GetVersionNumberFromPath(newServiceBinaryPath, newA, newB, newC, newD)) { LOG(("Could not obtain version number from new path\n")); return FALSE; } // Check if we need to replace the old binary with the new one // If we couldn't get the old version info then we assume we should // replace it. if (ForceInstallSvc == action || !obtainedExistingVersionInfo || (existingA < newA) || (existingA == newA && existingB < newB) || (existingA == newA && existingB == newB && existingC < newC) || (existingA == newA && existingB == newB && existingC == newC && existingD < newD)) { // We have a newer updater, so update the description from the INI file. UpdateServiceDescription(schService); schService.reset(); if (!StopService()) { return FALSE; } if (!wcscmp(newServiceBinaryPath, serviceConfig.lpBinaryPathName)) { LOG(("File is already in the correct location, no action needed for " "upgrade.\n")); return TRUE; } BOOL result = TRUE; // Attempt to copy the new binary over top the existing binary. // If there is an error we try to move it out of the way and then // copy it in. First try the safest / easiest way to overwrite the file. if (!CopyFileW(newServiceBinaryPath, serviceConfig.lpBinaryPathName, FALSE)) { LOG(("Could not overwrite old service binary file. " "This should never happen, but if it does the next upgrade will " "fix it, the service is not a critical component that needs to be " "installed for upgrades to work. (%d)\n", GetLastError())); // We rename the last 3 filename chars in an unsafe way. Manually // verify there are more than 3 chars for safe failure in MoveFileExW. const size_t len = wcslen(serviceConfig.lpBinaryPathName); if (len > 3) { // Calculate the temp file path that we're moving the file to. This // is the same as the proper service path but with a .old extension. LPWSTR oldServiceBinaryTempPath = new WCHAR[wcslen(serviceConfig.lpBinaryPathName) + 1]; wcscpy(oldServiceBinaryTempPath, serviceConfig.lpBinaryPathName); // Rename the last 3 chars to 'old' wcscpy(oldServiceBinaryTempPath + len - 3, L"old"); // Move the current (old) service file to the temp path. if (MoveFileExW(serviceConfig.lpBinaryPathName, oldServiceBinaryTempPath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { // The old binary is moved out of the way, copy in the new one. if (!CopyFileW(newServiceBinaryPath, serviceConfig.lpBinaryPathName, FALSE)) { // It is best to leave the old service binary in this condition. LOG(("ERROR: The new service binary could not be copied in." " The service will not be upgraded.\n")); result = FALSE; } else { LOG(("The new service binary was copied in by first moving the" " old one out of the way.\n")); } // Attempt to get rid of the old service temp path. if (DeleteFileW(oldServiceBinaryTempPath)) { LOG(("The old temp service path was deleted: %ls.\n", oldServiceBinaryTempPath)); } else { // The old temp path could not be removed. It will be removed // the next time the user can't copy the binary in or on uninstall. LOG(("WARNING: The old temp service path was not deleted.\n")); } } else { // It is best to leave the old service binary in this condition. LOG(("ERROR: Could not move old service file out of the way from:" " \"%ls\" to \"%ls\". Service will not be upgraded. (%d)\n", serviceConfig.lpBinaryPathName, oldServiceBinaryTempPath, GetLastError())); result = FALSE; } delete[] oldServiceBinaryTempPath; } else { // It is best to leave the old service binary in this condition. LOG(("ERROR: Service binary path was less than 3, service will" " not be updated. This should never happen.\n")); result = FALSE; } } else { LOG(("The new service binary was copied in.\n")); } // We made a copy of ourselves to the existing location. // The tmp file (the process of which we are executing right now) will be // left over. Attempt to delete the file on the next reboot. if (MoveFileExW(newServiceBinaryPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) { LOG(("Deleting the old file path on the next reboot: %ls.\n", newServiceBinaryPath)); } else { LOG(("Call to delete the old file path failed: %ls.\n", newServiceBinaryPath)); } return result; } // We don't need to copy ourselves to the existing location. // The tmp file (the process of which we are executing right now) will be // left over. Attempt to delete the file on the next reboot. MoveFileExW(newServiceBinaryPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); // nothing to do, we already have a newer service installed return TRUE; } // If the service does not exist and we are upgrading, don't install it. if (UpgradeSvc == action) { // The service does not exist and we are upgrading, so don't install it return TRUE; } // Quote the path only if it contains spaces. PathQuoteSpacesW(newServiceBinaryPath); // The service does not already exist so create the service as on demand schService.own(CreateServiceW(schSCManager, SVC_NAME, SVC_DISPLAY_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, newServiceBinaryPath, NULL, NULL, NULL, NULL, NULL)); if (!schService) { LOG(("Could not create Windows service. " "This error should never happen since a service install " "should only be called when elevated. (%d)\n", GetLastError())); return FALSE; } if (!SetUserAccessServiceDACL(schService)) { LOG(("Could not set security ACE on service handle, the service will not " "be able to be started from unelevated processes. " "This error should never happen. (%d)\n", GetLastError())); } UpdateServiceDescription(schService); return TRUE; }
/*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CurlBlastDlg::DoStartup(void) { QueryPerfFrequency(freq); InstallFlash(); log.LogEvent(event_Started); log.LogMachineInfo(); // register pagetest if we have a dll locally TCHAR pagetest[MAX_PATH]; if( GetModuleFileName(NULL, pagetest, _countof(pagetest)) ) { lstrcpy( PathFindFileName(pagetest), _T("pagetest.dll") ); HMODULE hPagetest = LoadLibrary(pagetest); if( hPagetest ) { SetStatus(_T("Registering pagetest...")); DLLREGISTERSERVER proc = (DLLREGISTERSERVER)GetProcAddress(hPagetest, "DllRegisterServer"); if( proc ) proc(); FreeLibrary(hPagetest); } } InstallSystemGDIHook(); // stop services that can interfere with our measurements SetStatus(_T("Stoping services...")); StopService(_T("WinDefend")); // defender StopService(_T("wscsvc")); // security center // kill the action center (next reboot) HKEY hKey; if( SUCCEEDED(RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_SET_VALUE, &hKey)) ) { DWORD val = 1; RegSetValueEx(hKey, _T("HideSCAHealth"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val)); RegCloseKey(hKey); } if( SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_SET_VALUE, &hKey)) ) { RegDeleteValue(hKey, _T("HideSCAHealth")); RegCloseKey(hKey); } // set the OS to not boost foreground processes if( SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\PriorityControl"), 0, KEY_SET_VALUE, &hKey)) ) { DWORD val = 0x18; RegSetValueEx(hKey, _T("Win32PrioritySeparation"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val)); RegCloseKey(hKey); } // block IE9 automatic install if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\Setup\\9.0"), 0, 0, 0, KEY_READ | KEY_WRITE, NULL, &hKey, NULL)) ) { DWORD val = 1; RegSetValueEx(hKey, _T("DoNotAllowIE90"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val)); RegCloseKey(hKey); } // block IE10 automatic install if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\Setup\\10.0"), 0, 0, 0, KEY_READ | KEY_WRITE, NULL, &hKey, NULL)) ) { DWORD val = 1; RegSetValueEx(hKey, _T("DoNotAllowIE10"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val)); RegCloseKey(hKey); } // block IE11 automatic install if( SUCCEEDED(RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\Setup\\11.0"), 0, 0, 0, KEY_READ | KEY_WRITE, NULL, &hKey, NULL)) ) { DWORD val = 1; RegSetValueEx(hKey, _T("DoNotAllowIE11"), 0, REG_DWORD, (LPBYTE)&val, sizeof(val)); RegCloseKey(hKey); } // start up the url manager urlManager.Start(); // create all of the worker SetStatus(_T("Starting worker...")); CRect desktop(0,0,browserWidth,browserHeight); // launch the worker thread worker = new CURLBlaster(m_hWnd, log, ipfw, testingMutex, *this); // pass on configuration information worker->errorLog = logFile; worker->urlManager = &urlManager; worker->timeout = timeout; worker->desktop = desktop; worker->customEventText= customEventText; worker->accountBase = accountBase; worker->password = password; worker->preLaunch = preLaunch; worker->postLaunch = postLaunch; worker->dynaTrace = dynaTrace; worker->pipeIn = pipeIn; worker->pipeOut = pipeOut; worker->useBitBlt = 1; worker->keepDNS = keepDNS; // force 1024x768 for screen shots worker->pos.right = browserWidth; worker->pos.bottom = browserHeight; if( useCurrentAccount ) worker->hProfile = HKEY_CURRENT_USER; worker->Start(1); SetStatus(_T("Running...")); running = true; }
BOOL DoStop(PMAIN_WND_INFO pInfo) { HWND hProgress; LPWSTR lpServiceList; BOOL bRet = FALSE; BOOL bStopMainService = TRUE; if (pInfo) { /* Does the service have any dependent services which need stopping first */ lpServiceList = GetListOfServicesToStop(pInfo->pCurrentService->lpServiceName); if (lpServiceList) { /* Tag the service list to the main wnd info */ pInfo->pTag = (PVOID)lpServiceList; /* List them and ask the user if they want to stop them */ if (DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_DLG_DEPEND_STOP), pInfo->hMainWnd, StopDependsDialogProc, (LPARAM)pInfo) == IDOK) { /* Create a progress window to track the progress of the stopping services */ hProgress = CreateProgressDialog(pInfo->hMainWnd, IDS_PROGRESS_INFO_STOP); /* Stop all the dependant services */ StopDependantServices(pInfo, lpServiceList, hProgress); /* Now stop the requested one */ bRet = StopService(pInfo, pInfo->pCurrentService->lpServiceName, hProgress); /* We've already stopped the main service, don't try to stop it again */ bStopMainService = FALSE; if (hProgress) { /* Complete and destroy the progress bar */ DestroyProgressDialog(hProgress, TRUE); } } else { /* Don't stop the main service if the user selected not to */ bStopMainService = FALSE; } HeapFree(GetProcessHeap(), 0, lpServiceList); } /* If the service has no running dependents, then we stop it here */ if (bStopMainService) { /* Create a progress window to track the progress of the stopping service */ hProgress = CreateProgressDialog(pInfo->hMainWnd, IDS_PROGRESS_INFO_STOP); /* Stop the requested service */ bRet = StopService(pInfo, pInfo->pCurrentService->lpServiceName, hProgress); if (hProgress) { /* Complete and destroy the progress bar */ DestroyProgressDialog(hProgress, TRUE); } } } return bRet; }
void main(int argc, char* argv[]) { // error message wchar_t pTemp[121]; unsigned int errStrSize = 120; // initialize global critical section ::InitializeCriticalSection(&gCS); // initialize variables for .exe, .ini, and .log file names wchar_t pModuleFile[nBufferSize + 1]; DWORD dwSize = GetModuleFileName(nullptr, (LPTSTR)pModuleFile, nBufferSize); pModuleFile[dwSize] = 0; if (dwSize > 4 && pModuleFile[dwSize - 4] == '.') { swprintf(pExeFile, nBufferSize, L"%s", pModuleFile); pModuleFile[dwSize - 4] = 0; swprintf(pLogFile, nBufferSize, L"%s.log", pModuleFile); } else { printf("Invalid module file name: %ws\r\n", pModuleFile); return; } WriteLog(pExeFile); WriteLog(pLogFile); wcscpy_s(pServiceName, 500, L"CodeXLDriversLoadService"); WriteLog(pServiceName); // uninstall service if switch is "-u" if (argc == 2 && _stricmp("-uninstall", argv[1]) == 0) { UnInstall(pServiceName); } // install service if switch is "-i" else if (argc == 2 && _stricmp("-install", argv[1]) == 0) { Install(pExeFile, pServiceName); } // stop a service with given name else if (argc == 2 && _stricmp("-stop", argv[1]) == 0) { if (StopService(pServiceName)) { swprintf(pTemp, errStrSize, L"Stopped service %s", pServiceName); WriteLog(pTemp); } else { swprintf(pTemp, errStrSize, L"Failed to stop service %s", pServiceName); WriteLog(pTemp); } } // run a service with given name else if (argc == 2 && _stricmp("-start", argv[1]) == 0) { WriteLog(L"StartService"); if (StartService(pServiceName, 0, nullptr)) { swprintf(pTemp, errStrSize, L"Ran service %s", pServiceName); WriteLog(pTemp); } else { swprintf(pTemp, errStrSize, L"Failed to run service %s", pServiceName); WriteLog(pTemp); } } // assume user is starting this service else { // start a worker thread to load driver if (_beginthread(WorkerProc, 0, nullptr) == -1) { WriteErrorLog(L"_beginthread failed"); } // pass dispatch table to service controller if (!StartServiceCtrlDispatcher(DispatchTable)) { WriteErrorLog(L"StartServiceCtrlDispatcher failed"); } // you don't get here unless the service is shutdown } ::DeleteCriticalSection(&gCS); }
//开始服务 bool CLogonService::StartService() { try { //变量定义 bool bSuccess=false; //创建服务对象 if (m_ServiceEngine.GetInterface()==false) { if (m_ServiceEngine.CreateInstance()==false) throw m_ServiceEngine.GetErrorMessage(); if (m_pIEventService!=NULL) m_ServiceEngine->SetEventService(m_pIEventService); //注册调度外挂服务 IUnknownEx * pIAttemperEngine=GET_OBJECT_INTERFACE(m_AttemperSink,IUnknownEx); if (m_ServiceEngine->SetAttemperEngineSink(pIAttemperEngine)==false) throw 0; //注册数据库外挂服务 IUnknownEx * pIDataBaseSink=GET_OBJECT_INTERFACE(m_DataBaseSink,IUnknownEx); if (m_ServiceEngine->SetDataBaseSink(pIDataBaseSink)==false) throw 0; } //判断状态 if (m_ServiceEngine->IsService()==true) { TraceEventString(TEXT("登录服务已经了启动了"),Level_Warning); return true; } //配置服务 m_InitParamter.LoadInitParamter(); if (m_DataBaseSink.InitDataBaseSink(&m_InitParamter,m_ServiceEngine.GetInterface())==false) throw 0; if (m_AttemperSink.InitAttemperSink(&m_InitParamter,&m_CenterSocket,m_ServiceEngine.GetInterface())==false) throw 0; if (m_ServiceEngine->InitServiceEngine(m_InitParamter.m_wListenPort,m_InitParamter.m_wMaxConnect)==false) throw 0; //获取调度引擎 IAttemperEngine * pIAttemperEngine=(IAttemperEngine *)m_ServiceEngine->GetAttemperEngine(IID_IAttemperEngine,VER_IAttemperEngine); ASSERT(pIAttemperEngine!=NULL); if (pIAttemperEngine==NULL) throw TEXT("调度引擎接口查询失败"); //获取调度队列 IQueueService * pIQueueService=(IQueueService *)pIAttemperEngine->GetQueueService(IID_IQueueService,VER_IQueueService); ASSERT(pIQueueService!=NULL); if (pIQueueService==NULL) throw TEXT("调度引擎队列服务接口查询失败"); //获取异步引擎 IAsynchronismEngine * pIAsynchronismEngine=(IAsynchronismEngine *)m_ServiceEngine->GetAsynchronismEngine(IID_IAsynchronismEngine,VER_IAsynchronismEngine); ASSERT(pIAsynchronismEngine!=NULL); if (pIAsynchronismEngine==NULL) throw TEXT("异步引擎队务接口查询失败"); //中心连接 if (m_CenterSocket.SetQueueService(pIQueueService)==false) throw 0; if (m_CenterSocket.SetAsynchronismEngine(pIAsynchronismEngine)==false) throw 0; //注册对象 IAsynchronismEngineSink * pIAsynchronismEngineSink=GET_OBJECT_INTERFACE(m_CenterSocket,IAsynchronismEngineSink); if (pIAsynchronismEngine->RegisterAsynchronismEngineSink(pIAsynchronismEngineSink)==false) throw TEXT("中心连接异步对象注册失败"); //启动服务 if (m_ServiceEngine->StartService()==false) throw 0; return true; } catch (LPCTSTR pszErrorMsg) { TraceEventString(pszErrorMsg,Level_Exception); TraceEventString(TEXT("登录服务启动失败"),Level_Exception); StopService(); } catch (...) { TraceEventString(TEXT("登录服务启动失败"),Level_Exception); StopService(); } return false; }