示例#1
0
    /*
     * Unregister the service with the  Windows SCM 
     * Input - ServiceName
     */
int
UnregisterService (LPCTSTR lpszServiceName, int quiet)
{
  TCHAR MsgErrorString[MAX_STR_SIZE];	/* Message or Error string */
  SC_HANDLE hSCManager = NULL;	/* SCM handle */
  SC_HANDLE hService = NULL;	/* Service Handle */
  SERVICE_STATUS sStatus;
  TCHAR szRegAppLogKey[] =
    _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\");
  TCHAR szRegKey[512];
  int exitStatus = 0;
/*  HKEY hKey = NULL;		?* Key to registry entry */
  TRY
  {
    /*
     * Open Service Control Manager 
     */
    hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE);
    if (hSCManager == NULL)
      {
        ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet);
        exitStatus = SERVICE_ERROR_SCM_OPEN;       
	LEAVE;
      }

    /*
     * Open registered service 
     */
    hService = OpenService (hSCManager, lpszServiceName, SERVICE_ALL_ACCESS);
    if (hService == NULL)
      {
	_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("Can't open service"),
		   lpszServiceName);
        ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
        exitStatus = SERVICE_ERROR_OPEN_SERVICE;       
	LEAVE;
      }

    /*
     * Query service status 
     * If running stop before deleting 
     */
    if (QueryServiceStatus (hService, &sStatus))
      {
	if (sStatus.dwCurrentState == SERVICE_RUNNING
	    || sStatus.dwCurrentState == SERVICE_PAUSED)
	  {
	    ControlService (hService, SERVICE_CONTROL_STOP, &sStatus);
	  }
      };

    /*
     * Delete the service  
     */
    if (DeleteService (hService) == FALSE)
      {
	_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), _T ("Can't delete service"),
		   lpszServiceName);

	/*
	 * Log message to eventlog 
	 */
        ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 0, quiet);
	LEAVE;
      }

    /*
     * Log "Service deleted successfully " message to eventlog
     */
    _sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"), lpszServiceName, _T ("service deleted"));
    ProcessError (EVENTLOG_INFORMATION_TYPE, MsgErrorString, 0, quiet);

    /*
     * Delete registry entries for EventLog 
     */
    _tcscpy (szRegKey, szRegAppLogKey);
    _tcscat (szRegKey, lpszServiceName);
    RegDeleteKey (HKEY_LOCAL_MACHINE, szRegKey);
  }

  /*
   * Delete the handles 
   */
  FINALLY
  {
    if (hService)
      CloseServiceHandle (hService);
    if (hSCManager)
      CloseServiceHandle (hSCManager);
  }
  return (exitStatus);
}
示例#2
0
文件: gojanus.cpp 项目: rsdn/janus
void DeletePrevInstance()
{
	TCHAR* janusguid = _T("{63C4751A-5B1B-41DD-862B-C1230691B403}");
	TCHAR* rootKey = _T("Software\\Microsoft\\Internet Explorer\\MenuExt\\");

	HKEY hCU;
	LONG lResult = RegOpenKeyEx(HKEY_CURRENT_USER,rootKey,
								0,KEY_ENUMERATE_SUB_KEYS | KEY_SET_VALUE | KEY_QUERY_VALUE | KEY_CREATE_SUB_KEY,
								&hCU);

	if(ERROR_SUCCESS == lResult)
	{

		TCHAR buffer[MAX_PATH] = {0};
		DWORD idx = 0;

		TCHAR subkeyName[MAX_PATH] = {0};
		DWORD subkeyLength = MAX_PATH;

		lResult = RegEnumKeyEx(hCU,idx,subkeyName,&subkeyLength,NULL,NULL,NULL,NULL);
		if(ERROR_SUCCESS == lResult)
		{
			do
			{
				lstrcpy(buffer,rootKey);
				lstrcat(buffer,subkeyName);

				
				HKEY hCheckKey;
				lResult = RegOpenKeyEx(HKEY_CURRENT_USER,buffer,0,KEY_QUERY_VALUE,&hCheckKey);
				if(ERROR_SUCCESS == lResult)
				{
					
					DWORD dwTmp;
					lResult = RegQueryValueEx(hCheckKey,janusguid,NULL,NULL,NULL,&dwTmp);
					if(ERROR_SUCCESS == lResult)
					{
						RegCloseKey(hCheckKey);
						//RegCloseKey(hCU);
						//hCU = NULL;

						RegDeleteKey(HKEY_CURRENT_USER,buffer);

						//continue;

					} // if(ERROR_SUCCESS == lResult)
					else
					{
						RegCloseKey(hCheckKey);
					}
				} // if(ERROR_SUCCESS == lResult)


				subkeyLength = MAX_PATH;
				idx++;
			} while(RegEnumKeyEx(hCU,idx,subkeyName,&subkeyLength,NULL,NULL,NULL,NULL) != ERROR_NO_MORE_ITEMS);

		} // if(ERROR_SUCCESS == lResult)

		if(hCU)
			RegCloseKey(hCU);
	} // if(ERROR_SUCCESS == lResult)
}
示例#3
0
int create_parameters(nssm_service_t *service, bool editing) {
  /* Try to open the registry */
  HKEY key = open_registry(service->name, KEY_WRITE);
  if (! key) return 1;

  /* Remember parameters in case we need to delete them. */
  TCHAR registry[KEY_LENGTH];
  int ret = service_registry_path(service->name, true, 0, registry, _countof(registry));

  /* Try to create the parameters */
  if (set_expand_string(key, NSSM_REG_EXE, service->exe)) {
    if (ret > 0) RegDeleteKey(HKEY_LOCAL_MACHINE, registry);
    RegCloseKey(key);
    return 2;
  }
  if (set_expand_string(key, NSSM_REG_FLAGS, service->flags)) {
    if (ret > 0) RegDeleteKey(HKEY_LOCAL_MACHINE, registry);
    RegCloseKey(key);
    return 3;
  }
  if (set_expand_string(key, NSSM_REG_DIR, service->dir)) {
    if (ret > 0) RegDeleteKey(HKEY_LOCAL_MACHINE, registry);
    RegCloseKey(key);
    return 4;
  }

  /* Other non-default parameters. May fail. */
  if (service->priority != NORMAL_PRIORITY_CLASS) set_number(key, NSSM_REG_PRIORITY, service->priority);
  else if (editing) RegDeleteValue(key, NSSM_REG_PRIORITY);
  if (service->affinity) {
    TCHAR *string;
    if (! affinity_mask_to_string(service->affinity, &string)) {
      if (RegSetValueEx(key, NSSM_REG_AFFINITY, 0, REG_SZ, (const unsigned char *) string, (unsigned long) (_tcslen(string) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) {
        log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_AFFINITY, error_string(GetLastError()), 0);
        HeapFree(GetProcessHeap(), 0, string);
        return 5;
      }
    }
    if (string) HeapFree(GetProcessHeap(), 0, string);
  }
  else if (editing) RegDeleteValue(key, NSSM_REG_AFFINITY);
  unsigned long stop_method_skip = ~service->stop_method;
  if (stop_method_skip) set_number(key, NSSM_REG_STOP_METHOD_SKIP, stop_method_skip);
  else if (editing) RegDeleteValue(key, NSSM_REG_STOP_METHOD_SKIP);
  if (service->default_exit_action < NSSM_NUM_EXIT_ACTIONS) create_exit_action(service->name, exit_action_strings[service->default_exit_action], editing);
  if (service->restart_delay) set_number(key, NSSM_REG_RESTART_DELAY, service->restart_delay);
  else if (editing) RegDeleteValue(key, NSSM_REG_RESTART_DELAY);
  if (service->throttle_delay != NSSM_RESET_THROTTLE_RESTART) set_number(key, NSSM_REG_THROTTLE, service->throttle_delay);
  else if (editing) RegDeleteValue(key, NSSM_REG_THROTTLE);
  if (service->kill_console_delay != NSSM_KILL_CONSOLE_GRACE_PERIOD) set_number(key, NSSM_REG_KILL_CONSOLE_GRACE_PERIOD, service->kill_console_delay);
  else if (editing) RegDeleteValue(key, NSSM_REG_KILL_CONSOLE_GRACE_PERIOD);
  if (service->kill_window_delay != NSSM_KILL_WINDOW_GRACE_PERIOD) set_number(key, NSSM_REG_KILL_WINDOW_GRACE_PERIOD, service->kill_window_delay);
  else if (editing) RegDeleteValue(key, NSSM_REG_KILL_WINDOW_GRACE_PERIOD);
  if (service->kill_threads_delay != NSSM_KILL_THREADS_GRACE_PERIOD) set_number(key, NSSM_REG_KILL_THREADS_GRACE_PERIOD, service->kill_threads_delay);
  else if (editing) RegDeleteValue(key, NSSM_REG_KILL_THREADS_GRACE_PERIOD);
  if (! service->kill_process_tree) set_number(key, NSSM_REG_KILL_PROCESS_TREE, 0);
  else if (editing) RegDeleteValue(key, NSSM_REG_KILL_PROCESS_TREE);
  if (service->stdin_path[0] || editing) {
    if (service->stdin_path[0]) set_expand_string(key, NSSM_REG_STDIN, service->stdin_path);
    else if (editing) RegDeleteValue(key, NSSM_REG_STDIN);
    if (service->stdin_sharing != NSSM_STDIN_SHARING) set_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_SHARING, service->stdin_sharing);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_SHARING);
    if (service->stdin_disposition != NSSM_STDIN_DISPOSITION) set_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_DISPOSITION, service->stdin_disposition);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_DISPOSITION);
    if (service->stdin_flags != NSSM_STDIN_FLAGS) set_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_FLAGS, service->stdin_flags);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_FLAGS);
  }
  if (service->stdout_path[0] || editing) {
    if (service->stdout_path[0]) set_expand_string(key, NSSM_REG_STDOUT, service->stdout_path);
    else if (editing) RegDeleteValue(key, NSSM_REG_STDOUT);
    if (service->stdout_sharing != NSSM_STDOUT_SHARING) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_SHARING, service->stdout_sharing);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_SHARING);
    if (service->stdout_disposition != NSSM_STDOUT_DISPOSITION) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_DISPOSITION, service->stdout_disposition);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_DISPOSITION);
    if (service->stdout_flags != NSSM_STDOUT_FLAGS) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_FLAGS, service->stdout_flags);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_FLAGS);
    if (service->stdout_copy_and_truncate) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_COPY_AND_TRUNCATE, 1);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_COPY_AND_TRUNCATE);
  }
  if (service->stderr_path[0] || editing) {
    if (service->stderr_path[0]) set_expand_string(key, NSSM_REG_STDERR, service->stderr_path);
    else if (editing) RegDeleteValue(key, NSSM_REG_STDERR);
    if (service->stderr_sharing != NSSM_STDERR_SHARING) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_SHARING, service->stderr_sharing);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_SHARING);
    if (service->stderr_disposition != NSSM_STDERR_DISPOSITION) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_DISPOSITION, service->stderr_disposition);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_DISPOSITION);
    if (service->stderr_flags != NSSM_STDERR_FLAGS) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_FLAGS, service->stderr_flags);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_FLAGS);
    if (service->stderr_copy_and_truncate) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_COPY_AND_TRUNCATE, 1);
    else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_COPY_AND_TRUNCATE);
  }
  if (service->timestamp_log) set_number(key, NSSM_REG_TIMESTAMP_LOG, 1);
  else if (editing) RegDeleteValue(key, NSSM_REG_TIMESTAMP_LOG);
  if (service->hook_share_output_handles) set_number(key, NSSM_REG_HOOK_SHARE_OUTPUT_HANDLES, 1);
  else if (editing) RegDeleteValue(key, NSSM_REG_HOOK_SHARE_OUTPUT_HANDLES);
  if (service->rotate_files) set_number(key, NSSM_REG_ROTATE, 1);
  else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE);
  if (service->rotate_stdout_online) set_number(key, NSSM_REG_ROTATE_ONLINE, 1);
  else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_ONLINE);
  if (service->rotate_seconds) set_number(key, NSSM_REG_ROTATE_SECONDS, service->rotate_seconds);
  else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_SECONDS);
  if (service->rotate_bytes_low) set_number(key, NSSM_REG_ROTATE_BYTES_LOW, service->rotate_bytes_low);
  else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_BYTES_LOW);
  if (service->rotate_bytes_high) set_number(key, NSSM_REG_ROTATE_BYTES_HIGH, service->rotate_bytes_high);
  else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_BYTES_HIGH);
  if (service->rotate_delay != NSSM_ROTATE_DELAY) set_number(key, NSSM_REG_ROTATE_DELAY, service->rotate_delay);
  else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_DELAY);
  if (service->no_console) set_number(key, NSSM_REG_NO_CONSOLE, 1);
  else if (editing) RegDeleteValue(key, NSSM_REG_NO_CONSOLE);

  /* Environment */
  if (service->env) {
    if (RegSetValueEx(key, NSSM_REG_ENV, 0, REG_MULTI_SZ, (const unsigned char *) service->env, (unsigned long) service->envlen * sizeof(TCHAR)) != ERROR_SUCCESS) {
      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_ENV, error_string(GetLastError()), 0);
    }
  }
  else if (editing) RegDeleteValue(key, NSSM_REG_ENV);
  if (service->env_extra) {
    if (RegSetValueEx(key, NSSM_REG_ENV_EXTRA, 0, REG_MULTI_SZ, (const unsigned char *) service->env_extra, (unsigned long) service->env_extralen * sizeof(TCHAR)) != ERROR_SUCCESS) {
      log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_ENV_EXTRA, error_string(GetLastError()), 0);
    }
  }
  else if (editing) RegDeleteValue(key, NSSM_REG_ENV_EXTRA);

  /* Close registry. */
  RegCloseKey(key);

  return 0;
}
void CUninstallApp::DelValveKeysIfEmpty()
{
	LONG lResult;
	HKEY hKey;
	
	char keyname[256]={0};
	DWORD namesize=256;
	
	//do HKEY_LOCAL_MACHINE first
	lResult=RegOpenKeyEx(HKEY_LOCAL_MACHINE,REG_VALVE_KEY,0,KEY_ALL_ACCESS,&hKey);
	if (lResult==ERROR_SUCCESS)
	{
		lResult=RegEnumKeyEx(hKey,0,keyname,&namesize,NULL,NULL,NULL,NULL);
		if (lResult==ERROR_NO_MORE_ITEMS)
		{
			RegCloseKey(hKey);
			lResult=RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE",0,KEY_ALL_ACCESS,&hKey);
			if (lResult==ERROR_SUCCESS)
			{
				RegDeleteKey(hKey,"Valve");
				RegCloseKey(hKey);
			}
#ifdef _DEBUG
			else 
			{
				AfxMessageBox("Couldn't open HKLM\\Software");
			}
#endif
		}
#ifdef _DEBUG
		else 
		{
			AfxMessageBox("found something in HKLM\\software\\valve, not deleting");
		}
#endif
	}
#ifdef _DEBUG
	else 
	{
		AfxMessageBox(CString("failed trying open: HKLM ")+CString(REG_VALVE_KEY));
	}
#endif

	//now do HKEY_CURRENT_USER
	lResult=RegOpenKeyEx(HKEY_CURRENT_USER,REG_VALVE_KEY,0,KEY_ALL_ACCESS,&hKey);
	if (lResult==ERROR_SUCCESS)
	{
		lResult=RegEnumKeyEx(hKey,0,keyname,&namesize,NULL,NULL,NULL,NULL);
		if (lResult==ERROR_NO_MORE_ITEMS)
		{
			RegCloseKey(hKey);
			lResult=RegOpenKeyEx(HKEY_CURRENT_USER,"SOFTWARE",0,KEY_ALL_ACCESS,&hKey);
			if (lResult==ERROR_SUCCESS)
			{
				RegDeleteKey(hKey,"Valve");
				RegCloseKey(hKey);
			}
#ifdef _DEBUG
			else 
			{
				AfxMessageBox("Couldn't open HKCU\\Software");
			}
#endif
		}
#ifdef _DEBUG
		else 
		{
			AfxMessageBox("found something in HKCU\\software\\valve, not deleting");
		}
#endif
	}
#ifdef _DEBUG
	else 
	{
		AfxMessageBox(CString("failed trying open: HKCU ")+CString(REG_VALVE_KEY));
	}
#endif
}
// Window positions saving/loading added by Philip Gruebele.
//<a href="mailto:[email protected]">[email protected]</a>
// philipg.  Saves the window position in the registry
static void
icvSaveWindowPos( const char* name, CvRect rect )
{
    static const DWORD MAX_RECORD_COUNT = 100;
    HKEY hkey;
    char szKey[1024];
    char rootKey[1024];
    strcpy( szKey, icvWindowPosRootKey );
    strcat( szKey, name );
    
    if( RegOpenKeyEx( HKEY_CURRENT_USER,szKey,0,KEY_READ,&hkey) != ERROR_SUCCESS )
    {
        HKEY hroot;
        DWORD count = 0;
        FILETIME oldestTime = { UINT_MAX, UINT_MAX };
        char oldestKey[1024];
        char currentKey[1024];

        strcpy( rootKey, icvWindowPosRootKey );
        rootKey[strlen(rootKey)-1] = '\0';
        if( RegCreateKeyEx(HKEY_CURRENT_USER, rootKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ+KEY_WRITE, 0, &hroot, NULL) != ERROR_SUCCESS )
            //RegOpenKeyEx( HKEY_CURRENT_USER,rootKey,0,KEY_READ,&hroot) != ERROR_SUCCESS )
            return;

        for(;;)
        {
            DWORD csize = sizeof(currentKey);
            FILETIME accesstime = { 0, 0 };
            LONG code = RegEnumKeyEx( hroot, count, currentKey, &csize, NULL, NULL, NULL, &accesstime );
            if( code != ERROR_SUCCESS && code != ERROR_MORE_DATA )
                break;
            count++;
            if( oldestTime.dwHighDateTime > accesstime.dwHighDateTime ||
                (oldestTime.dwHighDateTime == accesstime.dwHighDateTime &&
                oldestTime.dwLowDateTime > accesstime.dwLowDateTime) )
            {
                oldestTime = accesstime;
                strcpy( oldestKey, currentKey );
            }
        }

        if( count >= MAX_RECORD_COUNT )
            RegDeleteKey( hroot, oldestKey );
        RegCloseKey( hroot );

        if( RegCreateKeyEx(HKEY_CURRENT_USER,szKey,0,NULL,REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hkey, NULL) != ERROR_SUCCESS )
            return;
    }
    else
    {
        RegCloseKey( hkey );
        if( RegOpenKeyEx( HKEY_CURRENT_USER,szKey,0,KEY_WRITE,&hkey) != ERROR_SUCCESS )
            return;
    }
    
    RegSetValueEx(hkey, "Left", 0, REG_DWORD, (BYTE*)&rect.x, sizeof(rect.x));
    RegSetValueEx(hkey, "Top", 0, REG_DWORD, (BYTE*)&rect.y, sizeof(rect.y));
    RegSetValueEx(hkey, "Width", 0, REG_DWORD, (BYTE*)&rect.width, sizeof(rect.width));
    RegSetValueEx(hkey, "Height", 0, REG_DWORD, (BYTE*)&rect.height, sizeof(rect.height));
    RegCloseKey(hkey);
}
示例#6
0
STDAPI UnregisterServer(CLSID clsid, LPTSTR lpszTitle)
{
    int      i;
    LRESULT  lResult;
    TCHAR    szSubKey[MAX_PATH];
    TCHAR    szCLSID[MAX_PATH];
    TCHAR    szModule[MAX_PATH];
    LPWSTR   pwsz;
    DWORD    retval;
    HRESULT  hr;

    // Get the CLSID in string form.
    StringFromIID(clsid, &pwsz);

    if(pwsz)
    {
#ifdef UNICODE
        hr = StringCchCopyW(szCLSID, MAX_PATH, pwsz);
        // TODO: Add error handling for hr here.
#else
        WideCharToMultiByte( CP_ACP,
            0,
            pwsz,
            -1,
            szCLSID,
            MAX_PATH * sizeof(TCHAR),
            NULL,
            NULL);
#endif

        // Free the string.
        LPMALLOC pMalloc;
        CoGetMalloc(1, &pMalloc);
        pMalloc->Free(pwsz);
        pMalloc->Release();
    }

    // Get this app's path and file name.
    retval = GetModuleFileName(DllhInstance, szModule, MAX_PATH);
    // TODO: Add error handling to check return value for success/failure
    //       before using szModule.

    DOREGSTRUCT ClsidEntries[ ] = {
        {HKEY_CLASSES_ROOT,TEXT("CLSID\\%38s"),NULL,lpszTitle},
        {HKEY_CLASSES_ROOT,TEXT("CLSID\\%38s\\InprocServer32"),NULL,szModule},
        {HKEY_CLASSES_ROOT,TEXT("CLSID\\%38s\\InprocServer32"),TEXT("ThreadingModel"),TEXT("Apartment")},
        {NULL,NULL,NULL,NULL}
    };

    //register the CLSID entries
    for(i = 0; ClsidEntries[i].hRootKey; i++)
    {
        //create the sub key string - for this case, insert the file extension
        hr = StringCchPrintf(szSubKey, 
            MAX_PATH, 
            ClsidEntries[i].szSubKey, 
            szCLSID);
        // TODO: Add error handling code here to check the hr return value.

        lResult = RegDeleteKey(ClsidEntries[i].hRootKey,ClsidEntries[i].szSubKey);
    }
    return S_OK;  
}
void tst_QValueSpaceSubscriber::initTestCase()
{
    qRegisterMetaType<QVariant>("QVariant");
    qRegisterMetaType<QValueSpace::LayerOptions>("QValueSpace::LayerOptions");

#ifdef Q_OS_WIN
    HKEY key;
    long result = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Nokia",
                               0, KEY_ALL_ACCESS, &key);
    if (result == ERROR_SUCCESS) {
        result = RegDeleteKey(key, L"QtMobility\\volatileContext");
        result = RegDeleteKey(key, L"QtMobility\\nonVolatileContext");
        result = RegDeleteKey(key, L"QtMobility");

        RegCloseKey(key);
    }
#endif

#if defined(Q_OS_UNIX) && defined(QT_START_VALUESPACE)
    QFile::remove("/tmp/qt-0/valuespace_shmlayer");
#endif

#if defined(QT_START_VALUESPACE)
    QValueSpace::initValueSpaceServer();
#endif

    QList<QAbstractValueSpaceLayer *> layers = QValueSpaceManager::instance()->getLayers();
    for (int i = 0; i < layers.count(); ++i) {
        QValueSpacePublisher *root = new QValueSpacePublisher(layers.at(i)->id(), "/");
        root->setValue("/home/user/bool", true);
        root->setValue("/home/user/int", 3);
        root->setValue("/home/user/QString", QString("testString"));
        QStringList stringList;
        stringList << QString("String 1") << QString("String 2");
        root->setValue("/home/user/QStringList", stringList);
        root->setValue("/home/user/qint64", qint64(64));
        root->setValue("/home/user/QByteArray", QByteArray("testByteArray"));
        root->setValue("/home/user/double", 4.56);
        root->setValue("/home/user/float", (float)4.56f);
        root->setValue("/home/user/QChar", QChar('c'));
        //so far not a lot of data types are supported
        //root->setValue("/home/user/QRect", QRect(0,0,5,6));

        root->setValue("/home/usercount", 1);

        root->setValue("/layer/name", layers.at(i)->name());
        root->setValue("/layer/id", layers.at(i)->id().toString());
        root->setValue("/layer/options", uint(layers.at(i)->layerOptions()));

        root->sync();

        roots.insert(layers.at(i), root);

        QValueSpacePublisher *busy = new QValueSpacePublisher(layers.at(i)->id(), "/usr");
        busy->setValue("alex/busy", true);
        busy->setValue("lorn/busy", false);
        busy->sync();

        busys.insert(layers.at(i), busy);
    }
}
示例#8
0
文件: bv2recents.c 项目: apla/beevee
LRESULT CALLBACK BV2RecentsDlgProc (HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	int dlgItemID;
	int i;
	char filename[256];
	HWND mCtrl;
	RECT cr,r,r1;

	switch (message)
	{
		case WM_INITDIALOG:
		mCtrl = GetDlgItem(hDlg, IDC_LISTTEXT);
		sdata_init(&myrecents.rct);
		if (ReadRecentFilesInReg())
		{
		    for(i=0;i<sdata_jumlahdata(&myrecents.rct);i++)
		    {
		        sdata_ambildatanomor(&myrecents.rct, i, filename);
		        AddListBoxItem (mCtrl, filename, i);
		    }
		}

		//return TRUE;
		case WM_SIZE:
		GetClientRect (hDlg, &cr);
		mCtrl = GetDlgItem(hDlg, IDC_LISTTEXT);
		MoveWindow (mCtrl, 2, 2, cr.right-4, cr.bottom-28, TRUE);
		mCtrl = GetDlgItem(hDlg, IDOK);
		GetWindowRect(mCtrl, &r);
		MoveWindow (mCtrl, 2, cr.bottom-24, (r.right-r.left), (r.bottom-r.top), TRUE);
		mCtrl = GetDlgItem(hDlg, IDCANCEL);
		MoveWindow (mCtrl, 4+(r.right-r.left), cr.bottom-24, (r.right-r.left), (r.bottom-r.top), TRUE);
		mCtrl = GetDlgItem(hDlg, IDC_CLEAR);
		MoveWindow (mCtrl, 6+(r.right-r.left)*2, cr.bottom-24, (r.right-r.left), (r.bottom-r.top), TRUE);
		mCtrl = GetDlgItem(hDlg, IDC_NEWWINDOW);

		/* shb-20070906 */
		GetWindowRect(mCtrl, &r1);
		MoveWindow (mCtrl, 12+(r.right-r.left)*3, cr.bottom-20, (r1.right-r1.left), (r1.bottom-r1.top), TRUE);
		/* shb-20070906 */

		return TRUE;
		break;

		case WM_COMMAND:
		dlgItemID = LOWORD(wParam);
		if (dlgItemID==IDOK || (dlgItemID==IDC_LISTTEXT && HIWORD(wParam)==LBN_DBLCLK))
		{
            GetListBoxCurSelString (GetDlgItem(hDlg, IDC_LISTTEXT), myrecents.file);
            myrecents.newwin = IsDlgButtonChecked (hDlg, IDC_NEWWINDOW);
		    EndDialog(hDlg, IDOK);
		}
		else if (dlgItemID==IDCANCEL)
		{
		    EndDialog(hDlg, dlgItemID);
		}
		else if (dlgItemID==IDC_CLEAR)
		{
		    RegDeleteKey (HKEY_CURRENT_USER, "Software\\eshabe\\BeeVee\\MRU");
		    EndDialog(hDlg, dlgItemID);
		}
		break;
		case WM_DESTROY:
		sdata_hapussemua (&myrecents.rct);
		break;
	}
	return FALSE;
}
示例#9
0
BOOL 
RemoveService(const char* pServiceName)
{
    long	lRet		= 0;
    HKEY	hkParameters	= NULL;
    SC_HANDLE	schService	= NULL;
    SC_HANDLE   schSCManager	= NULL;
    BOOL	bStatus		= TRUE;

    SERVICE_STATUS  ssStatus; 
    
    // Open the service control manager
    schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if(schSCManager == NULL)
    {                           
	bStatus = FALSE;
	goto cleanup;
    }

    // Open the service entry
    schService = OpenService(schSCManager, pServiceName, SERVICE_ALL_ACCESS);

    if(schService == NULL) 
    {   
	if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
	{
	    bStatus = TRUE;
	    goto cleanup;
	}
	else 
	{
	    LPVOID lpMsgBuf;

	    FormatMessage( 
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL 
	    );

	    // Display the string
	    fprintf(stderr, "%s\n", lpMsgBuf);

	    // Free the buffer.
	    LocalFree( lpMsgBuf );

	    bStatus = FALSE;
	    goto cleanup;
	}
    }

    // Determine the status of the service (started/stopped)
    if (!QueryServiceStatus(schService, &ssStatus))
    {
	bStatus = FALSE;
	goto cleanup;
    }

    if (ssStatus.dwCurrentState == SERVICE_RUNNING)
    {
	// Service is still running!
	bStatus = FALSE;
	goto cleanup;
    }

    // Delete the service
    if (!DeleteService(schService))
    {
	bStatus = FALSE;
	goto cleanup;
    }

    // Clean up the registry entry associated with the service
    lRet = RegOpenKeyEx(
	HKEY_LOCAL_MACHINE,
	REGISTRY_KEY_EVENTLOG,
	0,
	KEY_ALL_ACCESS,
	&hkParameters);

    if (lRet != ERROR_SUCCESS)
    {
	bStatus = FALSE;
	goto cleanup;
    }

    // Delete the service specific keys
    lRet = RegDeleteKey(hkParameters, pServiceName);
    if (lRet != ERROR_SUCCESS)
    {
	bStatus = FALSE;
	goto cleanup;
    }

    bStatus = TRUE;

cleanup:

    FREEHSCM(schService);
    FREEHSCM(schSCManager);

    FREEHKEY(hkParameters);
    RegFlushKey(HKEY_LOCAL_MACHINE);
  
    return bStatus;
}
示例#10
0
文件: info.c 项目: hoangduit/reactos
/*
 * @unimplemented
 */
BOOL
WINAPI
DeletePrintProvidorW(LPWSTR Name, LPWSTR Environment, LPWSTR PrintProvidor)
{
   HKEY hKey;
   BOOL bFound;
   DWORD dwType, dwSize, dwOffset, dwLength;
   LPWSTR pOrder, pBuffer, pNew;

   if (Name || !Environment || !PrintProvidor)
   {
      SetLastError(ERROR_INVALID_PARAMETER);
      return FALSE;
   }

   if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Print\\Providers", 0, KEY_READ | KEY_WRITE, &hKey) != ERROR_SUCCESS)
   {
      return FALSE;
   }

   if (RegQueryValueExW(hKey, L"Order", NULL, &dwType, NULL, &dwSize) != ERROR_SUCCESS || dwType != REG_MULTI_SZ)
   {
      RegCloseKey(hKey);
      return FALSE;
   }

   pOrder = HeapAlloc(GetProcessHeap(), 0, dwSize);
   if (!pOrder)
   {
      RegCloseKey(hKey);
      return FALSE;
   }

   if (RegQueryValueExW(hKey, L"Order", NULL, &dwType, (LPBYTE)pOrder, &dwSize) != ERROR_SUCCESS || dwType != REG_MULTI_SZ)
   {
      RegCloseKey(hKey);
      return FALSE;
   }


   pBuffer = pOrder;
   bFound = FALSE;
   while(pBuffer[0])
   {
       if (!wcsicmp(pBuffer, PrintProvidor))
       {
            bFound = TRUE;
            break;
         }
         pBuffer += wcslen(pBuffer) + 1;
   }

   if (!bFound)
   {
      RegCloseKey(hKey);
      HeapFree(GetProcessHeap(), 0, pOrder);
      return FALSE;
   }

   pNew = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
   if (!pNew)
   {
      RegCloseKey(hKey);
      HeapFree(GetProcessHeap(), 0, pOrder);
      return FALSE;
   }

   dwOffset = pBuffer - pOrder;
   dwLength = (dwSize / sizeof(WCHAR)) - (dwOffset + wcslen(pBuffer) + 1);
   CopyMemory(pNew, pOrder, dwOffset * sizeof(WCHAR));
   CopyMemory(&pNew[dwOffset], pBuffer + wcslen(pBuffer) + 1, dwLength);

   RegSetValueExW(hKey, L"Order", 0, REG_MULTI_SZ, (LPBYTE)pNew, (dwOffset + dwLength) * sizeof(WCHAR));
   RegDeleteKey(hKey, PrintProvidor);

   HeapFree(GetProcessHeap(), 0, pOrder);
   HeapFree(GetProcessHeap(), 0, pNew);
   RegCloseKey(hKey);

   return TRUE;
}
STDAPI
DllUnregisterServer(
    void)
{
    LONG nStatus;
    DWORD dwDisp;
    HRESULT hReturnStatus = NO_ERROR;
    HKEY hProviders = NULL;
#ifdef SCARD_CSP
    SCARDCONTEXT hCtx = NULL;
#endif

#ifdef _AFXDLL
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
#endif


    //
    // Delete the Registry key for this CSP.
    //

    nStatus = RegCreateKeyEx(
                    HKEY_LOCAL_MACHINE,
                    TEXT("SOFTWARE\\Microsoft\\Cryptography\\Defaults\\Provider"),
                    0,
                    TEXT(""),
                    REG_OPTION_NON_VOLATILE,
                    KEY_ALL_ACCESS,
                    NULL,
                    &hProviders,
                    &dwDisp);
    if (ERROR_SUCCESS == nStatus)
    {
        RegDeleteKey(hProviders, l_szProviderName);
        RegCloseKey(hProviders);
        hProviders = NULL;
    }


#ifdef SCARD_CSP
    //
    // Forget the card type.
    //

    hCtx = NULL;
    SCardEstablishContext(SCARD_SCOPE_SYSTEM, 0, 0, &hCtx);
    SCardForgetCardType(hCtx, l_szCardName);
    if (NULL != hCtx)
    {
        SCardReleaseContext(hCtx);
        hCtx = NULL;
    }
#endif


    //
    // ?vendor?
    // Delete vendor specific registry entries.
    //



    //
    // All done!
    //

    return hReturnStatus;
}
示例#12
0
/* delete the given value or key in the registry with all of its subkeys in subkey */
bool CReg::DeleteKey (LPCTSTR pszSubKey, LPCTSTR pszValName)
{
  return RegDeleteKey (hKey, pszSubKey, pszValName);
}
示例#13
0
/* delete the given value or key in the registry with all of its subkeys */
bool CReg::DeleteKey (LPCTSTR pszValName)
{
  return RegDeleteKey (hKey, nullptr, pszValName);
}
示例#14
0
BOOL SavePasswordToRegistry(TCHAR *szAccount, TCHAR *szPassword, bool persistent)
{
	int nError;
	BOOL bResult = TRUE;
	
	TCHAR szKey[256];
	HKEY hRegKey = NULL;
	_tcscpy(szKey, MPICHKEY);
	
	if (persistent)
	{
		if (RegCreateKeyEx(HKEY_CURRENT_USER, szKey,
			0, 
			NULL, 
			REG_OPTION_NON_VOLATILE,
			KEY_ALL_ACCESS, 
			NULL,
			&hRegKey, 
			NULL) != ERROR_SUCCESS) 
		{
			nError = GetLastError();
			printf("SavePasswordToRegistry:RegCreateKeyEx(...) failed, error: %d\n", nError);
			return FALSE;
		}
	}
	else
	{
		RegDeleteKey(HKEY_CURRENT_USER, szKey);
		if (RegCreateKeyEx(HKEY_CURRENT_USER, szKey,
			0, 
			NULL, 
			REG_OPTION_VOLATILE,
			KEY_ALL_ACCESS, 
			NULL,
			&hRegKey, 
			NULL) != ERROR_SUCCESS) 
		{
			nError = GetLastError();
			printf("SavePasswordToRegistry:RegDeleteKey(...) failed, error: %d\n", nError);
			return FALSE;
		}
	}

	// Store the account name
	if (::RegSetValueEx(
			hRegKey, _T("Account"), 0, REG_SZ, 
			(BYTE*)szAccount, 
			sizeof(TCHAR)*(_tcslen(szAccount)+1)
			)!=ERROR_SUCCESS)
	{
		nError = GetLastError();
		printf("SavePasswordToRegistry:RegSetValueEx(...) failed, error: %d\n", nError);
		::RegCloseKey(hRegKey);
		return FALSE;
	}

	HCRYPTPROV hProv = NULL;
	HCRYPTKEY hKey = NULL;
	HCRYPTKEY hXchgKey = NULL;
	HCRYPTHASH hHash = NULL;
	DWORD dwLength;
	// Used to encrypt the real password
	TCHAR szLocalPassword[] = _T("MMPzI6C@HaA0NiL*I%Ll");

	// Get handle to user default provider.
	//if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0))
	if (CryptAcquireContext(&hProv, "MPICH", NULL, PROV_RSA_FULL, 0))
	{
		// Create hash object.
		if (CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
		{
			// Hash password string.
			dwLength = sizeof(TCHAR)*_tcslen(szLocalPassword);
			if (CryptHashData(hHash, (BYTE *)szLocalPassword, dwLength, 0))
			{
				// Create block cipher session key based on hash of the password.
				if (CryptDeriveKey(hProv, CALG_RC4, hHash, CRYPT_EXPORTABLE, &hKey))
				{
					// Determine number of bytes to encrypt at a time.
					dwLength = sizeof(TCHAR)*(_tcslen(szPassword)+1);

					// Allocate memory.
					BYTE *pbBuffer = (BYTE *)malloc(dwLength);
					if (pbBuffer != NULL)
					{
						memcpy(pbBuffer, szPassword, dwLength);
						// Encrypt data
						if (CryptEncrypt(hKey, 0, TRUE, 0, pbBuffer, &dwLength, dwLength)) 
						{
							// Write data to registry.
							DWORD dwType = REG_BINARY;
							// Add the password.
							if (::RegSetValueEx(hRegKey, _T("Password"), 0, REG_BINARY, pbBuffer, dwLength)!=ERROR_SUCCESS)
							{
								nError = GetLastError();
								printf("SavePasswordToRegistry:RegSetValueEx(...) failed, error: %d\n", nError);
								bResult = FALSE;
							}
							::RegCloseKey(hRegKey);
						}	
						else
						{
							nError = GetLastError();
							printf("SavePasswordToRegistry:CryptEncrypt(...) failed, error: %d\n", nError);
							bResult = FALSE;
						}
						// Free memory.
					  free(pbBuffer);
					}
					else
					{
						nError = GetLastError();
						printf("SavePasswordToRegistry:malloc(...) failed, error: %d\n", nError);
						bResult = FALSE;
					}
					CryptDestroyKey(hKey);  // Release provider handle.
				}
				else
				{
					// Error during CryptDeriveKey!
					nError = GetLastError();
					printf("SavePasswordToRegistry:CryptDeriveKey(...) failed, error: %d\n", nError);
					bResult = FALSE;
				}
			}
			else
			{
				// Error during CryptHashData!
				nError = GetLastError();
				printf("SavePasswordToRegistry:CryptHashData(...) failed, error: %d\n", nError);
				bResult = FALSE;
			}
			CryptDestroyHash(hHash); // Destroy session key.
		}
		else
		{
			// Error during CryptCreateHash!
			nError = GetLastError();
			printf("SavePasswordToRegistry:CryptCreateHash(...) failed, error: %d\n", nError);
			bResult = FALSE;
		}
		CryptReleaseContext(hProv, 0);
	}

	return bResult;
}
示例#15
0
LONG RegDeleteKey( HKEY hKey, const char* lpSubKey )
{ USES_CONVERSION; return RegDeleteKey( hKey, A2T(lpSubKey) ); }
示例#16
0
bool LoadDriver(char * szDrvName, char * szDrvPath)
{
	char szSubKey[MAX_PATH];
	char szDrvFullPath[MAX_PATH];
//	LSA_UNICODE_STRING buf1;
//	LSA_UNICODE_STRING buf2;
	int iBuffLen;
	HKEY hkResult;
//	char Data[4];
	DWORD dwOK;
	iBuffLen = sprintf_s(szSubKey, MAX_PATH, "System\\CurrentControlSet\\Services\\%s", szDrvName);
	szSubKey[iBuffLen]=0;
	dwOK = RegCreateKey(HKEY_LOCAL_MACHINE,szSubKey,&hkResult);
	if(dwOK!=ERROR_SUCCESS)
		return false;


	DWORD val;
	val = 1;
	if(RegSetValueEx(hkResult, "Type", 0, REG_DWORD, (PBYTE)&val, sizeof(val)) != ERROR_SUCCESS)
		return FALSE;

	if(RegSetValueEx(hkResult, "ErrorControl", 0, REG_DWORD, (PBYTE)&val, sizeof(val)) != ERROR_SUCCESS)
		return FALSE;

	val = 3;
	if(RegSetValueEx(hkResult, "Start", 0, REG_DWORD, (PBYTE)&val, sizeof(val)) != ERROR_SUCCESS)
		return FALSE;

	GetFullPathName(szDrvPath, MAX_PATH, szDrvFullPath, NULL);  
	printf("  Loading driver: %s\r\n", szDrvFullPath);
	iBuffLen = sprintf_s(szSubKey, MAX_PATH, "\\??\\%s", szDrvFullPath);
	szSubKey[iBuffLen]=0;
	dwOK=RegSetValueEx(hkResult,"ImagePath",0,1,(const unsigned char *)szSubKey,iBuffLen);
	RegCloseKey(hkResult); 


	HMODULE hntdll;

	hntdll = LoadLibrary( "ntdll.dll" ); 

	VOID (WINAPI *_RtlInitAnsiString)
		(IN OUT PANSI_STRING  DestinationString,
		IN PCHAR  SourceString);

	*(FARPROC *)&_RtlInitAnsiString = 
		GetProcAddress(hntdll, "RtlInitAnsiString");

	ANSI_STRING aStr;
	char szServicePath[MAX_PATH];
	sprintf_s(szServicePath, MAX_PATH, "\\Registry\\Machine\\System\\CurrentControlSet\\Services\\%s", szDrvName);
	_RtlInitAnsiString(&aStr, szServicePath);

	UNICODE_STRING uStr;

	if(RtlAnsiStringToUnicodeString(&uStr, &aStr, TRUE) != STATUS_SUCCESS)
	{
		return FALSE;
	}
	else
	{
		DWORD	dwRet=ZwLoadDriver(&uStr); 
		#define STATUS_IMAGE_ALREADY_LOADED      ((NTSTATUS)0xC000010EL)
		if (STATUS_IMAGE_ALREADY_LOADED== dwRet)
		{
			OutputDebugString("ZwLoadDriver return STATUS_IMAGE_ALREADY_LOADED\n");
		}
		if( dwRet== STATUS_SUCCESS || dwRet==STATUS_IMAGE_ALREADY_LOADED )
		{
			RtlFreeUnicodeString(&uStr);
		}
		else
		{

			
			RtlFreeUnicodeString(&uStr);			
			return FALSE;
		}
	}

	iBuffLen=sprintf_s(szSubKey, MAX_PATH, "%s%s\\Enum","System\\CurrentControlSet\\Services\\", szDrvName);
	szSubKey[iBuffLen]=0;
	RegDeleteKey(HKEY_LOCAL_MACHINE,szSubKey);
	iBuffLen=sprintf_s(szSubKey, MAX_PATH, "%s%s\\Security","System\\CurrentControlSet\\Services\\", szDrvName);
	szSubKey[iBuffLen]=0;
	RegDeleteKey(HKEY_LOCAL_MACHINE,szSubKey);
	iBuffLen=sprintf_s(szSubKey, MAX_PATH, "%s%s","System\\CurrentControlSet\\Services\\", szDrvName);
	szSubKey[iBuffLen]=0;
	RegDeleteKey(HKEY_LOCAL_MACHINE,szSubKey);
	iBuffLen=sprintf_s(szSubKey, MAX_PATH, "\\\\.\\%s", szDrvName);
	szSubKey[iBuffLen]=0;
	return true;
}
示例#17
0
// ----------------------------------------------------------------------------
// delete keys/values
// ----------------------------------------------------------------------------
bool wxRegKey::DeleteSelf()
{
  {
    wxLogNull nolog;
    if ( !Open() ) {
      // it already doesn't exist - ok!
      return true;
    }
  }

  // prevent a buggy program from erasing one of the root registry keys or an
  // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
  // key except HKCR (HKCR has some "deleteable" subkeys)
  if ( m_strKey.empty() ||
       ((m_hRootKey != (WXHKEY) aStdKeys[HKCR].hkey) &&
        (m_strKey.Find(REG_SEPARATOR) == wxNOT_FOUND)) ) {
      wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
                 GetFullName(this));

      return false;
  }

  // we can't delete keys while enumerating because it confuses GetNextKey, so
  // we first save the key names and then delete them all
  wxArrayString astrSubkeys;

  wxString strKey;
  long lIndex;
  bool bCont = GetFirstKey(strKey, lIndex);
  while ( bCont ) {
    astrSubkeys.Add(strKey);

    bCont = GetNextKey(strKey, lIndex);
  }

  size_t nKeyCount = astrSubkeys.Count();
  for ( size_t nKey = 0; nKey < nKeyCount; nKey++ ) {
    wxRegKey key(*this, astrSubkeys[nKey]);
    if ( !key.DeleteSelf() )
      return false;
  }

  // now delete this key itself
  Close();

  // deleting a key which doesn't exist is not considered an error
#if wxUSE_DYNLIB_CLASS
  wxDynamicLibrary dllAdvapi32(wxT("advapi32"));
  // Minimum supported OS for RegDeleteKeyEx: Vista, XP Pro x64, Win Server 2008, Win Server 2003 SP1
  if(dllAdvapi32.HasSymbol(wxT("RegDeleteKeyEx")))
  {
    typedef LONG (WINAPI *RegDeleteKeyEx_t)(HKEY, LPCTSTR, REGSAM, DWORD);
    wxDYNLIB_FUNCTION(RegDeleteKeyEx_t, RegDeleteKeyEx, dllAdvapi32);

    m_dwLastError = (*pfnRegDeleteKeyEx)((HKEY) m_hRootKey, m_strKey.t_str(),
        GetMSWViewFlags(m_viewMode),
        0);    // This parameter is reserved and must be zero.
  }
  else
#endif // wxUSE_DYNLIB_CLASS
  {
    m_dwLastError = RegDeleteKey((HKEY) m_hRootKey, m_strKey.t_str());
  }

  if ( m_dwLastError != ERROR_SUCCESS &&
          m_dwLastError != ERROR_FILE_NOT_FOUND ) {
    wxLogSysError(m_dwLastError, _("Can't delete key '%s'"),
                  GetName().c_str());
    return false;
  }

  return true;
}
示例#18
0
void installService(LPCTSTR serviceName, LPCTSTR displayName, LPCTSTR serviceExe,
                    LPCTSTR dependencies, int currentDependenciesLen,
                    LPCTSTR homeDir, LPCTSTR classPath, LPCTSTR jvmArgs, LPCSTR mainClass)  {
    LPCTSTR lpszBinaryPathName = serviceExe;
	char * allDependencies = new TCHAR[_DEPENDENCY_STR_LEN];
    char * ptr = allDependencies;
	int rest_len = _DEPENDENCY_STR_LEN;
	if (currentDependenciesLen > 0 && dependencies != NULL) {
		strcpy_s(ptr, rest_len, dependencies);
		ptr += currentDependenciesLen;
		rest_len -= currentDependenciesLen;
	}
	
    // add static dependencies
    strcpy_s(ptr, rest_len, NUP_SERVICE_NAME);
    ptr += sizeof(NUP_SERVICE_NAME);
	rest_len -= sizeof(NUP_SERVICE_NAME);
    strcpy_s(ptr, rest_len, TCPIP_SERVICE_NAME);
    ptr += sizeof(TCPIP_SERVICE_NAME);
	rest_len -= sizeof(TCPIP_SERVICE_NAME);
    strcpy_s(ptr, rest_len, AFD_SERVICE_NAME);
    ptr += sizeof(AFD_SERVICE_NAME);
    
    *ptr = '\0';
	BOOL needToFree = FALSE;
	if (strchr(lpszBinaryPathName, ' ') != NULL || TRUE) {
		int buf_len = strlen(lpszBinaryPathName)+3;
		char *quotedBinPath = new char[buf_len];
		
		sprintf_s(quotedBinPath, buf_len, "\"%s\"", lpszBinaryPathName);
		lpszBinaryPathName = quotedBinPath;
		needToFree = TRUE;
	}
	printf("Service %s.\n", lpszBinaryPathName);
	// TODO 1st store parameters, 2nd install service,, since if parameters failed, then service is not operable
    SC_HANDLE hService = CreateService(scm,                          // SCManager database
		serviceName,                 // name of service
		NULL,                 // name to display
		SERVICE_ALL_ACCESS,          // desired access
		SERVICE_WIN32_OWN_PROCESS,   // service type
		SERVICE_AUTO_START,          // start type
		SERVICE_ERROR_NORMAL,        // error control type
		lpszBinaryPathName,          // binary name
		NULL,                        // no load ordering group
		NULL,                        // no tag idenitifier
		allDependencies,                // we depend ???
		NULL,                        // loacalsystem account
		NULL);                       // no password
	delete allDependencies;
	if (needToFree)
		delete (void*)lpszBinaryPathName;
    if (hService != NULL) {
		printf("Added service %s (%s).\n", serviceName, displayName);
		// use to add description
		SERVICE_DESCRIPTION description;
		if (serviceName != displayName) {
			description.lpDescription = (LPSTR)displayName;
			ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &description);
		}
		HKEY hKey;	
		if(RegCreateKeyEx(HKEY_LOCAL_MACHINE,
			REG_ROOT,
			0,
			NULL,
			REG_OPTION_NON_VOLATILE,
			KEY_ALL_ACCESS,
			NULL,
			&hKey, NULL) == ERROR_SUCCESS) {
			if (RegSetValueEx(
				hKey,
				REG_K_CURRVER,
				0,
				REG_SZ,
				(const BYTE* )VERSION,
				sizeof VERSION 
				) == ERROR_SUCCESS) {
				HKEY hKeyVer;	
				if(RegCreateKeyEx(hKey,
					VERSION,
					0,
					NULL,
					REG_OPTION_NON_VOLATILE,
					KEY_ALL_ACCESS,
					NULL,
					&hKeyVer, NULL) == ERROR_SUCCESS) {
					if (RegSetValueEx(
						hKeyVer,
						REG_V_PATH,
						0,
						REG_SZ,
						(const BYTE* )homeDir,
						_tcslen(homeDir)+sizeof TCHAR 
						) == ERROR_SUCCESS) {
							printf("Set path %s.\n", homeDir);	
					}
					if (classPath) {
						if (RegSetValueEx(
							hKeyVer,
							REG_V_CP,
							0,
							REG_SZ,
							(const BYTE* )classPath,
							_tcslen(classPath)+sizeof TCHAR 
							) == ERROR_SUCCESS) {
							printf("Set class path %s.\n", classPath);	
						}
					}
					if (jvmArgs) {
						if (RegSetValueEx(
							hKeyVer,
							REG_V_JVM_ARGS,
							0,
							REG_SZ,
							(const BYTE* )jvmArgs,
							_tcslen(jvmArgs)+sizeof TCHAR 
							) == ERROR_SUCCESS) {
							printf("Set JVM args %s.\n", jvmArgs);	
						}
					}
					if (mainClass) {
						if (RegSetValueEx(
							hKeyVer,
							REG_V_ENTRY_POINT,
							0,
							REG_SZ,
							(const BYTE* )mainClass,
							_tcslen(mainClass)+sizeof TCHAR 
							) == ERROR_SUCCESS) {
							printf("Set main class to %s.\n", mainClass);	
						}
					} else {
						if (RegDeleteKey(hKeyVer,
							REG_V_ENTRY_POINT)  == ERROR_SUCCESS) 
							printf("Default main class used.");					
					}
					RegCloseKey(hKeyVer);
				}
				RegCloseKey(hKey);
			}
		} else {
			fprintf(stderr, "Cannot create config info in the Registry.");
		}
    } else {
		DWORD err = GetLastError();
		char *msg = getErrorMsg(err, serviceName);
		if (msg == 0) {
			fprintf(stderr, 
				"Cannot create service %s: unrecognized error %dL\n", 
				serviceName, err);
		} else {
			fprintf(stderr, "Cannot create service %s: %s\n", 
				serviceName, msg);
		}
		return;
    }
    CloseServiceHandle(hService);
}
示例#19
0
static void setperusersecvalues_test(void)
{
    PERUSERSECTION peruser;
    HRESULT hr;
    HKEY guid;

    lstrcpy(peruser.szDispName, "displayname");
    lstrcpy(peruser.szLocale, "locale");
    lstrcpy(peruser.szStub, "stub");
    lstrcpy(peruser.szVersion, "1,1,1,1");
    lstrcpy(peruser.szCompID, "compid");
    peruser.dwIsInstalled = 1;
    peruser.bRollback = FALSE;

    /* try a NULL pPerUser */
    if (0)
    {
        /* This crashes on systems with IE7 */
        hr = pSetPerUserSecValues(NULL);
        todo_wine
        ok(hr == S_OK, "Expected S_OK, got %d\n", hr);
        ok(!OPEN_GUID_KEY(), "Expected guid key to not exist\n");
    }

    /* at the very least, szGUID must be valid */
    peruser.szGUID[0] = '\0';
    hr = pSetPerUserSecValues(&peruser);
    ok(hr == S_OK, "Expected S_OK, got %d\n", hr);
    ok(!OPEN_GUID_KEY(), "Expected guid key to not exist\n");

    /* set initial values */
    lstrcpy(peruser.szGUID, "guid");
    hr = pSetPerUserSecValues(&peruser);
    if (hr == E_FAIL)
    {
        skip("SetPerUserSecValues is broken\n");
        return;
    }
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(OPEN_GUID_KEY(), "Expected guid key to exist\n");
    ok(check_reg_str(guid, NULL, "displayname"), "Expected displayname\n");
    ok(check_reg_str(guid, "ComponentID", "compid"), "Expected compid\n");
    ok(check_reg_str(guid, "Locale", "locale"), "Expected locale\n");
    ok(check_reg_str(guid, "StubPath", "stub"), "Expected stub\n");
    ok(check_reg_str(guid, "Version", "1,1,1,1"), "Expected 1,1,1,1\n");
    ok(check_reg_dword(guid, "IsInstalled", 1), "Expected 1\n");
    ok(!REG_VAL_EXISTS(guid, "OldDisplayName"), "Expected OldDisplayName to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "OldLocale"), "Expected OldLocale to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "OldStubPath"), "Expected OldStubPath to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "OldVersion"), "Expected OldVersion to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "RealStubPath"), "Expected RealStubPath to not exist\n");

    /* raise the version, but bRollback is FALSE, so vals not saved */
    lstrcpy(peruser.szVersion, "2,1,1,1");
    hr = pSetPerUserSecValues(&peruser);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(check_reg_str(guid, NULL, "displayname"), "Expected displayname\n");
    ok(check_reg_str(guid, "ComponentID", "compid"), "Expected compid\n");
    ok(check_reg_str(guid, "Locale", "locale"), "Expected locale\n");
    ok(check_reg_str(guid, "StubPath", "stub"), "Expected stub\n");
    ok(check_reg_str(guid, "Version", "2,1,1,1"), "Expected 2,1,1,1\n");
    ok(check_reg_dword(guid, "IsInstalled", 1), "Expected 1\n");
    ok(!REG_VAL_EXISTS(guid, "OldDisplayName"), "Expected OldDisplayName to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "OldLocale"), "Expected OldLocale to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "OldStubPath"), "Expected OldStubPath to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "OldVersion"), "Expected OldVersion to not exist\n");
    ok(!REG_VAL_EXISTS(guid, "RealStubPath"), "Expected RealStubPath to not exist\n");

    /* raise the version again, bRollback is TRUE so vals are saved */
    peruser.bRollback = TRUE;
    lstrcpy(peruser.szVersion, "3,1,1,1");
    hr = pSetPerUserSecValues(&peruser);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(check_reg_str(guid, NULL, "displayname"), "Expected displayname\n");
    ok(check_reg_str(guid, "ComponentID", "compid"), "Expected compid\n");
    ok(check_reg_str(guid, "Locale", "locale"), "Expected locale\n");
    ok(check_reg_dword(guid, "IsInstalled", 1), "Expected 1\n");
    ok(check_reg_str(guid, "Version", "3,1,1,1"), "Expected 3,1,1,1\n");
    todo_wine
    {
        ok(check_reg_str(guid, "OldDisplayName", "displayname"), "Expected displayname\n");
        ok(check_reg_str(guid, "OldLocale", "locale"), "Expected locale\n");
        ok(check_reg_str(guid, "RealStubPath", "stub"), "Expected stub\n");
        ok(check_reg_str(guid, "OldStubPath", "stub"), "Expected stub\n");
        ok(check_reg_str(guid, "OldVersion", "2,1,1,1"), "Expected 2,1,1,1\n");
        ok(check_reg_str(guid, "StubPath",
           "rundll32.exe advpack.dll,UserInstStubWrapper guid"),
           "Expected real stub\n");
    }

    RegDeleteKey(HKEY_LOCAL_MACHINE, GUID_KEY);
}
示例#20
0
//
// _RunRegKeysWorker
//
void StartupRunner::_RunRegKeysWorker(HKEY hkParent,
                                      LPCTSTR ptzSubKey, DWORD dwFlags)
{
    REGSAM samDesired = MAXIMUM_ALLOWED;

    if (dwFlags & ERK_WIN64_KEY32)
    {
        samDesired |= KEY_WOW64_32KEY;
    }
    
    if (dwFlags & ERK_WIN64_KEY64)
    {
        samDesired |= KEY_WOW64_64KEY;
    }

    HKEY hkey = NULL;

    LONG lResult = RegOpenKeyEx(hkParent, ptzSubKey, 0, samDesired, &hkey);

    if (lResult == ERROR_SUCCESS)
    {
        //
        // Run the key itself
        //
        for (DWORD dwLoop = 0; ; ++dwLoop)
        {
            TCHAR szName[MAX_PATH] = { 0 };
            TCHAR szValue[MAX_LINE_LENGTH] = { 0 };

            DWORD cchName = COUNTOF(szName);
            DWORD cbValue = sizeof(szValue);
            DWORD dwType;

            lResult = RegEnumValue(hkey, dwLoop, szName, &cchName,
                NULL, &dwType, (LPBYTE)szValue, &cbValue);

            if (lResult == ERROR_MORE_DATA)
            {
                // tzNameBuffer too small?
                continue;
            }
            else if (lResult == ERROR_SUCCESS)
            {
                if ((dwType == REG_SZ) || (dwType == REG_EXPAND_SZ))
                {
                    if (szValue[0])
                    {
                        _SpawnProcess(szValue, dwFlags);
                    }

                    if ((dwFlags & ERK_DELETE) && (szName[0] != _T('!')))
                    {
                        if (RegDeleteValue(hkey, szName) == ERROR_SUCCESS)
                        {
                            --dwLoop;
                        }
                    }
                }
            }
            else
            {
                break;
            }
        }

        //
        // Run subkeys as well?
        //
        if (dwFlags & ERK_RUNSUBKEYS)
        {
            dwFlags &= ~(ERK_RUNSUBKEYS);

            for (DWORD dwLoop = 0; ; ++dwLoop)
            {
                TCHAR szName[MAX_PATH] = { 0 };

                LONG lResult = RegEnumKey(
                    hkey, dwLoop, szName, COUNTOF(szName));

                if (lResult == ERROR_MORE_DATA)
                {
                    // szName too small?
                    continue;
                }
                else if (lResult == ERROR_SUCCESS)
                {
                    _RunRegKeys(hkey, szName, dwFlags);

                    if (dwFlags & ERK_DELETE)
                    {
                        if (RegDeleteKey(hkey, szName) == ERROR_SUCCESS)
                        {
                            --dwLoop;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }

        RegCloseKey(hkey);
    }
}
示例#21
0
int ExecuteEntry(HANDLE hFile, int offset, entry *thisentry)
{
  static TCHAR buf[MAX_PATH], buf2[MAX_PATH], tmpbuf[MAX_PATH];
  if (skip && thisentry->which != 15) return 0;
  switch (thisentry->which)
  {
    case 0: // set output directory
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        if (!buf[0]) 
        {
          _tcscpy(state_output_directory,state_install_directory);
        }
        else 
        {
          if (process_string(state_output_directory,buf,state_install_directory))
            _tcscpy(state_output_directory,state_install_directory);
        }
        log_printf3("SetOutPath: \"%s\"->\"%s\"\n",buf,state_output_directory);
		{
			INT32 args[] = { (INT32)state_output_directory };
			GETRESOURCE2(tmpbuf, JAVAWS_STATUS_OUTDIR, args);
			update_status_text(tmpbuf);
		}
        recursive_create_directory(state_output_directory);
        return 0;
      }
      log_printf("SetOutPath: INSTALLER CORRUPTED\n");
    break;
    case 1: // extract file
      {
	TCHAR tempFile[MAX_PATH];
	int queueForRebootFlag = 0;
        int overwriteflag=thisentry->offsets[0];
        LPTSTR p;
        _tcscpy(buf,state_output_directory);
        p=buf; while (*p) p=CharNext(p); if (p == buf || (CharPrev(buf,p))[0]!=_T('\\')) _tcscat(buf,_T("\\"));

        if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],buf2,MAX_PATH))
        {
          HANDLE hOut;
          int ret;
          log_printf3("File: overwriteflag=%d, name=\"%s\"\n",overwriteflag,buf2);
          _tcscat(buf,buf2);
_tryagain:
          if ((overwriteflag&3)==0)
          {
            int attr=GetFileAttributes(buf);
            if (attr & FILE_ATTRIBUTE_READONLY)
              SetFileAttributes(buf,attr^FILE_ATTRIBUTE_READONLY);
          }
          hOut=CreateFile(buf,GENERIC_WRITE,0,NULL,(overwriteflag&1)?CREATE_NEW:CREATE_ALWAYS,0,NULL);
          if (hOut == INVALID_HANDLE_VALUE)
          {
            if (overwriteflag&3) 
            {
	      INT32 args[] = { (INT32)buf };
	      GETRESOURCE2(tmpbuf, JAVAWS_STATUS_SKIPPED, args);
	      update_status_text(tmpbuf);
              log_printf3("File: skipping: \"%s\" (overwriteflag=%d)\n",buf,overwriteflag); 
              return 0;
            }
            log_printf2("File: error creating \"%s\"\n",buf);
	    {
	      INT32 args[] = { (INT32)buf };
	      GETRESOURCE2(tmpbuf, JAVAWS_ERROR_OPENWRITE, args);
	      wsprintf(buf2, _T("%s"), tmpbuf);
            }

	    /* If we're not in silent mode then tell the user up front that */
	    /* the file is locked.  Otherwise (silent mode), queue the file */
	    /* for copy on next reboot.                                     */
	    if (noisy) {
	      switch (MessageBox(g_hwnd,buf2,g_caption,MB_ABORTRETRYIGNORE|MB_ICONSTOP))
		{
		case IDABORT:
		  log_printf("File: on error, user selected abort.\n");
		  {
		    INT32 args[]={ (INT32)buf };
		    GETRESOURCE2(tmpbuf, JAVAWS_ERROR_ABORTWRITE, args);
		    update_status_text(tmpbuf);
		  }
		  return -2;
		case IDRETRY:
		  log_printf("File: on error, user selected retry.\n"); 
		  goto _tryagain;
		case IDIGNORE:
		  log_printf("File: on error, user selected cancel.\n"); 
		  return 0;
		}
	    } else {
	      /* try to queue the file for copy on reboot */	      
	      GetTempFileName(g_tempdir, "jws", 0, tempFile);
	      hOut=CreateFile(tempFile,GENERIC_WRITE,0,NULL,(overwriteflag&1)?CREATE_NEW:CREATE_ALWAYS,0,NULL);
	      if (hOut == INVALID_HANDLE_VALUE) return 0;
	      queueForRebootFlag = 1;
	    }
          }
	  {
	    INT32 args[] = { (INT32)buf };
	    GETRESOURCE2(tmpbuf, JAVAWS_STATUS_EXTRACT, args);
            update_status_text(tmpbuf);
	  }
          ret=GetCompressedDataFromDataBlock(hFile,offset+thisentry->offsets[2],hOut);
	  
          log_printf3("File: wrote %d to \"%s\"\n",ret,buf);

          CloseHandle(hOut);

          if (ret >= 0) {
	    if (queueForRebootFlag == 1) {
	      TCHAR winini[MAX_PATH];
	      TCHAR shortname[MAX_PATH];
	      TCHAR rebootFlagFile[MAX_PATH];
	      int len;
	      _tcscpy(rebootFlagFile, g_tempdir);
	      _tcscat(rebootFlagFile, JAVAWS_REBOOT_FILENAME);

	      if (IsRunningOnNT4() || IsRunningOn2000XP()) {
		MoveFileEx(tempFile, buf, MOVEFILE_DELAY_UNTIL_REBOOT);
		MoveFileEx(rebootFlagFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
	      } else {
		/* queue for copy on boot; tempFile is the file to be copied */
		/* buf holds the target filename that was locked previously. */
		GetWindowsDirectory(winini, MAX_PATH);
		/* append a trailing backslash if necessary */
		len = _tcslen(winini);
		if (winini[len - 1] != '\\') {
		  winini[len] = '\\';
		  winini[len+1] = 0;
		}
		_tcscat(winini, "WININIT.INI");
		/* write to the wininit.ini file to queue the file for copy on */
		/* reboot.                                                     */
		GetShortPathName(buf, shortname, MAX_PATH);
		WritePrivateProfileString("rename", shortname, tempFile, winini);
		
		/* write the wininit.ini file to tell Windows to delete the  */
		/* reboot flag file after it reboots                         */
		WritePrivateProfileString("rename", "NUL", rebootFlagFile,
					  winini);
	      }
	      /* write the reboot flag file                                */
	      WritePrivateProfileString(JAVAWS_APPLICATION_NAME,
					JAVAWS_REBOOT_KEY,
					"1",
					rebootFlagFile);
	      state_reboot_needed = 1;
	    }
	    return ret;
	  }
          if (ret == -3 || ret == -6)
          {
            log_printf2("File: INSTALLER CORRUPTED (gcdfdb:%d)\n",ret);          
            goto installer_corrupted;
          }
          else
          {
            DeleteFile(buf);
            log_printf("File: error writing. deleted.\n");
            return -2;
          }

        }
        log_printf("File: INSTALLER CORRUPTED\n");
      }
    break;
    case 2: // execute program
      {
        PROCESS_INFORMATION ProcInfo={0,};
        STARTUPINFO StartUp={sizeof(STARTUPINFO),};
	int disabled = 0;
        if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf2,sizeof(buf2)))
        {
          log_printf2("Exec: command=\"%s\"\n",buf2);
          if (process_string(buf,buf2,state_install_directory)) _tcscpy(buf,buf2);
		  {
			  INT32 args[] = { (INT32)buf };
			  GETRESOURCE2(tmpbuf, JAVAWS_STATUS_EXECUTE, args);
			  update_status_text(tmpbuf);
		  }
		  if (IsWindowEnabled(GetDlgItem(g_hwnd,IDOK))!=0) {
		    /* if Next button is already disabled, don't disable */
                    /* and re-enable it. (bug 4624948) */
		    EnableWindow(GetDlgItem(g_hwnd,IDOK), 0);
                    disabled = 1;
                  }
          if (CreateProcess( NULL, buf, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, state_output_directory, &StartUp, &ProcInfo) )
          {
            log_printf2("Exec: success (\"%s\")\n",buf);
            if (NULL != ProcInfo.hThread) CloseHandle( ProcInfo.hThread );
            if (NULL != ProcInfo.hProcess)
            {
              if (thisentry->offsets[1]==1) 
              {
                WaitForSingleObject(ProcInfo.hProcess,INFINITE);
                ShowWindow(g_hwnd,SW_HIDE);
                ShowWindow(g_hwnd,SW_SHOW);
                InvalidateRect(g_hwnd,NULL,TRUE);
                UpdateWindow(g_hwnd);
                while (1)
                {
                  MSG msg;
                  if (!PeekMessage(&msg,g_hwnd,WM_PAINT,WM_PAINT,PM_REMOVE)) break;
                  DispatchMessage(&msg);
                }      
              }
			  {
				  DWORD exitcode;
				  if (!GetExitCodeProcess(ProcInfo.hProcess, (LPDWORD)&exitcode)) {
					  log_printf("Exec: failed getting exit code\n");
					  state_return_value = STATE_RETURN_INVALID;
				  } else {
					  state_return_value = exitcode;
				  }
			  }
              CloseHandle( ProcInfo.hProcess );
            }
          }
          else { log_printf2("Exec: failed createprocess (\"%s\")\n",buf); }
	  if (disabled != 0) {
	    EnableWindow(GetDlgItem(g_hwnd,IDOK), 1);
	  }
          return 0;
        }
        log_printf("Exec: INSTALLER CORRUPTED\n"); 
      }
    break;
    case 3: // register DLL
#ifdef NSIS_SUPPORT_ACTIVEXREG
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf2,sizeof(buf2)))
      {
        HRESULT hr;
        hr=OleInitialize(NULL);
        if (hr == S_OK || hr == S_FALSE)
        {
          if (!process_string(buf,buf2,state_install_directory)) 
          {
            HANDLE h;
            int is_uninstall=0;
            if (buf[0] == _T('-') && buf[1] == _T(' '))
              is_uninstall=2;
            
            h=LoadLibrary(buf+is_uninstall);
            if (h)
            {
              FARPROC funke = GetProcAddress(h,is_uninstall?"DllUnregisterServer":"DllRegisterServer");
              if (funke) 
              {
                if (!is_uninstall) {
					INT32 args[] = { (INT32)buf };
					GETRESOURCE2(tmpbuf, JAVAWS_STATUS_REGDLL, args);
					update_status_text(tmpbuf);
				}
                else {
					INT32 args[] = { (INT32)buf+is_uninstall };
					GETRESOURCE2(tmpbuf, JAVAWS_STATUS_UNREGDLL, args);
					update_status_text(tmpbuf);
				}
                funke();
              }
              else if (!is_uninstall)
              {
				INT32 args[] = { (INT32)buf };
				GETRESOURCE2(buf2,JAVAWS_ERROR_REGDLL,args);
                if (noisy) MessageBox(g_hwnd,buf2,g_caption,MB_OK);
              }
              FreeModule(h);
            }
            else if (!is_uninstall)
            {
			  INT32 args[] = { (INT32)buf };
			  GETRESOURCE2(buf2,JAVAWS_ERROR_REGDLLU, args);
              if (noisy) MessageBox(g_hwnd,buf2,g_caption,MB_OK);
            }
          }
          if (hr == S_OK) OleUninitialize();
        }
        else
        {
		  INT32 args[] = { (INT32)buf };
		  GETRESOURCE2(buf2,JAVAWS_ERROR_OLEINIT,args);
          if (noisy) MessageBox(g_hwnd,buf2,g_caption,MB_OK);
        }
        return 0;
      }
#endif
    break;
    case 4: // install netscape plug-in
    case 11:
#ifdef NSIS_SUPPORT_NETSCAPEPLUGINS
#warning NSIS_SUPPORT_NETSCAPEPLUGINS defined, this section NOT internationalized, proceed with caution!
if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf2,sizeof(buf2)))
      {
        HKEY hKey;
		    if ( RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Netscape\\Netscape Navigator",0,KEY_READ,&hKey) == ERROR_SUCCESS)
		    {
          int x=0;
          while (1)
          {
            FILETIME pft;
            char name[256];
            HKEY subKey;
            DWORD lname=sizeof(name);
            if (RegEnumKeyEx(hKey,x++,name,&lname,NULL,NULL,NULL,&pft) != ERROR_SUCCESS) break;
            mini_strcat(name,"\\Main");
            if (RegOpenKeyEx(hKey,name,0,KEY_READ,&subKey) == ERROR_SUCCESS)
            {
			        int l = sizeof(buf);
			        int t=REG_SZ;
			        if (RegQueryValueEx(subKey,"Plugins Directory",NULL,&t,buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
			        {
				        mini_strcat(buf,"\\");
                mini_strcat(buf,buf2);
                {
                  HANDLE hOut=INVALID_HANDLE_VALUE;
                  retryagainns:
                  {
                    int attr=GetFileAttributes(buf);
                    if (attr & FILE_ATTRIBUTE_READONLY)
                      SetFileAttributes(buf,attr^FILE_ATTRIBUTE_READONLY);
                  }
                  
                  hOut=CreateFile(buf,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL);                  
                  if (thisentry->which != 4)
                  {
                    if (hOut != INVALID_HANDLE_VALUE)
                    {
                      CloseHandle(hOut);
                      hOut=(HANDLE)1;
                      if (!DeleteFile(buf))
                      {
                        log_printf2("InstNSPlug: error removing: %s\n",buf);
                        hOut=INVALID_HANDLE_VALUE;
                      }
                      else
                        log_printf2("InstNSPlug: removed: %s\n",buf);
                    }
                    else
                      hOut=(HANDLE)1;

                  }
                  
                  if (hOut == INVALID_HANDLE_VALUE)
                  {
                    if (MessageBox(g_hwnd,"Error accessing Netscape plug-in.\r\nMake sure all windows of Netscape are closed.\r\nHit Retry to try again, Cancel to skip",g_caption,MB_RETRYCANCEL|MB_APPLMODAL|MB_TOPMOST)==IDOK) goto retryagainns;
                    log_printf2("InstNSPlug: install to %s aborted by user.\n",buf);
                  }

                  if (hOut != INVALID_HANDLE_VALUE && thisentry->which == 4)
                  {
                    int ret=GetCompressedDataFromDataBlock(hFile,offset+thisentry->offsets[1],hOut);

                    CloseHandle(hOut);

                    if (ret<0)
                    {
                      DeleteFile(buf);
                      if (ret==-3)
                      {
                        log_printf("InstNSPlug: INSTALLER CORRUPTED (2)\n");
                        goto installer_corrupted;
                      }
                      log_printf2("InstNSPlug: couldn't write to: %s\n",buf);
                    }
                    else 
                    {
                      update_status_text("installed netscape plug-in: ",buf);
                      log_printf2("InstNSPlug: wrote: %s\n",buf);
                    }
                  }                  
                  else if (thisentry->which == 11)
                  {
                    update_status_text("removed netscape plug-in: ",buf);
                  }
                }
			        }
              RegCloseKey(subKey);
            }
          }
			    RegCloseKey(hKey);
        }
        else
        {
          log_printf("InstNSPlug: Netscape registry settings not found\n");
        }
        return 0;
      }
#endif
      log_printf("InstNSPlug: INSTALLER CORRUPTED\n");
    break;
    case 12:
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],buf,sizeof(buf)))
      {
        int rootkey=thisentry->offsets[0];
        if (thisentry->offsets[2] != -1)
        {
          HKEY hKey;
          if (RegOpenKey((HKEY)rootkey,buf,&hKey) == ERROR_SUCCESS) 
          {
            if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[2],buf2,sizeof(buf2)))
            {
              if (process_string(buf,buf2,state_install_directory)) _tcscpy(buf,buf2);
              RegDeleteValue(hKey,buf);
            }
            RegCloseKey(hKey);
          }
        }
        else
        {
          log_printf3("DeleteRegKey: %d\\%s\n",rootkey,buf);
          RegDeleteKey((HKEY)rootkey,buf);
        }
        return 0;
      }
    break;
    case 5: // write registry value
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],buf,sizeof(buf)) &&
          !GetStringFromDataBlock(hFile,offset+thisentry->offsets[2],buf2,sizeof(buf2)))
      {
        int rootkey=thisentry->offsets[0];
        int type=thisentry->offsets[4];
        HKEY hKey;
        if (RegCreateKey((HKEY)rootkey,buf,&hKey) == ERROR_SUCCESS) 
        {
          TCHAR buf4[MAX_PATH];
          if (type == 1)
          {
            if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[3],buf4,sizeof(buf4)))
            {
              TCHAR buf3[MAX_PATH];
              if (process_string(buf3,buf4,state_install_directory)) _tcscpy(buf3,buf4);
              if (process_string(buf4,buf2,state_install_directory)) _tcscpy(buf4,buf2);
              log_printf5("WriteRegStr: set %d\\%s\\%s to %s\n",rootkey,buf,buf4,buf3);
              RegSetValueEx(hKey,buf4,0,REG_SZ,buf3,_tcslen(buf3)+1);
            }
          }
          else if (type == 2)
          {
            if (process_string(buf4,buf2,state_install_directory)) _tcscpy(buf4,buf2);
            log_printf5("WriteRegDword: set %d\\%s\\%s to %d\n",rootkey,buf,buf4,thisentry->offsets[3]);
            RegSetValueEx(hKey,buf4,0,REG_DWORD,(BYTE*)&thisentry->offsets[3],4);
          }
          else if (type == 3)
          {
            BYTE data[512];
            int len=GetCompressedDataFromDataBlockToMemory(hFile, 
              offset+thisentry->offsets[3], data,sizeof(data));

            if (len >= 0)
            {
              if (process_string(buf4,buf2,state_install_directory)) _tcscpy(buf4,buf2);
              RegSetValueEx(hKey,buf4,0,REG_BINARY,data,len);
            }
            log_printf5("WriteRegBin: set %d\\%s\\%s with %d bytes\n",rootkey,buf,buf4,len);

          }
          RegCloseKey(hKey);
        }
        else { log_printf3("WriteReg: error creating key %d\\%s\n",rootkey,buf); }
        if (type > 0 && type < 4) return 0;
      }
      log_printf("WriteReg: INSTALLER CORRUPTED\n");
    break;
    case 6:
      {
        TCHAR section[MAX_PATH];
        TCHAR name[MAX_PATH];
        TCHAR t[MAX_PATH];
        TCHAR t2[MAX_PATH];
        if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],section,sizeof(section)) &&
            !GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],name,sizeof(name)) &&
            !GetStringFromDataBlock(hFile,offset+thisentry->offsets[2],buf,sizeof(buf)) &&
            !GetStringFromDataBlock(hFile,offset+thisentry->offsets[3],buf2,sizeof(buf2)))
        {
          if (process_string(t,buf2,state_install_directory)) _tcscpy(t,buf2);
          if (process_string(buf2,buf,state_install_directory)) _tcscpy(buf2,buf);
          if (process_string(t2,name,state_install_directory)) _tcscpy(t2,name);
          if (process_string(buf,section,state_install_directory)) _tcscpy(buf,section);
          log_printf5("WriteINIStr: wrote [%s] %s=%s in %s\n",buf,t2,buf2,t);
          WritePrivateProfileString(buf,t2,buf2,t);
          return 0;
        }
        log_printf("WriteINIStr: INSTALLER CORRUPTED\n");
      }
    break;
    case 7:
#ifdef NSIS_SUPPORT_CREATESHORTCUT
      {
        TCHAR scf[MAX_PATH],iconfile[MAX_PATH], parms[MAX_PATH];
        int iindex=thisentry->offsets[4];
        if (GetStringFromDataBlock(hFile,offset+thisentry->offsets[3],buf,sizeof(buf))) break;
        if (process_string(iconfile,buf,state_install_directory)) break;
        if (GetStringFromDataBlock(hFile,offset+thisentry->offsets[2],buf,sizeof(buf))) break;
        if (process_string(parms,buf,state_install_directory)) break;
        if (GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],buf,sizeof(buf))) break;
        if (process_string(buf2,buf,state_install_directory)) break;
        if (GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf))) break;
        if (process_string(scf,buf,state_install_directory)) break;

        log_printf6("CreateShortCut: out: \"%s\", in: \"%s %s\", icon: %s,%d\n",scf,buf2,parms,iconfile,iindex); 
        CreateShortCut(g_hwnd, scf, iconfile[0]?iconfile:NULL, iindex, buf2, parms[0]?parms:NULL,state_output_directory);
		{
			INT32 args[] = { (INT32)scf };
			GETRESOURCE2(tmpbuf, JAVAWS_STATUS_CREATESHORTCUT, args);
			update_status_text(tmpbuf);
		}
        return 0;
      }
#endif
      log_printf("CreateShortCut: INSTALLER CORRUPTED\n"); 
    break;
    case 8:
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        log_printf2("Delete: \"%s\"\n",buf); 
        if (!process_string(buf2,buf,state_install_directory))
        {
		      HANDLE h;
		      WIN32_FIND_DATA fd;
          LPTSTR p=buf;
          _tcscpy(buf,buf2);
          while (*p) p=CharNext(p);
          while (p > buf && *p != _T('\\')) p=CharPrev(buf, p);
          *p=_T('\0');
    		  h=FindFirstFile(buf2,&fd);
		      if (h != INVALID_HANDLE_VALUE)
		      {
            do
            {
			        if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
              {
                wsprintf(buf2,_T("%s\\%s"),buf,fd.cFileName);
                log_printf2("Delete: DeleteFile(\"%s\")\n",buf2);
				{
					INT32 args[] = { (INT32)buf2 };
					GETRESOURCE2(tmpbuf, JAVAWS_STATUS_DELETEFILE, args);
					update_status_text(tmpbuf);
				}
                DeleteFile(buf2);
              }
            } while (FindNextFile(h,&fd));
			      FindClose(h);
    		  } 
        }
        else { log_printf("Delete: error parsing parameter\n"); }
        return 0;
      }
      log_printf("Delete: INSTALLER CORRUPTED\n"); 
    break;
    case 9:
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],buf,sizeof(buf)))
      {
        int whattodo=thisentry->offsets[0];
        log_printf3("FindWindow: checking for window class: %s . whattodo=%d\n",buf,whattodo); 
        if (whattodo==2)
        {
          if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[2],buf2,sizeof(buf2)))
          {
            while (FindWindow(buf,NULL))
            {
				int r=noisy ? MessageBox(g_hwnd,buf2,g_caption,MB_ABORTRETRYIGNORE) : IDIGNORE;
              if (r == IDABORT) 
              {
                log_printf("FindWindow: user abort\n");
				{
					INT32 args[] = { (INT32)buf };
					GETRESOURCE2(tmpbuf, JAVAWS_STATUS_ABORTED, args);
					update_status_text(tmpbuf);
				}
                return -2;
              }
              if (r == IDIGNORE) 
              {
                log_printf("FindWindow: user ignore\n"); 
                break;
              }
            }
          }
          else
          {
            log_printf("FindWindow: INSTALLER CORRUPTED\n"); 
            break;
          }
        }
        else if (whattodo==1)
        {
          HWND hwnd=FindWindow(buf,NULL);
          if (hwnd) 
          {
            log_printf2("FindWindow: closing window (%s) (one-shot)\n",buf); 
            SendMessage(hwnd,WM_CLOSE,0,0);
          }
        }
        else if (whattodo==0)
        {
          HWND hwnd;
          int r=8;
          while ((hwnd=FindWindow(buf,NULL)))
          {
            SendMessage(hwnd,WM_CLOSE,0,0);
            Sleep(250);
            if (r--<0) 
            {
              break;
            }
          }
          if (!hwnd)
          {
            log_printf3("FindWindow: closed window (%s) (multi-try). %d\n",buf,r); 
          }
          else
          {
            log_printf2("FindWindow: gave up closing window (%s)\n",buf); 
          }
        }
        return 0;
      }
      log_printf("FindWindow: INSTALLER CORRUPTED\n"); 
    break;
    case 10: // MessageBox      
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],buf,sizeof(buf)))
      {
	if (!process_string(buf2, buf, state_install_directory)) {
	  log_printf3("MessageBox: %d,\"%s\"\n",thisentry->offsets[0],buf2);
	  if (noisy) {
	    DWORD ret=MessageBox(g_hwnd,buf2,g_caption,thisentry->offsets[0]);
	    if ( ret == IDNO || ret == IDCANCEL) {
	      state_return_value=0;
	    } else {
	      state_return_value=1;
	    }
	  }
	} else { log_printf("MessageBox: error parsing parameter\n"); }
	return 0;
      }
    log_printf("MessageBox: INSTALLER CORRUPTED\n"); 
    break;
   case 13: //RMDir
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        log_printf2("RMDir: \"%s\"\n",buf); 
        if (!process_string(buf2,buf,state_install_directory))
        {
          log_printf2("RMDir: RemoveDirectory(\"%s\")\n",buf2);
		  {
			  INT32 args[] = { (INT32)buf };
			  GETRESOURCE2(tmpbuf, JAVAWS_STATUS_REMOVEDIR, args);
			  update_status_text(tmpbuf);
		  }
	  RemoveDirectory(buf2);
        }
        else { log_printf("RMDir: error parsing parameter\n"); }
        return 0;
      }
      log_printf("RMDir: INSTALLER CORRUPTED\n"); 
    break;
   case 19:
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        log_printf2("RMDirRecursive: \"%s\"\n",buf); 
        if (!process_string(buf2,buf,state_install_directory))
        {
		  SHFILEOPSTRUCT fos;
          log_printf2("RMDirRecursive: RemoveDirectory(\"%s\")\n",buf2);
		  {
			  INT32 args[] = { (INT32)buf };
			  GETRESOURCE2(tmpbuf, JAVAWS_STATUS_REMOVEDIR, args);
			  update_status_text(tmpbuf);
		  }
		  buf2[_tcslen(buf2)]=0;
		  buf2[_tcslen(buf2)+1]=0;
		  if (GetFileAttributes(buf2)!=0xffffffff) {
		    // Only do SHFileOperation if file exists
		    fos.hwnd = g_hwnd;
		    fos.wFunc = FO_DELETE;
		    fos.pFrom = buf2;
		    fos.pTo = NULL;
		    fos.fFlags = FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMATION;
		    fos.hNameMappings = NULL;
		    fos.lpszProgressTitle = NULL;
		    SHFileOperation(&fos);
		  }
        }
        else { log_printf("RMDirRecursive: error parsing parameter\n"); }
        return 0;
      }
      log_printf("RMDirRecursive: INSTALLER CORRUPTED\n"); 
    break;
   case 14: // If
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        log_printf2("If: \"%s\"\n",buf); 
        if (!process_string(buf2,buf,state_install_directory))
        {
		  int  ret=0;
          log_printf2("If(variables evaluated): (\"%s\")\n",buf2);
		  if (!(ret=evalStr(buf2))) {
			  skip=1;
			  return 0;
		  }
		}
        else { log_printf("If: error parsing parameter\n"); }
        return 0;
      }
      log_printf("If: INSTALLER CORRUPTED\n"); 
    break;
   case 15: //EndIf
	   skip=0;
	   return 0;
	break;
   case 16: //RebootBox
	   if (noisy) {
			GETRESOURCE(buf,JAVAWS_MESSAGE_REBOOT);
			if (MessageBox(g_hwnd,buf,g_caption,MB_YESNO|MB_ICONWARNING)==IDYES) {
				if (!ExitWindowsEx(EWX_REBOOT, (DWORD)0)) {
					GETRESOURCE(buf,JAVAWS_ERROR_EXITWINDOWS);
					if (noisy) MessageBox(g_hwnd,buf,g_caption,MB_OK);
				}

			}
	   }
	   return 0;
	break;
   case 17: //Browser
	  if (!noisy) return 0;
      if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        log_printf2("Browser: \"%s\"\n",buf); 
        if (!process_string(buf2,buf,state_install_directory))
        {	
	  ShellExecute(g_hwnd, "open", buf2, "-new", state_install_directory, 0);
	}
        else { log_printf("Browser: error parsing parameter\n"); }
        return 0;
      }
      log_printf("Browser: INSTALLER CORRUPTED\n"); 
    break;
   case 18:  // AltDirBox
	   {
		   TCHAR name[MAX_PATH];
		   TCHAR buf3[MAX_PATH];
		   TCHAR buf4[MAX_PATH];
		   if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)) &&
			   !GetStringFromDataBlock(hFile,offset+thisentry->offsets[1],name,sizeof(name)) &&
			   !GetStringFromDataBlock(hFile,offset+thisentry->offsets[2],buf3,sizeof(buf3)))
		   {
			   if (!process_string(tmpbuf,buf,state_install_directory) &&
				   !process_string(buf4,buf3,state_install_directory) &&
				   !process_string(buf2,name,state_install_directory))
			   {
				   _tcscpy(state_alt_directory,tmpbuf);
				   _tcscpy(state_alt_name, buf2);
				   _tcscpy(state_alt_version,buf4);
				   state_return_value = noisy ? DialogBox(g_hInstance,MAKEINTRESOURCE(IDD_DIR1),g_hwnd,DirProc2): 1;
			   }
			   return 0;
		   }
	   }
	break;
   case 41:
	   if (!GetStringFromDataBlock(hFile,offset+thisentry->offsets[0],buf,sizeof(buf)))
      {
        log_printf2("MKDir: \"%s\"\n",buf); 
        if (!process_string(buf2,buf,state_install_directory))
        {
          log_printf2("MKDir: recursive_create_directory(\"%s\")\n",buf2);
		  {
			  INT32 args[] = { (INT32)buf };
			  GETRESOURCE2(tmpbuf, JAVAWS_STATUS_MAKEDIR, args);
			  update_status_text(tmpbuf);
		  }
          recursive_create_directory(buf2);
        }
        else { log_printf("RMDir: error parsing parameter\n"); }
        return 0;
      }
      log_printf("MKDir: INSTALLER CORRUPTED\n"); 
    break;
  }
installer_corrupted:
  {
     GETRESOURCE(tmpbuf, JAVAWS_ERROR_INSTCORRUPT);
     if (noisy) MessageBox(g_hwnd,tmpbuf,g_caption,MB_OK|MB_ICONSTOP);
  }
  return -1;
}
示例#22
0
文件: service.c 项目: bjoern-r/brickd
int service_uninstall(void) {
	SC_HANDLE service_control_manager;
	int rc;
	SC_HANDLE service;
	SERVICE_STATUS service_status;
	int tries = 0;

	// open service control manager
	service_control_manager = OpenSCManager(0, 0, SC_MANAGER_CONNECT);

	if (service_control_manager == NULL) {
		rc = ERRNO_WINAPI_OFFSET + GetLastError();

		fprintf(stderr, "Could not open service control manager: %s (%d)\n",
		        get_errno_name(rc), rc);

		return -1;
	}

	// open service
	service = OpenService(service_control_manager, _service_name,
	                      SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE);

	if (service == NULL) {
		rc = GetLastError();

		if (rc == ERROR_SERVICE_DOES_NOT_EXIST) {
			fprintf(stderr, "'%s' service is not installed\n", _service_name);

			CloseServiceHandle(service_control_manager);

			return -1;
		}

		rc += ERRNO_WINAPI_OFFSET;

		fprintf(stderr, "Could not open '%s' service: %s (%d)\n",
		        _service_name, get_errno_name(rc), rc);

		CloseServiceHandle(service_control_manager);

		return -1;
	}

	// get service status
	if (!QueryServiceStatus(service, &service_status)) {
		rc = ERRNO_WINAPI_OFFSET + GetLastError();

		fprintf(stderr, "Could not query status of '%s' service: %s (%d)\n",
		        _service_name, get_errno_name(rc), rc);

		CloseServiceHandle(service);
		CloseServiceHandle(service_control_manager);

		return -1;
	}

	// stop service
	if (service_status.dwCurrentState != SERVICE_STOPPED) {
		if (!ControlService(service, SERVICE_CONTROL_STOP, &service_status)) {
			rc = ERRNO_WINAPI_OFFSET + GetLastError();

			fprintf(stderr, "Could not send stop control code to '%s' service: %s (%d)\n",
			        _service_name, get_errno_name(rc), rc);

			CloseServiceHandle(service);
			CloseServiceHandle(service_control_manager);

			return -1;
		}

		while (service_status.dwCurrentState != SERVICE_STOPPED && tries < 60) {
			if (!QueryServiceStatus(service, &service_status)) {
				rc = ERRNO_WINAPI_OFFSET + GetLastError();

				fprintf(stderr, "Could not query status of '%s' service: %s (%d)\n",
				        _service_name, get_errno_name(rc), rc);

				CloseServiceHandle(service);
				CloseServiceHandle(service_control_manager);

				return -1;
			}

			Sleep(500);

			++tries;
		}

		if (service_status.dwCurrentState != SERVICE_STOPPED) {
			fprintf(stderr, "Could not stop '%s' service after 30 seconds\n",
			        _service_name);

			CloseServiceHandle(service);
			CloseServiceHandle(service_control_manager);

			return -1;
		}

		printf("Stopped '%s' service\n", _service_name);
	}

	// uninstall service
	if (!DeleteService(service)) {
		rc = ERRNO_WINAPI_OFFSET + GetLastError();

		fprintf(stderr, "Could not uninstall '%s' service: %s (%d)\n",
		        _service_name, get_errno_name(rc), rc);

		CloseServiceHandle(service);
		CloseServiceHandle(service_control_manager);

		return -1;
	}

	printf("Uninstalled '%s' service\n", _service_name);

	CloseServiceHandle(service);
	CloseServiceHandle(service_control_manager);

	// unregister message catalog for event log
	RegDeleteKey(HKEY_LOCAL_MACHINE, _event_log_key_name);

	return 0;
}
示例#23
0
// A helper function that creates a error report for testing
BOOL CreateErrorReport(CString sTmpFolder, CString& sErrorReportName, CString& sMD5Hash)
{
    BOOL bStatus = FALSE;
    CString sReportFolder;
    DWORD dwExitCode = 1;
    WIN32_FIND_DATA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    CString sSearchPattern = sTmpFolder + "\\*.zip";
    CString sMD5FileName;
    FILE* f = NULL;
    TCHAR szHashBuff[256] = _T("");
    HKEY hKey = NULL;
    LONG lResult = -1;
    CString sKeyName = _T("Software\\CrashRpt&&#4216wer\\应用程序名称");
    CString sKeyName2 = _T("HKEY_CURRENT_USER\\") + sKeyName;

    lResult = RegCreateKey(HKEY_CURRENT_USER, sKeyName, &hKey); 
    if(lResult!=ERROR_SUCCESS)
        goto cleanup;

    DWORD dwVal = 12345;
    lResult = RegSetValueEx(hKey, _T("Value$%^!@#&123fer"), 0, REG_DWORD, (LPBYTE)&dwVal, sizeof(DWORD));
    if(lResult!=ERROR_SUCCESS)
        goto cleanup;

    CR_INSTALL_INFOW infoW;
    memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
    infoW.cb = sizeof(CR_INSTALL_INFOW);  
    infoW.pszAppName = L"My& app Name & ' 应用程序名称"; // Use Chineese characters for app name
    // Use appname with restricted XML characters
    infoW.pszAppVersion = L"1.0.0 &<'a应> \"<"; 
    infoW.pszErrorReportSaveDir = sTmpFolder;
    infoW.dwFlags = CR_INST_NO_GUI|CR_INST_DONT_SEND_REPORT|CR_INST_STORE_ZIP_ARCHIVES;  

    int nInstallResult = crInstallW(&infoW);
    if(nInstallResult!=0)
        goto cleanup;

    crAddScreenshot(CR_AS_MAIN_WINDOW);
    crAddPropertyW(L"CustomProp", L"Property Value");
    crAddRegKey(sKeyName2, L"regkey.xml", 0);

    CR_EXCEPTION_INFO ei;
    memset(&ei, 0, sizeof(CR_EXCEPTION_INFO));
    ei.cb = sizeof(ei);
    ei.exctype = CR_SEH_EXCEPTION;
    ei.code = 0x123;

    // Generate error report
    int nGenResult = crGenerateErrorReport(&ei);
    if(nGenResult!=0)
        goto cleanup;

    // Wait until CrashSender process exits
    WaitForSingleObject(ei.hSenderProcess, INFINITE);

    // Check exit code  
    GetExitCodeProcess(ei.hSenderProcess, &dwExitCode);
    if(dwExitCode!=0)
        goto cleanup;

    // Get ZIP name  
    hFind = FindFirstFile(sSearchPattern, &ffd);
    if(hFind==INVALID_HANDLE_VALUE)
        goto cleanup;

    sErrorReportName = sTmpFolder + _T("\\") + CString(ffd.cFileName);

    FindClose(hFind);
    hFind = NULL;

    // Get MD5 name
    sSearchPattern = sTmpFolder + "\\*.md5";
    hFind = FindFirstFile(sSearchPattern, &ffd);
    if(hFind==INVALID_HANDLE_VALUE)
        goto cleanup;

    sMD5FileName = sTmpFolder + _T("\\") + CString(ffd.cFileName);

#if _MSC_VER < 1400
    f = _tfopen(sMD5FileName, _T("rt"));
#else
    _tfopen_s(&f, sMD5FileName, _T("rt"));
#endif
    if(f==NULL)
        goto cleanup;

    TCHAR* szHash = _fgetts(szHashBuff, 256, f);
    if(szHash==NULL)
        goto cleanup;

    sMD5Hash = szHash;

    if(sMD5Hash.GetLength()!=32)
        goto cleanup; // Hash must be 32 characters in length

    bStatus = TRUE;

cleanup:

    crUninstall();

    if(f!=NULL)
        fclose(f);

    if(hFind!=INVALID_HANDLE_VALUE)
        FindClose(hFind);

    if(hKey)    
        RegCloseKey(hKey);

    RegDeleteKey(HKEY_CURRENT_USER, sKeyName);

    return bStatus;
}
示例#24
0
LONG CRegistryKey::DeleteSubkey(const TCHAR *pszSubkeyName)
{
  return RegDeleteKey(m_hKey,pszSubkeyName);
}
示例#25
0
void UnRegisterSourceFilterExtension(const char* Extension)
{
	TCHAR RegistryKeyName[256];	
	wsprintf(RegistryKeyName, "Media Type\\Extensions\\%s", Extension);
	RegDeleteKey(HKEY_CLASSES_ROOT, RegistryKeyName);	
}
示例#26
0
/*-------------------------------------------------------------------------
  ssh_debug_trace_init()
  
  Initialize storing diagnostic messages in the registry.
  
  Arguments:
  reg_path - 2nd argument to DriverEntry(), i.e. registry path to driver
             config under HKLM, as a UNICODE string.
  
  Returns:
  ------------------------------------------------------------------------*/
void
ssh_debug_trace_init(PUNICODE_STRING reg_path)
{
  LONG error;
  HKEY key;
  DWORD type, size, enable, generation;
  char *debug_string = tmp_string_asc;

  /* Open the config subkey. */

  _snwprintf(tmp_subkey, SSH_DEBUG_TRACE_SUBKEY_CHARS, L"%.*s",
             reg_path->Length, (wchar_t *)reg_path->Buffer);
  tmp_subkey[SSH_DEBUG_TRACE_SUBKEY_CHARS - 1] = L'\0';

  error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, tmp_subkey, 0, 0, &key);
  if (error != ERROR_SUCCESS)
    return;

  /* Read the value that enables registry tracing. Stop here if it
     does not exist or is zero. */
  size = sizeof enable;
  error = RegQueryValueEx(key, L"TraceEnable", NULL, &type,
                          (BYTE *)&enable, &size);
  if (error != ERROR_SUCCESS || type != REG_DWORD || enable == 0)
    {
      RegCloseKey(key);
      return;
    }

  /* Read debug level string. Use "0" if it does not exist or is
     zero. */
  size = SSH_DEBUG_TRACE_STRING_CHARS * sizeof tmp_string[0];
  error = RegQueryValueEx(key, L"TraceString", NULL, &type,
                          (BYTE *)tmp_string, &size);
  if (error == ERROR_SUCCESS && type == REG_SZ && size > sizeof tmp_string[0])
    {
      tmp_string[size - 1] = L'\0';
      _snprintf(debug_string, SSH_DEBUG_TRACE_STRING_CHARS, "%ls", tmp_string);
      debug_string[SSH_DEBUG_TRACE_STRING_CHARS - 1] = '\0';
    }
  else
    {
      _snprintf(debug_string, SSH_DEBUG_TRACE_STRING_CHARS, "0");
    }

  /* Read the generation of the last trace and increment/wraparound
     it. Create it if it does not exist (ignoring error). */
  size = sizeof generation;
  error = RegQueryValueEx(key, L"TraceGeneration", NULL, &type,
                          (BYTE *)&generation, &size);

  if (error == ERROR_SUCCESS && type == REG_DWORD)
    {
      generation++;
      if (generation >= SSH_DEBUG_TRACE_GENERATIONS)
        generation = 0;
    }
  else
    {
      generation = 0;
    }

  if (error == ERROR_SUCCESS || error == ERROR_FILE_NOT_FOUND)
    RegSetValueEx(key, L"TraceGeneration", 0, REG_DWORD,
                  (BYTE *)&generation, sizeof generation);

  /* Close key. */
  RegCloseKey(key);

  /* Create/recreate the trace subkey. */
  _snwprintf(ssh_debug_trace_subkey, SSH_DEBUG_TRACE_SUBKEY_CHARS,
             L"%.*s\\Trace\\%02x",
             reg_path->Length, (wchar_t *)reg_path->Buffer,
             (unsigned)generation);
  ssh_debug_trace_subkey[SSH_DEBUG_TRACE_SUBKEY_CHARS - 1] = L'\0';

  /* Create/recreate the trace subkey of the current trace
     generation. Do not enable tracing if this fails. */
  error = RegDeleteKey(HKEY_LOCAL_MACHINE,
                       ssh_debug_trace_subkey);
  if (error == ERROR_SUCCESS || error == ERROR_FILE_NOT_FOUND)
    {
      error = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                             ssh_debug_trace_subkey,
                             0, NULL, 0, 0, NULL, &key, NULL);
      if (error == ERROR_SUCCESS)
        RegCloseKey(key);
    }
  if (error != ERROR_SUCCESS)
    return;

  /* Set the initial debug string and turn on tracing. */
  ssh_debug_set_level_string(debug_string);
  InitializeCriticalSection(&ssh_debug_trace_critsect);
  ssh_debug_trace_entry = 0;
  ssh_debug_trace_enabled = TRUE;
}
示例#27
0
//  Remove registry entries for implemented CLSIDs.
//  As DllUnregisterServer.
HRESULT CComDll::UnregisterServer()
{
    HRESULT	hres = ResultFromScode(E_UNEXPECTED);

    //  Determine our module (dll) path and name.
    char	szModuleName[_MAX_PATH];
    DWORD	dwModuleNameLen;
	 
	dwModuleNameLen = GetModuleFileName(szModuleName, sizeof(szModuleName));
    if (dwModuleNameLen == 0)
        return hres;
    
	// Get the list of CLSIDs
    const CLSID **ppCLSIDs = GetCLSIDs();

    if (ppCLSIDs) {
        const CLSID **ppTraverse = ppCLSIDs;
        char 		  szStringKey[80];

        while (*ppTraverse)    {
			LONG	lSize;
            
			// Get the information into registry key format.
			hres = BuildRegistryCLSIDKey(**ppTraverse, szStringKey);
			if (FAILED(hres))
				break;

            // Figure out if it points to us.
            // Continue if err, as it simply may not exist.
            if (RegQueryValue(HKEY_CLASSES_ROOT, szStringKey, NULL, &lSize) == ERROR_SUCCESS && lSize != 0) {
                LPSTR	lpszValue = NULL;

                //  Allocate a buffer large enough for it.
				lpszValue = (LPSTR)CoTaskMemAlloc(lSize);
                if (!lpszValue)  {
                    hres = ResultFromScode(E_OUTOFMEMORY);
                    break;
                }

                // We do err on not being able to query the value if we got the size
                if (RegQueryValue(HKEY_CLASSES_ROOT, szStringKey, lpszValue, &lSize) != ERROR_SUCCESS) {
                    hres = ResultFromScode(E_UNEXPECTED);
					CoTaskMemFree(lpszValue);
                    break;
                }

                // Only delete if the same; ignore the case
                if (lstrcmpi(lpszValue, szModuleName) == 0) {
                    // Delete the registry key.
                    if (RegDeleteKey(HKEY_CLASSES_ROOT, szStringKey) != ERROR_SUCCESS) {
                        hres = ResultFromScode(/*SELFREG_E_CLASS*/ E_UNEXPECTED);
                        break;
                    }
                }

				// Free the buffer
				CoTaskMemFree(lpszValue);
            }

			// Get the next CLSID
            ppTraverse++;
        }

        // Only if we made it through the loop do we consider this a success
        if (*ppTraverse == NULL)
            hres = NOERROR;

        // Free off the list of CLSIDs
		CoTaskMemFree((LPVOID)ppCLSIDs);
    }

    return hres;
}
示例#28
0
int reg(char *key, char *displayName, char *version, char *path, char *instpath, char *datapath)
{
	HKEY regKey = NULL;
	char *subkey = catstr(KEY_PREFIX, key);
	LONG result;
	DWORD disposition;


	/*
	 * Create or open the appropriate key in the registry
	 */
	result = RegCreateKeyEx(
		HKEY_LOCAL_MACHINE,			// handle of an open key
		subkey,						// address of subkey name
		0,							// reserved
    	"",							// address of class string
    	REG_OPTION_NON_VOLATILE,	// special options flag
		KEY_ALL_ACCESS,				// desired security access
		NULL,						// address of key security structure
		&regKey,					// address of buffer for opened handle
		&disposition				// address of disposition value buffer
   		);
	if (result != ERROR_SUCCESS)
		return 1;


	/*
	 * Store the name and path under the registry key
	 */
	result = RegSetValueEx(
		regKey,					// handle of key to set value for
		DISPLAY,				// address of name of value to set
		0,						// reserved
		REG_SZ,					// flag for value type
		displayName,			// address of value data
		strlen(displayName)+1	// size of value data
		);
	result = RegSetValueEx(
		regKey,					// handle of key to set value for
		VERSION,				// address of name of value to set
		0,						// reserved
		REG_SZ,					// flag for value type
		version,				// address of value data
		strlen(displayName)+1	// size of value data
		);

	path = frobPath(path);
	result = RegSetValueEx(
		regKey,			// handle of key to set value for
		PATH,			// address of name of value to set
		0,				// reserved
		REG_SZ,			// flag for value type
		path,			// address of value data
		strlen(path)+1	// size of value data
		);
	result = RegSetValueEx(
		regKey,			// handle of key to set value for
		INST_PATH,		// address of name of value to set
		0,				// reserved
		REG_SZ,			// flag for value type
		instpath,		// address of value data
		strlen(path)+1	// size of value data
		);
	result = RegSetValueEx(
		regKey,			// handle of key to set value for
		DATA_PATH,		// address of name of value to set
		0,				// reserved
		REG_SZ,			// flag for value type
		datapath,		// address of value data
		strlen(path)+1	// size of value data
		);


	/*
	 * Close the registry key
	 */
	RegCloseKey(regKey);


	/*
	 * Delete the old uninstallation data created by InstallShield
	 */
	subkey = catstr(KEY_PREFIX, OLD_KEY);
	result = RegDeleteKey(
		HKEY_LOCAL_MACHINE,	// handle of open key
		subkey);			// address of name of subkey


	return 0;
}
示例#29
0
BOOL CRegMgr::DeleteSubKey() {
  if (RegDeleteKey(m_hCompanyKey,m_sSubKey) == ERROR_SUCCESS) return TRUE;
  else return FALSE;
};
示例#30
0
/*
  FUNCTION: smpd_remove_service(BOOL bErrorOnNotInstalled)

  PURPOSE: Stops and removes the service

  PARAMETERS:
    none

  RETURN VALUE:
    none

  COMMENTS:
*/
SMPD_BOOL smpd_remove_service(SMPD_BOOL bErrorOnNotInstalled)
{
    SMPD_BOOL   bRetVal = SMPD_FALSE;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;
    TCHAR       szErr[256];

    schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS );
    if ( schSCManager )
    {
        schService = OpenService(schSCManager, TEXT(SMPD_SERVICE_NAME), SERVICE_ALL_ACCESS);

	if (schService)
        {
            /* try to stop the service */
            if ( ControlService( schService, SERVICE_CONTROL_STOP, &smpd_process.ssStatus ) )
            {
		_tprintf(TEXT("Stopping %s."), TEXT(SMPD_SERVICE_DISPLAY_NAME));
		fflush(stdout);
                Sleep( 1000 );
		
                while( QueryServiceStatus( schService, &smpd_process.ssStatus ) )
                {
                    if ( smpd_process.ssStatus.dwCurrentState == SERVICE_STOP_PENDING )
                    {
			_tprintf(TEXT("."));
			fflush(stdout);
                        Sleep( 250 );
                    }
                    else
                        break;
                }
		
                if ( smpd_process.ssStatus.dwCurrentState == SERVICE_STOPPED )
		{
                    _tprintf(TEXT("\n%s stopped.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME) );
		    fflush(stdout);
		}
                else
		{
                    _tprintf(TEXT("\n%s failed to stop.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME) );
		    fflush(stdout);
		}
		
            }
	    
	    /* Delete the registry entries for the service. */
	    RegDeleteKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\MPICH\\SMPD");

	    /* now remove the service */
            if (DeleteService(schService))
	    {
                _tprintf(TEXT("%s removed.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME) );
		fflush(stdout);
		bRetVal = SMPD_TRUE;
	    }
            else
	    {
                _tprintf(TEXT("DeleteService failed:\n%s\n"), smpd_get_last_error_text(szErr,256));
		fflush(stdout);
	    }

	    CloseServiceHandle(schService);
        }
        else
	{
	    if (bErrorOnNotInstalled)
	    {
		_tprintf(TEXT("OpenService failed:\n%s\n"), smpd_get_last_error_text(szErr,256));
		fflush(stdout);
	    }
	    else
	    {
		bRetVal = SMPD_TRUE;
	    }
	}

	CloseServiceHandle(schSCManager);
    }
    else
    {
        _tprintf(TEXT("OpenSCManager failed:\n%s\n"), smpd_get_last_error_text(szErr,256));
	fflush(stdout);
    }
    return bRetVal;
}