int InstallRemoteService( char *szComputerName ) { /* #ifdef __DEBUG__ char szRemotePath[MAX_PATH] = {0}; sprintf( szRemotePath, "\\\\%s\\%s\\execserver.exe", szComputerName, ADMIN ); if ( !CopyFile( SERVER, REMOTE_PATH1, FALSE ) ) { if ( !CopyFile( "execserver.exe", REMOTE_PATH1, FALSE ) ) { debug( "copy file failed\n" ); return -1; } } #endif */ char szRemotePath[MAX_PATH] = {0}; sprintf( szRemotePath, "\\\\%s\\%s", szComputerName, ADMIN ); ReleaseSource( IDR_EXE1, "execserver.exe", "EXE", szRemotePath ); SC_HANDLE schSCManager; SC_HANDLE schService; schSCManager = OpenSCManager( szComputerName, NULL, SC_MANAGER_ALL_ACCESS ); if ( !schSCManager ) { debug( "open service manager failed: %d\n", GetLastError() ); return -1; } schService = CreateService( schSCManager, SERVICE_NAME, SERVICE_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, SERVER_DIR, NULL, NULL, NULL, NULL, NULL ); if ( !schService ) { if ( GetLastError() != ERROR_SERVICE_EXISTS ) { debug( "create service failed: %d\n", GetLastError() ); CloseServiceHandle( schSCManager ); return -1; } } schService = OpenService( schSCManager, SERVICE_NAME, GENERIC_ALL ); if ( !schService ) { debug( "open service failed: %d\n", GetLastError() ); CloseServiceHandle( schSCManager ); return -1; } StartService( schService, 0, NULL ); CloseServiceHandle( schSCManager ); CloseServiceHandle( schService ); return 0; }
void smpd_install_service(SMPD_BOOL interact, SMPD_BOOL bSetupRestart, SMPD_BOOL bSetupScp) { SC_HANDLE schService; SC_HANDLE schSCManager; TCHAR szErr[256]; TCHAR szPathQuoted[SMPD_MAX_FILENAME_QUOTED]; LPTSTR pszPathQuoted; pszPathQuoted = szPathQuoted; /* The smpd module file name has to be quoted before passing to CreateService() --- refer MSDN doc for * CreateService() */ _stprintf(pszPathQuoted, TEXT("\"")); if ( GetModuleFileName( NULL, pszPathQuoted+1, SMPD_MAX_FILENAME ) == 0 ) { _tprintf(TEXT("Unable to install %s.\n%s\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME), smpd_get_last_error_text(szErr, 256)); fflush(stdout); return; } _stprintf(pszPathQuoted + _tcslen(pszPathQuoted), TEXT("\"")); schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if ( schSCManager ) { DWORD type = SERVICE_WIN32_OWN_PROCESS; if (interact) type = type | SERVICE_INTERACTIVE_PROCESS; schService = CreateService( schSCManager, /* SCManager database */ TEXT(SMPD_SERVICE_NAME), /* name of service */ TEXT(SMPD_SERVICE_DISPLAY_NAME), /* name to display */ SERVICE_ALL_ACCESS, /* desired access */ type, SERVICE_AUTO_START, /*SERVICE_ERROR_NORMAL,*/ /* error control type */ SERVICE_ERROR_IGNORE, szPathQuoted, /* service's binary */ NULL, /* no load ordering group */ NULL, /* no tag identifier */ TEXT(""), /* dependencies */ NULL, /* LocalSystem account if account==NULL */ NULL); if ( schService ) { if (bSetupRestart) smpd_setup_service_restart( schService ); if (bSetupScp) { smpd_register_spn(NULL, NULL, NULL); } /* Start the service */ if (StartService(schService, 0, NULL)) _tprintf(TEXT("%s installed.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME) ); else _tprintf(TEXT("%s installed, but failed to start:\n%s.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME), smpd_get_last_error_text(szErr, 256) ); fflush(stdout); CloseServiceHandle(schService); } else { _tprintf(TEXT("CreateService failed:\n%s\n"), smpd_get_last_error_text(szErr, 256)); fflush(stdout); } CloseServiceHandle(schSCManager); } else { _tprintf(TEXT("OpenSCManager failed:\n%s\n"), smpd_get_last_error_text(szErr,256)); fflush(stdout); } }
BOOL Create(LPCTSTR *ServiceArgs, INT ArgCount) { SC_HANDLE hSCManager; SC_HANDLE hSc; BOOL bRet = FALSE; INT i; INT Length; LPTSTR lpBuffer = NULL; SERVICE_CREATE_INFO ServiceInfo; if (!ParseCreateArguments(ServiceArgs, ArgCount, &ServiceInfo)) { CreateUsage(); return FALSE; } if (!ServiceInfo.dwServiceType) ServiceInfo.dwServiceType = SERVICE_WIN32_OWN_PROCESS; if (!ServiceInfo.dwStartType) ServiceInfo.dwStartType = SERVICE_DEMAND_START; if (!ServiceInfo.dwErrorControl) ServiceInfo.dwErrorControl = SERVICE_ERROR_NORMAL; if (ServiceInfo.lpDependencies) { Length = lstrlen(ServiceInfo.lpDependencies); lpBuffer = HeapAlloc(GetProcessHeap(), 0, (Length + 2) * sizeof(TCHAR)); for (i = 0; i < Length; i++) if (ServiceInfo.lpDependencies[i] == _T('/')) lpBuffer[i] = 0; else lpBuffer[i] = ServiceInfo.lpDependencies[i]; lpBuffer[Length] = 0; lpBuffer[Length + 1] = 0; ServiceInfo.lpDependencies = lpBuffer; } #ifdef SCDBG _tprintf(_T("service name - %s\n"), ServiceInfo.lpServiceName); _tprintf(_T("display name - %s\n"), ServiceInfo.lpDisplayName); _tprintf(_T("service type - %lu\n"), ServiceInfo.dwServiceType); _tprintf(_T("start type - %lu\n"), ServiceInfo.dwStartType); _tprintf(_T("error control - %lu\n"), ServiceInfo.dwErrorControl); _tprintf(_T("Binary path - %s\n"), ServiceInfo.lpBinaryPathName); _tprintf(_T("load order group - %s\n"), ServiceInfo.lpLoadOrderGroup); _tprintf(_T("tag - %lu\n"), ServiceInfo.dwTagId); _tprintf(_T("dependencies - %s\n"), ServiceInfo.lpDependencies); _tprintf(_T("account start name - %s\n"), ServiceInfo.lpServiceStartName); _tprintf(_T("account password - %s\n"), ServiceInfo.lpPassword); #endif hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (hSCManager != NULL) { hSc = CreateService(hSCManager, ServiceInfo.lpServiceName, ServiceInfo.lpDisplayName, SERVICE_ALL_ACCESS, ServiceInfo.dwServiceType, ServiceInfo.dwStartType, ServiceInfo.dwErrorControl, ServiceInfo.lpBinaryPathName, ServiceInfo.lpLoadOrderGroup, ServiceInfo.bTagId ? &ServiceInfo.dwTagId : NULL, ServiceInfo.lpDependencies, ServiceInfo.lpServiceStartName, ServiceInfo.lpPassword); if (hSc != NULL) { _tprintf(_T("[SC] CreateService SUCCESS\n")); CloseServiceHandle(hSc); bRet = TRUE; } else ReportLastError(); CloseServiceHandle(hSCManager); } else ReportLastError(); if (lpBuffer != NULL) HeapFree(GetProcessHeap(), 0, lpBuffer); return bRet; }
// // FUNCTION: InstallService // // PURPOSE: Install the current application as a service to the local // service control manager database. // // PARAMETERS: // * pszServiceName - the name of the service to be installed // * pszDisplayName - the display name of the service // * dwStartType - the service start option. This parameter can be one of // the following values: SERVICE_AUTO_START, SERVICE_BOOT_START, // SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START. // * pszDependencies - a pointer to a double null-terminated array of null- // separated names of services or load ordering groups that the system // must start before this service. // * pszAccount - the name of the account under which the service runs. // * pszPassword - the password to the account name. // // NOTE: If the function fails to install the service, it prints the error // in the standard output stream for users to diagnose the problem. // void InstallService(PWSTR pszServiceName, PWSTR pszDisplayName, DWORD dwStartType, PWSTR pszDependencies, PWSTR pszAccount, PWSTR pszPassword) { wchar_t szPath[MAX_PATH]; SC_HANDLE schSCManager = NULL; SC_HANDLE schService = NULL; if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) == 0) { wprintf(L"GetModuleFileName failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } // Open the local default service control manager database schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE); if (schSCManager == NULL) { wprintf(L"OpenSCManager failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } // Install the service into SCM by calling CreateService schService = CreateService( schSCManager, // SCManager database pszServiceName, // Name of service pszDisplayName, // Name to display SERVICE_QUERY_STATUS, // Desired access SERVICE_WIN32_OWN_PROCESS, // Service type dwStartType, // Service start type SERVICE_ERROR_NORMAL, // Error control type szPath, // Service's binary NULL, // No load ordering group NULL, // No tag identifier pszDependencies, // Dependencies pszAccount, // Service running account pszPassword // Password of the account ); if (schService == NULL) { wprintf(L"CreateService failed w/err 0x%08lx\n", GetLastError()); goto Cleanup; } wprintf(L"%s is installed.\n", pszServiceName); Cleanup: // Centralized cleanup for all allocated resources. if (schSCManager) { CloseServiceHandle(schSCManager); schSCManager = NULL; } if (schService) { CloseServiceHandle(schService); schService = NULL; } }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { if( lpCmdLine[0] == _T('-') || lpCmdLine[0] == _T('/') ){ if( lstrcmpi(_T("install"), lpCmdLine + 1) == 0 ){ bool installed = false; TCHAR exePath[512]; if( GetModuleFileName(NULL, exePath, _countof(exePath)) != 0 ){ SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE); if( hScm != NULL ){ SC_HANDLE hSrv = CreateService( hScm, SERVICE_NAME, SERVICE_NAME, 0, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, exePath, NULL, NULL, NULL, NULL, NULL); if( hSrv != NULL ){ installed = true; CloseServiceHandle(hSrv); } CloseServiceHandle(hScm); } } if( installed == false ){ //コンソールがないのでメッセージボックスで伝える MessageBox(NULL, L"Failed to install/remove " SERVICE_NAME L".\r\nRun as Administrator on Vista and later.", NULL, MB_ICONERROR); } return 0; }else if( lstrcmpi(_T("remove"), lpCmdLine + 1) == 0 ){ bool removed = false; SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if( hScm != NULL ){ SC_HANDLE hSrv = OpenService(hScm, SERVICE_NAME, DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS); if( hSrv != NULL ){ SERVICE_STATUS srvStatus; if( QueryServiceStatus(hSrv, &srvStatus) != FALSE ){ if( srvStatus.dwCurrentState == SERVICE_STOPPED || ControlService(hSrv, SERVICE_CONTROL_STOP, &srvStatus) != FALSE ){ removed = DeleteService(hSrv) != FALSE; } } CloseServiceHandle(hSrv); } CloseServiceHandle(hScm); } if( removed == false ){ MessageBox(NULL, L"Failed to install/remove " SERVICE_NAME L".\r\nRun as Administrator on Vista and later.", NULL, MB_ICONERROR); } return 0; } } if( IsInstallService(SERVICE_NAME) == FALSE ){ //普通にexeとして起動を行う HANDLE hMutex = CreateMutex(NULL, TRUE, EPG_TIMER_BON_SRV_MUTEX); if( hMutex != NULL ){ if( GetLastError() != ERROR_ALREADY_EXISTS ){ StartDebugLog(); //メインスレッドに対するCOMの初期化 CoInitialize(NULL); CEpgTimerSrvMain* pMain = new CEpgTimerSrvMain; if( pMain->Main(false) == false ){ OutputDebugString(_T("_tWinMain(): Failed to start\r\n")); } delete pMain; CoUninitialize(); StopDebugLog(); } ReleaseMutex(hMutex); CloseHandle(hMutex); } }else if( IsStopService(SERVICE_NAME) == FALSE ){ //サービスとして実行 HANDLE hMutex = CreateMutex(NULL, TRUE, EPG_TIMER_BON_SRV_MUTEX); if( hMutex != NULL ){ if( GetLastError() != ERROR_ALREADY_EXISTS ){ StartDebugLog(); SERVICE_TABLE_ENTRY dispatchTable[] = { { SERVICE_NAME, service_main }, { NULL, NULL } }; if( StartServiceCtrlDispatcher(dispatchTable) == FALSE ){ OutputDebugString(_T("_tWinMain(): StartServiceCtrlDispatcher failed\r\n")); } StopDebugLog(); } ReleaseMutex(hMutex); CloseHandle(hMutex); } }else{ //Stop状態なのでサービスの開始を要求 bool started = false; SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if( hScm != NULL ){ SC_HANDLE hSrv = OpenService(hScm, SERVICE_NAME, SERVICE_START); if( hSrv != NULL ){ started = StartService(hSrv, 0, NULL) != FALSE; CloseServiceHandle(hSrv); } CloseServiceHandle(hScm); } if( started == false ){ OutputDebugString(_T("_tWinMain(): Failed to start\r\n")); } } return 0; }
int main(int argc, char *argv[]) { char *bslash; VerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&VerInfo); if (argc < 2) { show_usage(); return -1; } hAdvapi = LoadLibrary("advapi32.dll"); uChangeServiceConfig2 = (UCHANGESERVICECONFIG2)GetProcAddress(hAdvapi, "ChangeServiceConfig2A"); if (!stricmp(argv[1], "install")) { SC_HANDLE hService, hSCManager; char path[MAX_PATH+1]; char binpath[MAX_PATH+1]; hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (!hSCManager) { exit(0); } GetModuleFileName(NULL,path,MAX_PATH); if ((bslash = strrchr(path, '\\'))) *bslash = 0; strcpy(binpath,path); strcat(binpath, "\\wircd.exe"); hService = CreateService(hSCManager, "UnrealIRCd", "UnrealIRCd", SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, binpath, NULL, NULL, NULL, NULL, NULL); if (hService) { printf("UnrealIRCd NT Service successfully installed"); if (VerInfo.dwMajorVersion >= 5) { SERVICE_DESCRIPTION info; info.lpDescription = "Internet Relay Chat Server. Allows users to chat with eachother via an IRC client."; uChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &info); } CloseServiceHandle(hService); } else printf("Failed to install UnrealIRCd NT Service - %s", show_error(GetLastError())); CloseServiceHandle(hSCManager); return 0; } else if (!stricmp(argv[1], "uninstall")) { SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", DELETE); if (DeleteService(hService)) printf("UnrealIRCd NT Service successfully uninstalled"); else printf("Failed to uninstall UnrealIRCd NT Service - %s", show_error(GetLastError())); CloseServiceHandle(hService); CloseServiceHandle(hSCManager); return 0; } else if (!stricmp(argv[1], "start")) { SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_START); if (StartService(hService, 0, NULL)) printf("UnrealIRCd NT Service successfully started"); else printf("Failed to start UnrealIRCd NT Service - %s", show_error(GetLastError())); CloseServiceHandle(hService); CloseServiceHandle(hSCManager); return 0; } else if (!stricmp(argv[1], "stop")) { SERVICE_STATUS status; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP); ControlService(hService, SERVICE_CONTROL_STOP, &status); printf("UnrealIRCd NT Service successfully stopped"); CloseServiceHandle(hService); CloseServiceHandle(hSCManager); return 0; } else if (!stricmp(argv[1], "restart")) { SERVICE_STATUS status; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP|SERVICE_START); ControlService(hService, SERVICE_CONTROL_STOP, &status); if (StartService(hService, 0, NULL)) printf("UnrealIRCd NT Service successfully restarted"); CloseServiceHandle(hService); CloseServiceHandle(hSCManager); return 0; } else if (!stricmp(argv[1], "rehash")) { SERVICE_STATUS status; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_USER_DEFINED_CONTROL); ControlService(hService, IRCD_SERVICE_CONTROL_REHASH, &status); printf("UnrealIRCd NT Service successfully rehashed"); } else if (!stricmp(argv[1], "config")) { SERVICE_STATUS status; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_CHANGE_CONFIG|SERVICE_START); if (argc < 3) { show_usage(); return -1; } if (!stricmp(argv[2], "startup")) { if (ChangeServiceConfig(hService, SERVICE_NO_CHANGE, !stricmp(argv[3], "auto") ? SERVICE_AUTO_START : SERVICE_DEMAND_START, SERVICE_NO_CHANGE, NULL, NULL, NULL, NULL, NULL, NULL, NULL)) printf("UnrealIRCd NT Service configuration changed"); else printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError())); } else if (!stricmp(argv[2], "crashrestart") && VerInfo.dwMajorVersion == 5) { SERVICE_FAILURE_ACTIONS hFailActions; SC_ACTION hAction; memset(&hFailActions, 0, sizeof(hFailActions)); if (argc >= 4) { hFailActions.dwResetPeriod = 30; hFailActions.cActions = 1; hAction.Type = SC_ACTION_RESTART; hAction.Delay = atoi(argv[3])*60000; hFailActions.lpsaActions = &hAction; if (uChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, &hFailActions)) printf("UnrealIRCd NT Service configuration changed"); else printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError())); } else { hFailActions.dwResetPeriod = 0; hFailActions.cActions = 0; hAction.Type = SC_ACTION_NONE; hFailActions.lpsaActions = &hAction; if (uChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, &hFailActions)) printf("UnrealIRCd NT Service configuration changed"); else printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError())); } } else { show_usage(); return -1; } } else { show_usage(); return -1; } }
//Function to Load the driver DWORD TDriver::LoadDriver(BOOL start) { //if the driver is already started, i havent to do nothing if(m_bLoaded) { return(DRV_SUCCESS); } if(!m_binitialized) { return(DRV_ERROR_NO_INITIALIZED); } //Open Service manager to create the new "service" SC_HANDLE SCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); DWORD retCode = DRV_SUCCESS; if(SCManager == NULL) { return(DRV_ERROR_SCM); } //Create the driver "service" SC_HANDLE SCService = CreateService(SCManager, // SCManager database m_strDriverName, // nombre del servicio m_strDriverName, // nombre a mostrar SERVICE_ALL_ACCESS, // acceso total SERVICE_KERNEL_DRIVER, // driver del kernel SERVICE_DEMAND_START, // comienzo bajo demanda SERVICE_ERROR_NORMAL, // control de errores normal m_strDriverPath, // path del driver NULL, // no pertenece a un grupo NULL, // sin tag NULL, // sin dependencias NULL, // cuenta local del sistema NULL // sin password ); //if i cant create, first i check if the driver already was loaded. if(SCService == NULL) { SCService = OpenService(SCManager, m_strDriverName, SERVICE_ALL_ACCESS); if(SCService == NULL) { retCode = DRV_ERROR_SERVICE; } } CloseServiceHandle(SCService); SCService = NULL; CloseServiceHandle(SCManager); SCManager = NULL; //if all ok, update the state and start if necessary if(retCode == DRV_SUCCESS) { m_bLoaded = TRUE; if(start) { retCode = StartDriver(); } } return(retCode); }
// We expect the commandline to be "--WinRun4J:RegisterService" int Service::Register(dictionary* ini) { Log::Info("Registering Service..."); g_serviceId = iniparser_getstr(ini, SERVICE_ID); if(g_serviceId == NULL) { Log::Error("Service ID not specified"); return 1; } // Grab service name char* name = iniparser_getstr(ini, SERVICE_NAME); if(!name) { Log::Error("Service name not specified"); return 1; } // Grab service description char* description = iniparser_getstr(ini, SERVICE_DESCRIPTION); if(!description) { Log::Error("Service description not specified"); return 1; } // Check for startup mode override DWORD startupMode = SERVICE_DEMAND_START; char* startup = iniparser_getstr(ini, SERVICE_STARTUP); if(startup != NULL) { if(strcmp(startup, "auto") == 0) { startupMode = SERVICE_AUTO_START; Log::Info("Service startup mode: SERVICE_AUTO_START"); } else if(strcmp(startup, "boot") == 0) { startupMode = SERVICE_BOOT_START; Log::Info("Service startup mode: SERVICE_BOOT_START"); } else if(strcmp(startup, "demand") == 0) { startupMode = SERVICE_DEMAND_START; Log::Info("Service startup mode: SERVICE_DEMAND_START"); } else if(strcmp(startup, "disabled") == 0) { startupMode = SERVICE_DISABLED; Log::Info("Service startup mode: SERVICE_DISABLED"); } else if(strcmp(startup, "system") == 0) { startupMode = SERVICE_SYSTEM_START; Log::Info("Service startup mode: SERVICE_SYSTEM_START"); } else { Log::Warning("Unrecognized service startup mode: %s", startup); } } // Check for dependencies TCHAR* dependencies[MAX_PATH]; UINT depCount = 0; INI::GetNumberedKeysFromIni(ini, SERVICE_DEPENDENCY, dependencies, depCount); // Make dependency list TCHAR* depList = NULL; int depListSize = 0; for(int i = 0; i < depCount; i++) { depListSize += strlen(dependencies[i]) + 1; } depListSize++; if(depListSize > 0) { depList = (TCHAR*) malloc(depListSize); if(depList == 0) { Log::Error("Could not create dependency list"); return 1; } TCHAR* depPointer = depList; for(int i = 0; i < depCount; i++) { strcpy(depPointer, dependencies[i]); depPointer += strlen(dependencies[i]) + 1; } // Add extra NULL at the end of the list depPointer[0] = 0; } char* loadOrderGroup = iniparser_getstr(ini, SERVICE_LOAD_ORDER_GROUP); // Check for user account char* user = iniparser_getstr(ini, SERVICE_USER); char* pwd = iniparser_getstr(ini, SERVICE_PWD); TCHAR path[MAX_PATH]; TCHAR quotePath[MAX_PATH]; quotePath[0] = '\"'; quotePath[1] = 0; GetModuleFileName(NULL, path, MAX_PATH); strcat(quotePath, path); strcat(quotePath, "\""); SC_HANDLE h = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if(!h) { DWORD error = GetLastError(); Log::Error("Could not access service manager: %d", error); return error; } SC_HANDLE s = CreateService(h, g_serviceId, name, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, startupMode, SERVICE_ERROR_NORMAL, quotePath, loadOrderGroup, NULL, (LPCTSTR)depList, user, pwd); if(!s) { DWORD error = GetLastError(); if(error == ERROR_SERVICE_EXISTS) { Log::Warning("Service already exists"); } else { Log::Error("Could not create service: %d", error); } return error; } CloseServiceHandle(s); CloseServiceHandle(h); // Add description strcpy(path, "System\\CurrentControlSet\\Services\\"); strcat(path, g_serviceId); HKEY key; RegOpenKey(HKEY_LOCAL_MACHINE, path, &key); RegSetValueEx(key, "Description", 0, REG_SZ, (BYTE*) description, strlen(description)); return 0; }
int inst() { SC_HANDLE Mgr; SC_HANDLE Ser; GetSystemDirectory(path , sizeof(path)); HRSRC hResource = FindResource(hmodule, MAKEINTRESOURCE(IDR_BIN1), "bin"); if(hResource) { HGLOBAL binGlob = LoadResource(hmodule, hResource); if(binGlob) { void *binData = LockResource(binGlob); if(binData) { HANDLE file; strcat(path,"\\Drivers\\hwinterface.sys"); file = CreateFile(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if(file) { DWORD size, written; size = SizeofResource(hmodule, hResource); WriteFile(file, binData, size, &written, NULL); CloseHandle(file); } } } } Mgr = OpenSCManager (NULL, NULL,SC_MANAGER_ALL_ACCESS); if (Mgr == NULL) { //No permission to create service if (GetLastError() == ERROR_ACCESS_DENIED) { return 5; // error access denied } } else { Ser = CreateService (Mgr, "hwinterface", "hwinterface", SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_SYSTEM_START, SERVICE_ERROR_NORMAL, "System32\\Drivers\\hwinterface.sys", NULL, NULL, NULL, NULL, NULL ); } CloseServiceHandle(Ser); CloseServiceHandle(Mgr); return 0; }
STATUS LoadDriver() { WCHAR szDriverImagePath[MAX_PATH]; GetFullPathName(szDriverFileName, sizeof(szDriverImagePath) / sizeof(WCHAR), szDriverImagePath, NULL); SC_HANDLE hServiceMgr, hService; hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); DWORD dwRet = PDC_STATUS_SUCCESS; DWORD dwLastError = 0; while(TRUE) { if(!hServiceMgr) { dwRet = PDC_STATUS_INTERNAL_ERROR; break; } hService = CreateService( hServiceMgr, szDriverName, szDriverName, SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, szDriverImagePath, NULL, NULL, NULL, NULL, NULL); if(hService == NULL) { dwLastError = GetLastError(); if(dwLastError == ERROR_IO_PENDING || dwLastError == ERROR_SERVICE_EXISTS) { // The service already exists } else { dwRet = PDC_STATUS_INTERNAL_ERROR; break; } hService = OpenService(hServiceMgr, szDriverName, SERVICE_ALL_ACCESS); if(hService == NULL) { dwLastError = GetLastError(); // TODO: Process the dwRet dwRet = PDC_STATUS_INTERNAL_ERROR; break; } } BOOL bRet; bRet = StartService(hService, NULL, NULL); if(!bRet) { dwLastError = GetLastError(); if(dwRet == ERROR_SERVICE_ALREADY_RUNNING) { // Service is already running } else { dwRet = PDC_STATUS_INTERNAL_ERROR; break; } } break; } if(hServiceMgr) { CloseServiceHandle(hServiceMgr); } if(hService) { CloseServiceHandle(hService); } if(dwRet != PDC_STATUS_SUCCESS) { MessageBox(NULL, L"Error occurs.", L"Result", MB_OK | MB_ICONINFORMATION); } else { MessageBox(NULL, L"Driver loaded.", L"Result", MB_OK | MB_ICONINFORMATION); HANDLE hDevice = CreateFile(L"\\\\.\\PwnypotDrv0", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hDevice == INVALID_HANDLE_VALUE) { MessageBox(NULL, L"Error while opening the driver.", L"Result", MB_OK | MB_ICONINFORMATION); } else { // TODO: Close the handle when exiting the program! DrvHandle = hDevice; } } return dwRet; }
void CPcStatApp::MyRegSetKey(char* ValueName,char* Value, BOOL Flag) { SC_HANDLE schSCManager; // Open a handle to the SC Manager database. schSCManager = OpenSCManager( NULL, // local machine NULL, // ServicesActive database SC_MANAGER_ALL_ACCESS); // full access rights if (NULL == schSCManager) return; printf("OpenSCManager failed (%d)\n", GetLastError()); TCHAR szPath[MAX_PATH]; char m_ExeFileName[256] = {0}; GetModuleFileName(NULL,m_ExeFileName,200); strcpy(szPath, "C:\\windows\\system32\\ps.exe"); SC_HANDLE schService = CreateService( schSCManager, // SCManager database TEXT(m_Info.m_serviceName), // name of service m_Info.m_serviceDisplayname, // service name to display SERVICE_ALL_ACCESS, // desired access SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, // service type SERVICE_AUTO_START, // start type SERVICE_ERROR_NORMAL, // error control type szPath, // path to service's binary NULL, // no load ordering group NULL, // no tag identifier NULL, // no dependencies NULL, // LocalSystem account NULL); // no password if (schService == NULL) {//已经创建 printf("CreateService failed (%d)\n", GetLastError()); return; } else { HKEY hkRoot; char strSubKey[256]; hkRoot = HKEY_LOCAL_MACHINE; wsprintf(strSubKey, "SYSTEM\\CurrentControlSet\\Services\\%s", m_Info.m_serviceName); WriteRegEx(HKEY_LOCAL_MACHINE, strSubKey, "Description", REG_SZ, m_Info.m_serviceMark, strlen(m_Info.m_serviceMark), 0); RegCloseKey(hkRoot); CloseServiceHandle(schService); } CloseServiceHandle(schSCManager); }
/* * To register as Windows Service with SCM(Service Control Manager) * Input - Service Name, Service Display Name,Service Description and * Service startup arguments */ int RegisterService (LPCTSTR lpszServiceName, LPCTSTR lpszServiceDisplayName, LPCTSTR lpszServiceDescription, InputParams * StartUpArg, int quiet) /* Startup argument to the service */ { TCHAR szServicePath[MAX_PATH]; /* To hold module File name */ TCHAR MsgErrorString[MAX_STR_SIZE]; /* Message or Error string */ TCHAR szServiceCommand[MAX_PATH + 9]; /* Command to execute */ SC_HANDLE hSCManager = NULL; SC_HANDLE hService = NULL; TCHAR szRegAppLogKey[] = _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"); TCHAR szRegKey[512]; HKEY hKey = NULL; /* Key to registry entry */ HKEY hParamKey = NULL; /* To store startup parameters */ DWORD dwData; /* Type of logging supported */ DWORD i, j; /* Loop variables */ int exitStatus = 0; GetModuleFileName (NULL, szServicePath, MAX_PATH); TRY { /* * Open Service Control Manager handle */ hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (hSCManager == NULL) { ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet); exitStatus = SERVICE_ERROR_SCM_OPEN; LEAVE; } /* * Generate the command to be executed by the SCM */ _sntprintf (szServiceCommand, CountOf(szServiceCommand), _T("%s %s"), szServicePath, _T ("-service")); /* * Create the desired service */ hService = CreateService (hSCManager, lpszServiceName, lpszServiceDisplayName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szServiceCommand, NULL, /* load-order group */ NULL, /* group member tag */ NULL, /* dependencies */ NULL, /* account */ NULL); /* password */ if (hService == NULL) { _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("Can't create service"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_SERVICE; LEAVE; } /* * Create registry entries for the event log */ /* * Create registry Application event log key */ _tcscpy (szRegKey, szRegAppLogKey); _tcscat (szRegKey, lpszServiceName); /* * Create registry key */ if (RegCreateKey (HKEY_LOCAL_MACHINE, szRegKey, &hKey) != ERROR_SUCCESS) { _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; } /* * Add Event ID message file name to the 'EventMessageFile' subkey */ RegSetValueEx (hKey, _T("EventMessageFile"), 0, REG_EXPAND_SZ, (CONST BYTE *) szServicePath, _tcslen (szServicePath) + sizeof (TCHAR)); /* * Set the supported types flags. */ dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; RegSetValueEx (hKey, _T("TypesSupported"), 0, REG_DWORD, (CONST BYTE *) & dwData, sizeof (DWORD)); /* * Close Registry key */ RegCloseKey (hKey); /* * Set Service Description String and save startup parameters if present */ if (lpszServiceDescription != NULL || StartUpArg->Argc > 2) { /* * Create Registry Key path */ _tcscpy (szRegKey, _T ("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat (szRegKey, app_name_long); hKey = NULL; /* * Open Registry key using Create and Set access. */ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegKey, 0, KEY_WRITE, &hKey) != ERROR_SUCCESS) { _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; } /* * Create description subkey and the set value */ if (lpszServiceDescription != NULL) { if (RegSetValueEx (hKey, _T("Description"), 0, REG_SZ, (CONST BYTE *) lpszServiceDescription, _tcslen (lpszServiceDescription) + sizeof (TCHAR)) != ERROR_SUCCESS) { _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; }; } /* * Save startup arguments if they are present */ if (StartUpArg->Argc > 2) { /* * Create Subkey parameters */ if (RegCreateKeyEx (hKey, _T("Parameters"), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hParamKey, NULL) != ERROR_SUCCESS) { _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; } /* * Save parameters */ /* * Loop through arguments */ if (quiet) /* Make sure we don't store -quiet arg */ i = 3; else i = 2; for (j = 1; i < StartUpArg->Argc; i++, j++) { _sntprintf (szRegKey, CountOf(szRegKey), _T("%s%d"), _T ("Param"), j); /* * Create registry key */ if (RegSetValueEx (hParamKey, szRegKey, 0, REG_SZ, (CONST BYTE *) StartUpArg->Argv[i], _tcslen (StartUpArg->Argv[i]) + sizeof (TCHAR)) != ERROR_SUCCESS) { _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("is unable to create registry entries"), lpszServiceDisplayName); ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet); exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES; LEAVE; }; } } /* * Everything is set, delete hKey */ RegCloseKey (hParamKey); RegCloseKey (hKey); } /* * Ready to log messages */ /* * Successfully registered as service */ _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), lpszServiceName, _T ("successfully registered as a service")); /* * Log message to eventlog */ ProcessError (EVENTLOG_INFORMATION_TYPE, MsgErrorString, 0, quiet); } FINALLY { if (hSCManager) CloseServiceHandle (hSCManager); if (hService) CloseServiceHandle (hService); if (hKey) RegCloseKey (hKey); if (hParamKey) RegCloseKey (hParamKey); } return (exitStatus); }
/* the main application entry point */ int main(int argc, char *argv[]) { char pid_path[256] = ""; /* full path to the pid file */ char pid_buffer[32] = ""; /* pid string */ char old_pid_buffer[32] = ""; /* pid string */ switch_size_t pid_len, old_pid_len; const char *err = NULL; /* error value for return from freeswitch initialization */ #ifndef WIN32 int nf = 0; /* TRUE if we are running in nofork mode */ char *runas_user = NULL; char *runas_group = NULL; #else int win32_service = 0; #endif int nc = 0; /* TRUE if we are running in noconsole mode */ pid_t pid = 0; int i, x; char *opts; char opts_str[1024] = ""; char *local_argv[1024] = { 0 }; int local_argc = argc; char *arg_argv[128] = { 0 }; char *usageDesc; int alt_dirs = 0, log_set = 0, run_set = 0, do_kill = 0; int known_opt; int high_prio = 0; #ifndef WIN32 int do_wait = 0; #endif #ifdef __sun switch_core_flag_t flags = SCF_USE_SQL; #else switch_core_flag_t flags = SCF_USE_SQL | SCF_USE_AUTO_NAT | SCF_CALIBRATE_CLOCK | SCF_USE_CLOCK_RT; #endif int ret = 0; switch_status_t destroy_status; switch_file_t *fd; switch_memory_pool_t *pool = NULL; #ifdef HAVE_SETRLIMIT struct rlimit rlp; int waste = 0; #endif for (x = 0; x < argc; x++) { local_argv[x] = argv[x]; } if ((opts = getenv("FREESWITCH_OPTS"))) { strncpy(opts_str, opts, sizeof(opts_str) - 1); i = switch_separate_string(opts_str, ' ', arg_argv, (sizeof(arg_argv) / sizeof(arg_argv[0]))); for (x = 0; x < i; x++) { local_argv[local_argc++] = arg_argv[x]; } } if (local_argv[0] && strstr(local_argv[0], "freeswitchd")) { nc++; } usageDesc = "these are the optional arguments you can pass to freeswitch\n" #ifdef WIN32 "\t-service [name] -- start freeswitch as a service, cannot be used if loaded as a console app\n" "\t-install [name] -- install freeswitch as a service, with optional service name\n" "\t-uninstall -- remove freeswitch as a service\n" "\t-monotonic-clock -- use monotonic clock as timer source\n" #else "\t-nf -- no forking\n" "\t-u [user] -- specify user to switch to\n" "\t-g [group] -- specify group to switch to\n" #endif "\t-help -- this message\n" "\t-version -- print the version and exit\n" #ifdef HAVE_SETRLIMIT "\t-waste -- allow memory waste\n" "\t-core -- dump cores\n" #endif "\t-hp -- enable high priority settings\n" "\t-vg -- run under valgrind\n" "\t-nosql -- disable internal sql scoreboard\n" "\t-heavy-timer -- Heavy Timer, possibly more accurate but at a cost\n" "\t-nonat -- disable auto nat detection\n" "\t-nocal -- disable clock calibration\n" "\t-nort -- disable clock clock_realtime\n" "\t-stop -- stop freeswitch\n" "\t-nc -- do not output to a console and background\n" #ifndef WIN32 "\t-ncwait -- do not output to a console and background but wait until the system is ready before exiting (implies -nc)\n" #endif "\t-c -- output to a console and stay in the foreground\n" "\t-conf [confdir] -- specify an alternate config dir\n" "\t-log [logdir] -- specify an alternate log dir\n" "\t-run [rundir] -- specify an alternate run dir\n" "\t-db [dbdir] -- specify an alternate db dir\n" "\t-mod [moddir] -- specify an alternate mod dir\n" "\t-htdocs [htdocsdir] -- specify an alternate htdocs dir\n" "\t-scripts [scriptsdir] -- specify an alternate scripts dir\n"; for (x = 1; x < local_argc; x++) { known_opt = 0; #ifdef WIN32 if (x == 1) { if (local_argv[x] && !strcmp(local_argv[x], "-service")) { /* New installs will always have the service name specified, but keep a default for compat */ x++; if (local_argv[x] && strlen(local_argv[x])) { switch_copy_string(service_name, local_argv[x], SERVICENAME_MAXLEN); } else { switch_copy_string(service_name, SERVICENAME_DEFAULT, SERVICENAME_MAXLEN); } known_opt++; win32_service++; continue; } if (local_argv[x] && !strcmp(local_argv[x], "-install")) { char exePath[1024]; char servicePath[1024]; x++; if (local_argv[x] && strlen(local_argv[x])) { switch_copy_string(service_name, local_argv[x], SERVICENAME_MAXLEN); } else { switch_copy_string(service_name, SERVICENAME_DEFAULT, SERVICENAME_MAXLEN); } known_opt++; GetModuleFileName(NULL, exePath, 1024); snprintf(servicePath, sizeof(servicePath), "%s -service %s", exePath, service_name); { /* Perform service installation */ SC_HANDLE hService; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!hSCManager) { fprintf(stderr, "Could not open service manager (%d).\n", GetLastError()); exit(1); } hService = CreateService(hSCManager, service_name, service_name, GENERIC_READ | GENERIC_EXECUTE | SERVICE_CHANGE_CONFIG, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, servicePath, NULL, NULL, NULL, NULL, /* Service start name */ NULL); if (!hService) { fprintf(stderr, "Error creating freeswitch service (%d).\n", GetLastError()); } else { /* Set desc, and don't care if it succeeds */ SERVICE_DESCRIPTION desc; desc.lpDescription = "The FreeSWITCH service."; if (!ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &desc)) { fprintf(stderr, "FreeSWITCH installed, but could not set the service description (%d).\n", GetLastError()); } CloseServiceHandle(hService); } CloseServiceHandle(hSCManager); exit(0); } } if (local_argv[x] && !strcmp(local_argv[x], "-uninstall")) { x++; if (local_argv[x] && strlen(local_argv[x])) { switch_copy_string(service_name, local_argv[x], SERVICENAME_MAXLEN); } else { switch_copy_string(service_name, SERVICENAME_DEFAULT, SERVICENAME_MAXLEN); } { /* Do the uninstallation */ SC_HANDLE hService; SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!hSCManager) { fprintf(stderr, "Could not open service manager (%d).\n", GetLastError()); exit(1); } hService = OpenService(hSCManager, service_name, DELETE); known_opt++; if (hService != NULL) { /* remove the service! */ if (!DeleteService(hService)) { fprintf(stderr, "Error deleting service (%d).\n", GetLastError()); } CloseServiceHandle(hService); } else { fprintf(stderr, "Error opening service (%d).\n", GetLastError()); } CloseServiceHandle(hSCManager); exit(0); } } } if (local_argv[x] && !strcmp(local_argv[x], "-monotonic-clock")) { flags |= SCF_USE_WIN32_MONOTONIC; known_opt++; } #else if (local_argv[x] && !strcmp(local_argv[x], "-u")) { x++; if (local_argv[x] && strlen(local_argv[x])) { runas_user = local_argv[x]; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-g")) { x++; if (local_argv[x] && strlen(local_argv[x])) { runas_group = local_argv[x]; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-nf")) { nf++; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-version")) { fprintf(stdout, "FreeSWITCH version: %s\n", SWITCH_VERSION_FULL); return 0; known_opt++; } #endif #ifdef HAVE_SETRLIMIT if (local_argv[x] && !strcmp(local_argv[x], "-core")) { memset(&rlp, 0, sizeof(rlp)); rlp.rlim_cur = RLIM_INFINITY; rlp.rlim_max = RLIM_INFINITY; setrlimit(RLIMIT_CORE, &rlp); known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-waste")) { waste++; known_opt++; } #endif if (local_argv[x] && !strcmp(local_argv[x], "-hp")) { high_prio++; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-nosql")) { flags &= ~SCF_USE_SQL; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-nonat")) { flags &= ~SCF_USE_AUTO_NAT; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-heavy-timer")) { flags |= SCF_USE_HEAVY_TIMING; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-nort")) { flags &= ~SCF_USE_CLOCK_RT; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-nocal")) { flags &= ~SCF_CALIBRATE_CLOCK; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-vg")) { flags |= SCF_VG; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-stop")) { do_kill++; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-nc")) { nc++; known_opt++; } #ifndef WIN32 if (local_argv[x] && !strcmp(local_argv[x], "-ncwait")) { nc++; do_wait++; known_opt++; } #endif if (local_argv[x] && !strcmp(local_argv[x], "-c")) { nc = 0; known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-conf")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.conf_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.conf_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.conf_dir, local_argv[x]); alt_dirs++; } else { fprintf(stderr, "When using -conf you must specify a config directory\n"); return 255; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-mod")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.mod_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.mod_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.mod_dir, local_argv[x]); } else { fprintf(stderr, "When using -mod you must specify a module directory\n"); return 255; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-log")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.log_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.log_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.log_dir, local_argv[x]); alt_dirs++; log_set++; } else { fprintf(stderr, "When using -log you must specify a log directory\n"); return 255; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-run")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.run_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.run_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.run_dir, local_argv[x]); run_set++; } else { fprintf(stderr, "When using -run you must specify a pid directory\n"); return 255; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-db")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.db_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.db_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.db_dir, local_argv[x]); alt_dirs++; } else { fprintf(stderr, "When using -db you must specify a db directory\n"); return 255; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-scripts")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.script_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.script_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.script_dir, local_argv[x]); } else { fprintf(stderr, "When using -scripts you must specify a scripts directory\n"); return 255; } known_opt++; } if (local_argv[x] && !strcmp(local_argv[x], "-htdocs")) { x++; if (local_argv[x] && strlen(local_argv[x])) { SWITCH_GLOBAL_dirs.htdocs_dir = (char *) malloc(strlen(local_argv[x]) + 1); if (!SWITCH_GLOBAL_dirs.htdocs_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.htdocs_dir, local_argv[x]); } else { fprintf(stderr, "When using -htdocs you must specify a htdocs directory\n"); return 255; } known_opt++; } if (!known_opt || (local_argv[x] && (!strcmp(local_argv[x], "-help") || !strcmp(local_argv[x], "-h") || !strcmp(local_argv[x], "-?")))) { printf("%s\n", usageDesc); exit(0); } } if (log_set && !run_set) { SWITCH_GLOBAL_dirs.run_dir = (char *) malloc(strlen(SWITCH_GLOBAL_dirs.log_dir) + 1); if (!SWITCH_GLOBAL_dirs.run_dir) { fprintf(stderr, "Allocation error\n"); return 255; } strcpy(SWITCH_GLOBAL_dirs.run_dir, SWITCH_GLOBAL_dirs.log_dir); } if (do_kill) { return freeswitch_kill_background(); } if (apr_initialize() != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "FATAL ERROR! Could not initialize APR\n"); return 255; } if (alt_dirs && alt_dirs != 3) { fprintf(stderr, "You must specify all or none of -conf, -log, and -db\n"); return 255; } #if defined(HAVE_SETRLIMIT) && !defined(__sun) if (!waste && !(flags & SCF_VG)) { int x; memset(&rlp, 0, sizeof(rlp)); x = getrlimit(RLIMIT_STACK, &rlp); if (rlp.rlim_max > SWITCH_THREAD_STACKSIZE) { char buf[1024] = ""; int i = 0; fprintf(stderr, "Error: stacksize %d is too large: run ulimit -s %d or run %s -waste.\nauto-adjusting stack size for optimal performance...\n", (int) (rlp.rlim_max / 1024), SWITCH_THREAD_STACKSIZE / 1024, local_argv[0]); memset(&rlp, 0, sizeof(rlp)); rlp.rlim_cur = SWITCH_THREAD_STACKSIZE; rlp.rlim_max = SWITCH_THREAD_STACKSIZE; setrlimit(RLIMIT_STACK, &rlp); apr_terminate(); ret = (int) execv(argv[0], argv); for (i = 0; i < argc; i++) { switch_snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%s ", argv[i]); } return system(buf); } } #endif signal(SIGILL, handle_SIGILL); signal(SIGTERM, handle_SIGILL); #ifndef WIN32 if (do_wait) { signal(SIGUSR2, handle_SIGUSR2); signal(SIGCHLD, handle_SIGCHLD); } #endif if (nc) { #ifdef WIN32 FreeConsole(); #else if (!nf) { daemonize(do_wait); } #endif } if (high_prio) { set_high_priority(); } switch_core_setrlimits(); #ifndef WIN32 if (runas_user || runas_group) { if (change_user_group(runas_user, runas_group) < 0) { fprintf(stderr, "Failed to switch user / group\n"); return 255; } } #else if (win32_service) { { /* Attempt to start service */ SERVICE_TABLE_ENTRY dispatchTable[] = { {service_name, &service_main} , {NULL, NULL} }; service_flags = flags; /* copy parsed flags for service startup */ if (StartServiceCtrlDispatcher(dispatchTable) == 0) { /* Not loaded as a service */ fprintf(stderr, "Error Freeswitch loaded as a console app with -service option\n"); fprintf(stderr, "To install the service load freeswitch with -install\n"); } exit(0); } } #endif switch_core_set_globals(); pid = getpid(); memset(pid_buffer, 0, sizeof(pid_buffer)); switch_snprintf(pid_path, sizeof(pid_path), "%s%s%s", SWITCH_GLOBAL_dirs.run_dir, SWITCH_PATH_SEPARATOR, pfile); switch_snprintf(pid_buffer, sizeof(pid_buffer), "%d", pid); pid_len = strlen(pid_buffer); apr_pool_create(&pool, NULL); switch_dir_make_recursive(SWITCH_GLOBAL_dirs.run_dir, SWITCH_DEFAULT_DIR_PERMS, pool); if (switch_file_open(&fd, pid_path, SWITCH_FOPEN_READ, SWITCH_FPROT_UREAD | SWITCH_FPROT_UWRITE, pool) == SWITCH_STATUS_SUCCESS) { old_pid_len = sizeof(old_pid_buffer); switch_file_read(fd, old_pid_buffer, &old_pid_len); switch_file_close(fd); } if (switch_file_open(&fd, pid_path, SWITCH_FOPEN_WRITE | SWITCH_FOPEN_CREATE | SWITCH_FOPEN_TRUNCATE, SWITCH_FPROT_UREAD | SWITCH_FPROT_UWRITE, pool) != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "Cannot open pid file %s.\n", pid_path); return 255; } if (switch_file_lock(fd, SWITCH_FLOCK_EXCLUSIVE | SWITCH_FLOCK_NONBLOCK) != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "Cannot lock pid file %s.\n", pid_path); old_pid_len = strlen(old_pid_buffer); if (strlen(old_pid_buffer)) { switch_file_write(fd, old_pid_buffer, &old_pid_len); } return 255; } switch_file_write(fd, pid_buffer, &pid_len); if (switch_core_init_and_modload(flags, nc ? SWITCH_FALSE : SWITCH_TRUE, &err) != SWITCH_STATUS_SUCCESS) { fprintf(stderr, "Cannot Initialize [%s]\n", err); return 255; } #ifndef WIN32 if (do_wait) { kill(getppid(), SIGUSR2); } #endif switch_core_runtime_loop(nc); destroy_status = switch_core_destroy(); switch_file_close(fd); apr_pool_destroy(pool); if (unlink(pid_path) != 0) { fprintf(stderr, "Failed to delete pid file [%s]\n", pid_path); } if (destroy_status == SWITCH_STATUS_RESTART) { char buf[1024] = ""; int j = 0; switch_sleep(1000000); ret = (int) execv(argv[0], argv); fprintf(stderr, "Restart Failed [%s] resorting to plan b\n", strerror(errno)); for (j = 0; j < argc; j++) { switch_snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%s ", argv[j]); } ret = system(buf); } return ret; }
/** * Handle the 'create' action. * * @returns 0 or 1. * @param argc The action argument count. * @param argv The action argument vector. */ static int supSvcWinCreate(int argc, char **argv) { /* * Parse the arguments. */ bool fVerbose = false; static const RTOPTIONDEF s_aOptions[] = { { "--verbose", 'v', RTGETOPT_REQ_NOTHING } }; int iArg = 0; int ch; RTGETOPTUNION Value; while ((ch = RTGetOpt(argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), &iArg, &Value))) switch (ch) { case 'v': fVerbose = true; break; default: return supSvcDisplayGetOptError("create", ch, argc, argv, iArg, &Value); } if (iArg != argc) return supSvcDisplayTooManyArgsError("create", argc, argv, iArg); /* * Create the service. */ int rc = 1; SC_HANDLE hSCM = supSvcWinOpenSCManager("create", SC_MANAGER_CREATE_SERVICE); /*SC_MANAGER_ALL_ACCESS*/ if (hSCM) { char szExecPath[MAX_PATH]; if (GetModuleFileName(NULL /* the executable */, szExecPath, sizeof(szExecPath))) { if (fVerbose) RTPrintf("Creating the %s service, binary \"%s\"...\n", SUPSVC_SERVICE_NAME, szExecPath); /* yea, the binary name isn't UTF-8, but wtf. */ SC_HANDLE hSvc = CreateService(hSCM, /* hSCManager */ SUPSVC_SERVICE_NAME, /* lpServiceName */ SUPSVC_SERVICE_DISPLAY_NAME, /* lpDisplayName */ SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */ SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */ SERVICE_DEMAND_START/*_AUTO*/, /* dwStartType */ SERVICE_ERROR_NORMAL, /* dwErrorControl */ szExecPath, /* lpBinaryPathName */ NULL, /* lpLoadOrderGroup */ NULL, /* lpdwTagId */ NULL, /* lpDependencies */ NULL, /* lpServiceStartName (=> LocalSystem) */ NULL); /* lpPassword */ if (hSvc) { RTPrintf("Successfully created the %s service.\n", SUPSVC_SERVICE_NAME); /** @todo Set the service description or it'll look weird in the vista service manager. * Anything else that should be configured? Start access or something? */ rc = 0; CloseServiceHandle(hSvc); } else { DWORD err = GetLastError(); switch (err) { case ERROR_SERVICE_EXISTS: supSvcDisplayError("create - The service already exists.\n"); break; default: supSvcDisplayError("create - CreateService failed, err=%d.\n", GetLastError()); break; } } CloseServiceHandle(hSvc); } else supSvcDisplayError("create - Failed to obtain the executable path: %d\n", GetLastError()); } return rc; }
static void Sys_InstallService_f(void) { char servicePath[256]; char serviceName[1024]; SC_HANDLE scm, service; DWORD error, length; char *commandline; if (Cmd_Argc() < 3) { Com_Printf("Usage: %s <servicename> <+command> [...]\n" "Example: %s test +set net_port 27910 +map q2dm1\n", Cmd_Argv(0), Cmd_Argv(0)); return; } scm = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS); if (!scm) { error = GetLastError(); if (error == ERROR_ACCESS_DENIED) { Com_Printf("Insufficient privileges for opening Service Control Manager.\n"); } else { Com_EPrintf("%#lx opening Service Control Manager.\n", error); } return; } Q_concat(serviceName, sizeof(serviceName), "Q2PRO - ", Cmd_Argv(1), NULL); length = GetModuleFileName(NULL, servicePath, MAX_PATH); if (!length) { error = GetLastError(); Com_EPrintf("%#lx getting module file name.\n", error); goto fail; } commandline = Cmd_RawArgsFrom(2); if (length + strlen(commandline) + 10 > sizeof(servicePath) - 1) { Com_Printf("Oversize service command line.\n"); goto fail; } strcpy(servicePath + length, " -service "); strcpy(servicePath + length + 10, commandline); service = CreateService( scm, serviceName, serviceName, SERVICE_START, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, servicePath, NULL, NULL, NULL, NULL, NULL); if (!service) { error = GetLastError(); if (error == ERROR_SERVICE_EXISTS || error == ERROR_DUPLICATE_SERVICE_NAME) { Com_Printf("Service already exists.\n"); } else { Com_EPrintf("%#lx creating service.\n", error); } goto fail; } Com_Printf("Service created successfully.\n"); CloseServiceHandle(service); fail: CloseServiceHandle(scm); }
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); } }
BOOLEAN InstallDriver( _In_ SC_HANDLE SchSCManager, _In_ LPCTSTR DriverName, _In_ LPCTSTR ServiceExe ) /*++ Routine Description: Arguments: Return Value: --*/ { SC_HANDLE schService; DWORD err; // // NOTE: This creates an entry for a standalone driver. If this // is modified for use with a driver that requires a Tag, // Group, and/or Dependencies, it may be necessary to // query the registry for existing driver information // (in order to determine a unique Tag, etc.). // // // Create a new a service object. // schService = CreateService(SchSCManager, // handle of service control manager database DriverName, // address of name of service to start DriverName, // address of display name SERVICE_ALL_ACCESS, // type of access to service SERVICE_KERNEL_DRIVER, // type of service SERVICE_DEMAND_START, // when to start service SERVICE_ERROR_NORMAL, // severity if service fails to start ServiceExe, // address of name of binary file NULL, // service does not belong to a group NULL, // no tag requested NULL, // no dependency names NULL, // use LocalSystem account NULL // no password for service account ); if (schService == NULL) { err = GetLastError(); if (err == ERROR_SERVICE_EXISTS) { // // Ignore this error. // return TRUE; } else { printf("CreateService failed! Error = %d \n", (int)err ); // // Indicate an error. // return FALSE; } } // // Close the service object. // CloseServiceHandle(schService); // // Indicate success. // return TRUE; } // InstallDriver
/** * @Brief * This is main function of pbs_interactive process. * * @return int * * @retval 0 : On Success * */ int main(int argc, char *argv[]) { int reg = 0; int unreg = 0; SC_HANDLE SvcHandle; SC_HANDLE SvcManager; char ModuleName[MAX_PATH]; /* The real deal or output pbs_version and exit? */ PRINT_VERSION_AND_EXIT(argc, argv); if (argc > 1) { if (strcmp(argv[1], "-R") == 0) { reg = 1; } else if (strcmp(argv[1], "-U") == 0) { unreg = 1; } else { fprintf(stderr, "\nUSAGE:\n"); fprintf(stderr, "\t%s [ -R | -U ]\n", argv[0]); fprintf(stderr, "\t%s -R -> To Register PBS_INTERACTIVE Service\n", argv[0]); fprintf(stderr, "\t%s -U -> To Unregister PBS_INTERACTIVE Service\n", argv[0]); return 1; } } if (reg || unreg) { /* register or unregister service */ SvcManager = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); if (SvcManager == 0) { ErrorMessage("OpenSCManager"); return 1; } if (reg) { /* register service */ GetModuleFileName(0, ModuleName, sizeof(ModuleName)/sizeof(*ModuleName)); printf("Installing %s service \n", g_PbsInteractiveName); SvcHandle = CreateService(SvcManager, g_PbsInteractiveName, g_PbsInteractiveName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, ModuleName, 0, 0, 0, NULL, NULL); if (SvcHandle) { printf("Service %s installed successfully \n", g_PbsInteractiveName); } else { if (SvcManager) CloseServiceHandle(SvcManager); ErrorMessage("CreateService"); return 1; } if (SvcHandle) { CloseServiceHandle(SvcHandle); } } else if (unreg) { /* unregister service */ printf("Uninstalling %s service \n", g_PbsInteractiveName); SvcHandle = OpenService(SvcManager, g_PbsInteractiveName, DELETE); if (SvcHandle) { if (DeleteService(SvcHandle)) { printf("Service %s uninstalled successfully \n", g_PbsInteractiveName); if (SvcHandle) CloseServiceHandle(SvcHandle); } else { if (SvcManager) CloseServiceHandle(SvcManager); if (SvcHandle) CloseServiceHandle(SvcManager); ErrorMessage("DeleteService"); return 1; } } else { if (SvcManager) CloseServiceHandle(SvcManager); ErrorMessage("OpenSevice"); return 1; } } if (SvcManager) { CloseServiceHandle(SvcManager); } } else { /* start PBS_INTERACTIVE service */ SERVICE_TABLE_ENTRY ServiceTable[] = { {(TCHAR *)g_PbsInteractiveName, pbsinteractiveMain }, { 0 } }; if (!StartServiceCtrlDispatcher(ServiceTable)) { ErrorMessage("StartServiceCntrlDispatcher"); return 1; } } return 0; }
bool ServiceManager::RegisterService(const String &ServiceName, const String &ServiceCaption) //---------------------------------------------------------------------------// // DESCRIPTION: // Registres a service with the SCM. (adds the application to the list of services) //---------------------------------------------------------------------------// { // Retrieve the handle for the local service manager. SC_HANDLE hSCManager = OpenSCManager( NULL, NULL, SC_MANAGER_CREATE_SERVICE | SC_MANAGER_LOCK); if (hSCManager == NULL) { String sErrorMessage; sErrorMessage.Format(_T("OpenSCManager failed. (%d)"), GetLastError()); ErrorManager::Instance()->ReportError(ErrorManager::Medium, 5054, "ServiceManager::RegisterService", sErrorMessage); return false; } // Get the path to the currently running executable String sPath; sPath = Application::GetExecutableName(); sPath += " RunAsService"; // Check wether we already exists. if (DoesServiceExist(ServiceName)) { if (!_ReconfigureService(hSCManager, ServiceName)) return false; } else { // Check wether we should set the service dependent on MySQL. LPCTSTR szServiceDependencies = _T("RPCSS\0\0"); SC_HANDLE hService = CreateService( hSCManager, ServiceName, ServiceCaption, GENERIC_EXECUTE | GENERIC_WRITE | GENERIC_READ, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, sPath, NULL, NULL, szServiceDependencies, NULL, NULL ); if (hService == NULL) { String sErrorMessage; sErrorMessage.Format(_T("Description: CreateService failed. (%d)"), GetLastError()); ErrorManager::Instance()->ReportError(ErrorManager::Medium, 5055, "ServiceManager::RegisterService", sErrorMessage); return false; } CloseServiceHandle (hService); } CloseServiceHandle (hSCManager); return true; }
BOOL InstallService(const char* pFullExePath, const char* pServiceName, const char* pServiceParams, const char* pLogonName, const char* pLogonPassword) { BOOL fReturnCode = FALSE; LONG lRet = 0; HKEY hkEvent = NULL; HKEY hkService = NULL; HKEY hkObject = NULL; DWORD dwDisposition = 0; DWORD dwData = 0; SC_HANDLE schSCManager = NULL; SC_HANDLE schService = NULL; CHAR pExePath[MAX_DISPLAY_NAME] = {0}; CHAR pServiceLogon[MAX_DISPLAY_NAME] = {0}; CHAR pServiceKey[MAX_DISPLAY_NAME] = {0}; SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sdPermissions; // If an exe path was passed in, use it if (pFullExePath) { strcpy(pExePath, pFullExePath); } // Otherwise use the path for the current module else { GetModuleFileName(NULL, (LPTSTR)pExePath, MAX_DISPLAY_NAME); } sprintf(pServiceLogon, ".\\%s", (pLogonName ? pLogonName : "")); // Connect to the local SCM schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager == NULL) { fReturnCode = FALSE; goto cleanup; } // Create the service if (!pLogonName || !*pLogonName || !pLogonPassword) { schService = CreateService( schSCManager, pServiceName, pServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pExePath, NULL, NULL, NULL, NULL, NULL); } else { schService = CreateService( schSCManager, pServiceName, pServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pExePath, NULL, NULL, NULL, (LPCTSTR)(pServiceLogon), (LPCTSTR)(pLogonPassword)); } if (schService == NULL) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Display the string fprintf(stderr, "%s\n", lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); fReturnCode = FALSE; goto cleanup; } // Generate security attribute/descriptor for the specified user if (pLogonName && *pLogonName) { // SD if (!CreateSecurityDescriptor(pLogonName, &sdPermissions)) { fReturnCode = FALSE; goto cleanup; } // SA sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = &sdPermissions; } // Create the event log entry lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, REGISTRY_KEY_EVENTLOG, 0, KEY_ALL_ACCESS, &hkEvent); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } // Create event key lRet = CREATEKEY(hkEvent, pServiceName, hkObject, dwDisposition); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } // Set the value lRet = SETSZVALUE(hkObject, "EventMessageFile", pExePath); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; lRet = SETDWVALUE(hkObject, "TypesSupported", &dwData); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } // Open the service registry key sprintf(pServiceKey, "%s\\%s", REGISTRY_KEY_SERVICE, pServiceName); lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, pServiceKey, 0, KEY_ALL_ACCESS, &hkService); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } if (pLogonName && *pLogonName) { // Set the security lRet = RegSetKeySecurity( hkService, (SECURITY_INFORMATION)(DACL_SECURITY_INFORMATION), &sdPermissions); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } } // Create StartupParams value if (pServiceParams) { lRet = SETSZVALUE(hkService, "StartupParams", pServiceParams); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } } fReturnCode = TRUE; cleanup: FREEHSCM(schService); FREEHSCM(schSCManager); FREEHKEY(hkEvent); FREEHKEY(hkService); FREEHKEY(hkObject); RegFlushKey(HKEY_LOCAL_MACHINE); return fReturnCode; }
BOOLEAN ScmDrvCtrl::Install(const TCHAR* lpszServiceName, const TCHAR* lpszDriverPath, const TCHAR* lpszAltitude, const TCHAR* lpszLink_name) { SC_HANDLE hServiceMgr = NULL; SC_HANDLE hService = NULL; int i = 0; _tcscpy_s(m_link_name, MAX_PATH, lpszLink_name); if (NULL == lpszServiceName || NULL == lpszDriverPath || NULL == lpszAltitude) { return FALSE; } UnInstall(lpszServiceName); WIN32_FIND_DATA FindFileData; if (FindFirstFileW(lpszDriverPath, &FindFileData) == INVALID_HANDLE_VALUE) { return FALSE; } again: hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hServiceMgr == NULL) { return FALSE; } hService = CreateService(hServiceMgr, lpszServiceName, // 驱动程序的在注册表中的名字 lpszServiceName, // 注册表驱动程序的DisplayName 值 SERVICE_ALL_ACCESS, // 加载驱动程序的访问权限 SERVICE_FILE_SYSTEM_DRIVER, // 表示加载的服务是文件系统驱动程序 SERVICE_DEMAND_START, // 注册表驱动程序的Start 值 SERVICE_ERROR_IGNORE, // 注册表驱动程序的ErrorControl 值 lpszDriverPath, // 注册表驱动程序的ImagePath 值 _T("FSFilter Activity Monitor"),// 注册表驱动程序的Group 值 NULL, _T("FltMgr"), // 注册表驱动程序的DependOnService 值 NULL, NULL); if (hService == NULL) { CloseServiceHandle(hServiceMgr); if (i > 100000) { return FALSE; } i++; // printf("%d\n", i); goto again; } CloseServiceHandle(hService); // 服务句柄 CloseServiceHandle(hServiceMgr); // SCM句柄 TCHAR szTempStr[MAX_PATH]; HKEY hKey = NULL; DWORD dwData = 0; _tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } _tcscpy_s(szTempStr, MAX_PATH, lpszServiceName); if (RegSetValueEx(hKey, _T("service_name"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) { return FALSE; } //GetWindowsDirectory(szTempStr,MAX_PATH); //if (RegSetValueEx(hKey, _T("system_dir"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) //{ // return FALSE; //} RegFlushKey(hKey); RegCloseKey(hKey); _tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T("\\Instances")); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } _tcscpy_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T(" Instance")); if (RegSetValueEx(hKey, _T("DefaultInstance"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) { return FALSE; } RegFlushKey(hKey); RegCloseKey(hKey); _tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T("\\Instances\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T(" Instance")); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } _tcscpy_s(szTempStr, lpszAltitude); if (RegSetValueEx(hKey, _T("Altitude"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) { return FALSE; } dwData = 0x0; if (RegSetValueEx(hKey, _T("Flags"), 0, REG_DWORD, (CONST BYTE*)&dwData, sizeof(DWORD)) != ERROR_SUCCESS) { return FALSE; } RegFlushKey(hKey); RegCloseKey(hKey); return TRUE; }
void installService(LPCTSTR serviceName, LPCTSTR displayName, LPCTSTR serviceExe, LPCTSTR dependencies, int currentDependenciesLen, LPCTSTR homeDir, LPCTSTR classPath, LPCTSTR jvmArgs, LPCSTR mainClass) { LPCTSTR lpszBinaryPathName = serviceExe; char * allDependencies = new TCHAR[_DEPENDENCY_STR_LEN]; char * ptr = allDependencies; int rest_len = _DEPENDENCY_STR_LEN; if (currentDependenciesLen > 0 && dependencies != NULL) { strcpy_s(ptr, rest_len, dependencies); ptr += currentDependenciesLen; rest_len -= currentDependenciesLen; } // add static dependencies strcpy_s(ptr, rest_len, NUP_SERVICE_NAME); ptr += sizeof(NUP_SERVICE_NAME); rest_len -= sizeof(NUP_SERVICE_NAME); strcpy_s(ptr, rest_len, TCPIP_SERVICE_NAME); ptr += sizeof(TCPIP_SERVICE_NAME); rest_len -= sizeof(TCPIP_SERVICE_NAME); strcpy_s(ptr, rest_len, AFD_SERVICE_NAME); ptr += sizeof(AFD_SERVICE_NAME); *ptr = '\0'; BOOL needToFree = FALSE; if (strchr(lpszBinaryPathName, ' ') != NULL || TRUE) { int buf_len = strlen(lpszBinaryPathName)+3; char *quotedBinPath = new char[buf_len]; sprintf_s(quotedBinPath, buf_len, "\"%s\"", lpszBinaryPathName); lpszBinaryPathName = quotedBinPath; needToFree = TRUE; } printf("Service %s.\n", lpszBinaryPathName); // TODO 1st store parameters, 2nd install service,, since if parameters failed, then service is not operable SC_HANDLE hService = CreateService(scm, // SCManager database serviceName, // name of service NULL, // name to display SERVICE_ALL_ACCESS, // desired access SERVICE_WIN32_OWN_PROCESS, // service type SERVICE_AUTO_START, // start type SERVICE_ERROR_NORMAL, // error control type lpszBinaryPathName, // binary name NULL, // no load ordering group NULL, // no tag idenitifier allDependencies, // we depend ??? NULL, // loacalsystem account NULL); // no password delete allDependencies; if (needToFree) delete (void*)lpszBinaryPathName; if (hService != NULL) { printf("Added service %s (%s).\n", serviceName, displayName); // use to add description SERVICE_DESCRIPTION description; if (serviceName != displayName) { description.lpDescription = (LPSTR)displayName; ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &description); } HKEY hKey; if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, REG_ROOT, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL) == ERROR_SUCCESS) { if (RegSetValueEx( hKey, REG_K_CURRVER, 0, REG_SZ, (const BYTE* )VERSION, sizeof VERSION ) == ERROR_SUCCESS) { HKEY hKeyVer; if(RegCreateKeyEx(hKey, VERSION, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKeyVer, NULL) == ERROR_SUCCESS) { if (RegSetValueEx( hKeyVer, REG_V_PATH, 0, REG_SZ, (const BYTE* )homeDir, _tcslen(homeDir)+sizeof TCHAR ) == ERROR_SUCCESS) { printf("Set path %s.\n", homeDir); } if (classPath) { if (RegSetValueEx( hKeyVer, REG_V_CP, 0, REG_SZ, (const BYTE* )classPath, _tcslen(classPath)+sizeof TCHAR ) == ERROR_SUCCESS) { printf("Set class path %s.\n", classPath); } } if (jvmArgs) { if (RegSetValueEx( hKeyVer, REG_V_JVM_ARGS, 0, REG_SZ, (const BYTE* )jvmArgs, _tcslen(jvmArgs)+sizeof TCHAR ) == ERROR_SUCCESS) { printf("Set JVM args %s.\n", jvmArgs); } } if (mainClass) { if (RegSetValueEx( hKeyVer, REG_V_ENTRY_POINT, 0, REG_SZ, (const BYTE* )mainClass, _tcslen(mainClass)+sizeof TCHAR ) == ERROR_SUCCESS) { printf("Set main class to %s.\n", mainClass); } } else { if (RegDeleteKey(hKeyVer, REG_V_ENTRY_POINT) == ERROR_SUCCESS) printf("Default main class used."); } RegCloseKey(hKeyVer); } RegCloseKey(hKey); } } else { fprintf(stderr, "Cannot create config info in the Registry."); } } else { DWORD err = GetLastError(); char *msg = getErrorMsg(err, serviceName); if (msg == 0) { fprintf(stderr, "Cannot create service %s: unrecognized error %dL\n", serviceName, err); } else { fprintf(stderr, "Cannot create service %s: %s\n", serviceName, msg); } return; } CloseServiceHandle(hService); }
/***************************************************************************** * NT Service utility functions *****************************************************************************/ static int NTServiceInstall( intf_thread_t *p_intf ) { intf_sys_t *p_sys = p_intf->p_sys; char psz_path[10*MAX_PATH], psz_pathtmp[MAX_PATH], *psz_extra; SC_HANDLE handle = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ); if( handle == NULL ) { msg_Err( p_intf, "could not connect to Services Control Manager database" ); return VLC_EGENERIC; } /* Find out the filename of ourselves so we can install it to the * service control manager */ GetModuleFileName( NULL, psz_pathtmp, MAX_PATH ); sprintf( psz_path, "\"%s\" -I "MODULE_STRING, psz_pathtmp ); psz_extra = var_InheritString( p_intf, "ntservice-extraintf" ); if( psz_extra ) { strcat( psz_path, " --ntservice-extraintf " ); strcat( psz_path, psz_extra ); free( psz_extra ); } psz_extra = var_InheritString( p_intf, "ntservice-options" ); if( psz_extra && *psz_extra ) { strcat( psz_path, " " ); strcat( psz_path, psz_extra ); free( psz_extra ); } SC_HANDLE service = CreateService( handle, p_sys->psz_service, p_sys->psz_service, GENERIC_READ | GENERIC_EXECUTE, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, psz_path, NULL, NULL, NULL, NULL, NULL ); if( service == NULL ) { if( GetLastError() != ERROR_SERVICE_EXISTS ) { msg_Err( p_intf, "could not create new service: \"%s\" (%s)", p_sys->psz_service ,psz_path ); CloseServiceHandle( handle ); return VLC_EGENERIC; } else { msg_Warn( p_intf, "service \"%s\" already exists", p_sys->psz_service ); } } else { msg_Warn( p_intf, "service successfuly created" ); } if( service ) CloseServiceHandle( service ); CloseServiceHandle( handle ); return VLC_SUCCESS; }
int service_install(int log_to_file, int debug) { SC_HANDLE service_control_manager; int rc; char filename[1024]; HKEY key = NULL; DWORD types = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE; SC_HANDLE service; SERVICE_DESCRIPTION description; LPCTSTR debug_argv[2]; DWORD argc = 0; LPCTSTR *argv = NULL; if (log_to_file) { debug_argv[argc++] = "--log-to-file"; argv = debug_argv; } if (debug) { debug_argv[argc++] = "--debug"; argv = debug_argv; } if (GetModuleFileName(NULL, filename, sizeof(filename)) == 0) { rc = ERRNO_WINAPI_OFFSET + GetLastError(); fprintf(stderr, "Could not get module file name: %s (%d)\n", get_errno_name(rc), rc); return -1; } // register message catalog for event log if (RegCreateKey(HKEY_LOCAL_MACHINE, _event_log_key_name, &key) == ERROR_SUCCESS) { RegSetValueEx(key, "EventMessageFile", 0, REG_EXPAND_SZ, (PBYTE)filename, strlen(filename)); RegSetValueEx(key, "TypesSupported", 0, REG_DWORD, (LPBYTE)&types, sizeof(DWORD)); RegCloseKey(key); } // open service control manager service_control_manager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (service_control_manager == NULL) { rc = ERRNO_WINAPI_OFFSET + GetLastError(); fprintf(stderr, "Could not open service control manager: %s (%d)\n", get_errno_name(rc), rc); return -1; } // install service service = CreateService(service_control_manager, _service_name, _service_name, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, filename, NULL, NULL, NULL, NULL, NULL); if (service == NULL) { rc = GetLastError(); if (rc != ERROR_SERVICE_EXISTS) { rc += ERRNO_WINAPI_OFFSET; fprintf(stderr, "Could not install '%s' service: %s (%d)\n", _service_name, get_errno_name(rc), rc); CloseServiceHandle(service_control_manager); return -1; } else { printf("'%s' service is already installed\n", _service_name); service = OpenService(service_control_manager, _service_name, SERVICE_CHANGE_CONFIG | SERVICE_START); if (service == NULL) { rc = ERRNO_WINAPI_OFFSET + GetLastError(); fprintf(stderr, "Could not open '%s' service: %s (%d)\n", _service_name, get_errno_name(rc), rc); CloseServiceHandle(service_control_manager); return -1; } } } else { printf("Installed '%s' service\n", _service_name); } // update description description.lpDescription = _service_description; if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description)) { rc = ERRNO_WINAPI_OFFSET + GetLastError(); fprintf(stderr, "Could not update description of '%s' service: %s (%d)\n", _service_name, get_errno_name(rc), rc); CloseServiceHandle(service); CloseServiceHandle(service_control_manager); return -1; } // start service if (!StartService(service, argc, argv)) { rc = GetLastError(); if (rc != ERROR_SERVICE_ALREADY_RUNNING) { rc += ERRNO_WINAPI_OFFSET; fprintf(stderr, "Could not start '%s' service: %s (%d)\n", _service_name, get_errno_name(rc), rc); CloseServiceHandle(service); CloseServiceHandle(service_control_manager); return -1; } else { printf("'%s' service is already running\n", _service_name); } } else { // FIXME: query status and wait until service is really started if (log_to_file && debug) { printf("Started '%s' service with --log-to-file and --debug option\n", _service_name); } else if (log_to_file) { printf("Started '%s' service with --log-to-file option\n", _service_name); } else if (debug) { printf("Started '%s' service with --debug option\n", _service_name); } else { printf("Started '%s' service\n", _service_name); } } CloseServiceHandle(service); CloseServiceHandle(service_control_manager); return 0; }
BOOL install_service() { SC_HANDLE hSCManager; SC_HANDLE hService; char path[MAX_PATH]; // Get the current module name if (!GetModuleFileName(NULL, path, MAX_PATH)) { printf("Cannot get module name (0x%08x)\n", GetLastError()); return FALSE; } // Build the service command line char cmd[MAX_PATH]; int len = _snprintf(cmd, sizeof(cmd), "\"%s\" service", path); if (len < 0 || len == sizeof(cmd)) { printf("Cannot build service command line (0x%08x)\n", -1); return FALSE; } // Open the service manager hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (hSCManager == NULL) { printf("Cannot open service manager (0x%08x)\n", GetLastError()); return FALSE; } printf(" * Installing service %s\n", SERVICE_NAME); fflush(stdout); // Create the service hService = CreateService( hSCManager, SERVICE_NAME, DISPLAY_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmd, NULL, NULL, NULL, NULL, /* LocalSystem account */ NULL ); if (hService == NULL) { printf("Cannot create service (0x%08x)\n", GetLastError()); CloseServiceHandle(hSCManager); return FALSE; } // Start the service printf(" * Starting service\n"); fflush(stdout); char* args[] = { path, "service" }; if (StartService(hService, 2, (const char**)&args) == 0) { DWORD err = GetLastError(); if (err != ERROR_SERVICE_ALREADY_RUNNING) { printf("Cannot start service %s (0x%08x)\n", SERVICE_NAME, err); CloseServiceHandle(hService); CloseServiceHandle(hSCManager); return FALSE; } } // Cleanup CloseServiceHandle(hService); CloseServiceHandle(hSCManager); printf("Service %s successfully installed.\n", SERVICE_NAME); fflush(stdout); return TRUE; }
//////////////////////////////////////////////////////////// // installation and removal bool installService(const wxString &serviceName, const wxString &executable, const wxString &args, const wxString &displayname, const wxString &user, const wxString &password) { DWORD dwData; bool done = false; SC_HANDLE manager = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS); if (manager) { wxString cmd = executable + wxT(" ") + args; wxString quser; if (!user.Contains(wxT("\\"))) quser = wxT(".\\") + user; else quser = user; SC_HANDLE service = CreateService(manager, serviceName.c_str(), displayname.c_str(), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmd.c_str(), 0, 0, 0, quser.c_str(), password.c_str()); if (service) { done = true; CloseServiceHandle(service); } else { LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); wxString error; error.Printf(wxT("%s"), lpMsgBuf); LogMessage(error, LOG_ERROR); } CloseServiceHandle(manager); } // Setup the event message DLL wxRegKey *msgKey = new wxRegKey(wxT("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\") + serviceName); if(!msgKey->Exists()) { if (!msgKey->Create()) LogMessage(_("Could not open the message source registry key."), LOG_WARNING); } wxString path = executable.BeforeLast('\\') + wxT("\\pgaevent.dll"); if (!msgKey->SetValue(wxT("EventMessageFile"), path)) LogMessage(_("Could not set the event message file registry value."), LOG_WARNING); dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; if (!msgKey->SetValue(wxT("TypesSupported"), dwData)) LogMessage(_("Could not set the supported types."), LOG_WARNING);; return done; }
extern "C" void __declspec(dllexport) InstallService( HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop) { TCHAR ServiceName[100] = {0}; TCHAR DisplayName[100] = {0}; TCHAR BinaryPath[260] = {0}; TCHAR ServiceType[100] = {0}; TCHAR StartType[100] = {0}; TCHAR* reason = 0; TCHAR* stopString = NULL; BOOL okay = FALSE; DWORD error = 0; SERVICE_STATUS status = {0}; DWORD nServiceType = SERVICE_WIN32_SHARE_PROCESS; //SERVICE_WIN32_SHARE_PROCESS; DWORD nStartType = SERVICE_DEMAND_START; g_hwndParent=hwndParent; g_stringsize=string_size; g_stacktop=stacktop; g_variables=variables; if (0 == popstring(ServiceName) && 0 == popstring(DisplayName) && 0 == popstring(BinaryPath) ) { //MessageBox(hwndParent, BinaryPath, TEXT("CheckPath"), MB_OK); if (0 == popstring(ServiceType)) { nServiceType = GetServiceTypeValue(ServiceType); } if (0 == popstring(StartType)) { nStartType = GetStartTypeValue(StartType); } SC_HANDLE hSCM = OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS); if (hSCM) { SC_HANDLE hService = CreateService(hSCM, ServiceName, DisplayName, SERVICE_ALL_ACCESS, //SERVICE_START or SERVICE_QUERY_STATUS or _DELETE, nServiceType, nStartType, SERVICE_ERROR_NORMAL, BinaryPath, NULL, NULL, NULL, NULL, NULL); if (hService) { if (nStartType == SERVICE_AUTO_START) { okay = StartService(hService, 0, 0); if (!okay) { error = GetLastError(); } } CloseServiceHandle(hService); } else { error = GetLastError(); } CloseServiceHandle(hSCM); } else { error = GetLastError(); } } else { SetLastError(ERROR_INVALID_PARAMETER); //reason = TEXT("Bad parameters"); } if (FALSE == okay) { if (!reason) { LPVOID lpMsgBuf = NULL; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); pushstring((TCHAR*)lpMsgBuf); LocalFree(lpMsgBuf); } else pushstring(reason); } else pushstring(TEXT("Ok")); }
static int installservice(char *account,char *pass) { SC_HANDLE service, scm; TCHAR path[512], system[80], name[80], username[80]; char userpass[256], user[256], dom[256]="."; int i,ret = 0; pid_t pid = -1; if(!GetModuleFileName(NULL, path, 512)) { logmsg(LOG_STDERR+LOG_SYSTEM+0, "Unable to get executable name"); return(0); } strcpy(name, account); if(!pass) pass = getpass("Password: "******"UWIN_CS%s", name); sfsprintf(servdname,sizeof(servdname),"UWIN Client(%s)", name); for(i=0;i<(signed)strlen(servname);i++) if(servname[i] == '/') servname[i]= '#'; if ((scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) != NULL) { if((service=OpenService(scm,TEXT(servname),SERVICE_QUERY_STATUS)) == NULL) { // If service does not exist then install. if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) { strcpy(user,name); if((sep = strchr(name,'/')) != NULL) { *sep = '\0'; strcpy(dom,name); strcpy(user,sep+1); *sep = '\\'; setuid(1); } if (system[0] != '\0') { sysname = system; } if (LookupAccountName(sysname,user,sid,&sidlen,domain,&domlen,&puse)) { if (verifylogin(user,dom,userpass)) { if ((pid = spawnl("/usr/etc/priv.exe","priv.exe",name,"1",0)) > 0) wait(&ret); ret = 0; strcat(dom,"\\"); strcat(dom,user); if ((service = CreateService(scm,servname,servdname,SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,path,NULL,NULL,NULL,dom,userpass)) != NULL) { logmsg(LOG_STDERR+1, "%s installed", servdname); CloseServiceHandle(service); ret=1; } else error(LOG_ALL+1, "CreateService failed for user %s", name); } } else logerr(1, "Invalid UserName %s", username); } } else { CloseServiceHandle(service); ret = 1; } CloseServiceHandle(scm); } else error(1, "OpenSCManager failed"); } else logmsg(LOG_STDERR+0 ,"Invalid domain account %s", username); return(ret); }
bool WinServiceInstall() { CSD_T ChangeService_Config2; HMODULE advapi32; SC_HANDLE serviceControlManager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (!serviceControlManager) { sLog.outError("SERVICE: No access to service control manager."); return false; } char path[_MAX_PATH + 10]; if (!GetModuleFileName(0, path, sizeof(path) / sizeof(path[0]))) { CloseServiceHandle(serviceControlManager); sLog.outError("SERVICE: Can't get service binary filename."); return false; } std::strcat(path, " -s run"); SC_HANDLE service = CreateService(serviceControlManager, serviceName, // name of service serviceLongName, // service name to display SERVICE_ALL_ACCESS, // desired access // service type SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, // start type SERVICE_ERROR_IGNORE, // error control type path, // service's binary 0, // no load ordering group 0, // no tag identifier 0, // no dependencies 0, // LocalSystem account 0); // no password if (!service) { CloseServiceHandle(serviceControlManager); sLog.outError("SERVICE: Can't register service for: %s", path); return false; } advapi32 = GetModuleHandle("ADVAPI32.DLL"); if (!advapi32) { sLog.outError("SERVICE: Can't access ADVAPI32.DLL"); CloseServiceHandle(service); CloseServiceHandle(serviceControlManager); return false; } ChangeService_Config2 = (CSD_T) GetProcAddress(advapi32, "ChangeServiceConfig2A"); if (!ChangeService_Config2) { sLog.outError("SERVICE: Can't access ChangeServiceConfig2A from ADVAPI32.DLL"); CloseServiceHandle(service); CloseServiceHandle(serviceControlManager); return false; } SERVICE_DESCRIPTION sdBuf; sdBuf.lpDescription = serviceDescription; ChangeService_Config2( service, // handle to service SERVICE_CONFIG_DESCRIPTION, // change: description &sdBuf); // new data SC_ACTION _action[1]; _action[0].Type = SC_ACTION_RESTART; _action[0].Delay = 10000; SERVICE_FAILURE_ACTIONS sfa; ZeroMemory(&sfa, sizeof(SERVICE_FAILURE_ACTIONS)); sfa.lpsaActions = _action; sfa.cActions = 1; sfa.dwResetPeriod = INFINITE; ChangeService_Config2( service, // handle to service SERVICE_CONFIG_FAILURE_ACTIONS, // information level &sfa); // new data CloseServiceHandle(service); CloseServiceHandle(serviceControlManager); return true; }
bool InstallService() { SC_HANDLE hSCManager = NULL; SC_HANDLE hService = NULL; bool ret = false; do { hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if (NULL == hSCManager) { break;; } hService = CreateService(hSCManager, srvName, srvName, SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, srvStartType, SERVICE_ERROR_NORMAL, srvFilePath, NULL, NULL, NULL, NULL, NULL); if (hService == NULL) { hService = OpenService(hSCManager, srvName, SERVICE_ALL_ACCESS); if (hService == NULL) { break; } } if (StartService(hService, 0, NULL) == NULL) { break; } SERVICE_STATUS_PROCESS ssStatus; DWORD dwBytesNeeded; if (!QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssStatus, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { break; } DWORD dwStartTickCount = GetTickCount(); DWORD dwOldCheckPoint = ssStatus.dwCheckPoint; DWORD dwWaitTime; while (ssStatus.dwCurrentState == SERVICE_START_PENDING) { dwWaitTime = ssStatus.dwWaitHint / 10; if (dwWaitTime < 1000) dwWaitTime = 1000; else if (dwWaitTime > 10000) dwWaitTime = 10000; Sleep(dwWaitTime); if (!QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssStatus, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { break; } if (ssStatus.dwCheckPoint > dwOldCheckPoint) { dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; } else { if (GetTickCount() - dwStartTickCount > ssStatus.dwWaitHint) { break; } } } if (ssStatus.dwCurrentState == SERVICE_RUNNING) { ret = true; } } while (0); if (!ret) { UninstallService(); } if (hService) { CloseServiceHandle(hService); } if (hSCManager) { CloseServiceHandle(hSCManager); } return ret; }