Esempio n. 1
0
static void InstallService() {
  SC_HANDLE hSCManager;
  int status;
  RemoveService();
  hSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE);
  if (hSCManager) {
    SC_HANDLE hService;
    char *pgm;
    char *cmd;
    static const char* multi_opt="--multi";
    static const char* server_opt="--server";
    static const char* data_opt="";
    char *opts = GetMulti() ? (GetContextSwitching() ? "--multi" : "--server") : "";
    SERVICE_DESCRIPTION sd;
    LPTSTR description=(LPTSTR)malloc(4096);
    if (GetMulti()) {
      if (GetContextSwitching()) {
	opts=multi_opt;
	wsprintf(description,TEXT("MDSplus data service listening on port %s.\nPermits multiple connections each with own tdi and tree context\n"),
		 GetPortname());
      } else {
	opts=server_opt;
	wsprintf(description,TEXT("MDSplus data service listening on port %s.\nPermits multiple connections with shared tdi and tree context\n"),
		 GetPortname());
      }
    } else {
      opts=data_opt;
      wsprintf(description,TEXT("MDSplus data service listening on port %s.\nEach connections will spawn a private server.\n"),
	       GetPortname());
    }
    sd.lpDescription=description;
    _get_pgmptr(&pgm);
    cmd = (char *)malloc(strlen(pgm)+strlen(GetPortname())+strlen(GetHostfile())+100);
    sprintf(cmd,"%s --port=%s --hostfile=\"%s\" %s",pgm,GetPortname(),GetHostfile(),opts);
    hService = CreateService(hSCManager, ServiceName(1), ServiceName(0), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
			     SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmd, NULL, NULL, NULL, NULL, NULL);
    if (hService == NULL)
      status = GetLastError();
	else {
      ChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&sd);
	  if (GetMulti()) {
		SERVICE_FAILURE_ACTIONS sfa;
		SC_ACTION actions[] = {{SC_ACTION_RESTART,5000}};
		sfa.dwResetPeriod = INFINITE;
		sfa.lpRebootMsg = NULL;
		sfa.lpCommand = NULL;
		sfa.cActions = 1;
		sfa.lpsaActions=actions;
		status = ChangeServiceConfig2(hService,SERVICE_CONFIG_FAILURE_ACTIONS, &sfa);
		status = GetLastError();
	  }
	}
    free(description);
    free(cmd);
    if (hService)
      CloseServiceHandle(hService);
    CloseServiceHandle(hSCManager);
  }
}
Esempio n. 2
0
BOOLEAN EspChangeServiceConfig2(
    _In_ PWSTR ServiceName,
    _In_opt_ SC_HANDLE ServiceHandle,
    _In_ ULONG InfoLevel,
    _In_ PVOID Info
    )
{
    if (ServiceHandle)
    {
        return !!ChangeServiceConfig2(ServiceHandle, InfoLevel, Info);
    }
    else
    {
        NTSTATUS status;

        if (NT_SUCCESS(status = PhSvcCallChangeServiceConfig2(ServiceName, InfoLevel, Info)))
        {
            return TRUE;
        }
        else
        {
            SetLastError(PhNtStatusToDosError(status));
            return FALSE;
        }
    }
}
Esempio n. 3
0
BOOL installservice(int serviceNo)
{
	SC_HANDLE schSCManager, schService;
	SERVICE_DESCRIPTION sdBuf;

    TCHAR szPath[MAX_PATH], cmdLine[MAX_PATH]; 
	TCHAR serviceName[64];
	TCHAR displayName[64];

	wxLogMessage(wxT("* Installing NWNX Service %d..."), serviceNo);

	schSCManager = getSCManager();
	if (NULL == schSCManager) 
		return FALSE;

    if(!GetModuleFileName(NULL, szPath, MAX_PATH ) )
    {
		wxLogError(wxT("* GetModuleFileName failed (%d)"), GetLastError()); 
        return FALSE;
    }

	_stprintf_s(serviceName, 64, _T("NWNX4-%d"), serviceNo);
	_stprintf_s(displayName, 64, _T("NWNX4 Service %d"), serviceNo);
	_stprintf_s(cmdLine, MAX_PATH, _T("%s -serviceno %d -runservice"), szPath, serviceNo);
	sdBuf.lpDescription = _T("Neverwinter Nights Extender 4 service instance");

    schService = CreateService( 
        schSCManager,              // SCManager database 
        serviceName,		       // name of service 
        displayName,               // service name to display 
        SERVICE_ALL_ACCESS,        // desired access 
        SERVICE_WIN32_OWN_PROCESS, // service type 
        SERVICE_DEMAND_START,      // start type 
        SERVICE_ERROR_NORMAL,      // error control type 
        cmdLine,                   // 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) 
    {
		wxLogError(wxT("* CreateService failed (%d)"), GetLastError()); 
        return FALSE;
    }

    if(!ChangeServiceConfig2(
        schService,                 // handle to service
        SERVICE_CONFIG_DESCRIPTION, // change: description
        &sdBuf) )                   // value: new description
    {
        wxLogError(wxT("ChangeServiceConfig2 failed"));
        return FALSE;
    }

    CloseServiceHandle(schService); 
    return TRUE;

}
/* In case of an unexpected termination, configure the action to be
 * taken. */
static void
set_config_failure_actions()
{
    /* In case of a failure, restart the process the first two times
     * After 'dwResetPeriod', the failure count is reset. */
    SC_ACTION fail_action[3] = {
        {SC_ACTION_RESTART, 0},
        {SC_ACTION_RESTART, 0},
        {SC_ACTION_NONE, 0}
    };
    SERVICE_FAILURE_ACTIONS service_fail_action;

    /* Reset failure count after (in seconds). */
    service_fail_action.dwResetPeriod = 10;

    /* Reboot message. */
    service_fail_action.lpRebootMsg = NULL;

    /* The command line of the process. */
    service_fail_action.lpCommand = NULL;

    /* Number of elements in 'fail_actions'. */
    service_fail_action.cActions = sizeof(fail_action)/sizeof(fail_action[0]);

    /* A pointer to an array of SC_ACTION structures. */
    service_fail_action.lpsaActions = fail_action;

    if (!ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS,
                              &service_fail_action)) {
        char *msg_buf = ovs_lasterror_to_string();
        VLOG_FATAL("Failed to configure service fail actions (%s).", msg_buf);
    }
}
Esempio n. 5
0
bool BaseService::Install(TCHAR szFilePath[]) {

    // Open the Service Control Manager
    SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

    if (!hSCM) return false;

    // Create the service
    SC_HANDLE hService = CreateService(hSCM,
									m_szServiceName,
									m_szServiceName,
									SERVICE_ALL_ACCESS,
									m_Status.dwServiceType,
									m_dwStartType,
									SERVICE_ERROR_NORMAL,
									szFilePath,
									NULL,
									NULL,
									NULL,
									NULL,
									NULL);
    if (!hService) {
        CloseServiceHandle(hSCM);
        return false;
    }

	const char *szDescribe="Backend Command Service Tools.";

	ChangeServiceConfig2(hService,1,(LPVOID) &szDescribe);

    // tidy up
    CloseServiceHandle(hService);
    CloseServiceHandle(hSCM);
    return true;
}
Esempio n. 6
0
/* Make sure service recovery actions are taken where necessary */
void set_service_recovery(SC_HANDLE service, char *service_name) {
  SC_HANDLE services = 0;

  if (! service) {
    services = open_service_manager();
    if (! services) return;

    service = OpenService(services, service_name, SC_MANAGER_ALL_ACCESS);
    if (! service) return;
  }

  SERVICE_FAILURE_ACTIONS_FLAG flag;
  ZeroMemory(&flag, sizeof(flag));
  flag.fFailureActionsOnNonCrashFailures = true;

  /* This functionality was added in Vista so the call may fail */
  if (! ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, &flag)) {
    unsigned long error = GetLastError();
    /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
    if (error != ERROR_INVALID_LEVEL) {
      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CHANGESERVICECONFIG2_FAILED, service_name, error_string(error), 0);
    }
  }

  if (services) {
    CloseServiceHandle(service);
    CloseServiceHandle(services);
  }
}
Esempio n. 7
0
bool CInstaller::ServiceAddInt(CString &sServicename, CString &sFilename, CString &sParams) {
	SC_HANDLE hServiceControl=OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
	if(!hServiceControl) return false;

	CString sSvcCmd; sSvcCmd.Format("\"%s\" %s", sFilename.CStr(), sParams.CStr());
	SC_HANDLE hService=CreateService(hServiceControl, sServicename.CStr(),
		g_pMainCtrl->m_cBot.as_valname.sValue.CStr(), SERVICE_ALL_ACCESS, \
		SERVICE_WIN32_SHARE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, \
		sSvcCmd.CStr(), NULL, NULL, NULL, NULL, NULL);
	if(!hService) {
		DWORD dwError=GetLastError();
		if(dwError==ERROR_SERVICE_EXISTS) {
			ServiceDel(sServicename); CloseServiceHandle(hService);
			CloseServiceHandle(hServiceControl);
			return ServiceAdd(sServicename, sFilename);
		} else {
			CloseServiceHandle(hServiceControl); return false; }
	}

	SC_ACTION scActions[1]; scActions[0].Delay=1; scActions[0].Type=SC_ACTION_RESTART;
	SERVICE_FAILURE_ACTIONS sfActions; sfActions.dwResetPeriod=INFINITE; sfActions.lpRebootMsg=NULL;
	sfActions.lpCommand=NULL; sfActions.cActions=1; sfActions.lpsaActions=scActions;

	if(!ChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, &sfActions)) {
		CloseServiceHandle(hService); CloseServiceHandle(hServiceControl); return false;
	}

	CloseServiceHandle(hService); CloseServiceHandle(hServiceControl); return true;
}
Esempio n. 8
0
int ServiceInstall()
{
    int ok = 0;
    SC_HANDLE service;
    SERVICE_DESCRIPTION sdBuf;
    SC_HANDLE serviceControlManager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);

    if(serviceControlManager) {
        char exe_path[MAX_PATH + 1];
        if(GetModuleFileName(0, exe_path, sizeof(exe_path)) > 0) {
            char launch_cmd[MAX_PATH + 50];
            sprintf(launch_cmd, "\"%s\" -d runservice", exe_path);
            service = CreateService(serviceControlManager,
                            PACKAGE_NAME, PACKAGE_NAME,
                            SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
                            SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, launch_cmd,
                            0, 0, 0, 0, 0);
            if(service) {
                sdBuf.lpDescription = PACKAGE_DESCRIPTION;
                ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &sdBuf);
                CloseServiceHandle(service);
                ok = 1;
            }
        }
        CloseServiceHandle(serviceControlManager);
    }
    return ok;
}
Esempio n. 9
0
bool install_service(void) {
	char command[4096] = "\"";
	char **argp;
	bool space;
	SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};

	manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager) {
		logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
		return false;
	}

	if(!strchr(program_name, '\\')) {
		GetCurrentDirectory(sizeof command - 1, command + 1);
		strncat(command, "\\", sizeof command - strlen(command));
	}

	strncat(command, program_name, sizeof command - strlen(command));

	strncat(command, "\"", sizeof command - strlen(command));

	for(argp = g_argv + 1; *argp; argp++) {
		space = strchr(*argp, ' ');
		strncat(command, " ", sizeof command - strlen(command));
		
		if(space)
			strncat(command, "\"", sizeof command - strlen(command));
		
		strncat(command, *argp, sizeof command - strlen(command));

		if(space)
			strncat(command, "\"", sizeof command - strlen(command));
	}

	service = CreateService(manager, identname, identname,
			SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
			command, NULL, NULL, NULL, NULL, NULL);
	
	if(!service) {
		DWORD lasterror = GetLastError();
		logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
		if(lasterror != ERROR_SERVICE_EXISTS)
			return false;
	}

	if(service) {
		ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
		logger(LOG_INFO, "%s service installed", identname);
	} else {
		service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
	}

	if(!StartService(service, 0, NULL))
		logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
	else
		logger(LOG_INFO, "%s service started", identname);

	return true;
}
HRESULT CHTFileTransferSystemServiceModule::RegisterAppId(bool bService) throw() 
{
	HRESULT hr = S_OK; 
	BOOL res = CAtlServiceModuleT<CHTFileTransferSystemServiceModule, IDS_SERVICENAME>::RegisterAppId(bService);   
	if(bService) 
	{ 
		if(IsInstalled()) 
		{                 
			SC_HANDLE hSCM = ::OpenSCManagerW(NULL, NULL, SERVICE_CHANGE_CONFIG); 
			SC_HANDLE hService = NULL; 
			if (hSCM == NULL) 
				hr = AtlHresultFromLastError(); 
			else 
			{ 
				hService = ::OpenService(hSCM, m_szServiceName, SERVICE_CHANGE_CONFIG); 
				if(hService != NULL) 
				{ 
					const int m_szServiceNameLen = 4096; 
					const int m_szServiceDescriptionLen = 2000; 
					CAString strServiceDescription = L"HTFileTransferSystemService"; 
					SERVICE_DESCRIPTION sdBuf = {strServiceDescription.GetBuffer(0)};
					strServiceDescription.ReleaseBuffer();
					res = ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuf); 
					if (res)
					{
						res = ChangeServiceConfig( 
							hService,        // handle of service 
							SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, // service type: no change 
							SERVICE_AUTO_START,  // service start type 
							SERVICE_NO_CHANGE, // error control: no change 
							NULL,              // binary path: no change 
							NULL,              // load order group: no change 
							NULL,              // tag ID: no change 
							NULL,              // dependencies: no change 
							NULL,              // account name: no change 
							NULL,              // password: no change 
							NULL);
						if (res != 0)
						{
							hr = AtlHresultFromLastError();
						}
					}
					else
					{
						hr = AtlHresultFromLastError();
					}
					::CloseServiceHandle(hService); 
				} 
				else 
				{
					hr = AtlHresultFromLastError(); 
				}
				::CloseServiceHandle(hSCM); 
			} 
		} 
	} 
	return   hr; 
}
int ga_install_service(const char *path, const char *logfile)
{
    int ret = EXIT_FAILURE;
    SC_HANDLE manager;
    SC_HANDLE service;
    TCHAR module_fname[MAX_PATH];
    GString *esc;
    GString *cmdline;
    SERVICE_DESCRIPTION desc = { (char *)QGA_SERVICE_DESCRIPTION };

    if (GetModuleFileName(NULL, module_fname, MAX_PATH) == 0) {
        printf_win_error("No full path to service's executable");
        return EXIT_FAILURE;
    }

    esc     = g_string_new("");
    cmdline = g_string_new("");

    g_string_append_printf(cmdline, "%s -d",
                           win_escape_arg(module_fname, esc));

    if (path) {
        g_string_append_printf(cmdline, " -p %s", win_escape_arg(path, esc));
    }
    if (logfile) {
        g_string_append_printf(cmdline, " -l %s -v",
                               win_escape_arg(logfile, esc));
    }

    g_debug("service's cmdline: %s", cmdline->str);

    manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (manager == NULL) {
        printf_win_error("No handle to service control manager");
        goto out_strings;
    }

    service = CreateService(manager, QGA_SERVICE_NAME, QGA_SERVICE_DISPLAY_NAME,
        SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL, cmdline->str, NULL, NULL, NULL, NULL, NULL);
    if (service == NULL) {
        printf_win_error("Failed to install service");
        goto out_manager;
    }

    ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &desc);
    fprintf(stderr, "Service was installed successfully.\n");
    ret = EXIT_SUCCESS;
    CloseServiceHandle(service);

out_manager:
    CloseServiceHandle(manager);

out_strings:
    g_string_free(cmdline, TRUE);
    g_string_free(esc, TRUE);
    return ret;
}
Esempio n. 12
0
// 
//  FUNCTION: CmdInstallService() 
// 
//  PURPOSE: Installs the service 
// 
//  PARAMETERS: 
//    none 
// 
//  RETURN VALUE: 
//    none 
// 
//  COMMENTS: 
// 
void CmdInstallService() 
{ 
    SC_HANDLE   schService; 
    SC_HANDLE   schSCManager; 
 
    TCHAR szPath[512]; 
 
    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ) 
    { 
        _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(SZSERVICEDISPLAYNAME), GetLastErrorText(szErr, 256)); 
        return; 
    } 
 
    schSCManager = OpenSCManager( 
                        NULL,                   // machine (NULL == local) 
                        NULL,                   // database (NULL == default) 
                        SC_MANAGER_ALL_ACCESS   // access required 
                        ); 
    if ( schSCManager ) 
    { 
        schService = CreateService( 
            schSCManager,               // SCManager database 
            TEXT(SZSERVICENAME),        // name of service 
            TEXT(SZSERVICEDISPLAYNAME), // 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,                     // service's binary 
            NULL,                       // no load ordering group 
            NULL,                       // no tag identifier 
            TEXT(SZDEPENDENCIES),       // dependencies 
            NULL,                       // LocalSystem account 
            NULL);                      // no password 
 
        if ( schService ) 
        {   Sleep(1001);
            StartService(schService,0,0);
                        SC_ACTION sa={SC_ACTION_RESTART,60000};
                        SERVICE_FAILURE_ACTIONS sfa={60,0,0,1,&sa};
            ChangeServiceConfig2(schService,SERVICE_CONFIG_FAILURE_ACTIONS,&sfa);
            _tprintf(TEXT("%s installed.\n"), TEXT(SZSERVICEDISPLAYNAME) ); 
            CloseServiceHandle(schService); 
        } 
        else 
        { 
            _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256)); 
        } 
 
        CloseServiceHandle(schSCManager); 
    } 
    else 
        _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256)); 
} 
Esempio n. 13
0
int
install_service(char *program_name, char *service_name, char *config_file)
{
    HANDLE schSCManager,schService;
    SERVICE_DESCRIPTION sdBuf;

    if (config_file != NULL)
	snprintf(&program_name[strlen(program_name)],
		 _MAX_PATH - strlen(program_name),
		 " -e %s", config_file);

    if (service_name == NULL)
	service_name = DEFAULT_SERVICE_NAME;
    else if (service_name[0] == '\0')
	service_name = DEFAULT_SERVICE_NAME;

    schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);

    if (schSCManager == NULL) {
	fprintf(stderr, "install_service failed to open Service Control Manager\n");
	return EXIT_FAILURE;
    }

    schService = CreateService(schSCManager,
	service_name,
	service_name,			/* service 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 */
	program_name,			/* service's binary */
	NULL,				/* no load ordering group */
	NULL,				/* no tag identifier */
	NULL,				/* database service dependency */
	NULL,				/* LocalSystem account */
	NULL);				/* no password */

    if (schService == NULL) {
	fprintf(stderr, "install_service failed to create service %s\n", service_name);
	return EXIT_FAILURE;
    }
    sdBuf.lpDescription = "Server for Empire game";

    if(!ChangeServiceConfig2(
	  schService,		      /* handle to service */
	  SERVICE_CONFIG_DESCRIPTION, /* change: description */
	  &sdBuf)) {		      /* value: new description */
	fprintf(stderr, "install_service failed to set the description\n");
    }

    printf("Service %s installed.\n", service_name);
    CloseServiceHandle(schService);
    return EXIT_SUCCESS;
}
Esempio n. 14
0
int
_shttpd_set_nt_service(struct shttpd_ctx *ctx, const char *action)
{
	SC_HANDLE	hSCM, hService;
	char		path[FILENAME_MAX], key[128];
	HKEY		hKey;
	DWORD		dwData;


	if (!strcmp(action, "install")) {
		if ((hSCM = OpenSCManager(NULL, NULL,
		    SC_MANAGER_ALL_ACCESS)) == NULL)
			_shttpd_elog(E_FATAL, NULL, "Error opening SCM (%d)", ERRNO);

		GetModuleFileName(NULL, path, sizeof(path));

		hService = CreateService(hSCM, SERVICE_NAME, SERVICE_NAME,
		    SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
		    SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, path,
		    NULL, NULL, NULL, NULL, NULL);

		if (!hService)
			_shttpd_elog(E_FATAL, NULL,
			    "Error installing service (%d)", ERRNO);

		ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION,
		    &service_descr);
		_shttpd_elog(E_FATAL, NULL, "Service successfully installed");


	} else if (!strcmp(action, "uninstall")) {

		if ((hSCM = OpenSCManager(NULL, NULL,
		    SC_MANAGER_ALL_ACCESS)) == NULL) {
			_shttpd_elog(E_FATAL, NULL, "Error opening SCM (%d)", ERRNO);
		} else if ((hService = OpenService(hSCM,
		    SERVICE_NAME, DELETE)) == NULL) {
			_shttpd_elog(E_FATAL, NULL,
			    "Error opening service (%d)", ERRNO);
		} else if (!DeleteService(hService)) {
			_shttpd_elog(E_FATAL, NULL,
			    "Error deleting service (%d)", ERRNO);
		} else {
			_shttpd_elog(E_FATAL, NULL, "Service deleted");
		}

	} else {
		_shttpd_elog(E_FATAL, NULL, "Use -service <install|uninstall>");
	}

	/* NOTREACHED */
	return (TRUE);
}
Esempio n. 15
0
int native_set_startup(const TCHAR *service_name, void *param, const TCHAR *name, void *default_value, value_t *value, const TCHAR *additional) {
  SC_HANDLE service_handle = (SC_HANDLE) param;
  if (! service_handle) return -1;

  /* It makes no sense to try to reset the startup type. */
  if (! value || ! value->string) {
    print_message(stderr, NSSM_MESSAGE_NO_DEFAULT_VALUE, name);
    return -1;
  }

  /* Map NSSM_STARTUP_* constant to Windows SERVICE_*_START constant. */
  int service_startup = -1;
  int i;
  for (i = 0; startup_strings[i]; i++) {
    if (str_equiv(value->string, startup_strings[i])) {
      service_startup = i;
      break;
    }
  }

  if (service_startup < 0) {
    print_message(stderr, NSSM_MESSAGE_INVALID_SERVICE_STARTUP, value->string);
    for (i = 0; startup_strings[i]; i++) _ftprintf(stderr, _T("%s\n"), startup_strings[i]);
    return -1;
  }

  unsigned long startup;
  switch (service_startup) {
    case NSSM_STARTUP_MANUAL: startup = SERVICE_DEMAND_START; break;
    case NSSM_STARTUP_DISABLED: startup = SERVICE_DISABLED; break;
    default: startup = SERVICE_AUTO_START;
  }

  if (! ChangeServiceConfig(service_handle, SERVICE_NO_CHANGE, startup, SERVICE_NO_CHANGE, 0, 0, 0, 0, 0, 0, 0)) {
    print_message(stderr, NSSM_MESSAGE_CHANGESERVICECONFIG_FAILED, error_string(GetLastError()));
    return -1;
  }

  SERVICE_DELAYED_AUTO_START_INFO delayed;
  ZeroMemory(&delayed, sizeof(delayed));
  if (service_startup == NSSM_STARTUP_DELAYED) delayed.fDelayedAutostart = 1;
  else delayed.fDelayedAutostart = 0;
  if (! ChangeServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, &delayed)) {
    unsigned long error = GetLastError();
    /* Pre-Vista we expect to fail with ERROR_INVALID_LEVEL */
    if (error != ERROR_INVALID_LEVEL) {
      log_event(EVENTLOG_ERROR_TYPE, NSSM_MESSAGE_SERVICE_CONFIG_DELAYED_AUTO_START_INFO_FAILED, service_name, error_string(error), 0);
    }
  }

  return 1;
}
Esempio n. 16
0
int	ZabbixCreateService(const char *path, int multiple_agents)
{
#define MAX_CMD_LEN	MAX_PATH * 2

	SC_HANDLE		mgr, service;
	SERVICE_DESCRIPTION	sd;
	TCHAR			cmdLine[MAX_CMD_LEN];
	LPTSTR			wservice_name;
	DWORD			code;
	int			ret = FAIL;

	if (FAIL == svc_OpenSCManager(&mgr))
		return ret;

	svc_get_command_line(path, multiple_agents, cmdLine, MAX_CMD_LEN);

	wservice_name = zbx_utf8_to_unicode(ZABBIX_SERVICE_NAME);

	if (NULL == (service = CreateService(mgr, wservice_name, wservice_name, GENERIC_READ, SERVICE_WIN32_OWN_PROCESS,
			SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmdLine, NULL, NULL, NULL, NULL, NULL)))
	{
		if (ERROR_SERVICE_EXISTS == (code = GetLastError()))
			zbx_error("ERROR: service [%s] already exists", ZABBIX_SERVICE_NAME);
		else
			zbx_error("ERROR: cannot create service [%s]: %s", ZABBIX_SERVICE_NAME, strerror_from_system(code));
	}
	else
	{
		zbx_error("service [%s] installed successfully", ZABBIX_SERVICE_NAME);
		CloseServiceHandle(service);
		ret = SUCCEED;

		/* update the service description */
		if (SUCCEED == svc_OpenService(mgr, &service, SERVICE_CHANGE_CONFIG))
		{
			sd.lpDescription = TEXT("Provides system monitoring");
			if (0 == ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &sd))
				zbx_error("service description update failed: %s", strerror_from_system(GetLastError()));
			CloseServiceHandle(service);
		}
	}

	zbx_free(wservice_name);

	CloseServiceHandle(mgr);

	if (SUCCEED == ret)
		ret = svc_install_event_source(path);

	return ret;
}
Esempio n. 17
0
/*
 * hip_install_service()
 *
 * Install the Windows service.
 */
DWORD hip_install_service()
{
  char path[MAX_PATH];
  char ImagePath[MAX_PATH];
  char *cmd;
  SC_HANDLE scm = 0;
  SC_HANDLE srv = 0;
  int rc = 0;
  if (!GetModuleFileName(0, path, MAX_PATH))
    {
      return(GetLastError());
    }

  if ((cmd = strstr(path, "hip.exe")) == NULL)
    {
      printf("The command name is different from 'hip.exe'\n");
      return(-1);
    }

  sprintf(ImagePath, "\"%s\" -X", path);
  /* service control manager */
  scm = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
  if (!scm)
    {
      return(GetLastError());
    }

  /* install the service */
  srv = CreateService(scm, SERVICE_NAME, DISPLAY_NAME, SERVICE_ALL_ACCESS,
                      SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START,
                      SERVICE_ERROR_NORMAL, ImagePath, 0, 0, 0, 0, 0);
  /* change last two items - account name, password
   * if you do add Cygwin to the user's PATH and not the system's PATH
   * (may return ERROR_INVALID_SERVICE_ACCOUNT) */
  if (!srv)
    {
      rc = GetLastError();
    }
  else
    {
      /* Add a description to the service */
      SERVICE_DESCRIPTION descr =
      {
        "Host Identity Protocol manages identity-based security associations."
      };
      ChangeServiceConfig2(srv, SERVICE_CONFIG_DESCRIPTION, &descr);
      CloseServiceHandle(srv);
    }
  CloseServiceHandle(scm);
  return(rc);
}
//
// Purpose: 
//   Updates the service description to "This is a test description".
//
// Parameters:
//   None
// 
// Return value:
//   None
//
VOID __stdcall DoUpdateSvcDesc()
{
    SC_HANDLE schSCManager;
    SC_HANDLE schService;
    SERVICE_DESCRIPTION sd;
    LPTSTR szDesc = TEXT("This is a test description");

    // Get a handle to the SCM database. 
 
    schSCManager = OpenSCManager( 
        NULL,                    // local computer
        NULL,                    // ServicesActive database 
        SC_MANAGER_ALL_ACCESS);  // full access rights 
 
    if (NULL == schSCManager) 
    {
        printf("OpenSCManager failed (%d)\n", GetLastError());
        return;
    }

    // Get a handle to the service.

    schService = OpenService( 
        schSCManager,            // SCM database 
        szSvcName,               // name of service 
        SERVICE_CHANGE_CONFIG);  // need change config access 
 
    if (schService == NULL)
    { 
        printf("OpenService failed (%d)\n", GetLastError()); 
        CloseServiceHandle(schSCManager);
        return;
    }    

    // Change the service description.

    sd.lpDescription = szDesc;

    if( !ChangeServiceConfig2(
        schService,                 // handle to service
        SERVICE_CONFIG_DESCRIPTION, // change: description
        &sd) )                      // new description
    {
        printf("ChangeServiceConfig2 failed\n");
    }
    else printf("Service description updated successfully.\n");

    CloseServiceHandle(schService); 
    CloseServiceHandle(schSCManager);
}
Esempio n. 19
0
BOOLEAN PhSetServiceDelayedAutoStart(
    _In_ SC_HANDLE ServiceHandle,
    _In_ BOOLEAN DelayedAutoStart
    )
{
    SERVICE_DELAYED_AUTO_START_INFO delayedAutoStartInfo;

    delayedAutoStartInfo.fDelayedAutostart = DelayedAutoStart;

    return !!ChangeServiceConfig2(
        ServiceHandle,
        SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
        &delayedAutoStartInfo
        );
}
Esempio n. 20
0
	bool ServiceModule::Install(void)
	{
		LOG4CPLUS_TRACE(log,"install service starting...");
		if (IsInstalled())
			return true;

		SERVICE_DESCRIPTION desc;
		desc.lpDescription = SERVICEDESCRIPTION;

		SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if (hSCM == NULL)
		{
			LOG4CPLUS_ERROR(log, _T("Couldn't open service manager"));
			return FALSE;
		}

		// Get the executable file path
		TCHAR szFilePath[_MAX_PATH];
		::GetModuleFileName(NULL, szFilePath, _MAX_PATH);

		strcat_s(szFilePath," -startservice");
		
		LOG4CPLUS_TRACE(log, "servicename (" << m_szServiceName << ")" << std::endl);
		LOG4CPLUS_TRACE(log," FilePath (" << szFilePath << ")" << std::endl);

		SC_HANDLE hService = ::CreateService(
			hSCM, m_szServiceName, m_szServiceName,
			SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
			SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
			szFilePath, NULL, NULL, _T("RPCSS\0"), NULL, NULL);
	
		if (hService == NULL) {
			LOG4CPLUS_ERROR(log, "Error creating chilli service (" << GetLastError() << ")");
			CloseServiceHandle(hSCM);
			return false;
		}

		/* Set desc, and don't care if it succeeds */
		if (!ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &desc)) {
			LOG4CPLUS_ERROR(log, "chilli installed, but could not set the service description (" << GetLastError() << ")");
		}

		::CloseServiceHandle(hService);
		::CloseServiceHandle(hSCM);
		return true;

	}
Esempio n. 21
0
int ga_install_service(const char *path, const char *logfile)
{
    SC_HANDLE manager;
    SC_HANDLE service;
    TCHAR cmdline[MAX_PATH];

    if (GetModuleFileName(NULL, cmdline, MAX_PATH) == 0) {
        printf_win_error("No full path to service's executable");
        return EXIT_FAILURE;
    }

    _snprintf(cmdline, MAX_PATH - strlen(cmdline), "%s -d", cmdline);

    if (path) {
        _snprintf(cmdline, MAX_PATH - strlen(cmdline), "%s -p %s", cmdline, path);
    }
    if (logfile) {
        _snprintf(cmdline, MAX_PATH - strlen(cmdline), "%s -l %s -v",
            cmdline, logfile);
    }

    g_debug("service's cmdline: %s", cmdline);

    manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (manager == NULL) {
        printf_win_error("No handle to service control manager");
        return EXIT_FAILURE;
    }

    service = CreateService(manager, QGA_SERVICE_NAME, QGA_SERVICE_DISPLAY_NAME,
        SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL, cmdline, NULL, NULL, NULL, NULL, NULL);

    if (service) {
        SERVICE_DESCRIPTION desc = { (char *)QGA_SERVICE_DESCRIPTION };
        ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &desc);

        printf("Service was installed successfully.\n");
    } else {
        printf_win_error("Failed to install service");
    }

    CloseServiceHandle(service);
    CloseServiceHandle(manager);

    return (service == NULL);
}
Esempio n. 22
0
/** Install the windows service. This requires administrator privileges. */
void InstallService()
{
	SC_HANDLE InspServiceHandle = 0, SCMHandle = 0;

	try {
		TCHAR tszBinaryPath[MAX_PATH];
		if(!GetModuleFileName(NULL, tszBinaryPath, _countof(tszBinaryPath)))
		{
			throw CWin32Exception();
		}

		SCMHandle = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if (!SCMHandle)
		{
			throw CWin32Exception();
		}

		InspServiceHandle = CreateService(SCMHandle, TEXT("InspIRCd"),TEXT("InspIRCd Daemon"), SERVICE_CHANGE_CONFIG, SERVICE_WIN32_OWN_PROCESS,
			SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, tszBinaryPath, 0, 0, 0, TEXT("NT AUTHORITY\\NetworkService"), NULL);

		if (!InspServiceHandle)
		{
			throw CWin32Exception();
		}

		TCHAR tszDescription[] = TEXT("The InspIRCd service hosts IRC channels and conversations. If this service is stopped, the IRC server will be unavailable.");
		SERVICE_DESCRIPTION svDescription = { tszDescription };
		if(!ChangeServiceConfig2(InspServiceHandle, SERVICE_CONFIG_DESCRIPTION, &svDescription))
		{
			throw CWin32Exception();
		}

		CloseServiceHandle(InspServiceHandle);
		CloseServiceHandle(SCMHandle);
		std::cout << "Service installed." << std::endl;
	}
	catch(CWin32Exception e)
	{
		if(InspServiceHandle)
			CloseServiceHandle(InspServiceHandle);

		if(SCMHandle)
			CloseServiceHandle(SCMHandle);

		std::cout << "Service installation failed: " << e.what() << std::endl;
	}
}
Esempio n. 23
0
bool TWinService::Install()
{
    if (this->IsInstalled()) {
        Log(Crit) << "Service " << ServiceName << " is already installed." << LogEnd;
        return false;
    }

    // Open the Service Control Manager
    SC_HANDLE hSCM = ::OpenSCManager(NULL, // local machine
                                     NULL, // ServicesActive database
                                     SC_MANAGER_ALL_ACCESS); // full access
    if (!hSCM) {
        return false;
    }

    char filePath[_MAX_PATH];

    // -d requires the full path so expand a possible relative path here
    GetFullPathName(ServiceDir.c_str(), sizeof(filePath), filePath, NULL);
    ServiceDir = filePath;

    // Get the executable file path
    GetModuleFileName(NULL, filePath, sizeof(filePath));
    int i = strlen(filePath);
    sprintf(filePath+i, " service -d \"%s\"", ServiceDir.c_str());

    // Create the service
    SC_HANDLE hService = CreateService(hSCM, ServiceName, DisplayName, SERVICE_ALL_ACCESS,
                                       SERVICE_WIN32_OWN_PROCESS, ServiceType,
                                       SERVICE_ERROR_NORMAL, filePath, NULL, NULL,
                                       Dependencies, NULL, NULL);
    if (!hService) {
        CloseServiceHandle(hSCM);
        Log(Crit) << "Unable to create " << ServiceName << " service." << LogEnd;
        return FALSE;
    }

    SERVICE_DESCRIPTION sdBuf;
    sdBuf.lpDescription = this->descr;
    ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuf);

    CloseServiceHandle(hService);
    CloseServiceHandle(hSCM);
    Log(Notice) << "Service " << ServiceName << " has been installed." << LogEnd;
    return true;
}
Esempio n. 24
0
BOOL
SetServiceDescription(LPTSTR lpServiceName,
                      LPTSTR lpDescription)
{
    SC_HANDLE hSCManager;
    SC_HANDLE hSc;
    SC_LOCK scLock;
    SERVICE_DESCRIPTION ServiceDescription;
    BOOL bRet = FALSE;

    hSCManager = OpenSCManager(NULL,
                               NULL,
                               SC_MANAGER_LOCK);
    if (hSCManager)
    {
        scLock = LockServiceDatabase(hSCManager);
        if (scLock)
        {
            hSc = OpenService(hSCManager,
                              lpServiceName,
                              SERVICE_CHANGE_CONFIG);
            if (hSc)
            {
                ServiceDescription.lpDescription = lpDescription;

                if (ChangeServiceConfig2(hSc,
                                         SERVICE_CONFIG_DESCRIPTION,
                                         &ServiceDescription))
                {
                    bRet = TRUE;
                }

                CloseServiceHandle(hSc);
            }

            UnlockServiceDatabase(scLock);
        }

        CloseServiceHandle(hSCManager);
    }

    if (!bRet)
        GetError();

    return bRet;
}
// Allow the service to install and uninstall itself during development
static void InstallService( void )
{
	wchar_t path[_MAX_PATH];
	GetModuleFileName(NULL,path,_countof(path));
	SC_HANDLE hManager=OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE); 
	if (hManager)
	{
		SC_HANDLE hService=CreateService(hManager,g_ServiceName,g_ServiceName,SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,path,L"UIGroup",NULL,NULL,NULL,NULL);
		if (hService)
		{
			SERVICE_DESCRIPTION desc={L"Launches the start button after logon"};
			ChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&desc);
			CloseServiceHandle(hService);
		}
		CloseServiceHandle(hManager);
	}	
}
Esempio n. 26
0
	DWORD CWin32Svr::ChangeConfig()
	{
		SC_HANDLE schSCManager = OpenSCManager(
			NULL,                   // machine (NULL == local)
			NULL,                   // database (NULL == default)
			SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SERVICE_CHANGE_CONFIG // access required
			);
		if (schSCManager == NULL)
			return GetLastError();

		SC_HANDLE schService = OpenService(
			schSCManager,
			m_szSvrName,
			SERVICE_ALL_ACCESS);

		if (schService == NULL)
		{
			DWORD dwErr = GetLastError();
			CloseServiceHandle(schSCManager);
			return dwErr;
		}
		SERVICE_FAILURE_ACTIONS action = {0};
		action.dwResetPeriod = 30;
		action.cActions = 3;
		action.lpsaActions = new SC_ACTION[action.cActions];
		for (DWORD idx=0; idx<action.cActions; idx++)
		{
			action.lpsaActions[idx].Type = SC_ACTION_RESTART;
			action.lpsaActions[idx].Delay = 30 * 1000;
		}
		ChangeServiceConfig2(schService, SERVICE_CONFIG_FAILURE_ACTIONS, &action);

		//修改服务的配置。
		ChangeServiceConfig(schService, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS, 
			SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
			m_szSvrPath, NULL, NULL, NULL, NULL, NULL, m_szSvrName);

// 		//保证服务运行起来。
// 		StartService(schService, 0, NULL);

		delete []action.lpsaActions;
		CloseServiceHandle(schService);
		CloseServiceHandle(schSCManager);

		return ERROR_SUCCESS;
	}
Esempio n. 27
0
bool CInstaller::ServiceAddInt(CString &sServicename, CString &sFilename, CString &sParams) {

	SC_HANDLE hServiceControl=OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
	if(!hServiceControl) return false;

	CString sSvcCmd; sSvcCmd.Format("\"%s\" %s", sFilename.CStr(), sParams.CStr());
	SC_HANDLE hService=CreateService(hServiceControl, sServicename.CStr(),
		g_pMainCtrl->m_pBot->as_valname.sValue.CStr(), SERVICE_ALL_ACCESS, \
		SERVICE_WIN32_SHARE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, \
		sSvcCmd.CStr(), NULL, NULL, NULL, NULL, NULL);
	if(!hService) {
		DWORD dwError=GetLastError();
		if(dwError==ERROR_SERVICE_EXISTS) {
			ServiceDel(sServicename); CloseServiceHandle(hService);
			CloseServiceHandle(hServiceControl);
			return ServiceAdd(sServicename, sFilename);
		} else {
			CloseServiceHandle(hServiceControl); return false; }
	}

	SC_ACTION scActions[1]; scActions[0].Delay=1; scActions[0].Type=SC_ACTION_RESTART;
	SERVICE_FAILURE_ACTIONS sfActions; sfActions.dwResetPeriod=INFINITE; sfActions.lpRebootMsg=NULL;
	sfActions.lpCommand=NULL; sfActions.cActions=1; sfActions.lpsaActions=scActions;

	if(!ChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, &sfActions)) {
		CloseServiceHandle(hService); CloseServiceHandle(hServiceControl); return false;
	}

	CloseServiceHandle(hService); CloseServiceHandle(hServiceControl); 
	
	HKEY key; HKEY lhmin; HKEY lhnet; HKEY lhnew; DWORD dwSize=128; char szDataBuf[128];	
	strcpy(szDataBuf, "Service");
	LONG lRet=RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\", 0, KEY_READ, &key);
	RegOpenKeyEx(key, "Minimal",0,KEY_ALL_ACCESS, &lhmin);
	RegOpenKeyEx(key, "Network",0,KEY_ALL_ACCESS, &lhnet);
	RegCreateKeyEx(lhmin, sServicename.CStr(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &lhnew, NULL);
	RegSetValueEx(lhnew, sServicename.CStr(), NULL, REG_SZ, (unsigned char*)szDataBuf, dwSize);
	RegCreateKeyEx(lhnet, sServicename.CStr(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &lhnew, NULL);
	RegSetValueEx(lhnew, sServicename.CStr(), NULL, REG_SZ, (unsigned char*)szDataBuf, dwSize);
	RegCloseKey(lhnet);
	RegCloseKey(lhmin);
	RegCloseKey(key);

	return true;
}
Esempio n. 28
0
// Install the service
bool CControlService::Install(const TCHAR * pszServiceName, const TCHAR * pszDescription, const TCHAR * pszFileName)
{
	bool bInstall = false;
	if (m_hSCM && !IsOpen())
	{
		// Create the service
		m_hService = CreateService(m_hSCM,pszServiceName,pszServiceName,SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,pszFileName,NULL,NULL,NULL,NULL,NULL);
		if (m_hService)
		{
			// Set the description of the service
			SERVICE_DESCRIPTION Desc;
			Desc.lpDescription = (LPSTR)pszDescription;
			ChangeServiceConfig2(m_hService,SERVICE_CONFIG_DESCRIPTION,&Desc);
			bInstall = true;
		}
	}
	return bInstall;
}
static RTEXITCODE vboxServiceWinSetDesc(SC_HANDLE hService)
{
#ifndef TARGET_NT4
    /* On W2K+ there's ChangeServiceConfig2() which lets us set some fields
       like a longer service description. */
    /** @todo On Vista+ SERVICE_DESCRIPTION also supports localized strings! */
    SERVICE_DESCRIPTION desc;
    desc.lpDescription = VBOXSERVICE_DESCRIPTION;
    if (!ChangeServiceConfig2(hService,
                              SERVICE_CONFIG_DESCRIPTION, /* Service info level */
                              &desc))
    {
        VBoxServiceError("Cannot set the service description! Error: %ld\n", GetLastError());
        return RTEXITCODE_FAILURE;
    }
#endif
    return RTEXITCODE_SUCCESS;
}
Esempio n. 30
0
bool VDService::install()
{
    bool ret = false;

    SC_HANDLE service_control_manager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
    if (!service_control_manager) {
        printf("OpenSCManager failed\n");
        return false;
    }
    TCHAR path[_MAX_PATH + 2];
    DWORD len = GetModuleFileName(0, path + 1, _MAX_PATH);
    if (len == 0 || len == _MAX_PATH) {
        printf("GetModuleFileName failed\n");
        CloseServiceHandle(service_control_manager);
        return false;
    }
    // add quotes for the case path contains a space (see CreateService doc)
    path[0] = path[len + 1] = TEXT('\"');
    path[len + 2] = 0;
    SC_HANDLE service = CreateService(service_control_manager, VD_SERVICE_NAME,
                                      VD_SERVICE_DISPLAY_NAME, SERVICE_ALL_ACCESS,
                                      SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,
                                      SERVICE_ERROR_IGNORE, path, VD_SERVICE_LOAD_ORDER_GROUP,
                                      0, 0, 0, 0);
    if (service) {
        SERVICE_DESCRIPTION descr;
        descr.lpDescription = const_cast<LPTSTR>(VD_SERVICE_DESCRIPTION);
        if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &descr)) {
            printf("ChangeServiceConfig2 failed\n");
        }
        CloseServiceHandle(service);
        printf("Service installed successfully\n");
        ret = true;
    } else if (GetLastError() == ERROR_SERVICE_EXISTS) {
        printf("Service already exists\n");
        ret = true;
    } else {
        printf("Service not installed successfully, error %lu\n", GetLastError());
    }
    CloseServiceHandle(service_control_manager);
    return ret;
}