void WinService::registerService(const std::string& path, const std::string& displayName)
{
    close();
#if defined(POCO_WIN32_UTF8)
    std::wstring uname;
    Poco::UnicodeConverter::toUTF16(_name, uname);
    std::wstring udisplayName;
    Poco::UnicodeConverter::toUTF16(displayName, udisplayName);
    std::wstring upath;
    Poco::UnicodeConverter::toUTF16(path, upath);
    _svcHandle = CreateServiceW(
                     _scmHandle,
                     uname.c_str(),
                     udisplayName.c_str(),
                     SERVICE_ALL_ACCESS,
                     SERVICE_WIN32_OWN_PROCESS,
                     SERVICE_DEMAND_START,
                     SERVICE_ERROR_NORMAL,
                     upath.c_str(),
                     NULL, NULL, NULL, NULL, NULL);
#else
    _svcHandle = CreateServiceA(
                     _scmHandle,
                     _name.c_str(),
                     displayName.c_str(),
                     SERVICE_ALL_ACCESS,
                     SERVICE_WIN32_OWN_PROCESS,
                     SERVICE_DEMAND_START,
                     SERVICE_ERROR_NORMAL,
                     path.c_str(),
                     NULL, NULL, NULL, NULL, NULL);
#endif
    if (!_svcHandle)
        throw SystemException("cannot register service", _name);
}
Example #2
0
static SC_HANDLE register_service(const char *test_name)
{
    char service_cmd[MAX_PATH+150], *ptr;
    SC_HANDLE service;

    ptr = service_cmd + GetModuleFileNameA(NULL, service_cmd, MAX_PATH);

    /* If the file doesn't exist, assume we're using built-in exe and append .so to the path */
    if(GetFileAttributesA(service_cmd) == INVALID_FILE_ATTRIBUTES) {
        strcpy(ptr, ".so");
        ptr += 3;
    }

    strcpy(ptr, " service ");
    ptr += strlen(ptr);
    sprintf(ptr, "%s ", test_name);
    ptr += strlen(ptr);
    strcpy(ptr, service_name);

    trace("service_cmd \"%s\"\n", service_cmd);

    service = CreateServiceA(scm_handle, service_name, service_name, GENERIC_ALL,
                             SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE,
                             service_cmd, NULL, NULL, NULL, NULL, NULL);
    if(!service && GetLastError() == ERROR_ACCESS_DENIED) {
        skip("Not enough access right to create service\n");
        return NULL;
    }

    ok(service != NULL, "CreateService failed: %u\n", GetLastError());
    return service;
}
Example #3
0
static DWORD DoRegServer(void)
{
    SC_HANDLE scm, service;
    CHAR path[MAX_PATH+12];
    DWORD ret = 0;

    scm = OpenSCManagerA(NULL, SERVICES_ACTIVE_DATABASEA, SC_MANAGER_CREATE_SERVICE);
    if (!scm)
    {
        fprintf(stderr, "Failed to open the service control manager.\n");
        return 1;
    }

    GetSystemDirectoryA(path, MAX_PATH);
    lstrcatA(path, "\\msiexec.exe /V");

    service = CreateServiceA(scm, "MSIServer", "MSIServer", GENERIC_ALL,
                             SERVICE_WIN32_SHARE_PROCESS, SERVICE_DEMAND_START,
                             SERVICE_ERROR_NORMAL, path, NULL, NULL,
                             NULL, NULL, NULL);

    if (service) CloseServiceHandle(service);
    else if (GetLastError() != ERROR_SERVICE_EXISTS)
    {
        fprintf(stderr, "Failed to create MSI service\n");
        ret = 1;
    }
    CloseServiceHandle(scm);
    return ret;
}
Example #4
0
DWORD MyDriver::LoadDriver(BOOL start)
{
	
	if(loaded)
		return DRV_SUCCESS;

	if(!initialized)
		return DRV_ERROR_NO_INITIALIZED;

	
	SC_HANDLE SCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	DWORD retCode = DRV_SUCCESS;
	
	if (SCManager == NULL) 
		return DRV_ERROR_SCM;

    


    SC_HANDLE  SCService = CreateServiceA(SCManager,			  // SCManager database
									     driverName,            // nombre del servicio
							    		 driverName,            // 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
										 driverPath,	          // path del driver
										 NULL,                  // no pertenece a un grupo
										 NULL,                  // sin tag
										 NULL,                  // sin dependencias
										 NULL,                  // cuenta local del sistema
										 NULL                   // sin password
										 );
    
	if (SCService == NULL) 
	{
		SCService = OpenServiceA(SCManager, driverName, SERVICE_ALL_ACCESS);
		
		if (SCService == NULL) 
			retCode = DRV_ERROR_SERVICE;
	}

    CloseServiceHandle(SCService);
	SCService=NULL;

	CloseServiceHandle(SCManager);
	SCManager = NULL;

	
	if(retCode == DRV_SUCCESS)
	{
		loaded = TRUE;

		if(start)
			retCode = StarMyDriver();
	}

	return retCode;
}
Example #5
0
int cw_installservice(const char *name, const char *dname, const char *desc)
{
    SC_HANDLE sm, svc;
    char modulepath[MAX_PATH];
    char binpath[MAX_PATH];
    SERVICE_DESCRIPTIONA sdesc = { (char *) desc };

    if (!GetModuleFileName(NULL, modulepath, MAX_PATH - 1))
    {
        fprintf(stderr, "Unable to get the executable name (%d)\n", GetLastError());
        return 0;
    }

    if (!cw_uninstallservice(name, 0)) return 0;

    if (!(sm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CREATE_SERVICE | DELETE)))
    {
        if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
            fprintf(stderr, "Windows Services are not supported on this Platform\n");
        else
            fprintf(stderr, "Unable to Open SCManager (%d)\n", GetLastError());
        return 0;
    }

    if (strchr(modulepath, ' '))
        gnulib_snprintf(binpath, MAX_PATH - 1, "\"%s\" --daemon", modulepath);
    else
        gnulib_snprintf(binpath, MAX_PATH - 1, "%s --daemon", modulepath);

    svc = CreateServiceA(sm, name, dname, SERVICE_CHANGE_CONFIG,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_DEMAND_START,
        SERVICE_ERROR_NORMAL,
        binpath,
        NULL, /* Load group order */
        NULL, /* Tag Id */
        NULL, /* Dependencies */
        NULL, /* User -> Local System */
        "");

    if (!svc)
    {
        fprintf(stderr, "Unable to Create Service %s (%d)\n", name, GetLastError());
        CloseServiceHandle(sm);
        return 0;
    }

    /* ChangeServiceConfig2A() */
    if (cw_helpers.av32.ChangeServiceConfig2A &&
        (!cw_helpers.av32.ChangeServiceConfig2A(svc, SERVICE_CONFIG_DESCRIPTION, &sdesc)))
        fprintf(stderr, "Unable to set description for Service %s (%d)\n", name, GetLastError());

    CloseServiceHandle(svc);
    CloseServiceHandle(sm);

    printf("Service %s successfully created\n", name);
    return 1;
}
Example #6
0
SC_HANDLE register_service_exA(
    SC_HANDLE scm_handle,
    PCSTR test_name,
    PCSTR service_name, // LPCSTR lpServiceName,
    PCSTR extra_args OPTIONAL,
    DWORD dwDesiredAccess,
    DWORD dwServiceType,
    DWORD dwStartType,
    DWORD dwErrorControl,
    LPCSTR lpLoadOrderGroup OPTIONAL,
    LPDWORD lpdwTagId OPTIONAL,
    LPCSTR lpDependencies OPTIONAL,
    LPCSTR lpServiceStartName OPTIONAL,
    LPCSTR lpPassword OPTIONAL)
{
    SC_HANDLE service;
    CHAR service_cmd[MAX_PATH+150];

    /* Retrieve our full path */
    if (!GetModuleFileNameA(NULL, service_cmd, MAX_PATH))
    {
        skip("GetModuleFileNameW failed with error %lu!\n", GetLastError());
        return NULL;
    }

    /*
     * Build up our custom command line. The first parameter is the test name,
     * the second parameter is the flag used to decide whether we should start
     * as a service.
     */
    StringCbCatA(service_cmd, sizeof(service_cmd), " ");
    StringCbCatA(service_cmd, sizeof(service_cmd), test_name);
    StringCbCatA(service_cmd, sizeof(service_cmd), " ");
    StringCbCatA(service_cmd, sizeof(service_cmd), service_name);
    if (extra_args)
    {
        StringCbCatA(service_cmd, sizeof(service_cmd), " ");
        StringCbCatA(service_cmd, sizeof(service_cmd), extra_args);
    }

    trace("service_cmd \"%s\"\n", service_cmd);

    service = CreateServiceA(scm_handle, service_name, service_name,
                             dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl,
                             service_cmd, lpLoadOrderGroup, lpdwTagId, lpDependencies,
                             lpServiceStartName, lpPassword);
    if (!service && GetLastError() == ERROR_ACCESS_DENIED)
    {
        skip("Not enough access right to create service.\n");
        return NULL;
    }

    ok(service != NULL, "CreateService failed: %lu\n", GetLastError());
    return service;
}
Example #7
0
BOOL CServiceModule::InstallService(char * szAccount, char * szPassword)
{
    SC_HANDLE schMgr;
    SC_HANDLE schSvc;
    char szPath[512];

    schMgr = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE);

    if (!schMgr)
    {
        printf("Unable to open SCManager.  Service not installed.\n");
        return FALSE;
    }

    GetModuleFileNameA(NULL,szPath,sizeof(szPath));

    schSvc = CreateServiceA(schMgr,
                           m_szServiceName,
                           m_szServiceDesc,
                           SERVICE_ALL_ACCESS,
                           SERVICE_WIN32_OWN_PROCESS,
                           SERVICE_AUTO_START,
                           SERVICE_ERROR_NORMAL,
                           szPath,
                           NULL,
                           NULL,
                           "RPCSS\0",
                           szAccount,
                           szPassword);

    if (!schSvc)
    {
        ::CloseServiceHandle(schMgr);
        MessageBoxA(NULL, "Couldn't create service", m_szServiceName, MB_OK);
        return FALSE;
    }

    CloseServiceHandle(schSvc);
    CloseServiceHandle(schMgr);
    printf("%s service installed.\n", m_szServiceName);

    if (szAccount)
    {
        TCUserAccount acct;
        acct.Init(szAccount);  // example: szAccount == Redmond\federat which was passed in on the cmdline
        if (S_OK != acct.HasRight(SE_SERVICE_LOGON_NAME))
        {
          acct.SetRight(SE_SERVICE_LOGON_NAME);
          printf("The account %ls\\%ls has been granted the Logon As A Service right.", acct.GetDomainNameW(), acct.GetUserNameW());
        }
    }

    return TRUE;
}
Example #8
0
static BOOL InstallService(const char * rutaDriver, LPCSTR  lpServiceName, LPCSTR  lpDisplayName) {
	HANDLE hService;
	BOOL ret = FALSE;
	HANDLE hSCManager = OpenSCManagerA (NULL, NULL, SC_MANAGER_CREATE_SERVICE);
	if (hSCManager)	{
		hService = CreateServiceA (hSCManager, lpServiceName, lpDisplayName, SERVICE_START | DELETE | SERVICE_STOP, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, rutaDriver, NULL, NULL, NULL, NULL, NULL);
		if (hService) {
			CloseServiceHandle (hService);
			ret = TRUE;
		}
		CloseServiceHandle (hSCManager);
	}
	return ret;
}
bool _stdcall InstallWinIoDriver(char* pszWinIoDriverPath, bool IsDemandLoaded)
{
  SC_HANDLE hSCManager;
  SC_HANDLE hService;

  // Remove any previous instance of the driver

  RemoveWinIoDriver();

  hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

  if (hSCManager)
  {
    // Install the driver
    
    hService = CreateServiceA(hSCManager,
                             "WinRing0_1_2_0",
                             "WinRing0_1_2_0",
                             SERVICE_ALL_ACCESS,
                             SERVICE_KERNEL_DRIVER,
                             (IsDemandLoaded == true) ? SERVICE_DEMAND_START : SERVICE_SYSTEM_START,
                             SERVICE_ERROR_NORMAL,
                             pszWinIoDriverPath,
                             NULL,
                             NULL,
                             NULL,
                             NULL,
                             NULL);

    CloseServiceHandle(hSCManager);

    if (hService == NULL)
      return false;
  }
  else
    return false;

  CloseServiceHandle(hService);
  
  return true;
}
Example #10
0
void vctrlService(void)
{
	char ServiceFilePath[1024] = "";

	SC_HANDLE scmHandle = OpenSCManager ( NULL, NULL, SC_MANAGER_ALL_ACCESS );

	if (scmHandle == NULL) // Perform error handling.
	{
		WriteLog(sLogFile, "(%d)서비스 매니저와 연결하는데, 오류가 발생하였습니다.\n", GetLastError() ); 
		return;
	}

	sprintf_s(ServiceFilePath, "%s\\%s", sExecPath, sCmd);

	SC_HANDLE scHandle = CreateServiceA (
			scmHandle, 
			"CUBRIDService",
            "CUBRIDService",
			SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,
            SERVICE_AUTO_START,
            SERVICE_ERROR_NORMAL,
            ServiceFilePath,
			NULL,
			NULL,
			NULL,
			NULL,
			NULL );

	if ( scHandle == NULL ) // Process error
	{
		WriteLog(sLogFile, "(%d)서비스 매니저에 CUBRIDService.exe를 등록하는데, 오류가 발생하였습니다.\n", GetLastError() ); 
		return;
	}


	CloseServiceHandle(scHandle);
	CloseServiceHandle(scmHandle);

	return;
}
Example #11
0
static int manage_service(int action) {
  static const char *service_name = "Mongoose";
  SC_HANDLE hSCM = NULL, hService = NULL;
  SERVICE_DESCRIPTIONA descr = {server_name};
  char path[PATH_MAX + 20];  // Path to executable plus magic argument
  int success = 1;

  if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
                            GENERIC_WRITE : GENERIC_READ)) == NULL) {
    success = 0;
    show_error();
  } else if (action == ID_INSTALL_SERVICE) {
    GetModuleFileNameA(NULL, path, sizeof(path));
    strncat(path, " ", sizeof(path));
    strncat(path, service_magic_argument, sizeof(path));
    hService = CreateServiceA(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) {
      ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
    } else {
      show_error();
    }
  } else if (action == ID_REMOVE_SERVICE) {
    if ((hService = OpenServiceA(hSCM, service_name, DELETE)) == NULL ||
        !DeleteService(hService)) {
      show_error();
    }
  } else if ((hService = OpenServiceA(hSCM, service_name,
                                     SERVICE_QUERY_STATUS)) == NULL) {
    success = 0;
  }

  CloseServiceHandle(hService);
  CloseServiceHandle(hSCM);

  return success;
}
Example #12
0
//installation du driver ./rkdetect.sys
bool analysis::install_driver()
{
	char* currentPath=new char[1024];
	char* fullDriverPath=NULL;

	if(!manager)
		manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager)
		return false;

	
	GetCurrentDirectoryA(1024, currentPath);
	std::string temp=std::string(currentPath)+"\\hookrevealer.sys";
	delete currentPath;
	fullDriverPath=(char*)temp.c_str();

	service = CreateServiceA(manager,"hookrevealer","hookrevealer",SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,fullDriverPath,NULL,NULL,NULL,NULL,NULL);
	if(!service)
		return false;

	return true;
}
BOOL CServiceModule::InstallService(int argc, char * argv[])
{
	SC_HANDLE schMgr;
	SC_HANDLE schSvc;
	char szPath[512];
	char * szUserName;
	char * szPassword;


	schMgr = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

	if (!schMgr)
	{
		printf("Unable to open SCManager.  Service not installed.\n");
		return FALSE;
	}

	GetModuleFileNameA(NULL, szPath, sizeof(szPath));

	if (argc > 3)
	{
		szUserName = argv[2];
		szPassword = argv[3];
	}
	else
	{
		szUserName = NULL;
		szPassword = NULL;
	}

	schSvc = CreateServiceA(schMgr,
		c_szSvcName,
		"MS Allegiance Game Server",
		SERVICE_ALL_ACCESS,
		SERVICE_WIN32_OWN_PROCESS,
		SERVICE_AUTO_START,
		SERVICE_ERROR_NORMAL,
		szPath,
		NULL,
		NULL,
		"RPCSS\0",
		szUserName,
		szPassword);

	if (!schSvc)
	{
		char szBuf[MAX_PATH];
		DWORD dwErrorCode(GetLastError());
		sprintf(szBuf, "Unable to create service [0x%08x].  Service not installed.\n", dwErrorCode);
		PrintSystemErrorMessage(szBuf, dwErrorCode);

		CloseServiceHandle(schMgr);
		return FALSE;
	}

	//Imago #167
	/*
	schSvc = OpenService(schMgr, c_szSvcName, SERVICE_CHANGE_CONFIG);
	if (!schSvc)
	{
	  char szBuf[MAX_PATH];
	  DWORD dwErrorCode(GetLastError());
	  sprintf(szBuf, "Unable to open to modify service [0x%08x].  Service not installed corectly.\n", dwErrorCode);
	  PrintSystemErrorMessage(szBuf, dwErrorCode);
	  CloseServiceHandle(schMgr);
	  return FALSE;
	}
	*/
	SERVICE_FAILURE_ACTIONS failureActions;
	failureActions.cActions = 2;
	SC_ACTION actions[2];
	actions[0].Type = SC_ACTION_RESTART;
	actions[0].Delay = 15000;
	actions[1].Type = SC_ACTION_RESTART;
	actions[1].Delay = 15000;
	//actions[2].Type = SC_ACTION_RESTART;
	//actions[2].Delay = 15000;
	failureActions.lpsaActions = actions;
	failureActions.dwResetPeriod = 120;
	failureActions.lpRebootMsg = L"";
	failureActions.lpCommand = NULL;
	if (!ChangeServiceConfig2(schSvc, SERVICE_CONFIG_FAILURE_ACTIONS, &failureActions))
	{
		char szBuf[MAX_PATH];
		DWORD dwErrorCode(GetLastError());
		sprintf(szBuf, "Unable to modify service [0x%08x].  Service not installed.\n", dwErrorCode);
		PrintSystemErrorMessage(szBuf, dwErrorCode);

		CloseServiceHandle(schMgr);
		return FALSE;
	}

	CloseServiceHandle(schSvc);
	CloseServiceHandle(schMgr);
	printf("%s service installed.\n", c_szSvcName);

	if (szUserName)
	{
		TCUserAccount acct;
		acct.Init(szUserName);  // example: szUserName == Redmond\federat which was passed in on the cmdline
		if (S_OK != acct.HasRight(SE_SERVICE_LOGON_NAME))
		{
			acct.SetRight(SE_SERVICE_LOGON_NAME);
			printf("The account %ls\\%ls has been granted the Logon As A Service right.", acct.GetDomainNameW(), acct.GetUserNameW());
		}
	}

	return TRUE;
}
Example #14
0
BOOL LoadNTDriver(char* lpszDriverName,char* lpszDriverPath)
{
	char szDriverImagePath[256];
	//得到完整的驱动路径
	GetFullPathNameA(lpszDriverPath, 256, szDriverImagePath, NULL);

	BOOL bRet = FALSE;

	SC_HANDLE hServiceMgr=NULL;//SCM管理器的句柄
	SC_HANDLE hServiceDDK=NULL;//NT驱动程序的服务句柄

	//打开服务控制管理器
	hServiceMgr = OpenSCManagerA( NULL, NULL, SC_MANAGER_ALL_ACCESS );

	if( hServiceMgr == NULL )  
	{
		//OpenSCManager失败
		printf( "OpenSCManager() Faild %d ! \n", GetLastError() );
		bRet = FALSE;
		goto BeforeLeave;
	}
	else
	{
		////OpenSCManager成功
		printf( "OpenSCManager() ok ! \n" );  
	}

	//创建驱动所对应的服务
	hServiceDDK = CreateServiceA( hServiceMgr,
		lpszDriverName, //驱动程序的在注册表中的名字  
		lpszDriverName, // 注册表驱动程序的 DisplayName 值  
		SERVICE_ALL_ACCESS, // 加载驱动程序的访问权限  
		SERVICE_KERNEL_DRIVER,// 表示加载的服务是驱动程序  
		SERVICE_DEMAND_START, // 注册表驱动程序的 Start 值  
		SERVICE_ERROR_IGNORE, // 注册表驱动程序的 ErrorControl 值  
		szDriverImagePath, // 注册表驱动程序的 ImagePath 值  
		NULL,  
		NULL,  
		NULL,  
		NULL,  
		NULL);  

	DWORD dwRtn;
	//判断服务是否失败
	if( hServiceDDK == NULL )  
	{  
		dwRtn = GetLastError();
		if( dwRtn != ERROR_IO_PENDING && dwRtn != ERROR_SERVICE_EXISTS )  
		{  
			//由于其他原因创建服务失败
			printf( "CrateService() Faild %d ! \n", dwRtn );  
			bRet = FALSE;
			goto BeforeLeave;
		}  
		else  
		{
			//服务创建失败,是由于服务已经创立过
			printf( "CrateService() Faild Service is ERROR_IO_PENDING or ERROR_SERVICE_EXISTS! \n" );  
		}

		// 驱动程序已经加载,只需要打开  
		hServiceDDK = OpenServiceA( hServiceMgr, lpszDriverName, SERVICE_ALL_ACCESS );  
		if( hServiceDDK == NULL )  
		{
			//如果打开服务也失败,则意味错误
			dwRtn = GetLastError();  
			printf( "OpenService() Faild %d ! \n", dwRtn );  
			bRet = FALSE;
			goto BeforeLeave;
		}  
		else
		{
			printf( "OpenService() ok ! \n" );
		}
	}  
	else  
	{
		printf( "CrateService() ok ! \n" );
	}

	//开启此项服务
	bRet= StartServiceA( hServiceDDK, NULL, NULL );  
	if( !bRet )  
	{  
		DWORD dwRtn = GetLastError();  
		if( dwRtn != ERROR_IO_PENDING && dwRtn != ERROR_SERVICE_ALREADY_RUNNING )  
		{  
			printf( "StartService() Faild %d ! \n", dwRtn );  
			bRet = FALSE;
			goto BeforeLeave;
		}  
		else  
		{  
			if( dwRtn == ERROR_IO_PENDING )  
			{  
				//设备被挂住
				printf( "StartService() Faild ERROR_IO_PENDING ! \n");
				bRet = FALSE;
				goto BeforeLeave;
			}  
			else  
			{  
				//服务已经开启
				printf( "StartService() Faild ERROR_SERVICE_ALREADY_RUNNING ! \n");
				bRet = TRUE;
				goto BeforeLeave;
			}  
		}  
	}
	bRet = TRUE;
	//离开前关闭句柄
BeforeLeave:
	if(hServiceDDK)
	{
		CloseServiceHandle(hServiceDDK);
	}
	if(hServiceMgr)
	{
		CloseServiceHandle(hServiceMgr);
	}
	//删除注册表键值
	char lpszSrvices[256] = {0};
	sprintf(lpszSrvices,"SYSTEM\\CurrentControlSet\\Services\\%s",lpszDriverName);
	SHDeleteKeyA(HKEY_LOCAL_MACHINE,lpszSrvices);

	return bRet;
}
Example #15
0
bool CNTService::Install(void) {

    SC_HANDLE   ServiceHandle;
    SC_HANDLE   ServiceManager;

    CString ModuleFilename;
    DWORD dwLen = MAX_PATH;
    ModuleFilename.SetLength(dwLen);    
    if (!(dwLen = GetModuleFileNameA(GetModuleHandle(NULL),
        (char *) ModuleFilename.GetBuffer(), 
        dwLen))) {
        cout << "Error getting module path." << endl;
        CObject::ShowLastError();
        return false;
    } else {
        ModuleFilename.SetLength(dwLen);
    }    

    cout << "Attempting to install " << m_ServiceName << " (" << ModuleFilename << ") ..." << endl;
    
    ServiceManager = OpenSCManagerA(
        NULL,                   // machine (NULL == local)
        NULL,                   // database (NULL == default)
        SC_MANAGER_ALL_ACCESS   // access required
        );

    if ( !ServiceManager ) {
        cout << "OpenSCManager failed." << endl;
        CObject::ShowLastError();
        return false;
    }


    CString ServiceDependencies;
    for (register int i=0; i < (int) m_Dependencies.GetSize(); i++) {
        ServiceDependencies += m_Dependencies[i];
        ServiceDependencies += (char) 0;
    }
    ServiceDependencies += (char) 0;
        
    ModuleFilename += " service dispatch";
	ModuleFilename += (" --servicename=" + m_ServiceName);
	ModuleFilename += (" --servicedisplayname=" + m_ServiceDisplayName);

    ServiceHandle = CreateServiceA(
        ServiceManager,                         // SCManager database
        m_ServiceName.GetBuffer(),              // name of service
        m_ServiceDisplayName.GetBuffer(),       // 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
        ModuleFilename.GetBuffer(),             // service's binary
        NULL,                                   // no load ordering group
        NULL,                                   // no tag identifier
        ServiceDependencies.GetBuffer(),        // dependencies
        m_RunasUsername.GetLength() ? m_RunasUsername.GetBuffer() : NULL,  // account
        m_RunasPassword.GetLength() ? m_RunasPassword.GetBuffer() : NULL); // password

	/* not supported on NT4
	// set service description if any
	DWORD dwSystemVersion = GetVersion();

	if (ServiceHandle && 
		m_ServiceDescription.GetLength() && 
		(dwSystemVersion  < 0x80000000) && // Windows 2000, XP, NT
		(LOBYTE(LOWORD(dwSystemVersion)) >= 5) // Windows 2000, XP
		) {
		SERVICE_DESCRIPTIONA ServiceDescription;
		ServiceDescription.lpDescription = (char *) m_ServiceDescription.GetBuffer();

		if (! ChangeServiceConfig2(ServiceHandle, SERVICE_CONFIG_DESCRIPTION, & ServiceDescription)) {
			cout << "ChangeServiceConfig2 failed." << endl;
			CObject::ShowLastError();
			CloseServiceHandle( ServiceHandle );
			if (ServiceManager) CloseServiceHandle( ServiceManager );
			return false;
		}
	}
	*/

    if (! ServiceHandle) {        
		cout << "CreateService failed." << endl;
        CObject::ShowLastError();
		if (ServiceManager) CloseServiceHandle( ServiceManager );
        return false;
    } else {
		CloseServiceHandle( ServiceHandle );
	}

	if (ServiceManager) {
        CloseServiceHandle( ServiceManager );
	}

    cout << m_ServiceDisplayName << " successfuly installed." << endl;
    return true;
}
Example #16
0
void
vctrlService (void)
{
  char ServiceFilePath[1024] = "";

  SC_HANDLE scmHandle = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
  SERVICE_DESCRIPTION service_description;

  if (scmHandle == NULL)	// Perform error handling.
    {
      WriteLog (sLogFile,
		"(%d)Cannot connect to the Windows Service Control Manager.\n",
		GetLastError ());
      return;
    }

  sprintf_s (ServiceFilePath, "%s\\%s", sExecPath, sCmd);

  SC_HANDLE scHandle = CreateServiceA (scmHandle,
				       "CUBRIDService",
				       "CUBRIDService",
				       SERVICE_ALL_ACCESS,
				       SERVICE_WIN32_OWN_PROCESS |
				       SERVICE_INTERACTIVE_PROCESS,
				       SERVICE_AUTO_START,
				       SERVICE_ERROR_NORMAL,
				       ServiceFilePath,
				       NULL,
				       NULL,
				       NULL,
				       NULL,
				       NULL);

  if (scHandle == NULL)		// Process error
    {
      WriteLog (sLogFile,
		"(%d)Cannot add a Windows Service for CUBRID to the Windows Service Control Manager.\n",
		GetLastError ());
      return;
    }

  service_description.lpDescription =
    "Service to execute master,broker,database server and manager server processes for CUBRID.\r\n"
    "Service start/stop menu is equal to the command of \"cubrid service start/stop\".\r\n"
    "If you setup \"startup type\" of this service to \"Disabled\", you can't use \"cubrid service\" command.";


  if (ChangeServiceConfig2 (scHandle,
			    SERVICE_CONFIG_DESCRIPTION,
			    (LPVOID) & service_description) == 0)
    {
      WriteLog (sLogFile, "ChangeServiceConfig error.\n");

      CloseServiceHandle (scHandle);
      CloseServiceHandle (scmHandle);

      return;
    }

  CloseServiceHandle (scHandle);
  CloseServiceHandle (scmHandle);

  return;
}
Example #17
0
/*****************************************************************************
 * 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_extra;
    TCHAR psz_pathtmp[MAX_PATH];

    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, FromT(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 =
        CreateServiceA( 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;
}
Example #18
0
void InstallService()
// this function is executed, if someone starts our service exe manually
// if our service is installed, we uninstall it and vice versa
{
  CHAR                   arrCh [MAX_PATH + 1];
  SC_HANDLE              c1, c2;
  DWORD                  c3;
  SERVICE_STATUS         ss;
  LPQUERY_SERVICE_CONFIG qsc;
  int                    i1;
  bool                   b1;

  GetModuleFileName(GetModuleHandle(NULL), arrCh, MAX_PATH);
  // first we contact the service control manager
  c1 = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  if (!c1)
    // didn't work, maybe we asked for too many access rights?
    c1 = OpenSCManagerA(NULL, NULL, 0);
  if (c1) {
    // okay, that worked, now we try to open our service
    c2 = OpenServiceA(c1, CServiceName, SERVICE_ALL_ACCESS | DELETE);
    if (c2) {
      // our service is already installed, let's check the parameters
      b1 = false;
      c3 = 0;
      QueryServiceConfigA(c2, NULL, 0, &c3);
      if (c3) {
        qsc = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, c3 * 2);
        b1 = (QueryServiceConfigA(c2, qsc, c3 * 2, &c3)) &&
             ( (qsc->dwServiceType != CServiceType ) ||
               (qsc->dwStartType   != CServiceStart) ||
               (lstrcmpiA(qsc->lpDisplayName, CServiceDescr)) );
        LocalFree(qsc);
      }
      if (!ControlService(c2, SERVICE_CONTROL_INTERROGATE, &ss))
        ss.dwCurrentState = SERVICE_STOPPED;
      if ((!b1) && (ss.dwCurrentState == SERVICE_RUNNING)) {
        // the parameters are correct, so we try to stop and remove it
        if (ControlService(c2, SERVICE_CONTROL_STOP, &ss)) {
          if (DeleteService(c2))
               MessageBox(0, "the service is removed again",                "information...", MB_ICONINFORMATION);
          else MessageBox(0, "the service is stopped, but removing failed", "warning...",     MB_ICONWARNING);
        } else
          MessageBox(0, "stopping failed", "warning...", MB_ICONWARNING);
      } else {
        if (b1)
          // not all parameters are correct, so we try to correct them
          if (ChangeServiceConfigA(c2, CServiceType, CServiceStart, SERVICE_ERROR_NORMAL,
                                   arrCh, NULL, NULL, NULL, NULL, NULL, CServiceDescr))
               MessageBox(0, "correction of service parameters succeeded", "information...", MB_ICONINFORMATION);
          else MessageBox(0, "correction of service parameters failed",    "warning...",     MB_ICONWARNING);
        if (ss.dwCurrentState != SERVICE_RUNNING)
          // our service was installed, but not running, so we start it
          if (StartServiceA(c2, 0, NULL))
               MessageBox(0, "the service was restarted", "information...", MB_ICONINFORMATION);
          else MessageBox(0, "restarting failed",         "warning...",     MB_ICONWARNING);
      }
      CloseServiceHandle(c2);
    } else {
      // probably our service is not installed yet, so we do that now
      c2 = CreateServiceA(c1, CServiceName, CServiceDescr,
                          SERVICE_ALL_ACCESS | STANDARD_RIGHTS_ALL,
                          CServiceType, CServiceStart,
                          SERVICE_ERROR_NORMAL, arrCh, NULL, NULL, NULL, NULL, NULL);
      if (c2) {
        // installation went smooth
        // we want to give everyone full access to our service
        if (!AddAccessForEveryone(c2, SERVICE_ALL_ACCESS | DELETE))
          MessageBox(0, "access manipulation didn't work", "warning...", MB_ICONWARNING);
        // now let's start the service
        if (StartServiceA(c2, 0, NULL)) {
          // starting succeeded, but does the service run through?
          // the service tries to create an ipc queue
          // if that fails, it stops and removes itself
          for (i1 = 1; (i1 < 50); i1++) {
            if (!ControlService(c2, SERVICE_CONTROL_INTERROGATE, &ss))
              ss.dwCurrentState = SERVICE_STOPPED;
            if ((ss.dwCurrentState == SERVICE_RUNNING) || (ss.dwCurrentState == SERVICE_STOPPED))
              break;
            Sleep(50);
          }
          if (ss.dwCurrentState == SERVICE_RUNNING)
               MessageBox(0, "the service is installed now",      "information...", MB_ICONINFORMATION);
          else MessageBox(0, "installation failed (ipc failure)", "warning...",     MB_ICONWARNING);
        } else 
          MessageBox(0, "installation succeeded, but starting failed", "warning...", MB_ICONWARNING);
        CloseServiceHandle(c2);
      } else
        MessageBox(0, "you don't have enough privileges", "sorry...", MB_ICONWARNING);
    }
    CloseServiceHandle(c1);
  } else
    MessageBox(0, "you don't have enough privileges", "sorry...", MB_ICONWARNING);
}