示例#1
2
/**
 * Handles tasks done at beginning of uninstallation
 */
codeUNINSTALL_INIT Uninstall_Init(
  HWND hwndparent,LPCTSTR pszinstalldir)
{
  HKEY hKey = NULL;

  if (RegOpenKeyEx(HKEY_LOCAL_MACHINE ,
      TEXT("\\Software\\Microsoft\\Today\\Items\\XCSoar"),
      0, KEY_ALL_ACCESS, &hKey
    ) == ERROR_SUCCESS){

    DebugMessage("Setup", "Delete Value DLL");

    RegDeleteValue(hKey, TEXT("DLL"));

    RegCloseKey(hKey);

    DebugMessage("Setup", "Refresh Today");

    SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0);

  }

  if (RegOpenKeyEx(HKEY_LOCAL_MACHINE ,
      TEXT("\\Software\\Microsoft\\Today\\Items"),
      0, KEY_ALL_ACCESS, &hKey
    ) == ERROR_SUCCESS){

    DebugMessage("Setup", "Delete Key \\...Today\\XCSoar");

    RegDeleteKey(hKey, TEXT("XCSoar"));

    RegCloseKey(hKey);

  }

  return codeUNINSTALL_INIT_CONTINUE;
}
示例#2
0
文件: registry.c 项目: lizard007/msf3
/*
 * Deletes a registry value from the supplied registry key
 *
 * TLVs:
 *
 * req: TLV_TYPE_HKEY       - The HKEY from which to delete the value
 * req: TLV_TYPE_VALUE_NAME = The name of the value to delete
 */
DWORD request_registry_delete_value(Remote *remote, Packet *packet)
{
	Packet *response = packet_create_response(packet);
	LPCSTR valueName = NULL;
	DWORD result = ERROR_SUCCESS;
	HKEY hkey = NULL;

	hkey      = (HKEY)packet_get_tlv_value_uint(packet, TLV_TYPE_HKEY);
	valueName = (LPCSTR)packet_get_tlv_value_string(packet, TLV_TYPE_VALUE_NAME);

	// Check for invalid parameters
	if ((!hkey) || 
	    (!valueName))
		result = ERROR_INVALID_PARAMETER;
	else
		result = RegDeleteValue(hkey, valueName);

	// Set the result and send the response
	packet_add_tlv_uint(response, TLV_TYPE_RESULT, result);

	packet_transmit(remote, response, NULL);

	return ERROR_SUCCESS;
}
示例#3
0
    bool DeleteSubKey(
#ifdef FAR3
                KEY_TYPE root)
    {
	FarSettingsValue value = {sizeof value, root, NULL};
	return SettingsControl(handle,SCTL_DELETE,0,&value) != 0;
#else
                PCWSTR szName, KEY_TYPE root = 0)
    {
        if(root == 0) root = hKey;
        return RegDeleteKeyW(root, szName) == ERROR_SUCCESS;
#endif
    }

    bool DeleteValue(PCTSTR szName, KEY_TYPE root = 0)
    {
#ifdef FAR3
	FarSettingsValue value = {sizeof value, root, szName};
	return SettingsControl(handle,SCTL_DELETE,0,&value) != 0;
#else
        if(root == 0) root = hKey;
        return RegDeleteValue(root, szName) == ERROR_SUCCESS;
#endif
    }
示例#4
0
static boolean winregdeletevalue (HKEY hkey, Handle h, bigstring bsitem) {

	/*
	7.0.2b1 Radio PBS: delete a value.
	*/

	long lentext;
	char item [256];
	char * itemptr;
	boolean fl = true;

	lentext = gethandlesize (h);

	sethandlesize (h, lentext + 1);

	(*h) [lentext] = '\0'; /*null terminate*/

	copyptocstring (bsitem, item);

	itemptr = item;

	lockhandle (h);

	if (RegOpenKeyEx (hkey, *h, 0, KEY_SET_VALUE, &hkey) == ERROR_SUCCESS) {

		if (RegDeleteValue (hkey, itemptr) == ERROR_SUCCESS)

			fl = true;

		RegCloseKey (hkey);
		} /*if*/

	unlockhandle (h);

	return (fl);
	} /*winregdeletevalue*/
/** write a to registry (at User)
params - none
*/
void WriteReg(HKEY key, LPCTSTR path, LPCTSTR val_name, LPBYTE value, DWORD len) 
{	
	HKEY hKey;
	LONG ret;
		
	if( ret=RegOpenKeyEx(key, path, 0, KEY_ALL_ACCESS | KEY_WOW64_32KEY, &hKey) ) {
		//if (ret==5)		
			if( ret=RegOpenKeyEx(key, path, 0, KEY_ALL_ACCESS , &hKey) )
				if ( ret=RegCreateKeyEx(key, path, 0, NULL, 0, KEY_WOW64_32KEY | KEY_ALL_ACCESS, NULL, &hKey, NULL) )	
					RegCreateKeyEx(key, path, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL);
	}

	if (value==NULL) 
		ret = RegDeleteValue(hKey, val_name);
	else {		
		ret = RegSetValueEx(hKey, val_name, 0, REG_BINARY, value, len);
		if ( ERROR_SUCCESS != ret)
			WriteLog( TEXT("WriteReg failed %X %s %s"), ret, path, val_name);
	}

	RegCloseKey(hKey);

	return ;
}
示例#6
0
void RegisterPreLoad(bool bRegister)
{
	const std_string strPath = GetKeePassExePath();
	if(strPath.size() == 0) return;

	HKEY hKey = NULL;
	if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
		0, KEY_WRITE, &hKey) != ERROR_SUCCESS) return;
	if(hKey == NULL) return;

	const std_string strItemName = _T("KeePass 2 PreLoad");
	std_string strItemValue = _T("\"");
	strItemValue += strPath;
	strItemValue += _T("\" --preload");

	if(bRegister)
		RegSetValueEx(hKey, strItemName.c_str(), 0, REG_SZ,
			(const BYTE*)strItemValue.c_str(), static_cast<DWORD>((strItemValue.size() +
			1) * sizeof(TCHAR)));
	else
		RegDeleteValue(hKey, strItemName.c_str());

	RegCloseKey(hKey);
}
示例#7
0
void SetRegRun(bool isSet, LPCWSTR path)
{
	HKEY hkey;
	LPCWSTR keyName = L"SecMon";

	LONG reg = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0L, KEY_ALL_ACCESS, &hkey);
	if (ERROR_SUCCESS == reg) {

		if (isSet) {
			WCHAR getValue[MAX_PATH] = L"";
			DWORD dwType, dwBytes = MAX_PATH;
			reg = RegQueryValueEx(hkey, keyName, 0, &dwType, (BYTE*)getValue, &dwBytes);

			if (reg != ERROR_SUCCESS || 1 > wcslen(getValue)) {
				reg = RegSetValueEx(hkey, keyName, 0, REG_SZ, (BYTE*)path, MAX_PATH);
			}
		}
		else {
			RegDeleteValue(hkey, keyName);
		}

		RegCloseKey(hkey);
	}
}
//---------------------------------------------------------------------------
//	◎함수명 : RegDelete
//	◎함수설명 : 레지스트리의 특정 데이터를 삭제한다
//	◎인자 : CString 레지스트리경로, CString 삭제할이름
//	삭제할이름이 빈문자열이거나 "0"일 경우 해당 경로를 포함한 하위
//	서브키들까지 모조리 삭제한다.
//	◎반환값 : 성공시 TRUE, 실패시 FALSE
//---------------------------------------------------------------------------
BOOL CRegistryMgr::RegDelete(CString rpath, CString name)
{
	int strindex;
	CString temp = _T("");
	HKEY hCategoryKey;

	strindex = rpath.Find('\\');
	if(strindex<0) return FALSE;
	temp = rpath.Left(strindex);
	if(temp.CompareNoCase(_T("HKEY_CLASSES_ROOT"))==0) hCategoryKey = HKEY_CLASSES_ROOT;
	else if(temp.CompareNoCase(_T("HKEY_CURRENT_CONFIG"))==0) hCategoryKey = HKEY_CURRENT_CONFIG;
	else if(temp.CompareNoCase(_T("HKEY_CURRENT_USER"))==0) hCategoryKey = HKEY_CURRENT_USER;
	else if(temp.CompareNoCase(_T("HKEY_LOCAL_MACHINE"))==0) hCategoryKey = HKEY_LOCAL_MACHINE;
	else if(temp.CompareNoCase(_T("HKEY_USERS"))==0) hCategoryKey = HKEY_USERS;
	else return FALSE;

	
	rpath = rpath.Mid(strindex+1);
	long lRet;
	if(name.IsEmpty() || name.Compare(_T("0"))==0){		// 하위 경로까지 몽땅 지우기
		lRet = RegDeleteRecursive(hCategoryKey, rpath);
		if(lRet != ERROR_SUCCESS) return FALSE;
	}
	else{											// 특정키만 지우기
		HKEY hKey;
		lRet = RegOpenKeyEx(hCategoryKey, rpath, 0, KEY_ALL_ACCESS, &hKey);
		if(lRet == ERROR_SUCCESS) // 오픈 성공하면...
		{
			lRet = RegDeleteValue(hKey, name);
			if(lRet != ERROR_SUCCESS) return FALSE;
		}
		else return FALSE;
	}

	return TRUE;
}
示例#9
0
int APIENTRY WinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/,
                     int /*nCmdShow*/)
{
    HKEY hKey = NULL;
    LONG lResult;

    lResult = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\SIL\\Installer\\ProductKeys", NULL,
                           KEY_WRITE, &hKey);

    if (lResult == ERROR_SUCCESS)
    {
        lResult = RegDeleteValue(hKey, "Last");
        RegCloseKey(hKey);
        hKey = NULL;

        if (lResult == ERROR_SUCCESS)
            MessageBox(NULL, "'Last' product key cleared. Try installation again.", "", 0);
        else
            MessageBox(NULL, "Error: there is no 'Last' product key.", "", 0);
        return 0;
    }
    MessageBox(NULL, "Error: cannot clear 'Last' product key.", "", 0);
    return 0;
}
示例#10
0
void CConfig::DelString(
    tLocation location,                     /**< In:    tells to use the SYSTEM or USER configuration = CConfig::SYSTEM or CConfig::USER*/
    const std::wstring &csName,             /**< In:    parameter name */
    const std::wstring &czSection           /**< In:    the configuration-section where you can find above specified parameter */
    )
{

    wchar_t     wcsKeyRegName[MAX_PATH];

    LONG    lRes;
    HKEY    hRegKeyTree;
    HKEY    hRegKey;

    if(location == SYSTEM)
        hRegKeyTree = HKEY_LOCAL_MACHINE;
    else
        hRegKeyTree = HKEY_CURRENT_USER ;


    //--- Open the KeyInfo entry
    swprintf_s(wcsKeyRegName, sizeof(wcsKeyRegName)/sizeof(wchar_t), L"%s\\%s", SC_CONF_REG, czSection.c_str());
    lRes = RegOpenKeyEx(hRegKeyTree, wcsKeyRegName, 0L, KEY_SET_VALUE, &hRegKey);
    if (lRes != ERROR_SUCCESS){
        RegCloseKey(hRegKey);
        throw CMWEXCEPTION(EIDMW_CONF);
    }

    //--- delete the value
    lRes = RegDeleteValue(hRegKey, csName.c_str());
    if (lRes != ERROR_SUCCESS){
        RegCloseKey(hRegKey);
        throw CMWEXCEPTION(EIDMW_ERR_PARAM_BAD);
    }

    RegCloseKey(hRegKey);
}
示例#11
0
static VOID
SetScreenSaver(HWND hwndDlg, PDATA pData)
{
    HKEY regKey;
    BOOL DeleteMode = FALSE;

    DBG_UNREFERENCED_LOCAL_VARIABLE(DeleteMode);

    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                     _T("Control Panel\\Desktop"),
                     0,
                     KEY_ALL_ACCESS,
                     &regKey) == ERROR_SUCCESS)
    {
        INT Time;
        BOOL bRet;
        TCHAR Sec;
        UINT Ret;

        /* Set the screensaver */
        if (pData->ScreenSaverItems[pData->Selection].bIsScreenSaver)
        {
            SIZE_T Length = _tcslen(pData->ScreenSaverItems[pData->Selection].szFilename) * sizeof(TCHAR);
            RegSetValueEx(regKey,
                          _T("SCRNSAVE.EXE"),
                          0,
                          REG_SZ,
                          (PBYTE)pData->ScreenSaverItems[pData->Selection].szFilename,
                          (DWORD)Length);

            SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, TRUE, 0, SPIF_UPDATEINIFILE);
        }
        else
        {
            /* Windows deletes the value if no screensaver is set */
            RegDeleteValue(regKey, _T("SCRNSAVE.EXE"));
            DeleteMode = TRUE;

            SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, 0, SPIF_UPDATEINIFILE);
        }

        /* Set the secure value */
        Ret = SendDlgItemMessage(hwndDlg,
                                 IDC_SCREENS_USEPASSCHK,
                                 BM_GETCHECK,
                                 0,
                                 0);
        Sec = (Ret == BST_CHECKED) ? _T('1') : _T('0');
        RegSetValueEx(regKey,
                      _T("ScreenSaverIsSecure"),
                      0,
                      REG_SZ,
                      (PBYTE)&Sec,
                      sizeof(TCHAR));

        /* Set the screensaver time delay */
        Time = GetDlgItemInt(hwndDlg,
                             IDC_SCREENS_TIMEDELAY,
                             &bRet,
                             FALSE);
        if (Time == 0)
            Time = 60;
        else
            Time *= 60;

        SystemParametersInfoW(SPI_SETSCREENSAVETIMEOUT, Time, 0, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);

        RegCloseKey(regKey);
    }
}
示例#12
0
LONG PortParameters::Save()
{
  if (!Changed()) {
    return ERROR_SUCCESS;
  }

  char reqKey[100];

  FillParametersKey(reqKey, sizeof(reqKey)/sizeof(reqKey[0]));

  LONG err;
  HKEY hKey;

  err = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                       reqKey,
                       0,
                       NULL,
                       0,
                       KEY_WRITE,
                       NULL,
                       &hKey,
                       NULL);

  if (err != ERROR_SUCCESS)
    return err;

  if (maskChanged & m_portName) {
    if (maskExplicit & m_portName) {
      err = RegSetValueEx(hKey,
                          "PortName",
                          NULL,
                          REG_SZ,
                          (PBYTE)portName,
                          (lstrlen(portName) + 1) * sizeof(portName[0]));
    } else {
      err = RegDeleteValue(hKey, "PortName");

      if (err == ERROR_FILE_NOT_FOUND)
        err = ERROR_SUCCESS;
    }

    if (err != ERROR_SUCCESS)
      goto err;

    maskChanged &= ~m_portName;

    //Trace("  New PortName=%s\n", portName);
  }

  int i;

  for (i = 0 ; i < sizeof(bits)/sizeof(bits[0]) ; i++) {
    if (!GetDwPtr(bits[i].bit))
      continue;

    if (SaveDw(hKey, bits[i].bit) != ERROR_SUCCESS)
      goto err;
  }

err:

  RegCloseKey(hKey);

  return err;
}
示例#13
0
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CBrowserEvents::DocumentComplete(CString & szUrl, DWORD code)
{
	CheckReadyState();
	
	// make sure we are actually measuring something
	if( active )
	{
		CheckStuff();

		EnterCriticalSection(&cs);

		// if we got an error code, use it
		if( code )
			errorCode = code;

    // update the end time
		QueryPerfCounter(lastActivity);
    end = lastActivity;
		endDoc = end;
		lastDoc = lastActivity;
		GetCPUTime(docCPU, docCPUtotal);

		// throw away any objects that happen outside of a document load
		currentDoc = 0;

		LeaveCriticalSection(&cs);

		// grab a screen shot of the document complete event
		if( saveEverything )
    {
      FindBrowserWindow();
      screenCapture.Capture(hBrowserWnd, CapturedImage::DOCUMENT_COMPLETE);
    }

		// update the waterfall
		RepaintWaterfall();
	}
	else if(szUrl == _T("about:blank"))
	{
    FindBrowserWindow();
		ResizeWindow();

		// reset the UI on an about:blank navigation		
		if( interactive && !available )
		{
			Reset();
			available = true;
		}

		// see if we have an url to test
		testUrl.Empty();
		testOptions.Empty();
		HKEY hKey;
		if( RegOpenKeyEx(HKEY_CURRENT_USER, _T("SOFTWARE\\AOL\\ieWatch"), 0, KEY_READ | KEY_WRITE, &hKey) == ERROR_SUCCESS )
		{
			// get the url value out
			TCHAR buff[4096];
			DWORD buffLen = sizeof(buff);
			if( RegQueryValueEx(hKey, _T("url"), 0, 0, (LPBYTE)buff, &buffLen) == ERROR_SUCCESS )
			{
				// delete the value since we already got it and we get a new value there for every run
				RegDeleteValue(hKey, _T("url"));
				
				// split off any options that were embedded in the url
				CString tmp = buff;
				int index = tmp.Find(_T("??pt"));
				if( index >= 0 )
				{
					testUrl = tmp.Left(index);
					testOptions = tmp.Mid(index + 2);
				}
				else
					testUrl = buff;
				
				// if we have an url to test, launch it
				if( testUrl.GetLength() ) {
					if( !testUrl.Left(9).CompareNoCase(_T("script://")) ) {
						CString script = testUrl.Right(testUrl.GetLength() - 9);
						LoadScript(script);
					}
					StartTimer(2, 100);
				}
			}

			RegCloseKey(hKey);
		}
	}
	else
	{
		CString buff;
		buff.Format(_T("[Pagetest] * Document Complete (not active) - %s\n"), (LPCTSTR)szUrl);
		OutputDebugString(buff);
	}
}
示例#14
0
HRESULT Uninstall( )
{
	HRESULT hr = S_OK;

	TCHAR szCurrentDllPath[MAX_PATH << 1];
	TCHAR szTemp[MAX_PATH << 1];

	LPTSTR lpszFileToDelete = szCurrentDllPath;
	LPTSTR lpszTempAppend = szTemp + GetModuleFileName(g_hModThisDll, szTemp, countof(szTemp));

    StringCbCopy(szCurrentDllPath, sizeof(szCurrentDllPath), szTemp);

#ifdef _WIN64
    // If this 64-bit dll was installed to the default location,
    // uninstall the 32-bit dll if it exists in its default location

    TCHAR lpszDefInstallPath[MAX_PATH + 0x20];
    UINT uSize = GetSystemDirectory(lpszDefInstallPath, MAX_PATH);

    if (uSize && uSize < MAX_PATH)
    {
        LPTSTR lpszPathAppend = lpszDefInstallPath + uSize;

        if (*(lpszPathAppend - 1) != TEXT('\\'))
            *lpszPathAppend++ = TEXT('\\');

        static const TCHAR szFolderAndFilename[] = TEXT("ShellExt") TEXT("\\") TEXT(HASHCHECK_FILENAME_STR);
        SSStaticCpy(lpszPathAppend, szFolderAndFilename);

        // If this 64-bit dll was installed to the default location
        if (StrCmpI(szCurrentDllPath, lpszDefInstallPath) == 0)
        {
            TCHAR lpszSystemWow64[MAX_PATH + 0x20];
            uSize = GetSystemWow64Directory(lpszSystemWow64, MAX_PATH);

            if (uSize && uSize < MAX_PATH)
            {
                LPTSTR lpszSystemWow64Append = lpszSystemWow64 + uSize;

                if (*(lpszSystemWow64Append - 1) != TEXT('\\'))
                    SSCpy2Ch(lpszSystemWow64Append++, TEXT('\\'), 0);

                StringCbCopyEx(lpszDefInstallPath, sizeof(lpszDefInstallPath), lpszSystemWow64, &lpszPathAppend, NULL, 0);

                SSStaticCpy(lpszPathAppend, szFolderAndFilename);

                // If the 32-bit dll exists in its default location
                if (PathFileExists(lpszDefInstallPath))
                {
                    static const TCHAR szRegsvr32[] = TEXT("regsvr32.exe");
                    SSStaticCpy(lpszSystemWow64Append, szRegsvr32);
                    // the lpszSystemWow64 buffer now contains the full regsvr32.exe path

                    TCHAR lpszCommandLine[MAX_PATH + 0x20];
                    LPTSTR lpszCommandLineAppend;
                    
                    static const TCHAR szCommandOpts[] = TEXT("regsvr32.exe /u /i /n /s ");
                    lpszCommandLineAppend = SSStaticCpy(lpszCommandLine, szCommandOpts) - 1;

                    StringCbCopy(lpszCommandLineAppend, sizeof(lpszCommandLine)-sizeof(szCommandOpts), lpszDefInstallPath);

                    STARTUPINFO si;
                    memset(&si, 0, sizeof(si));
                    si.cb = sizeof(si);

                    PROCESS_INFORMATION pi;
                    memset(&pi, 0, sizeof(pi));

                    if (!CreateProcess(lpszSystemWow64, lpszCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
                        return E_FAIL;

                    DWORD dwExit;
                    WaitForSingleObject(pi.hProcess, INFINITE);
                    GetExitCodeProcess(pi.hProcess, &dwExit);
                    CloseHandle(pi.hThread);
                    CloseHandle(pi.hProcess);

                    if (dwExit != 0)
                        return E_FAIL;
                }
            }
        }
    }
#endif

	// Rename the DLL prior to scheduling it for deletion
	*lpszTempAppend++ = TEXT('.');
	SSCpy2Ch(lpszTempAppend, 0, 0);

	for (TCHAR ch = TEXT('0'); ch <= TEXT('9'); ++ch)
	{
		*lpszTempAppend = ch;

		if (MoveFileEx(szCurrentDllPath, szTemp, MOVEFILE_REPLACE_EXISTING))
		{
			lpszFileToDelete = szTemp;
			break;
		}
	}

	// Schedule the DLL to be deleted at shutdown/reboot
	if (!MoveFileEx(lpszFileToDelete, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) hr = E_FAIL;

	// Unregister
	if (DllUnregisterServer() != S_OK) hr = E_FAIL;

	// Disassociate file extensions; see the comment in DllUnregisterServer for
	// why this step is skipped for Wow64 processes
	if (!Wow64CheckProcess())
	{
		for (UINT i = 0; i < countof(g_szHashExtsTab); ++i)
		{
			HKEY hKey;

			if (hKey = RegOpen(HKEY_CLASSES_ROOT, g_szHashExtsTab[i], NULL, FALSE))
			{
                RegGetSZ(hKey, NULL, szTemp, sizeof(szTemp));
                if (_tcscmp(szTemp, PROGID_STR_HashCheck) == 0)
                    RegDeleteValue(hKey, NULL);
                RegCloseKey(hKey);
			}
		}
	}

	// We don't need the uninstall strings any more...
	RegDelete(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s"), CLSNAME_STR_HashCheck);

	return(hr);
}
示例#15
0
int
main(int argc, char **argv) {
    HKEY hkSubmounts;
    HKEY hkParameters;
    char mountRoot[64]="/afs";
    char * mountstring;

    if (argc < 2 || argc > 3) {
        fprintf(stderr, "afsshare.exe <submount> [<afs mount path>]\n");
        exit(1);
    }

    if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
                        AFSREG_CLT_OPENAFS_SUBKEY "\\Submounts",
                        0,
                        NULL,
                        REG_OPTION_NON_VOLATILE,
                        (IsWow64()?KEY_WOW64_64KEY:0)|KEY_READ|KEY_WRITE,
                        NULL,
                        &hkSubmounts,
                        NULL) == ERROR_SUCCESS) 
    {
        if ( argc == 2 ) {
            if (RegDeleteValue(hkSubmounts, argv[1])) {
                fprintf(stderr,"Submount Deletion failure for [%s]: %lX",
                         argv[1], GetLastError());
                RegCloseKey(hkSubmounts);
                return 1;
            }
        } else {
            if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
                                AFSREG_CLT_SVC_PARAM_SUBKEY,
                                0,
                                NULL,
                                REG_OPTION_NON_VOLATILE,
                                (IsWow64()?KEY_WOW64_64KEY:0)|KEY_READ,
                                NULL,
                                &hkParameters,
                                NULL) == ERROR_SUCCESS) 
            {
                DWORD dwSize = sizeof(mountRoot);
                RegQueryValueEx (hkParameters, "MountRoot", NULL, NULL, (PBYTE)mountRoot, &dwSize);
                RegCloseKey(hkParameters);
            }


            if ( !strncmp(mountRoot, argv[2], strlen(mountRoot)) )
                mountstring = argv[2] + strlen(mountRoot);
            else
                mountstring = argv[2];

            if (RegSetValueEx(hkSubmounts, argv[1], 0, REG_EXPAND_SZ, mountstring, (DWORD)strlen(mountstring)+1)) {
                fprintf(stderr,"Submount Set failure for [%s]: %lX",
                         argv[1], GetLastError());
                RegCloseKey(hkSubmounts);
                return 2;
            }
        }
        RegCloseKey(hkSubmounts);
    } else {
        fprintf(stderr,"Submount access denied: %lX", GetLastError());
        return 3;
    }
    return 0;
}
示例#16
0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REGistry eXecution
HRESULT REGX(PTSTR ptzCmd)
{
	HKEY hRoot = GetRootKey(ptzCmd);
	if (!hRoot)
	{
		return E_INVALIDARG;
	}

	PTSTR ptzVal = UStrChr(ptzCmd, '=');
	if (ptzVal)
	{
		*ptzVal++ = 0;
	}

	PTSTR ptzName = UStrRChr(ptzCmd, '\\');
	if (!ptzName)
	{
		return E_INVALIDARG;
	}
	else
	{
		*ptzName++ = 0;
	}

	HKEY hKey;
	HRESULT hResult = RegCreateKeyEx(hRoot, ptzCmd, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL);
	if (hResult != S_OK)
	{
		return hResult;
	}

	if (ptzVal)
	{
		if (*ptzName == '#')
		{
			DWORD dwData = UStrToInt(ptzVal);
			hResult = RegSetValueEx(hKey, ptzName + 1, 0, REG_DWORD, (PBYTE) &dwData, sizeof(DWORD));
		}
		else if (*ptzName == '@')
		{
			UINT i = 0;
			PBYTE pbVal = (PBYTE) ptzVal;
			while (*ptzVal)
			{
				pbVal[i++] = (UChrToHex(ptzVal[0]) << 4) | UChrToHex(ptzVal[1]);
				while (*ptzVal && (*ptzVal++ != ','));
			}
			hResult = RegSetValueEx(hKey, ptzName + 1, 0, REG_BINARY, pbVal, i);
		}
		else
		{
			hResult = RegSetValueEx(hKey, ptzName, 0, REG_SZ, (PBYTE) ptzVal, (UStrLen(ptzVal) + 1) * sizeof(TCHAR));
		}
	}
	else
	{
		if (*ptzName == '-')
		{
			if (ptzName[1])
			{
				hResult = RegDeleteValue(hKey, ptzName + 1);
			}
			else
			{
				RegCloseKey(hKey);
				return SHDeleteKey(hRoot, ptzCmd);
			}
		}
		else if (*ptzName == '#')
		{
			DWORD dwSize = sizeof(hResult);
			RegQueryValueEx(hKey, ptzName + 1, NULL, NULL, (PBYTE) &hResult, &dwSize);
		}
		else
		{
			g_tzXVar[0][0] = 0;
			DWORD dwSize = sizeof(g_tzXVar[0]);
			hResult = RegQueryValueEx(hKey, ptzName, NULL, NULL, (PBYTE) g_tzXVar[0], &dwSize);
		}
	}

	RegCloseKey(hKey);
	return hResult;
}
示例#17
0
BOOL CMortScriptApp::InitInstance()
{
    SetRegistryKey( L"Mort" );

	CParseCmdLine myCmdLine;
	myCmdLine.ParseCmdLine( m_lpCmdLine );

	TCHAR exe[MAX_PATH];
   ::GetModuleFileName(NULL,exe,MAX_PATH);

	ExecuteFileName = exe;

    CStr file = myCmdLine.Filename; // m_lpCmdLine;
    // file.TrimLeft( '\"' ); file.TrimRight( '\"' );

    if ( myCmdLine.RegOnly || file.IsEmpty() )
    {
        RegisterFileClass();
        RegisterFileType( L".jscr", L"JScripts" );
        RegisterFileType( L".mscr", L"JScripts" );
		if ( !myCmdLine.RegOnly )
		{
			MessageBox( NULL
					  , L".jscr and .mscr extensions registered.\nPlease run any .jscr/.mscr file or read the manual.\n\n"
						L"(c) Mirko Schenk 2005-2007"
					  , L"JScripts V" + CStr( VERSION_INFO )
					  , MB_OK|MB_SETFOREGROUND );
		}
    }
	else
	{
		if (   file.GetLength() >= 4
			/* file.GetLength() >= 8 && file.Right(8).CompareNoCase( L".mortrun" ) == 0
			|| file.GetLength() >= 5 && file.Right(5).CompareNoCase( L".mscr" ) == 0 */
		   )
		{
            CStr mutexName = file;
            mutexName.MakeLower();
#ifdef DESKTOP
			// Windows XP doesn't like some path characters in the mutex' name
			mutexName.Replace( ':', '_' );
			mutexName.Replace( '\\', '/' );
#endif
          MutexName = (LPCTSTR)mutexName;

	        HANDLE mutex = ::CreateMutex(NULL, FALSE, MutexName);

            if ( mutex!=NULL )
	        {
				int exists = ::GetLastError();
		        if ( exists == ERROR_ALREADY_EXISTS) 
		        {
					DWORD procId = GetRunningScriptProcId( file );

					if ( procId != NULL )
					{
						/*
						 CString msg;
						 msg.Format( L"Process ID: %08x", procId );
						 MessageBox( NULL, msg, L"Debug", MB_SETFOREGROUND );
						*/

						FindAppT findApp;
						findApp.procId = procId;
						findApp.hWnd   = NULL;
						::EnumWindows( FindApplicationWindowProc, (LPARAM)&findApp );
						if ( findApp.hWnd != NULL )
						{
							// msg.Format( L"Set foreground window: %08x", findApp.hWnd );
							// MessageBox( NULL, msg, L"Debug", MB_SETFOREGROUND );
							::SetForegroundWindow( findApp.hWnd );
						}
					}
					else
						exists = 0;

					//MessageBox( NULL, L"Process opened", L"Debug", MB_SETFOREGROUND );
					/*
						TCHAR procName[256];
				    	::GetModuleFileName((HMODULE)procId,procName,256);
						//MessageBox( NULL, procName, L"Debug", MB_SETFOREGROUND );
						if ( CString(procName).Right(14).CompareNoCase( L"MortScript.exe" ) == 0 )
						{
							int aw = MessageBox( NULL
											   , L"Script seems to be running. Cancel old script?"
											   , L"Script already running"
											   , MB_YESNO|MB_SETFOREGROUND
											   );
							if ( aw == IDYES )
							{
								RegWriteDW( HKEY_CURRENT_USER, L"Software\\JScripts\\Abort", MutexName, 1 );
								DWORD exitCode = 0;
								SetCursor(LoadStandardCursor(IDC_WAIT));
								for ( int i=0; i<=10; i++ )
								{
									Sleep(1000);
									if ( GetExitCodeProcess( hProc, &exitCode ) == FALSE )
									{
										//MessageBox( NULL, L"GetExitCode failed", L"Debug", MB_SETFOREGROUND );
										exitCode = 0;
										break;
									}
									else
									{
										if ( exitCode != STILL_ACTIVE )
										{
											//MessageBox( NULL, L"No longer active", L"Debug", MB_SETFOREGROUND );
											break;
										}
									}
								}
								SetCursor(LoadStandardCursor(IDC_ARROW)); 
								if ( exitCode == STILL_ACTIVE )
								{
									int aw = MessageBox( NULL
													   , L"Script seems to be hanging or busy. Terminate old script?"
													   , L"Script still running"
													   , MB_YESNO|MB_SETFOREGROUND
													   );
									if ( aw == IDYES )
									{
										TerminateProcess( hProc, 0 );
									}
								}
							}
						}
						else
						{
							exists = 0;
						}

						CloseHandle( hProc );
					}
					else
					{
						exists = 0;
					}
					*/
                }

                if ( exists != ERROR_ALREADY_EXISTS )
                {
	                HKEY    key;
	                if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, 0, &key ) == ERROR_SUCCESS )
	                {
                        RegDeleteValue( key, MutexName );
		                RegCloseKey( key );
	                }

					DWORD currProcId = GetCurrentProcessId();
					//CString dbg;
					//dbg.Format(L"ProcId: %d", GetCurrentProcessId());
					//MessageBox( NULL, dbg, L"Debug", MB_SETFOREGROUND );

					// Remove old script entries with same process id
	                if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, 0, &key ) == ERROR_SUCCESS )
	                {
						int   idx;
						TCHAR valName[MAX_PATH];
						DWORD valSize = MAX_PATH, type;
						DWORD value, valueSize = sizeof(DWORD);

						CStrArray oldProcesses;
						for ( idx = 0; RegEnumValue( key, idx, valName, &valSize, NULL, &type, (BYTE*)&value, &valueSize ) == ERROR_SUCCESS; idx++ )
						{
							if ( type == REG_DWORD && value == currProcId )
							{
								oldProcesses.Add( valName );
							}
							valSize = MAX_PATH;
							valueSize = sizeof(DWORD);
						}

						for ( idx = 0; idx < oldProcesses.GetSize(); idx++ )
						{
							RegDeleteValue( key, oldProcesses.GetAt(idx) );
						}

		                RegCloseKey( key );
					}

					RegWriteDW( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", MutexName, currProcId );

					if ( myCmdLine.WaitForFile > 0 && (long)FileOrDirExists( file, 0 ) == 0 )
					{
						CDlgWait wait(NULL);
						wait.AllowOK = TRUE;
						wait.Countdown = myCmdLine.WaitForFile;
						wait.Expression = L"FileExists(\"" + file + L"\")";
						wait.Title = L"JScripts";
						wait.m_Label = L"Script " + file + " not found, waiting for existance (storage card not initialized?)";
						wait.DoModal();
					}

					if ( myCmdLine.WaitForFile <= 0 || (long)FileOrDirExists( file, 0 ) == 1 )
					{
						g_hInst = theApp.m_hInstance;

						SYSTEMTIME now;
						GetLocalTime( &now );
						long seed = SystemTimeToUnixTime( now );
						srand( seed );

						AppPath = m_pszHelpFilePath;
						AppPath = AppPath.Left( AppPath.ReverseFind('\\') );

						ScriptAborted = CreateEvent( 0, TRUE, FALSE, CStr(MutexName)+L"ScriptAborted" );
					    StatusDialog = new CDlgStatus( file );
						//status.DoModal();

						CInterpreter interpreter;
						//Debug(file);

						//jwz:modi
						interpreter.RunFile( file );
						interpreter.Parser();
						//jwz:modi end

						if ( StatusWindow != NULL )
						{
							StatusDialog->ScriptFinished = TRUE;
							SendMessage( StatusWindow, WM_EXIT_STATUS, 0, 0 );
							WaitForSingleObject( StatusDialogFinished, INFINITE );
							CloseHandle( StatusDialogFinished );
						}

						delete StatusDialog;

						UnloadToolhelp();

						CloseHandle( ScriptAborted );
						ReleaseMutex( mutex );

						Variables.RemoveAll();
						for ( int i = 0; i<LocalVariablesStack.GetSize(); i++ )
							delete (CMapStrToValue*)LocalVariablesStack.GetAt(i);

						POSITION pos = FileHandles.GetStartPosition();
						CStr key; void *value;
						while ( pos != 0 )
						{
							FileHandles.GetNextAssoc( pos, key, value );
							if ( value != NULL )
							{
								delete (CFileInfo*)value;
							}
						}
						FileHandles.RemoveAll();

						if ( ChoiceFont != NULL ) DeleteObject( ChoiceFont );
						if ( StatusListFont != NULL ) DeleteObject( StatusListFont );
					}

					if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, KEY_WRITE, &key ) == ERROR_SUCCESS )
	                {
                        RegDeleteValue( key, MutexName );
		                RegCloseKey( key );
	                }
                }
                CloseHandle( mutex );
            }
			else
			{
				int error = ::GetLastError();
				MessageBox( NULL
						  , L"Error creating mutex"
						  , L"JScripts"
						  , MB_OK|MB_SETFOREGROUND );
			}
		}
		else
		{
			MessageBox( NULL
					  , L"Invalid file type for MortScript"
					  , L"JScripts"
					  , MB_OK|MB_SETFOREGROUND );
		}
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
示例#18
0
BOOL Config_SetAuthentFlag (BOOL fFlag, ULONG *pStatus)
{
   ULONG status = 0;
   BOOL rc = FALSE;

   HKEY hk;
   DWORD dwDisp;
   if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, TEXT("System\\CurrentControlSet\\Control\\NetworkProvider\\Order"), 0, TEXT("container"), 0, KEY_QUERY_VALUE | KEY_SET_VALUE, NULL, &hk, &dwDisp)) == ERROR_SUCCESS)
      {
      if (g.fIsWinNT)
         {
         TCHAR szOldProviders[ MAX_PATH ] = TEXT("");
         TCHAR szNewProviders[ MAX_PATH ] = TEXT("");
         DWORD dwSize = sizeof(szOldProviders);
         RegQueryValueEx (hk, TEXT("ProviderOrder"), NULL, NULL, (PBYTE)szOldProviders, &dwSize);

         for (LPTSTR pch = szOldProviders; *pch; )
            {
            BOOL fCopy = TRUE;
            if (!lstrncmpi (pch, TEXT("TransarcAFSDaemon"), lstrlen(TEXT("TransarcAFSDaemon"))))
               {
               fCopy = fFlag;
               fFlag = FALSE;
               }

            if (fCopy)
               {
               LPTSTR pchOut = &szNewProviders[ lstrlen(szNewProviders) ];
               if (szNewProviders[0])
                  *pchOut++ = TEXT(',');
               for ( ; *pch && (*pch != TEXT(',')); )
                  *pchOut++ = *pch++;
               *pchOut = TEXT('\0');
               }

            for ( ; *pch && (*pch != TEXT(',')); ++pch)
               ;
            for ( ; *pch == TEXT(','); ++pch)
               ;
            }

         if (fFlag)
            {
            if (szNewProviders[0])
               lstrcat (szNewProviders, TEXT(","));
            lstrcat (szNewProviders, TEXT("TransarcAFSDaemon"));
            }

         if ((status = RegSetValueEx (hk, TEXT("ProviderOrder"), NULL, REG_SZ, (PBYTE)szNewProviders, sizeof(TCHAR)*(1+lstrlen(szNewProviders)))) == ERROR_SUCCESS)
            rc = TRUE;
         }
      else // (!g.fIsWinNT)
         {
         TCHAR szLHS[ cchRESOURCE ] = TEXT("TransarcAFSDaemon");
         TCHAR szRHS[ cchRESOURCE ] = TEXT("");

         if (fFlag)
            {
            if ((status = RegSetValueEx (hk, szLHS, NULL, REG_SZ, (PBYTE)szRHS, sizeof(TCHAR)*(lstrlen(szRHS)+1))) == 0)
               rc = TRUE;
            }
         else
            {
            RegDeleteValue (hk, szLHS);
            rc = TRUE;
            }
         }

      RegCloseKey (hk);
      }

   if (pStatus && !rc)
      *pStatus = status;
   if (!rc)
      Message (MB_ICONHAND, GetErrorTitle(), IDS_FAILCONFIG_AUTHENT, TEXT("%ld"), status);
   return rc;
}
示例#19
0
void
HandleALOption (
    int argc,
    TCHAR **argv
    )
{
    DWORD returnValue;
    HKEY  registryKey;
    TCHAR appid [256];
    TCHAR keyName [256];

    if (argc < 4)
        ShowUsage (TEXT("Invalid number of arguments."));

    if (_tcscmp (_tcsupr (argv[3]), TEXT("LIST")) == 0)
    {
        if (argc < 4)
            ShowUsage (TEXT("Invalid number of arguments.\n"));

        _tprintf (TEXT("Launch permission list for AppID %s:\n\n"), argv[2]);
        ListAppIDLaunchACL (argv[2]);
        return;
    }

    if (_tcscmp (_tcsupr (argv[3]), TEXT("DEFAULT")) == 0)
    {
        if (argv [2][0] == '{')
            wsprintf (appid, TEXT("%s"), argv [2]); else
            wsprintf (appid, TEXT("{%s}"), argv [2]);

        wsprintf (keyName, TEXT("APPID\\%s"), appid);

        returnValue = RegOpenKeyEx (HKEY_CLASSES_ROOT, keyName, 0, KEY_ALL_ACCESS, &registryKey);
        if (returnValue != ERROR_SUCCESS && returnValue != ERROR_FILE_NOT_FOUND)
            Error (TEXT("ERROR: Cannot open AppID registry key."), returnValue);

        returnValue = RegDeleteValue (registryKey, TEXT("LaunchPermission"));
        if (returnValue != ERROR_SUCCESS && returnValue != ERROR_FILE_NOT_FOUND)
            Error (TEXT("ERROR: Cannot delete LaunchPermission value."), returnValue);

        RegCloseKey (registryKey);
        return;
    }

    if (argc < 5)
        ShowUsage (TEXT("Invalid number of arguments."));

    if (_tcscmp (_tcsupr (argv [3]), TEXT("SET")) == 0)
    {
        if (argc < 6)
            ShowUsage (TEXT("Invalid number of arguments."));

        if (_tcscmp (_tcsupr (argv [5]), TEXT("PERMIT")) == 0)
            returnValue = ChangeAppIDLaunchACL (argv[2], argv [4], TRUE, TRUE); else

        if (_tcscmp (_tcsupr (argv [5]), TEXT("DENY")) == 0)
            returnValue = ChangeAppIDLaunchACL (argv[2], argv [4], TRUE, FALSE); else
        {
            ShowUsage (TEXT("You can only set a user's permissions to \"permit\" or \"deny\".\n\n"));
        }

        if (returnValue != ERROR_SUCCESS)
            Error (TEXT("ERROR: Cannot add user to application launch ACL."), returnValue);
    } else
    if (_tcscmp (_tcsupr (argv [3]), TEXT("REMOVE")) == 0)
    {
        returnValue = ChangeAppIDLaunchACL (argv[2], argv[4], FALSE, FALSE);

        if (returnValue != ERROR_SUCCESS)
            Error (TEXT("ERROR: Cannot remove user from application launch ACL."), returnValue);
    } else
        ShowUsage (TEXT("You can only \"set\" or \"remove\" a user."));
}
示例#20
0
文件: runonce.c 项目: GYGit/reactos
INT
WINAPI
_tWinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPTSTR lpCmdLine, INT nCmdShow)
{
    LPCTSTR lpCmd = GetCommandLine();
    TCHAR szAppPath[MAX_PATH], szData[MAX_PATH];
    DWORD dwIndex, dwSize, dwType, dwData;
    PROCESS_INFORMATION pi;
    STARTUPINFOW si;
    BOOL bRunApps = FALSE;
    HKEY hKey;

    while (*lpCmd)
    {
        while (*lpCmd && *lpCmd != _T('/') && *lpCmd != _T('-')) lpCmd++;
        if (!*lpCmd) break;
        if (*++lpCmd == _T('r')) bRunApps = TRUE;
        lpCmd++;
    }

    if (bRunApps)
    {
        if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                         _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"),
                         0,
                         KEY_QUERY_VALUE,
                         &hKey) == ERROR_SUCCESS)
        {
            for (dwIndex = 0; ; dwIndex++)
            {
                dwSize = sizeof(szAppPath);
                dwData = sizeof(szData) / sizeof(TCHAR);

                if (RegEnumValue(hKey,
                                 dwIndex,
                                 szAppPath,
                                 &dwSize,
                                 NULL,
                                 &dwType,
                                 (LPBYTE)szData,
                                 &dwData) == ERROR_SUCCESS)
                {
                    RegDeleteValue(hKey, szAppPath);

                    if (dwType != REG_SZ) continue;

                    ZeroMemory(&si, sizeof(si));
                    si.cb = sizeof(si);
                    si.dwFlags = STARTF_USESHOWWINDOW;
                    si.wShowWindow = SW_SHOW;

                    if (!CreateProcess(NULL, szData, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
                        continue;

                    WaitForSingleObjectEx(pi.hProcess, INFINITE, TRUE);

                    CloseHandle(pi.hProcess);
                    CloseHandle(pi.hThread);
                }
            }

            RegCloseKey(hKey);
        }

        return 1;
    }

    DialogBox(hInst, MAKEINTRESOURCE(IDD_RUNONCE_DLG), NULL, RunOnceDlgProc);

    return 0;
}
示例#21
0
INT_PTR
CALLBACK
HandleCrashDlgProc(
    HWND    hDlg,
    UINT    msg,
    WPARAM  wParam,
    LPARAM  lParam)
/*++

Routine Description:

    Dialog box used to ask user what action he wants to take when an application
    crashes.

Arguments:

    Refer to DialogProc in MSDN

Returns:

    TRUE - Message Handled
    FALSE - Message not handled

--*/
{
    static PROC_DBG_DATA sProcDbgData;

    switch(msg)
    {
        case WM_INITDIALOG:
        {
            //
            // Insert *specific* dialog initialization code here.
            // lParam can contain information required for initialization.
            //

            //
            // Set dialog and application Icon
            //
            HICON hIcon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_APP_ICON_SM));
            SendMessage (hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
            hIcon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_APP_ICON));
            SendMessage (hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon);

            SetWindowText(hDlg, _T("IntellectualHeaven(R) CrashDoctor"));

            //
            // Set list control properties
            //
            HWND hListCtrl;
            hListCtrl = GetDlgItem(hDlg, IDC_LIST_DEBUGGER);
            ListView_SetExtendedListViewStyle(
                                        hListCtrl,
                                        LVS_EX_FULLROWSELECT);

            ListView_SetTextColor(  hListCtrl,
                                    RGB(0, 0, 255));

            LVCOLUMN lvColumn;
            lvColumn.mask = LVCF_TEXT | LVCF_WIDTH;

            lvColumn.cx         = 260;
            lvColumn.pszText    = _T(" Debuggers Available");

            ListView_InsertColumn(  hListCtrl,
                                    0,
                                    &lvColumn);

            CenterDialog(hDlg);

            PPROC_DBG_DATA procDbgData  = (PPROC_DBG_DATA)lParam;

            //
            // Store the PROC_DBG_DATA, it will be needed later
            //
            sProcDbgData = *procDbgData;


            // Find the process given in PROC_DBG_DATA
            DWORD processId = sProcDbgData.processId;

            IHU_PROCESS_INFO            processInfo;
            IHU_PROCESS_LIST        processList;
            IHU_PROCESS_LIST_ITER   processListIter;
            bool                        processFound = false;

            IhuGetProcessList(processList);

            for (   processListIter = processList.begin();
                    processListIter != processList.end();
                    ++processListIter)
            {
                processInfo = *processListIter;
                if (processId == processInfo.mProcessId)
                {
                    processFound = true;
                    break;
                }
            }

            //
            // Set process name and image
            //
            if (processFound)
            {
                SetWindowText(
                        GetDlgItem(hDlg, IDC_EDIT_PROCESS_NAME),
                        processInfo.mBinaryName.c_str());

                hIcon = NULL;

                IhuGetFileIcon(
                            processInfo.mBinaryName,
                            hIcon);

                if (hIcon)
                {
                    SendMessage(
                        GetDlgItem(hDlg, IDC_ICON_PROCESS),
                        STM_SETICON,
                        (WPARAM)hIcon,
                        0);
                }
            }
            else
            {
                SetWindowText(
                        GetDlgItem(hDlg, IDC_EDIT_PROCESS_NAME),
                        _T("<Unknown Process>"));
                //
                // To-Do!!!
                // This should *NEVER* happen. How to handle this?
                //
            }


            //
            // Add debugger list to the list ctrl
            //
            AddDebuggersToListCtrl(
                            hListCtrl);

            return TRUE;
        }
        case WM_COMMAND:
        {
            switch(wParam)
            {
                case IDC_BTN_RECOVER:
                {
                    EndDialog(hDlg, IDC_BTN_RECOVER);
                    return TRUE;
                }
                case IDC_BTN_TERMINATE:
                {
                    EndDialog(hDlg, IDC_BTN_TERMINATE);
                    return TRUE;
                }
                case IDC_BTN_DEBUG:
                {
                    HWND hListCtrl = GetDlgItem(hDlg, IDC_LIST_DEBUGGER);
                    int nSelectedItem = ListView_GetSelectionMark(hListCtrl);

                    if (nSelectedItem >= 0)
                    {
                        TCHAR debugCmdFormat[MAX_PATH] = {0};

                        LVITEM lvItem       = {0};
                        lvItem.mask         = LVIF_TEXT;
                        lvItem.iItem        = nSelectedItem;
                        lvItem.iSubItem     = 0;
                        lvItem.pszText      = debugCmdFormat;
                        lvItem.cchTextMax   = MAX_PATH;

                        if (ListView_GetItem(hListCtrl, &lvItem))
                        {
                            if (_tcslen(debugCmdFormat) > 0)
                            {
                                TCHAR launchDebuggerCmd[MAX_PATH * 2] = {0};
                                _stprintf(  launchDebuggerCmd,
                                            debugCmdFormat,
                                            sProcDbgData.processId,
                                            sProcDbgData.eventHandle);

                                STARTUPINFO         startupInfo;
                                PROCESS_INFORMATION procInfo;

                                ZeroMemory(&startupInfo, sizeof(startupInfo));
                                startupInfo.cb = sizeof(startupInfo);

                                ZeroMemory(&procInfo, sizeof(procInfo));

                                BOOL bResult = CreateProcess(
                                                    NULL,
                                                    launchDebuggerCmd,
                                                    NULL,
                                                    NULL,
                                                    TRUE,
                                                    0,
                                                    NULL,
                                                    NULL,
                                                    &startupInfo,
                                                    &procInfo);


                                if (!bResult)
                                {
                                    cdHandleError(
                                            hDlg,
                                            GetLastError(),
                                            _T("Unable to launch debugger."));
                                }
                                else
                                {
                                    ShowWindow(hDlg, SW_HIDE);
                                    if (sProcDbgData.eventHandle)
                                    {
                                        //
                                        // wait till either the actual debugger dies or it sets the event
                                        // This wait is necessary because if we exit before the debugger
                                        // got attached to the target. The target dies because it thinks
                                        // we are the debugger.
                                        //
                                        HANDLE waitHandle[2];
                                        waitHandle[0] = sProcDbgData.eventHandle;
                                        waitHandle[1] = procInfo.hProcess;
                                        WaitForMultipleObjects(2, (const HANDLE *)&waitHandle, FALSE, INFINITE);
                                    }
                                    else
                                    {
                                        //
                                        // wait till either the actual debugger dies or 10 seconds are over
                                        // This wait is necessary because if we exit before the debugger
                                        // got attached to the target. The target dies because it thinks
                                        // we are the debugger.
                                        //
                                        WaitForSingleObject(procInfo.hProcess, 10000);
                                    }

                                    EndDialog(hDlg, IDC_BTN_DEBUG);
                                    return FALSE;
                                }
                            }
                        }
                    }

                    break;
                }
                case IDC_BTN_ADD_DEBUGGER:
                {
                    TCHAR tempFileName[MAX_PATH];
                    tempFileName[0] = 0;

                    OPENFILENAME ofn = {0};

                    ofn.lStructSize     = OPENFILENAME_SIZE_VERSION_400;
                    ofn.hwndOwner       = hDlg;
                    ofn.hInstance       = ghInstance;
                    ofn.lpstrFilter     = _T("Executable (*.exe)\0*.exe\0\0");
                    ofn.lpstrFile       = tempFileName;
                    ofn.nMaxFile        = MAX_PATH;
                    ofn.lpstrTitle      = _T("Select a debugger");
                    ofn.Flags           = OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST;

                    if (GetOpenFileName(&ofn))
                    {
                        DEBUGGER_INFO debuggerInfo;
                        debuggerInfo.debuggerPath   = ofn.lpstrFile;
                        debuggerInfo.cmdLine        = _T("-p %ld -e %ld");

                        DialogBoxParam(
                                    ghInstance,
                                    MAKEINTRESOURCE(IDD_DIALOG_ADD_DEBUGGER),
                                    hDlg,
                                    (DLGPROC)DebuggerDataDlgProc,
                                    (LPARAM)&debuggerInfo);

                        tstring debuggerCmd = _T("\"") + debuggerInfo.debuggerPath + _T("\" ") + debuggerInfo.cmdLine;
                        AddDebuggerToRegistry(hDlg, debuggerCmd);
                        AddDebuggersToListCtrl(GetDlgItem(hDlg, IDC_LIST_DEBUGGER));
                    }

                    break;
                }
                case IDC_BTN_MODIFY_DEBUGGER:
                {
                    HWND hListCtrl = GetDlgItem(hDlg, IDC_LIST_DEBUGGER);
                    int nSelectedItem = ListView_GetSelectionMark(hListCtrl);

                    if (nSelectedItem >= 0)
                    {
                        TCHAR debugCmdLine[MAX_PATH] = {0};

                        LVITEM lvItem       = {0};
                        lvItem.mask         = LVIF_TEXT | LVIF_PARAM;
                        lvItem.iItem        = nSelectedItem;
                        lvItem.iSubItem     = 0;
                        lvItem.pszText      = debugCmdLine;
                        lvItem.cchTextMax   = MAX_PATH;

                        if (ListView_GetItem(hListCtrl, &lvItem))
                        {
                            LPARAM regIndex = lvItem.lParam;

                            if (_tcslen(debugCmdLine) > 0)
                            {
                                DEBUGGER_INFO debuggerInfo;
                                debuggerInfo.cmdLine = debugCmdLine;

                                DialogBoxParam(
                                            ghInstance,
                                            MAKEINTRESOURCE(IDD_DIALOG_MODIFY_DEBUGGER),
                                            hDlg,
                                            (DLGPROC)DebuggerDataDlgProc,
                                            (LPARAM)&debuggerInfo);

                                if (_tcscmp(debugCmdLine, debuggerInfo.cmdLine.c_str()) != 0)
                                {
                                    //
                                    // Modify the particular registry entry
                                    //
                                    TCHAR valueName[32];
                                    _stprintf(valueName, _T("Debugger%02d"), regIndex);

                                    int nReturnValue        = 0;
                                    HKEY hAppDebuggerKey    = NULL;


                                    nReturnValue = RegOpenKey(
                                                            HKEY_LOCAL_MACHINE,
                                                            REG_APP_ROOT REG_APP_DEBUGGERS,
                                                            &hAppDebuggerKey);

                                    if (hAppDebuggerKey)
                                    {
                                        if (RegSetValueEx(
                                                    hAppDebuggerKey,
                                                    valueName,
                                                    0,
                                                    REG_SZ,
                                                    (LPBYTE)debuggerInfo.cmdLine.c_str(),
                                                    (DWORD)(debuggerInfo.cmdLine.length() * sizeof(TCHAR))) != ERROR_SUCCESS)
                                        {
                                            cdHandleError(
                                                    hDlg,
                                                    GetLastError(),
                                                    _T("Modify Debugger Failed. Unable to update the registry key."));
                                        }

                                        RegCloseKey(hAppDebuggerKey);

                                        AddDebuggersToListCtrl(GetDlgItem(hDlg, IDC_LIST_DEBUGGER));
                                    }
                                    else
                                    {
                                        cdHandleError(
                                                    hDlg,
                                                    GetLastError(),
                                                    _T("Modify Debugger Failed. Unable to open required registry key."));

                                    }
                                }
                            }
                        }
                    }

                    break;
                }
                case IDC_BTN_DELETE_DEBUGGER:
                {
                    HWND hListCtrl = GetDlgItem(hDlg, IDC_LIST_DEBUGGER);
                    int nSelectedItem = ListView_GetSelectionMark(hListCtrl);

                    if (nSelectedItem >= 0)
                    {
                        TCHAR debugCmdLine[MAX_PATH] = {0};

                        LVITEM lvItem       = {0};
                        lvItem.mask         = LVIF_TEXT | LVIF_PARAM;
                        lvItem.iItem        = nSelectedItem;
                        lvItem.iSubItem     = 0;
                        lvItem.pszText      = debugCmdLine;
                        lvItem.cchTextMax   = MAX_PATH;

                        if (ListView_GetItem(hListCtrl, &lvItem))
                        {
                            LPARAM regIndex = lvItem.lParam;

                            //
                            // Modify the particular registry entry
                            //
                            TCHAR valueName[32];
                            _stprintf(valueName, _T("Debugger%02d"), regIndex);

                            int nReturnValue        = 0;
                            HKEY hAppDebuggerKey    = NULL;


                            nReturnValue = RegOpenKey(
                                                    HKEY_LOCAL_MACHINE,
                                                    REG_APP_ROOT REG_APP_DEBUGGERS,
                                                    &hAppDebuggerKey);

                            if (hAppDebuggerKey)
                            {
                                if (RegDeleteValue(
                                            hAppDebuggerKey,
                                            valueName) != ERROR_SUCCESS)
                                {
                                    cdHandleError(
                                            hDlg,
                                            GetLastError(),
                                            _T("Delete Debugger Failed. Unable to delete the registry key."));
                                }

                                RegCloseKey(hAppDebuggerKey);

                                AddDebuggersToListCtrl(GetDlgItem(hDlg, IDC_LIST_DEBUGGER));
                            }
                            else
                            {
                                cdHandleError(
                                            hDlg,
                                            GetLastError(),
                                            _T("Delete Debugger Failed. Unable to open required registry key."));

                            }
                        }
                    }

                    break;
                }
                //
                // Don't allow closing from the title bar button.
                //
                /*
                case IDCANCEL:
                {
                    EndDialog(hDlg, IDCANCEL);
                    return TRUE;
                }
                */
            }

            break;
        }
        case WM_CTLCOLORSTATIC:
        {
            HDC hdc = (HDC)wParam;
            HWND hwndCtl = (HWND)lParam;

            if (hwndCtl == GetDlgItem(hDlg, IDC_EDIT_PROCESS_NAME))
            {
                if (SetTextColor(hdc, RGB(255, 0, 0)) == CLR_INVALID)
                {
                    cdHandleError(hDlg, GetLastError(), _T("Failed to set control color"));
                    break;
                }
                SetBkMode(hdc, TRANSPARENT);
                SetBkColor(hdc, GetSysColor(COLOR_WINDOW));
                SelectObject(hdc, GetSysColorBrush(COLOR_WINDOW));
                return TRUE;
            }

            break;
        }
        case WM_DESTROY:
        {
            return TRUE;
        }
        case WM_CLOSE:
        {
            break;
        }
    }

    //
    // Not handled by us
    //
    return FALSE;
}
示例#22
0
文件: u3util.c 项目: flaub/HotFuzz
void uninstall(char *regkey, char *u3installed, char *uninstall)
{
  char buffer[BUFSIZ];
  int buflen = BUFSIZ;
  char *u3_device_serial;
  char reg_key[BUFSIZ];
  HKEY  key;

  /* UNINSTALL ONLY IF WE INSTALLED IT */
  buffer[0] = '\0';

  /* see if it is installed */
  if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey, 0, (KEY_READ | KEY_WRITE), &key) == ERROR_SUCCESS) {

    buflen = BUFSIZ;

    /* see if a U3 device installed the package */
    if(RegQueryValueEx(key, u3installed, NULL, NULL, buffer, &buflen) == ERROR_SUCCESS) {

      u3_device_serial = getenv("U3_DEVICE_SERIAL");

      /* see if this U3 device installed the package */
      if(!strncmp(buffer, u3_device_serial, strlen(u3_device_serial) + 1)) {

	buffer[0] = '"';
	buflen = BUFSIZ-1;
	/* we installed WinPcap - we should now uninstall it - read the uninstall string */
	(void) RegQueryValueEx(key, uninstall, NULL, NULL, &buffer[1], &buflen);


	if(!strncmp(buffer, "\"MsiExec.exe", 12)) {
	  /* run msiexec.exe quietly */
	  strncat(buffer, " /qn", 5);

	}

	strncat(buffer, "\"", 2); /* close the quotes */

	/* delete our value */
	RegDeleteValue(key, u3installed);

      } else {
	/* empty the buffer */
	buffer[0] = '\0';
      }
    }

    RegCloseKey(key);
  }

  if(*buffer) {
#if 0
    MessageBox(NULL,
	       buffer,
	       "Uninstall",
	       MB_YESNO|MB_TOPMOST|MB_ICONQUESTION);
#endif 

    /* we have an uninstall string */
    ExecuteAndWait(buffer);
  }
}
示例#23
0
/*
void CL_RegistryKey::set_value_multi_string(const CL_StringRef &name, const std::vector<CL_String> &value)
{
	int size = 1;
	for (std::vector<CL_String>::size_type i = 0; i < value.size(); i++)
		size += value[i].length()+1;
	CL_DataBuffer buffer(size * sizeof(TCHAR));
	int pos = 0;
	// gosh this is too boring..
}
*/
void CL_RegistryKey::delete_value(const CL_StringRef &name)
{
	RegDeleteValue(impl->key, CL_StringHelp::utf8_to_ucs2(name).c_str());
}
示例#24
0
//------------------------------------------------------------------------
///| Parsing the command line |///////////////////////////////////////////
//------------------------------------------------------------------------
// Returns:
//   true  - continue normal startup
//   false - exit process with iResult code
bool CConEmuStart::ParseCommandLine(LPCWSTR pszCmdLine, int& iResult)
{
	bool bRc = false;
	iResult = 100;

	_ASSERTE(pszCmdLine!=NULL);
	opt.cmdLine.Set(pszCmdLine ? pszCmdLine : L"");

	// pszCmdLine *may* or *may not* start with our executable or full path to our executable
	LPCWSTR pszTemp = opt.cmdLine;
	LPCWSTR cmdLineRest = SkipNonPrintable(opt.cmdLine);
	LPCWSTR pszName, pszArgStart;
	LPCWSTR psUnknown = NULL;
	CmdArg  szArg, szNext;
	CEStr   szExeName, szExeNameOnly;

	// Set %ConEmuArgs% env var
	// It may be useful if we need to restart ConEmu
	// from batch/script with the same arguments (selfupdate etc.)
	LPCWSTR pszCopyToEnvStart = NULL;

	// Have to get our exectuable name and name without extension
	szExeName.Set(PointToName(gpConEmu->ms_ConEmuExe));
	szExeNameOnly.Set(szExeName);
	wchar_t* pszDot = (wchar_t*)PointToExt(szExeNameOnly.ms_Val);
	_ASSERTE(pszDot);
	if (pszDot) *pszDot = 0;


	// Check the first argument in the command line (most probably it will be our executable path/name)
	if (!(pszTemp = NextArg(pszTemp, szArg)))
	{
		_ASSERTE(FALSE && "GetCommandLine() is empty");
		// Treat as empty command line, allow to start
		bRc = true; iResult = 0;
		goto wrap;
	}
	pszName = PointToName(szArg);
	if ((lstrcmpi(pszName, szExeName) == 0)
		|| (lstrcmpi(pszName, szExeNameOnly) == 0))
	{
		// OK, our executable was specified properly in the command line
		_ASSERTE(*pszTemp != L' ');
		cmdLineRest = SkipNonPrintable(pszTemp);
	}


	// Must be empty at the moment
	_ASSERTE(opt.runCommand.IsEmpty());

	// Does the command line contain our switches?
	// Or we need to append all switches to starting shell?
	if (cmdLineRest && *cmdLineRest)
	{
		pszTemp = cmdLineRest;
		if ((pszTemp = NextArg(pszTemp, szArg)))
		{
			if ((*szArg.ms_Val != L'/')
				&& (*szArg.ms_Val != L'-')
				/*&& !wcschr(szArg.ms_Val, L'/')*/
				)
			{
				// Save it for further use
				opt.runCommand.Set(cmdLineRest);
				// And do not process it (no switches at all)
				cmdLineRest = NULL;
				opt.params = -1;
			}
		}
	}

	struct RunAsAdmin
	{
		static bool Check(LPCWSTR asSwitch)
		{
			bool bRunAsAdmin = false; // isPressed(VK_SHIFT);
			return bRunAsAdmin;
		};
	};


	// Let parse the reset
	szArg.Empty();
	szNext.Empty();

	// Processing loop begin
	if (cmdLineRest && *cmdLineRest)
	{
		pszCopyToEnvStart = cmdLineRest;
		opt.cfgSwitches.Set(pszCopyToEnvStart);

		while ((cmdLineRest = NextArg(cmdLineRest, szArg, &pszArgStart)))
		{
			bool lbNotFound = false;

			TODO("Replace NeedNextArg with GetCfgParm?")
			#define NeedNextArg() \
				if (!(cmdLineRest = NextArg(cmdLineRest, szNext))) { iResult = CERR_CARGUMENT; goto wrap; }


			if (!szArg.IsPossibleSwitch())
			{
				// -- // continue; // Try next switch?

				// Show error on unknown switch
				psUnknown = pszArgStart;
				break;
			}

			// Main processing cycle
			{
				opt.params++;

				if (szArg.IsSwitch(L"-autosetup"))
				{
					BOOL lbTurnOn = TRUE;

					NeedNextArg();

					if (szNext.Compare(L"0") == 0)
					{
						lbTurnOn = FALSE;
					}
					else if (szNext.Compare(L"1") == 0)
					{
						NeedNextArg();

						DWORD dwAttr = GetFileAttributes(szNext);

						if (dwAttr == (DWORD)-1 || (dwAttr & FILE_ATTRIBUTE_DIRECTORY))
						{
							iResult = 102;
							goto wrap;
						}
					}
					else
					{
						iResult = CERR_CARGUMENT;
						goto wrap;
					}

					HKEY hk = NULL; DWORD dw;
					int nSetupRc = 100;

					if (0 != RegCreateKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Command Processor"),
										   0, NULL, 0, KEY_ALL_ACCESS, NULL, &hk, &dw))
					{
						iResult = 103;
						goto wrap;
					}

					if (lbTurnOn)
					{
						size_t cchMax = szNext.GetLen();
						LPCWSTR pszArg1 = NULL;
						if (*cmdLineRest)
						{
							// May be ‘/GHWND=NEW’ or smth else
							pszArg1 = cmdLineRest;
							cchMax += _tcslen(pszArg1);
						}
						cchMax += 16; // + quotations, spaces and so on

						wchar_t* pszCmd = (wchar_t*)calloc(cchMax, sizeof(*pszCmd));
						swprintf_c(pszCmd, cchMax/*#SECURELEN*/, L"\"%s\"%s%s%s", szNext.ms_Val,
							pszArg1 ? L" \"" : L"", pszArg1 ? pszArg1 : L"", pszArg1 ? L"\"" : L"");


						if (0 == RegSetValueEx(hk, _T("AutoRun"), 0, REG_SZ, (LPBYTE)pszCmd,
											(DWORD)sizeof(*pszCmd)*(_tcslen(pszCmd)+1)))
							nSetupRc = 1;

						free(pszCmd);
					}
					else
					{
						if (0==RegDeleteValue(hk, _T("AutoRun")))
							nSetupRc = 1;
					}

					RegCloseKey(hk);
					// сбросить CreateInNewEnvironment для ConMan
					ResetConman();
					iResult = nSetupRc;
					goto wrap;
				}
				else if (szArg.OneOfSwitches(L"-bypass", L"-apparent", L"-system:", L"-interactive:", L"-demote"))
				{
					// -bypass
					// Этот ключик был придуман для прозрачного запуска консоли
					// в режиме администратора
					// (т.е. чтобы окно UAC нормально всплывало, но не мелькало консольное окно)
					// Но не получилось, пока требуются хэндлы процесса, а их не получается
					// передать в НЕ приподнятый процесс (исходный ConEmu GUI).

					// -apparent
					// Same as -bypass, but run the process as SW_SHOWNORMAL

					// -demote
					// Запуск процесса (ком.строка после "/demote") в режиме простого юзера,
					// когда текущий процесс уже запущен "под админом". "Понизить" текущие
					// привилегии просто так нельзя, поэтому запуск идет через TaskSheduler.

					// -system
					// Non-interactive process, started as System account
					// It's used when starting consoles, our server works fine as non-interactive

					// -interactive
					// Used when ConEmu.exe is started under System account,
					// but we need to give starting process interactive capabilities.

					_ASSERTE(opt.runCommand.IsEmpty());
					pszTemp = cmdLineRest;
					if ((pszTemp = NextArg(pszTemp, szNext))
						&& szNext.OneOfSwitches(L"-run",L"-cmd"))
					{
						opt.runCommand.Set(pszTemp);
					}
					else
					{
						opt.runCommand.Set(cmdLineRest);
					}

					if (opt.runCommand.IsEmpty())
					{
						CEStr lsMsg(L"Invalid command line. '", szArg, L"' exists, command line is empty");
						DisplayLastError(lsMsg, -1);
						goto wrap;
					}

					// Information
					#ifdef _DEBUG
					STARTUPINFO siOur = {sizeof(siOur)};
					GetStartupInfo(&siOur);
					#endif

					STARTUPINFO si = {sizeof(si)};
					PROCESS_INFORMATION pi = {};
					si.dwFlags = STARTF_USESHOWWINDOW;
					// Only `-demote` and `-apparent` switches were implemented to start application visible
					// All others are intended to run our server process, without blinking of course
					if (szArg.OneOfSwitches(L"-demote", L"-apparent"))
						si.wShowWindow = SW_SHOWNORMAL;
					else
						si.wShowWindow = SW_HIDE;

					wchar_t szCurDir[MAX_PATH+1] = L"";
					GetCurrentDirectory(countof(szCurDir), szCurDir);

					BOOL b;
					DWORD nErr = 0;

					// if we were started from TaskScheduler, it would be nice to wait a little
					// to let parent (creator of the scheduler task) know we were started successfully
					bool bFromScheduler = false;

					// Log the command to be started
					{
						CEStr lsLog(
							L"Starting process",
							L": ", szArg,
							L" `", opt.runCommand.ms_Val, L"`");
						LogString(lsLog);
					}

					if (szArg.IsSwitch(L"-demote"))
					{
						b = CreateProcessDemoted(opt.runCommand.ms_Val, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL,
							szCurDir, &si, &pi, &nErr);
					}
					else if (szArg.IsSwitch(L"-system:"))
					{
						DWORD nSessionID = wcstoul(szArg.ms_Val+wcslen(L"-system:"), NULL, 10);
						b = CreateProcessSystem(nSessionID, opt.runCommand.ms_Val, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL,
							szCurDir, &si, &pi);
					}
					else if (szArg.IsSwitch(L"-interactive:"))
					{
						DWORD nSessionID = wcstoul(szArg.ms_Val+wcslen(L"-interactive:"), NULL, 10);
						b = CreateProcessInteractive(nSessionID, NULL, opt.runCommand.ms_Val, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL,
							szCurDir, &si, &pi, &nErr);
						bFromScheduler = true;
					}
					else // -bypass, -apparent
					{
						b = CreateProcess(NULL, opt.runCommand.ms_Val, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL,
							NULL, &si, &pi);
						nErr = b ? 0 : GetLastError();
						bFromScheduler = true;
					}

					// Log the result
					{
						CEStr lsLog; wchar_t szExtra[32] = L"";
						if (b)
						{
							if (pi.dwProcessId)
								swprintf_c(szExtra, L", PID=%u", pi.dwProcessId);
							lsLog = lstrmerge(
								L"Process was created successfully",
								szExtra);
						}
						else
						{
							swprintf_c(szExtra, L", ErrorCode=%u", nErr);
							lsLog = lstrmerge(
								L"Failed to start process",
								szExtra);
						}
						LogString(lsLog);
					}

					// If the error was not shown yet
					if (nErr) DisplayLastError(opt.runCommand, nErr);

					// if we were started from TaskScheduler, it would be nice to wait a little
					// to let parent (creator of the scheduler task) know we were started successfully
					if (bFromScheduler)
					{
						LogString(L"Sleeping for 5 seconds");
						Sleep(5*1000);
					}

					// Success?
					if (b)
					{
						iResult = 0;
					}

					// Done, close handles, if they were opened
					SafeCloseHandle(pi.hProcess);
					SafeCloseHandle(pi.hThread);

					goto wrap;
				}
				else if (szArg.IsSwitch(L"-multi"))
				{
					gpConEmu->AppendExtraArgs(szArg);
					gpConEmu->opt.MultiConValue = true;
				}
				else if (szArg.IsSwitch(L"-NoMulti"))
				{
					gpConEmu->AppendExtraArgs(szArg);
					gpConEmu->opt.MultiConValue = false;
				}
				else if (szArg.IsSwitch(L"-visible"))
				{
					gpConEmu->opt.VisValue = true;
				}
				else if (szArg.OneOfSwitches(L"-ct", L"-cleartype", L"-ct0", L"-ct1", L"-ct2"))
				{
					switch (szArg[3])
					{
					case L'0':
						gpConEmu->opt.ClearTypeVal = NONANTIALIASED_QUALITY; break;
					case L'1':
						gpConEmu->opt.ClearTypeVal = ANTIALIASED_QUALITY; break;
					default:
						gpConEmu->opt.ClearTypeVal = CLEARTYPE_NATURAL_QUALITY;
					}
				}
				// Interface language
				else if (szArg.IsSwitch(L"-lng"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.Language.Exists)
					{
						gpConEmu->opt.Language = (LPCWSTR)szNext;
						gpConEmu->AppendExtraArgs(L"-lng", szNext);
					}
				}
				// Optional specific "ConEmu.l10n"
				else if (szArg.IsSwitch(L"-lngfile"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.LanguageFile.Exists)
					{
						gpConEmu->opt.LanguageFile = (LPCWSTR)szNext;
						gpConEmu->AppendExtraArgs(L"-lngfile", szNext);
					}
				}
				// Change font name
				else if (szArg.IsSwitch(L"-Font"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.FontVal.Exists)
					{
						gpConEmu->opt.FontVal = (LPCWSTR)szNext;
						gpConEmu->AppendExtraArgs(L"-font", szNext);
					}
				}
				// Change font height
				else if (szArg.IsSwitch(L"-FontSize") || szArg.IsSwitch(L"-Size"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.SizeVal.Exists)
					{
						gpConEmu->opt.SizeVal.SetInt(szNext);
					}
				}
				// ADD fontname; by Mors
				else if (szArg.IsSwitch(L"-FontFile"))
				{
					CESwitch szFile(sw_Str);
					if (!GetCfgParm(cmdLineRest, szFile, MAX_PATH))
					{
						goto wrap;
					}
					gpConEmu->AppendExtraArgs(L"-FontFile", szFile.GetStr());
					gpFontMgr->RegisterFont(szFile.GetStr(), TRUE);
				}
				// Register all fonts from specified directory
				else if (szArg.IsSwitch(L"-FontDir"))
				{
					CESwitch szDir(sw_Str);
					if (!GetCfgParm(cmdLineRest, szDir, MAX_PATH))
					{
						goto wrap;
					}
					gpConEmu->AppendExtraArgs(L"-FontDir", szDir.GetStr());
					gpFontMgr->RegisterFontsDir(szDir.GetStr());
				}
				else if (szArg.IsSwitch(L"-fs"))
				{
					gpConEmu->opt.WindowModeVal = wmFullScreen;
				}
				else if (szArg.IsSwitch(L"-max"))
				{
					gpConEmu->opt.WindowModeVal = wmMaximized;
				}
				else if (szArg.OneOfSwitches(L"-min", L"-MinTSA", L"-StartTSA"))
				{
					gpConEmu->WindowStartMinimized = true;
					if (!szArg.IsSwitch(L"-min"))
					{
						gpConEmu->WindowStartTsa = true;
						gpConEmu->WindowStartNoClose = szArg.IsSwitch(L"-MinTSA");
					}
				}
				else if (szArg.OneOfSwitches(L"-tsa", L"-tray"))
				{
					gpConEmu->ForceMinimizeToTray = true;
				}
				else if (szArg.IsSwitch(L"-detached"))
				{
					gpConEmu->m_StartDetached = crb_On;
					opt.Detached = true;
				}
				else if (szArg.IsSwitch(L"-NoAutoClose"))
				{
					opt.NoAutoClose = true;
				}
				else if (szArg.IsSwitch(L"-here"))
				{
					gpConEmu->mb_ConEmuHere = true;
					gpConEmu->StoreWorkDir();
				}
				else if (szArg.IsSwitch(L"-update"))
				{
					gpConEmu->opt.AutoUpdateOnStart = true;
				}
				else if (szArg.IsSwitch(L"-NoUpdate"))
				{
					// This one has more weight than AutoUpdateOnStart
					gpConEmu->opt.DisableAutoUpdate = true;
				}
				else if (szArg.IsSwitch(L"-NoHooksWarn"))
				{
					// Don't try to warn users about known problems with third-party detours
					gpConEmu->opt.NoHooksWarn = true;
				}
				else if (szArg.OneOfSwitches(L"-NoKeyHook", L"-NoKeyHooks", L"-NoKeybHook", L"-NoKeybHooks"))
				{
					gpConEmu->DisableKeybHooks = true;
				}
				else if (szArg.IsSwitch(L"-NoCloseConfirm"))
				{
					gpConEmu->DisableCloseConfirm = true;
				}
				else if (szArg.IsSwitch(L"-NoMacro"))
				{
					gpConEmu->DisableAllMacro = true;
				}
				else if (szArg.OneOfSwitches(L"-NoHotkey", L"-NoHotkeys"))
				{
					gpConEmu->DisableAllHotkeys = true;
				}
				else if (szArg.OneOfSwitches(L"-NoDefTrm", L"-NoDefTerm"))
				{
					gpConEmu->DisableSetDefTerm = true;
				}
				else if (szArg.OneOfSwitches(L"-NoRegFont", L"-NoRegFonts"))
				{
					gpConEmu->DisableRegisterFonts = true;
				}
				else if (szArg.OneOfSwitches(L"-inside", L"-inside="))
				{
					bool bRunAsAdmin = RunAsAdmin::Check(szArg.ms_Val);
					bool bSyncDir = false;
					LPCWSTR pszSyncFmt = NULL;

					gpConEmu->mb_ConEmuHere = true;
					gpConEmu->StoreWorkDir();

					// Both `-inside:...` and `-inside=...` are supported
					if (szArg.IsSwitch(L"-inside="))
					{
						bSyncDir = true;
						pszSyncFmt = szArg.ms_Val+8; // \eCD /d %1 - \e - ESC, \b - BS, \n - ENTER, %1 - "dir", %2 - "bash dir"
					}

					CConEmuInside::InitInside(bRunAsAdmin, bSyncDir, pszSyncFmt, 0, NULL);
				}
				else if (szArg.IsSwitch(L"-InsidePID"))
				{
					NeedNextArg();

					bool bRunAsAdmin = RunAsAdmin::Check(szArg.ms_Val);

					wchar_t* pszEnd;
					// Здесь указывается PID, в который нужно внедриться.
					DWORD nInsideParentPID = wcstol(szNext, &pszEnd, 10);
					if (nInsideParentPID)
					{
						CConEmuInside::InitInside(bRunAsAdmin, false, NULL, nInsideParentPID, NULL);
					}
				}
				else if (szArg.IsSwitch(L"-InsideWnd"))
				{
					NeedNextArg();

					LPCWSTR pszHWnd = szNext.ms_Val;

					if (pszHWnd[0] == L'0' && (pszHWnd[1] == L'x' || pszHWnd[1] == L'X'))
						pszHWnd += 2;
					else if (pszHWnd[0] == L'x' || pszHWnd[0] == L'X')
						pszHWnd ++;

					bool bRunAsAdmin = RunAsAdmin::Check(szArg.ms_Val);

					wchar_t* pszEnd;
					// Здесь указывается HWND, в котором нужно создаваться.
					HWND hParent = (HWND)(DWORD_PTR)wcstoul(pszHWnd, &pszEnd, 16);
					if (hParent && IsWindow(hParent))
					{
						CConEmuInside::InitInside(bRunAsAdmin, false, NULL, 0, hParent);
					}
				}
				else if (szArg.IsSwitch(L"-icon"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.IconPrm.Exists && !szNext.IsEmpty())
					{
						gpConEmu->opt.IconPrm = true;
						gpConEmu->mps_IconPath = ExpandEnvStr(szNext);
					}
				}
				else if (szArg.IsSwitch(L"-dir"))
				{
					NeedNextArg();

					if (!szNext.IsEmpty())
					{
						// Например, "%USERPROFILE%"
						CEStr szExpand;
						if (wcschr(szNext, L'%') && ((szExpand = ExpandEnvStr(szNext)) != NULL))
						{
							gpConEmu->StoreWorkDir(szExpand);
						}
						else
						{
							gpConEmu->StoreWorkDir(szNext);
						}
					}
				}
				else if (szArg.IsSwitch(L"-UpdateJumpList"))
				{
					// Copy current Task list to Win7 Jump list (Taskbar icon)
					gpConEmu->mb_UpdateJumpListOnStartup = true;
				}
				else if (szArg.OneOfSwitches(L"-log", L"-log0", L"-log1", L"-log2", L"-log3", L"-log4"))
				{
					if (szArg.OneOfSwitches(L"-log", L"-log0"))
						gpConEmu->opt.AdvLogging.SetInt(1);
					else
						gpConEmu->opt.AdvLogging.SetInt((BYTE)(szArg[4] - L'0')); // 1..4
					// Do create logging service
					DEBUGSTRSTARTUP(L"Creating log file");
					gpConEmu->CreateLog();
				}
				else if (szArg.OneOfSwitches(L"-Single", L"-Reuse"))
				{
					// "/reuse" switch to be remastered
					gpConEmu->AppendExtraArgs(szArg);
					gpSetCls->SingleInstanceArg = sgl_Enabled;
				}
				else if (szArg.IsSwitch(L"-NoSingle"))
				{
					gpConEmu->AppendExtraArgs(szArg);
					gpSetCls->SingleInstanceArg = sgl_Disabled;
				}
				else if (szArg.IsSwitch(L"-DesktopMode"))
				{
					gpConEmu->opt.DesktopMode = true;
				}
				else if (szArg.OneOfSwitches(L"-Quake", L"-QuakeAuto", L"-NoQuake"))
				{
					if (szArg.IsSwitch(L"-Quake"))
						gpConEmu->opt.QuakeMode = 1;
					else if (szArg.IsSwitch(L"-QuakeAuto"))
						gpConEmu->opt.QuakeMode = 2;
					else
					{
						gpConEmu->opt.QuakeMode = 0;
						if (gpSetCls->SingleInstanceArg == sgl_Default)
							gpSetCls->SingleInstanceArg = sgl_Disabled;
					}
				}
				else if (szArg.OneOfSwitches(L"-FrameWidth", L"-Frame"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.FrameWidth.Exists)
						gpConEmu->opt.FrameWidth.SetInt(szNext);
				}
				else if (szArg.OneOfSwitches(L"-ShowHide", L"-ShowHideTSA"))
				{
					gpSetCls->SingleInstanceArg = sgl_Enabled;
					gpSetCls->SingleInstanceShowHide = szArg.IsSwitch(L"-ShowHide")
						? sih_ShowMinimize : sih_ShowHideTSA;
				}
				else if (szArg.OneOfSwitches(L"-Reset", L"-ResetDefault", L"-Basic"))
				{
					gpConEmu->opt.ResetSettings = true;
					if (szArg.IsSwitch(L"-ResetDefault"))
					{
						gpSetCls->isFastSetupDisabled = true;
					}
					else if (szArg.IsSwitch(L"-Basic"))
					{
						gpSetCls->isFastSetupDisabled = true;
						gpSetCls->isResetBasicSettings = true;
					}
				}
				else if (szArg.OneOfSwitches(L"-NoCascade", L"-DontCascade"))
				{
					gpConEmu->AppendExtraArgs(szArg);
					gpSetCls->isDontCascade = true;
				}
				else if (szArg.OneOfSwitches(L"-WndX", L"-WndY", L"-WndW", L"-WndWidth", L"-WndH", L"-WndHeight"))
				{
					wchar_t ch = szArg[4];
					CharUpperBuff(&ch, 1);

					CESwitch psz(sw_Str); bool bParm = false;
					if (!GetCfgParm(cmdLineRest, bParm, psz, 32))
					{
						goto wrap;
					}
					gpConEmu->opt.SizePosPrm = true;

					// Direct X/Y implies /nocascade
					if (ch == _T('X') || ch == _T('Y'))
					{
						// TODO: isDontCascade must be in our opt struct !!!
						gpSetCls->isDontCascade = true;
					}

					switch (ch)
					{
					case _T('X'): gpConEmu->opt.sWndX.SetStr(psz.Str, sw_Str); break;
					case _T('Y'): gpConEmu->opt.sWndY.SetStr(psz.Str, sw_Str); break;
					case _T('W'): gpConEmu->opt.sWndW.SetStr(psz.Str, sw_Str); break;
					case _T('H'): gpConEmu->opt.sWndH.SetStr(psz.Str, sw_Str); break;
					}
				}
				else if (szArg.IsSwitch(L"-Monitor"))
				{
					CESwitch psz(sw_Str); bool bParm = false;
					if (!GetCfgParm(cmdLineRest, bParm, psz, 64))
					{
						goto wrap;
					}

					if ((gpConEmu->opt.Monitor.Mon = MonitorFromParam(psz.Str)) != NULL)
					{
						gpConEmu->opt.Monitor.Exists = true;
						gpConEmu->opt.Monitor.Type = sw_Int;
						gpStartEnv->hStartMon = gpConEmu->opt.Monitor.Mon;
					}
				}
				else if (szArg.IsSwitch(L"-Theme"))
				{
					const wchar_t* kDefaultTheme = L"DarkMode_Explorer";
					bool bParm = false;
					if (!cmdLineRest || (*cmdLineRest == L'-' || *cmdLineRest == L'/')
						|| !GetCfgParm(cmdLineRest, bParm, gpConEmu->opt.WindowTheme, 128))
					{
						gpConEmu->opt.WindowTheme.SetStr(kDefaultTheme);
					}
				}
				else if (szArg.OneOfSwitches(L"-Buffer", L"-BufferHeight"))
				{
					NeedNextArg();

					if (!gpConEmu->opt.BufferHeightVal.Exists)
					{
						gpConEmu->opt.BufferHeightVal.SetInt(szNext);

						if (gpConEmu->opt.BufferHeightVal.GetInt() < 0)
						{
							//setParent = true; -- Maximus5 - нефиг, все ручками
							gpConEmu->opt.BufferHeightVal = -gpConEmu->opt.BufferHeightVal.GetInt();
						}

						if (gpConEmu->opt.BufferHeightVal.GetInt() < LONGOUTPUTHEIGHT_MIN)
							gpConEmu->opt.BufferHeightVal = LONGOUTPUTHEIGHT_MIN;
						else if (gpConEmu->opt.BufferHeightVal.GetInt() > LONGOUTPUTHEIGHT_MAX)
							gpConEmu->opt.BufferHeightVal = LONGOUTPUTHEIGHT_MAX;
					}
				}
				else if (szArg.IsSwitch(L"-Config"))
				{
					// -- используем последний из параметров, если их несколько
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.ConfigVal, 127))
					{
						goto wrap;
					}
				}
				else if (szArg.IsSwitch(L"-Palette"))
				{
					// -- используем последний из параметров, если их несколько
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.PaletteVal, MAX_PATH))
					{
						goto wrap;
					}
				}
				else if (szArg.IsSwitch(L"-LoadRegistry"))
				{
					gpConEmu->AppendExtraArgs(szArg);
					gpConEmu->opt.ForceUseRegistryPrm = true;
				}
				else if (szArg.OneOfSwitches(L"-LoadCfgFile", L"-LoadXmlFile"))
				{
					// -- используем последний из параметров, если их несколько
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.LoadCfgFile, MAX_PATH, true))
					{
						goto wrap;
					}
				}
				else if (szArg.OneOfSwitches(L"-SaveCfgFile", L"-SaveXmlFile"))
				{
					// -- используем последний из параметров, если их несколько
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.SaveCfgFile, MAX_PATH, true))
					{
						goto wrap;
					}
				}
				else if (szArg.IsSwitch(L"-GuiMacro"))
				{
					// -- выполняется только последний
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.ExecGuiMacro, 0x8000, false))
					{
						goto wrap;
					}
				}
				else if (szArg.IsSwitch(L"-UpdateSrcSet"))
				{
					// -- используем последний из параметров, если их несколько
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.UpdateSrcSet, MAX_PATH*4, false))
					{
						goto wrap;
					}
				}
				else if (szArg.IsSwitch(L"-AnsiLog"))
				{
					// -- используем последний из параметров, если их несколько
					if (!GetCfgParm(cmdLineRest, gpConEmu->opt.AnsiLogPath, MAX_PATH-40, true))
					{
						goto wrap;
					}
				}
				else if (szArg.IsSwitch(L"-SetDefTerm"))
				{
					gpConEmu->opt.SetUpDefaultTerminal = true;
				}
				else if (szArg.IsSwitch(L"-ZoneId"))
				{
					gpConEmu->opt.FixZoneId = true;
				}
				else if (szArg.IsSwitch(L"-Exit"))
				{
					gpConEmu->opt.ExitAfterActionPrm = true;
				}
				else if (szArg.IsSwitch(L"-QuitOnClose"))
				{
					gpConEmu->mb_ForceQuitOnClose = true;
				}
				else if (szArg.IsSwitch(L"-Title"))
				{
					bool bOk = false;
					CESwitch pszTitle(sw_Str);
					if (!GetCfgParm(cmdLineRest, bOk, pszTitle, 127))
					{
						goto wrap;
					}
					gpConEmu->SetTitleTemplate(pszTitle.GetStr());
				}
				else if (szArg.IsSwitch(L"-Settings"))
				{
					gpConEmu->mb_SettingsRequested = true;
				}
				else if (szArg.IsSwitch(L"-FindBugMode"))
				{
					gpConEmu->mb_FindBugMode = true;
				}
				else if (szArg.OneOfSwitches(L"-debug", L"-debugw", L"-debugi"))
				{
					// These switches were already processed
				}
				else if (szArg.OneOfSwitches(L"-?", L"-h", L"-help"))
				{
					if (gpLng) gpLng->Reload();
					ConEmuAbout::OnInfo_About();
					iResult = -1;
					goto wrap;
				}
				// Final `-run ...` or `-runlist ...` (old names `-cmd ...` or `-cmdlist ...`)
				else if (
					szArg.OneOfSwitches(L"-run", L"-runlist", L"-cmd", L"-cmdlist")
					)
				{
					if (opt.cfgSwitches.ms_Val)
					{
						_ASSERTE(pszArgStart>=pszCopyToEnvStart); // If there is only "-run cmd" in arguments
						_ASSERTE((INT_PTR)(pszArgStart - pszCopyToEnvStart) <= opt.cfgSwitches.GetLen());
						opt.cfgSwitches.ms_Val[pszArgStart - pszCopyToEnvStart] = 0;
					}

					opt.runCommand.Set(SkipNonPrintable(cmdLineRest));
					opt.isScript = szArg.OneOfSwitches(L"-runlist", L"-cmdlist");
					break;
				}
				else
				{
					// Show error on unknown switch
					psUnknown = pszArgStart;
					break;
				}
			}
			// Main processing cycle end

			// Avoid assertions in NextArg
			szArg.Empty(); szNext.Empty();
		} // while (NextArg(&cmdLineRest, szArg, &pszArgStart) == 0)
	}
示例#25
0
文件: ansicon.c 项目: kmkkmk/app
// Add or remove ANSICON to AutoRun.
void process_autorun( TCHAR cmd )
{
  HKEY	 cmdkey;
  TCHAR  ansicon[MAX_PATH+8];
  LPTSTR autorun, ansirun;
  DWORD  len, type, exist;
  BOOL	 inst;

  len = GetModuleFileName( NULL, ansicon+2, MAX_PATH );
  ansicon[0] = '&';
  ansicon[1] = ansicon[2+len] = '"';
  wcscpy( ansicon + 3+len, L" -p" );
  len += 6;

  inst = (towlower( cmd ) == 'i');
  RegCreateKeyEx( (iswlower( cmd )) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE,
		  CMDKEY, 0, NULL,
		  REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
		  &cmdkey, &exist );
  exist = 0;
  RegQueryValueEx( cmdkey, AUTORUN, NULL, NULL, NULL, &exist );
  autorun = malloc( exist + len * sizeof(TCHAR) + sizeof(TCHAR) );
  // Let's assume there's sufficient memory.
  if (exist > sizeof(TCHAR))
  {
    exist += sizeof(TCHAR);
    RegQueryValueEx( cmdkey, AUTORUN, NULL, &type, (PBYTE)autorun, &exist );
    ansirun = wcsstr( autorun, ansicon+1 );
    if (inst)
    {
      if (!ansirun)
      {
	wcscpy( (LPTSTR)((PBYTE)autorun + exist - sizeof(TCHAR)), ansicon );
	RegSetValueEx( cmdkey, AUTORUN, 0, type, (PBYTE)autorun,
		       exist + len*sizeof(TCHAR) );
      }
    }
    else
    {
      if (ansirun)
      {
	if (ansirun == autorun && exist == len*sizeof(TCHAR))
	  RegDeleteValue( cmdkey, AUTORUN );
	else
	{
	  if (ansirun > autorun && ansirun[-1] == '&')
	    --ansirun;
	  else if (autorun[len-1] != '&')
	    --len;
	  memcpy( ansirun, ansirun + len, exist - len*sizeof(TCHAR) );
	  RegSetValueEx( cmdkey, AUTORUN, 0, type, (PBYTE)autorun,
			 exist - len*sizeof(TCHAR) );
	}
      }
    }
  }
  else if (inst)
  {
    RegSetValueEx( cmdkey, AUTORUN, 0, REG_SZ, (PBYTE)(ansicon+1),
		   len*sizeof(TCHAR) );
  }

  free( autorun );
  RegCloseKey( cmdkey );
}
示例#26
0
HRESULT Install( BOOL bRegisterUninstaller, BOOL bCopyFile )
{
	TCHAR szCurrentDllPath[MAX_PATH << 1];
	GetModuleFileName(g_hModThisDll, szCurrentDllPath, countof(szCurrentDllPath));

	TCHAR szSysDir[MAX_PATH + 0x20];
	UINT uSize = GetSystemDirectory(szSysDir, MAX_PATH);

	if (uSize && uSize < MAX_PATH)
	{
		LPTSTR lpszPath = szSysDir;
		LPTSTR lpszPathAppend = lpszPath + uSize;

		if (*(lpszPathAppend - 1) != TEXT('\\'))
			*lpszPathAppend++ = TEXT('\\');

		LPTSTR lpszTargetPath = (bCopyFile) ? lpszPath : szCurrentDllPath;

		if ( (!bCopyFile || InstallFile(szCurrentDllPath, lpszTargetPath, lpszPathAppend)) &&
		     DllRegisterServerEx(lpszTargetPath) == S_OK )
		{
			HKEY hKey, hKeySub;

			// Associate file extensions
			for (UINT i = 0; i < countof(g_szHashExtsTab); ++i)
			{
				if (hKey = RegOpen(HKEY_CLASSES_ROOT, g_szHashExtsTab[i], NULL, TRUE))
				{
					RegSetSZ(hKey, NULL, PROGID_STR_HashCheck);
					RegSetSZ(hKey, TEXT("PerceivedType"), TEXT("text"));

					if (hKeySub = RegOpen(hKey, TEXT("PersistentHandler"), NULL, TRUE))
					{
						RegSetSZ(hKeySub, NULL, TEXT("{5e941d80-bf96-11cd-b579-08002b30bfeb}"));
						RegCloseKey(hKeySub);
					}

					RegCloseKey(hKey);
				}
			}

            // Disassociate former file extensions; see the comment in DllUnregisterServer for
            // why this step is skipped for Wow64 processes
            if (!Wow64CheckProcess())
            {
                for (UINT i = 0; i < countof(szFormerHashExtsTab); ++i)
                {
                    HKEY hKey;

                    if (hKey = RegOpen(HKEY_CLASSES_ROOT, szFormerHashExtsTab[i], NULL, FALSE))
                    {
                        TCHAR szTemp[countof(PROGID_STR_HashCheck)];
                        RegGetSZ(hKey, NULL, szTemp, sizeof(szTemp));
                        if (_tcscmp(szTemp, PROGID_STR_HashCheck) == 0)
                            RegDeleteValue(hKey, NULL);
                        RegCloseKey(hKey);
                    }
                }
            }

			// Uninstaller entries
			RegDelete(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s"), CLSNAME_STR_HashCheck);

			if (bRegisterUninstaller && (hKey = RegOpen(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s"), CLSNAME_STR_HashCheck, TRUE)))
			{
				TCHAR szUninstall[MAX_PATH << 1];
				StringCchPrintf(szUninstall, countof(szUninstall), TEXT("regsvr32.exe /u /i /n \"%s\""), lpszTargetPath);

				static const TCHAR szURLFull[] = TEXT("https://github.com/gurnec/HashCheck/issues");
				TCHAR szURLBase[countof(szURLFull)];
				SSStaticCpy(szURLBase, szURLFull);
				szURLBase[35] = 0; // strlen("https://github.com/gurnec/HashCheck")

				RegSetSZ(hKey, TEXT("DisplayIcon"), lpszTargetPath);
				RegSetSZ(hKey, TEXT("DisplayName"), TEXT(HASHCHECK_NAME_STR));
				RegSetSZ(hKey, TEXT("DisplayVersion"), TEXT(HASHCHECK_VERSION_STR));
				RegSetDW(hKey, TEXT("EstimatedSize"), 1073);
				RegSetSZ(hKey, TEXT("HelpLink"), szURLFull);
				RegSetDW(hKey, TEXT("NoModify"), 1);
				RegSetDW(hKey, TEXT("NoRepair"), 1);
				RegSetSZ(hKey, TEXT("UninstallString"), szUninstall);
				RegSetSZ(hKey, TEXT("URLInfoAbout"), szURLBase);
				RegSetSZ(hKey, TEXT("URLUpdateInfo"), TEXT("https://github.com/gurnec/HashCheck/releases/latest"));
				RegCloseKey(hKey);
			}

			return(S_OK);

		} // if copied & registered

	} // if valid sysdir

	return(E_FAIL);
}
示例#27
0
HRESULT Import(PTSTR ptzScript, PCTSTR* pptzStop = NULL)
{
	HKEY hKey = NULL;
	_SkipBlank(ptzScript);
	HRESULT hResult = S_OK;
	PTSTR ptzEnd = ptzScript;
	PTSTR ptzStart = ptzScript;
	while (*ptzScript)
	{
		switch (*ptzScript)
		{
		case '"':
			if (*ptzStart != '[')
			{
				ptzScript++;
				*ptzEnd++ = CC_SEP;
				continue;
			}
			break;

		case '\\':
			if (*ptzStart != '[')
			{
				ptzScript++;
				_SkipBlank(ptzScript);
				*ptzEnd++ = *ptzScript++;
				continue;
			}
			break;

		case '\r':
		case '\n':
			*ptzEnd = 0;
			if (*ptzStart == '[')
			{
				if (hKey)
				{
					RegCloseKey(hKey);
					hKey = NULL;
				}
				ptzScript[-1] = 0;
				if (*++ptzStart == '-')
				{
					HKEY hRoot = GetRootKey(++ptzStart);
					if (hRoot)
					{
						SHDeleteKey(hRoot, ptzStart);
					}
				}
				else
				{
					HKEY hRoot = GetRootKey(ptzStart);
					if (hRoot)
					{
						RegCreateKeyEx(hRoot, ptzStart, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL);
					}
				}
			}
			else if (hKey && ((*ptzStart == '@') || (*ptzStart == CC_SEP)))
			{
				PTSTR ptzVal;
				if (*ptzStart++ == '@')
				{
					ptzVal = UStrChr(ptzStart, '=');
					ptzStart = NULL;
				}
				else if (ptzVal = UStrChr(ptzStart, CC_SEP))
				{
					*ptzVal++ = 0;
					ptzVal = UStrChr(ptzVal, '=');
				}

				if (ptzVal)
				{
					PTSTR ptzTemp;
					if (ptzTemp = UStrStrI(ptzVal, TEXT("DWORD:")))
					{
						ptzVal = ptzTemp + 4;
						ptzVal[0] = '0';
						ptzVal[1] = 'x';
						DWORD dwData = UStrToInt(ptzVal);
						RegSetValueEx(hKey, ptzStart, 0, REG_DWORD, (PBYTE) &dwData, sizeof(DWORD));
					}
					else if (ptzTemp = UStrStrI(ptzVal, TEXT("HEX")))
					{
						DWORD dwType = REG_BINARY;
						if (ptzTemp[3] == '(')
						{
							ptzVal[2] = '0';
							ptzVal[3] = 'x';
							dwType = UStrToInt(ptzTemp + 2);
						}

						if (ptzVal = UStrChr(ptzTemp, ':'))
						{
							ptzVal++;
							UINT i = 0;
							PBYTE pbVal = (PBYTE) ptzVal;
							while (*ptzVal)
							{
								BYTE bVal = (UChrToHex(ptzVal[0]) << 4) | UChrToHex(ptzVal[1]);
								while (*ptzVal && (*ptzVal++ != ','));
								pbVal[i++] = bVal;
							}
							RegSetValueEx(hKey, ptzStart, 0, dwType, pbVal, i);
						}
					}
					else if (ptzTemp = UStrStrI(ptzVal, TEXT("MULTI_SZ:")))
					{
						if (ptzVal = UStrChr(ptzTemp, CC_SEP))
						{
							ptzEnd = ++ptzVal;
							ptzTemp = ptzVal;
							while (*ptzTemp)
							{
								if (*ptzTemp == CC_SEP)
								{
									ptzTemp++;
									*ptzEnd++ = 0;
									while (*ptzTemp && (*ptzTemp++ != CC_SEP));
								}
								else
								{
									*ptzEnd++ =*ptzTemp++;
								}
							}
							*ptzEnd++ = 0;
							RegSetValueEx(hKey, ptzStart, 0, REG_MULTI_SZ, (PBYTE) ptzVal, (DWORD) (ptzEnd - ptzVal) * sizeof(TCHAR));
						}
					}
					else
					{
						DWORD dwType = UStrStrI(ptzVal, TEXT("MUI_SZ:")) ? REG_MUI_SZ : REG_SZ;
						if (ptzTemp = UStrChr(ptzVal, CC_SEP))
						{
							ptzVal = ptzTemp + 1;
							if (ptzTemp = UStrChr(ptzVal, CC_SEP))
							{
								*ptzTemp++ = 0;
								RegSetValueEx(hKey, ptzStart, 0, dwType, (PBYTE) ptzVal, (DWORD) (ptzTemp - ptzVal) * sizeof(TCHAR));
							}
						}
						else if (ptzVal[1] == '-')
						{
							RegDeleteValue(hKey, ptzStart);
						}
					}
				}
			}
			else if (*ptzStart != ';')
			{
				hResult = ERROR_NOT_REGISTRY_FILE;
				if (pptzStop)
				{
					*ptzScript = '\n';
					ptzScript = ptzStart;
					goto _Stop;
				}				
			}
			ptzScript++;
			_SkipBlank(ptzScript);
			ptzStart = ptzEnd = ptzScript;
			continue;
		}

		*ptzEnd++ = *ptzScript++;
	}

_Stop:
	if (pptzStop)
	{
		*pptzStop = ptzScript;
	}
	if (hKey)
	{
		RegCloseKey(hKey);
	}
	return hResult;
}
示例#28
0
bool VDRegistryKey::removeValue(const char *name) {
	if (!pHandle || RegDeleteValue((HKEY)pHandle, name))
		return false;

	return true;
}
LONG CPropertyArchiveRegistry::DeleteValue(const CString &strValue)
{
	assert(GetKey() != NULL);
	return RegDeleteValue(GetKey(), (LPTSTR)(LPCTSTR)strValue);
}
示例#30
0
// Nettoie la clé de PuTTY pour enlever les clés et valeurs spécifique à KiTTY
BOOL RegCleanPuTTY( void ) {
	HKEY hKey, hSubKey ;
	DWORD retCode, i;
	TCHAR    achKey[MAX_KEY_LENGTH];   // buffer for subkey name
	DWORD    cbName;                   // size of name string 
	TCHAR    achClass[MAX_PATH] = TEXT("");  // buffer for class name 
	DWORD    cchClassName = MAX_PATH;  // size of class string 
	DWORD    cSubKeys=0;               // number of subkeys 
	DWORD    cbMaxSubKey;              // longest subkey size 
	DWORD    cchMaxClass;              // longest class string 
	DWORD    cValues;              // number of values for key 
	DWORD    cchMaxValue;          // longest value name 
	DWORD    cbMaxValueData;       // longest value data 
	DWORD    cbSecurityDescriptor; // size of security descriptor 
	FILETIME ftLastWriteTime;      // last write time 
	char *buffer = NULL ;
#ifdef FDJ
return 1 ;
#endif
	if( (retCode = RegOpenKeyEx ( HKEY_CURRENT_USER, "Software\\SimonTatham\\PuTTY", 0, KEY_WRITE, &hSubKey)) == ERROR_SUCCESS ) {
		RegDeleteValue( hSubKey, "Build" ) ;
		RegDeleteValue( hSubKey, "Folders" ) ;
		RegDeleteValue( hSubKey, "KiCount" ) ;
		RegDeleteValue( hSubKey, "KiLastSe" ) ;
		RegDeleteValue( hSubKey, "KiLastUH" ) ;
		RegDeleteValue( hSubKey, "KiLastUp" ) ;
		RegDeleteValue( hSubKey, "KiPath" ) ;
		RegDeleteValue( hSubKey, "KiSess" ) ;
		RegDeleteValue( hSubKey, "KiVers" ) ;
		RegDeleteValue( hSubKey, "CtHelperPath" ) ;
		RegDeleteValue( hSubKey, "PSCPPath" ) ;
		RegDeleteValue( hSubKey, "WinSCPPath" ) ;
		RegDeleteValue( hSubKey, "KiClassName" ) ;
		RegCloseKey(hSubKey) ;
		}
	
	RegDelTree (HKEY_CURRENT_USER, "Software\\SimonTatham\\PuTTY\\Commands" ) ;
	RegDelTree (HKEY_CURRENT_USER, "Software\\SimonTatham\\PuTTY\\Folders" ) ;
	RegDelTree (HKEY_CURRENT_USER, "Software\\SimonTatham\\PuTTY\\Launcher" ) ;
	
	// On ouvre la clé
	if( RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\SimonTatham\\PuTTY\\Sessions", 0, KEY_READ|KEY_WRITE, &hKey) != ERROR_SUCCESS ) return 0;
	
	retCode = RegQueryInfoKey(
        hKey,                    // key handle 
        achClass,                // buffer for class name 
        &cchClassName,           // size of class string 
        NULL,                    // reserved 
        &cSubKeys,               // number of subkeys 
        &cbMaxSubKey,            // longest subkey size 
        &cchMaxClass,            // longest class string 
        &cValues,                // number of values for this key 
        &cchMaxValue,            // longest value name 
        &cbMaxValueData,         // longest value data 
        &cbSecurityDescriptor,   // security descriptor 
        &ftLastWriteTime);
	
	// Enumerate the subkeys, until RegEnumKeyEx fails.
	if (cSubKeys) {  //printf( "\nNumber of subkeys: %d\n", cSubKeys);
		for (i=0; i<cSubKeys; i++) { 
			cbName = MAX_KEY_LENGTH;
			if( ( retCode = RegEnumKeyEx(hKey, i, achKey, &cbName,NULL,NULL,NULL, &ftLastWriteTime) ) == ERROR_SUCCESS ) {
				buffer = (char*) malloc( strlen( achKey ) + 50 ) ;
				sprintf( buffer, "Software\\SimonTatham\\PuTTY\\Sessions\\%s\\Commands", achKey ) ;
				RegDelTree( HKEY_CURRENT_USER, buffer );
				sprintf( buffer, "Software\\SimonTatham\\PuTTY\\Sessions\\%s", achKey ) ;
				if( (retCode = RegOpenKeyEx ( HKEY_CURRENT_USER, buffer, 0, KEY_WRITE, &hSubKey)) == ERROR_SUCCESS ) {
					RegDeleteValue( hSubKey, "BCDelay" ) ;
					RegDeleteValue( hSubKey, "BgOpacity" ) ;
					RegDeleteValue( hSubKey, "BgSlideshow" ) ;
					RegDeleteValue( hSubKey, "BgType" ) ;
					RegDeleteValue( hSubKey, "BgImageFile" ) ;
					RegDeleteValue( hSubKey, "BgImageStyle" ) ;
					RegDeleteValue( hSubKey, "BgImageAbsoluteX" ) ;
					RegDeleteValue( hSubKey, "BgImageAbsoluteY" ) ;
					RegDeleteValue( hSubKey, "BgImagePlacement" ) ;
					RegDeleteValue( hSubKey, "Maximize" ) ;
					RegDeleteValue( hSubKey, "SendToTray" ) ;
					RegDeleteValue( hSubKey, "SaveOnExit" ) ;
					RegDeleteValue( hSubKey, "Folder" ) ;
					RegDeleteValue( hSubKey, "Icone" ) ;
					RegDeleteValue( hSubKey, "IconeFile" ) ;
					RegDeleteValue( hSubKey, "InitDelay" ) ;
					RegDeleteValue( hSubKey, "Password" ) ;
					RegDeleteValue( hSubKey, "Autocommand" ) ;
					RegDeleteValue( hSubKey, "AutocommandOut" ) ;
					RegDeleteValue( hSubKey, "AntiIdle" ) ;
					RegDeleteValue( hSubKey, "LogTimestamp" ) ;
					RegDeleteValue( hSubKey, "Notes" ) ;
					RegDeleteValue( hSubKey, "CygtermCommand" ) ;
					RegDeleteValue( hSubKey, "WakeupReconnect" ) ;
					RegDeleteValue( hSubKey, "FailureReconnect" ) ;
					RegDeleteValue( hSubKey, "Scriptfile" ) ;
					RegDeleteValue( hSubKey, "TransparencyValue" ) ;
					RegDeleteValue( hSubKey, "TermXPos" ) ;
					RegDeleteValue( hSubKey, "TermYPos" ) ;
					RegDeleteValue( hSubKey, "AuthPKCS11" ) ;
					RegDeleteValue( hSubKey, "PKCS11LibFile" ) ;
					RegDeleteValue( hSubKey, "PKCS11TokenLabel" ) ;
					RegDeleteValue( hSubKey, "PKCS11CertLabel" ) ;
					RegDeleteValue( hSubKey, "CopyURLDetection" ) ;
					RegDeleteValue( hSubKey, "HyperlinkUnderline" ) ;
					RegDeleteValue( hSubKey, "HyperlinkUseCtrlClick" ) ;
					RegDeleteValue( hSubKey, "HyperlinkBrowserUseDefault" ) ;
					RegDeleteValue( hSubKey, "HyperlinkBrowser" ) ;
					RegDeleteValue( hSubKey, "HyperlinkRegularExpressionUseDefault" ) ;
					RegDeleteValue( hSubKey, "HyperlinkRegularExpression" ) ;
					RegDeleteValue( hSubKey, "rzCommand" ) ;
					RegDeleteValue( hSubKey, "rzOptions" ) ;
					RegDeleteValue( hSubKey, "szCommand" ) ;
					RegDeleteValue( hSubKey, "szOptions" ) ;
					RegDeleteValue( hSubKey, "zDownloadDir" ) ;
					RegDeleteValue( hSubKey, "SaveWindowPos" ) ;
					//RegDeleteValue( hSubKey, "" ) ;
 					RegCloseKey(hSubKey) ;
					}
				free( buffer );
				}
			}
		} 
 
	RegCloseKey( hKey ) ;
	
	return 1;
	}