Exemple #1
0
static int tncc_read_config_reg(struct tncc_data *tncc, HKEY hive)
{
	HKEY hk, hk2;
	LONG ret;
	DWORD i;
	struct tnc_if_imc *imc, *last;
	int j;

	last = tncc->imc;
	while (last && last->next)
		last = last->next;

	ret = RegOpenKeyEx(hive, TNC_WINREG_PATH, 0, KEY_ENUMERATE_SUB_KEYS,
			   &hk);
	if (ret != ERROR_SUCCESS)
		return 0;

	for (i = 0; ; i++) {
		TCHAR name[255], *val;
		DWORD namelen, buflen;

		namelen = 255;
		ret = RegEnumKeyEx(hk, i, name, &namelen, NULL, NULL, NULL,
				   NULL);

		if (ret == ERROR_NO_MORE_ITEMS)
			break;

		if (ret != ERROR_SUCCESS) {
			wpa_printf(MSG_DEBUG, "TNC: RegEnumKeyEx failed: 0x%x",
				   (unsigned int) ret);
			break;
		}

		if (namelen >= 255)
			namelen = 255 - 1;
		name[namelen] = '\0';

		wpa_printf(MSG_DEBUG, "TNC: IMC '" TSTR "'", name);

		ret = RegOpenKeyEx(hk, name, 0, KEY_QUERY_VALUE, &hk2);
		if (ret != ERROR_SUCCESS) {
			wpa_printf(MSG_DEBUG, "Could not open IMC key '" TSTR
				   "'", name);
			continue;
		}

		ret = RegQueryValueEx(hk2, TEXT("Path"), NULL, NULL, NULL,
				      &buflen);
		if (ret != ERROR_SUCCESS) {
			wpa_printf(MSG_DEBUG, "TNC: Could not read Path from "
				   "IMC key '" TSTR "'", name);
			RegCloseKey(hk2);
			continue;
		}

		val = os_malloc(buflen);
		if (val == NULL) {
			RegCloseKey(hk2);
			continue;
		}

		ret = RegQueryValueEx(hk2, TEXT("Path"), NULL, NULL,
				      (LPBYTE) val, &buflen);
		if (ret != ERROR_SUCCESS) {
			os_free(val);
			RegCloseKey(hk2);
			continue;
		}

		RegCloseKey(hk2);

		wpa_unicode2ascii_inplace(val);
		wpa_printf(MSG_DEBUG, "TNC: IMC Path '%s'", (char *) val);

		for (j = 0; j < TNC_MAX_IMC_ID; j++) {
			if (tnc_imc[j] == NULL)
				break;
		}
		if (j >= TNC_MAX_IMC_ID) {
			wpa_printf(MSG_DEBUG, "TNC: Too many IMCs");
			os_free(val);
			continue;
		}

		imc = os_zalloc(sizeof(*imc));
		if (imc == NULL) {
			os_free(val);
			break;
		}

		imc->imcID = j;

		wpa_unicode2ascii_inplace(name);
		imc->name = os_strdup((char *) name);
		imc->path = os_strdup((char *) val);

		os_free(val);

		if (last == NULL)
			tncc->imc = imc;
		else
			last->next = imc;
		last = imc;

		tnc_imc[imc->imcID] = imc;
	}

	RegCloseKey(hk);

	return 0;
}
static int wpa_supplicant_thread(void)
{
	int exitcode;
	struct wpa_params params;
	struct wpa_global *global;
	HKEY hk, ihk;
	DWORD val, buflen, i;
	LONG ret;

	if (os_program_init())
		return -1;

	os_memset(&params, 0, sizeof(params));
	params.wpa_debug_level = MSG_INFO;

	ret = RegOpenKeyEx(WPA_KEY_ROOT, WPA_KEY_PREFIX,
			   0, KEY_QUERY_VALUE, &hk);
	if (ret != ERROR_SUCCESS) {
		printf("Could not open wpa_supplicant registry key\n");
		return -1;
	}

	buflen = sizeof(val);
	ret = RegQueryValueEx(hk, TEXT("debug_level"), NULL, NULL,
			      (LPBYTE) &val, &buflen);
	if (ret == ERROR_SUCCESS && buflen == sizeof(val)) {
		params.wpa_debug_level = val;
	}

	buflen = sizeof(val);
	ret = RegQueryValueEx(hk, TEXT("debug_show_keys"), NULL, NULL,
			      (LPBYTE) &val, &buflen);
	if (ret == ERROR_SUCCESS && buflen == sizeof(val)) {
		params.wpa_debug_show_keys = val;
	}

	buflen = sizeof(val);
	ret = RegQueryValueEx(hk, TEXT("debug_timestamp"), NULL, NULL,
			      (LPBYTE) &val, &buflen);
	if (ret == ERROR_SUCCESS && buflen == sizeof(val)) {
		params.wpa_debug_timestamp = val;
	}

	buflen = sizeof(val);
	ret = RegQueryValueEx(hk, TEXT("debug_use_file"), NULL, NULL,
			      (LPBYTE) &val, &buflen);
	if (ret == ERROR_SUCCESS && buflen == sizeof(val) && val) {
		params.wpa_debug_file_path = "\\Temp\\wpa_supplicant-log.txt";
	}

	exitcode = 0;
	global = wpa_supplicant_init(&params);
	if (global == NULL) {
		printf("Failed to initialize wpa_supplicant\n");
		exitcode = -1;
	}

	ret = RegOpenKeyEx(hk, TEXT("interfaces"), 0, KEY_ENUMERATE_SUB_KEYS,
			   &ihk);
	RegCloseKey(hk);
	if (ret != ERROR_SUCCESS) {
		printf("Could not open wpa_supplicant interfaces registry "
		       "key\n");
		return -1;
	}

	for (i = 0; ; i++) {
		TCHAR name[255];
		DWORD namelen;

		namelen = 255;
		ret = RegEnumKeyEx(ihk, i, name, &namelen, NULL, NULL, NULL,
				   NULL);

		if (ret == ERROR_NO_MORE_ITEMS)
			break;

		if (ret != ERROR_SUCCESS) {
			printf("RegEnumKeyEx failed: 0x%x\n",
			       (unsigned int) ret);
			break;
		}

		if (namelen >= 255)
			namelen = 255 - 1;
		name[namelen] = '\0';

		wpa_printf(MSG_DEBUG, "interface %d: %s\n", (int) i, name);
		if (read_interface(global, ihk, name) < 0)
			exitcode = -1;
	}

	RegCloseKey(ihk);

	if (exitcode == 0)
		exitcode = wpa_supplicant_run(global);

	wpa_supplicant_deinit(global);

	os_program_deinit();

	return exitcode;
}
static int is_tap_win32_dev(const char *guid)
{
    HKEY netcard_key;
    LONG status;
    DWORD len;
    int i = 0;

    status = RegOpenKeyEx(
        HKEY_LOCAL_MACHINE,
        ADAPTER_KEY,
        0,
        KEY_READ,
        &netcard_key);

    if (status != ERROR_SUCCESS) {
        return FALSE;
    }

    for (;;) {
        char enum_name[256];
        char unit_string[256];
        HKEY unit_key;
        char component_id_string[] = "ComponentId";
        char component_id[256];
        char net_cfg_instance_id_string[] = "NetCfgInstanceId";
        char net_cfg_instance_id[256];
        DWORD data_type;

        len = sizeof (enum_name);
        status = RegEnumKeyEx(
            netcard_key,
            i,
            enum_name,
            &len,
            NULL,
            NULL,
            NULL,
            NULL);

        if (status == ERROR_NO_MORE_ITEMS)
            break;
        else if (status != ERROR_SUCCESS) {
            return FALSE;
        }

        snprintf (unit_string, sizeof(unit_string), "%s\\%s",
                  ADAPTER_KEY, enum_name);

        status = RegOpenKeyEx(
            HKEY_LOCAL_MACHINE,
            unit_string,
            0,
            KEY_READ,
            &unit_key);

        if (status != ERROR_SUCCESS) {
            return FALSE;
        } else {
            len = sizeof (component_id);
            status = RegQueryValueEx(
                unit_key,
                component_id_string,
                NULL,
                &data_type,
                (LPBYTE)component_id,
                &len);

            if (!(status != ERROR_SUCCESS || data_type != REG_SZ)) {
                len = sizeof (net_cfg_instance_id);
                status = RegQueryValueEx(
                    unit_key,
                    net_cfg_instance_id_string,
                    NULL,
                    &data_type,
                    (LPBYTE)net_cfg_instance_id,
                    &len);

                if (status == ERROR_SUCCESS && data_type == REG_SZ) {
                    if (/* !strcmp (component_id, TAP_COMPONENT_ID) &&*/
                        !strcmp (net_cfg_instance_id, guid)) {
                        RegCloseKey (unit_key);
                        RegCloseKey (netcard_key);
                        return TRUE;
                    }
                }
            }
            RegCloseKey (unit_key);
        }
        ++i;
    }

    RegCloseKey (netcard_key);
    return FALSE;
}
Exemple #4
0
bool Win32Vif::InitTap(const char* vifName, const ProtoAddress& vifAddr, unsigned int maskLen)
{
	HKEY key;
    ULONG status;
	char adapterid[1024];
	char tapname[1024];
    long len;

    /// Open Registry and get a list of network adapters
    status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                          NETWORK_CONNECTIONS_KEY,
                          0,
                          KEY_READ,
                          &key);

    if (status != ERROR_SUCCESS)
    {
        PLOG(PL_ERROR,"Win32Vif::InitTap() Error opening registry key:%s\n",NETWORK_CONNECTIONS_KEY);
        return false;
    }

	/* find the adapter with TAPSUFFIX */
    for (int enum_index = 0; ; enum_index++) 
    {
		len = sizeof(adapterid);
		if (RegEnumKeyEx(key, enum_index, adapterid, (LPDWORD)&len, 
                        NULL, NULL, NULL, NULL) != ERROR_SUCCESS) 
        {
			RegCloseKey(key);
			PLOG(PL_ERROR,"Win32Vif::InitTap() error: Couldn't find TAP-Win32 adapter.\n");
			return false;
		}
		sprintf(tapname, USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
        // Get the tap handle
		tap_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ,
			    0, 0, OPEN_EXISTING, 
                FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
		
		if (tap_handle != INVALID_HANDLE_VALUE) 
        {
            break;
		}
	}
    
    RegCloseKey(key);
	PLOG(PL_INFO,"win32Vif::InitTap() found tap adapter %s\n",tapname);

    if (!ConfigureTap(adapterid,vifName,vifAddr,maskLen))
        return false;

    if (NULL == (input_handle = CreateEvent(NULL,TRUE,FALSE,NULL)))
    {
        input_handle = INVALID_HANDLE_VALUE;
        PLOG(PL_ERROR,"Win32Vif::InitTap() CreateEvent(input_handle) error: %s\n", ::GetErrorString());
        Close(); // ljt??
        return false;
    }
    if (NULL == (output_handle = CreateEvent(NULL,TRUE,FALSE,NULL)))
    {
        output_handle = INVALID_HANDLE_VALUE;
        PLOG(PL_ERROR,"Win32Vif::InitTap() CreateEvent(output_handle) error: %s\n",::GetErrorString());
        Close(); // ljt??
        return false;
    }
    
    memset(&read_overlapped,0,sizeof(read_overlapped));
    read_overlapped.hEvent = input_handle;
    memset(&write_overlapped,0,sizeof(write_overlapped));
    write_overlapped.hEvent = output_handle;
    
    StartInputNotification();

    // Start overlapped notifications
    if (NULL != GetNotifier())
    {
        // Initiate overlapped I/O ...
        DWORD bytesRead;
        if (0 != ReadFile(tap_handle, read_buffer, BUFFER_MAX, &bytesRead, &read_overlapped))
        {
            input_ready = true;
            read_count = bytesRead;
        }
        else
        {
            switch(GetLastError())
            {
                case ERROR_IO_PENDING:
                  read_count = 0;
                  input_ready = false;
                  break;
                //case ERROR_BROKEN_PIPE: 
                default:
                  PLOG(PL_ERROR,"Win32Vif::InitTap() ReadFile() error: %s\n", ::GetErrorString());
                  Close();
                  return false;
            }
        }
    }

    if (!UpdateNotification())
    {
        PLOG(PL_ERROR, "Win32Vif::InitTap() error updating notification\n");
        Close();
        return false;
    }

    return true;  
    
} // end Win32Vif::InitTap() 
// используется в GUI при загрузке настроек
void FindComspec(ConEmuComspec* pOpt, bool bCmdAlso /*= true*/)
{
	if (!pOpt)
		return;

	pOpt->Comspec32[0] = 0;
	pOpt->Comspec64[0] = 0;

	// Ищем tcc.exe
	if (pOpt->csType == cst_AutoTccCmd)
	{
		HKEY hk;
		BOOL bWin64 = IsWindows64();
		wchar_t szPath[MAX_PATH+1];

		// If tcc.exe can be found near to ConEmu location
		LPCWSTR ppszPredefined[] = {
			L"%ConEmuBaseDir%\\tcc.exe",
			L"%ConEmuDir%\\tcc.exe",
			// Sort of PortableApps locations
			L"%ConEmuDir%\\..\\tcc\\tcc.exe",
			L"%ConEmuDir%\\..\\..\\tcc\\tcc.exe",
			// End of predefined list
			NULL};
		for (INT_PTR i = 0; ppszPredefined[i]; i++)
		{
			DWORD nExpand = ExpandEnvironmentStrings(ppszPredefined[i], szPath, countof(szPath));
			if (nExpand && (nExpand < countof(szPath)))
			{
				if (FileExists(szPath))
				{
					wcscpy_c(pOpt->Comspec32, szPath);
					wcscpy_c(pOpt->Comspec64, szPath);
					break;
				}
			}
		}

		// On this step - check "Take Command"!
		if (!*pOpt->Comspec32 || !*pOpt->Comspec64)
		{
			// [HKEY_LOCAL_MACHINE\SOFTWARE\JP Software\Take Command 13.0]
			// @="\"C:\\Program Files\\JPSoft\\TCMD13\\tcmd.exe\""
			for (int b = 0; b <= 1; b++)
			{
				// b==0 - 32bit, b==1 - 64bit
				if (b && !bWin64)
					continue;
				bool bFound = false;
				DWORD nOpt = (b == 0) ? (bWin64 ? KEY_WOW64_32KEY : 0) : (bWin64 ? KEY_WOW64_64KEY : 0);
				if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\JP Software", 0, KEY_READ|nOpt, &hk))
				{
					wchar_t szName[MAX_PATH+1]; DWORD nLen;
					for (DWORD k = 0; !bFound && !RegEnumKeyEx(hk, k, szName, &(nLen = countof(szName)-1), 0,0,0,0); k++)
					{
						HKEY hk2;
						if (!RegOpenKeyEx(hk, szName, 0, KEY_READ|nOpt, &hk2))
						{
							// Just in case, check "Path" too
							LPCWSTR rsNames[] = {NULL, L"Path"};

							for (size_t n = 0; n < countof(rsNames); n++)
							{
								ZeroStruct(szPath); DWORD nSize = (countof(szPath)-1)*sizeof(szPath[0]);
								if (!RegQueryValueExW(hk2, rsNames[n], NULL, NULL, (LPBYTE)szPath, &nSize) && *szPath)
								{
									wchar_t* psz, *pszEnd;
									psz = (wchar_t*)Unquote(szPath, true);
									pszEnd = wcsrchr(psz, L'\\');
									if (!pszEnd || lstrcmpi(pszEnd, L"\\tcmd.exe") || !FileExists(psz))
										continue;
									lstrcpyn(pszEnd+1, L"tcc.exe", 8);
									if (FileExists(psz))
									{
										bFound = true;
										if (b == 0)
											wcscpy_c(pOpt->Comspec32, psz);
										else
											wcscpy_c(pOpt->Comspec64, psz);
									}
								}
							} // for (size_t n = 0; n < countof(rsNames); n++)
							RegCloseKey(hk2);
						}
					} //  for, подключи
					RegCloseKey(hk);
				} // L"SOFTWARE\\JP Software"
			} // for (int b = 0; b <= 1; b++)

			// Если установлен TCMD - предпочтительно использовать именно его, независимо от битности
			if (*pOpt->Comspec32 && !*pOpt->Comspec64)
				wcscpy_c(pOpt->Comspec64, pOpt->Comspec32);
			else if (*pOpt->Comspec64 && !*pOpt->Comspec32)
				wcscpy_c(pOpt->Comspec32, pOpt->Comspec64);
		}

		// If "Take Command" not installed - try "TCC/LE"
		if (!*pOpt->Comspec32 || !*pOpt->Comspec64)
		{
			// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{16A21882-4138-4ADA-A390-F62DC27E4504}]
			// "DisplayVersion"="13.04.60"
			// "Publisher"="JP Software"
			// "DisplayName"="Take Command 13.0"
			// или
			// "DisplayName"="TCC/LE 13.0"
			// и наконец
			// "InstallLocation"="C:\\Program Files\\JPSoft\\TCMD13\\"
			for (int b = 0; b <= 1; b++)
			{
				// b==0 - 32bit, b==1 - 64bit
				if (b && !bWin64)
					continue;
				if (((b == 0) ? *pOpt->Comspec32 : *pOpt->Comspec64))
					continue; // этот уже нашелся в TCMD

				bool bFound = false;
				DWORD nOpt = (b == 0) ? (bWin64 ? KEY_WOW64_32KEY : 0) : (bWin64 ? KEY_WOW64_64KEY : 0);
				if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", 0, KEY_READ|nOpt, &hk))
				{
					wchar_t szName[MAX_PATH+1]; DWORD nLen;
					for (DWORD n = 0; !bFound && !RegEnumKeyEx(hk, n, szName, &(nLen = countof(szName)-1), 0,0,0,0); n++)
					{
						if (*szName != L'{')
							continue;
						HKEY hk2;
						if (!RegOpenKeyEx(hk, szName, 0, KEY_READ|nOpt, &hk2))
						{
							ZeroStruct(szPath); DWORD nSize = (countof(szPath) - 1)*sizeof(szPath[0]);
							if (!RegQueryValueExW(hk2, L"Publisher", NULL, NULL, (LPBYTE)szPath, &nSize)
								&& !lstrcmpi(szPath, L"JP Software"))
							{
								nSize = (countof(szPath)-12)*sizeof(szPath[0]);
								if (!RegQueryValueExW(hk2, L"InstallLocation", NULL, NULL, (LPBYTE)szPath, &nSize)
									&& *szPath)
								{
									wchar_t* psz, *pszEnd;
									if (szPath[0] == L'"')
									{
										psz = szPath + 1;
										pszEnd = wcschr(psz, L'"');
										if (pszEnd)
											*pszEnd = 0;
									}
									else
									{
										psz = szPath;
									}
									if (*psz)
									{
										pszEnd = psz+lstrlen(psz);
										if (*(pszEnd-1) != L'\\')
											*(pszEnd++) = L'\\';
										lstrcpyn(pszEnd, L"tcc.exe", 8);
										if (FileExists(psz))
										{
											bFound = true;
											if (b == 0)
												wcscpy_c(pOpt->Comspec32, psz);
											else
												wcscpy_c(pOpt->Comspec64, psz);
										}
									}
								}
							}
							RegCloseKey(hk2);
						}
					} // for, подключи
					RegCloseKey(hk);
				} // L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
			} // for (int b = 0; b <= 1; b++)
		}

		// Попытаться "в лоб" из "Program Files"
		if (!*pOpt->Comspec32 && !*pOpt->Comspec64)
		{

			const wchar_t* pszTcmd  = L"C:\\Program Files\\JPSoft\\TCMD13\\tcc.exe";
			const wchar_t* pszTccLe = L"C:\\Program Files\\JPSoft\\TCCLE13\\tcc.exe";
			if (FileExists(pszTcmd))
				wcscpy_c(pOpt->Comspec32, pszTcmd);
			else if (FileExists(pszTccLe))
				wcscpy_c(pOpt->Comspec32, pszTccLe);
		}

		if (*pOpt->Comspec32 && !*pOpt->Comspec64)
			wcscpy_c(pOpt->Comspec64, pOpt->Comspec32);
		else if (*pOpt->Comspec64 && !*pOpt->Comspec32)
			wcscpy_c(pOpt->Comspec32, pOpt->Comspec64);
	} // if (pOpt->csType == cst_AutoTccCmd)

	// С поиском tcc закончили. Теперь, если pOpt->Comspec32/pOpt->Comspec64 остались не заполнены
	// нужно сначала попытаться обработать переменную окружения ComSpec, а потом - просто "cmd.exe"
	if (!*pOpt->Comspec32)
		GetComspecFromEnvVar(pOpt->Comspec32, countof(pOpt->Comspec32), csb_x32);
	if (!*pOpt->Comspec64)
		GetComspecFromEnvVar(pOpt->Comspec64, countof(pOpt->Comspec64), csb_x64);
}
Exemple #6
0
// This routine initializes the list of activity timers.  It returns ERROR_SUCCESS 
// if successful or a Win32 error code otherwise.
DWORD
ActivityTimerInitList(VOID)
{
    DWORD dwStatus;
    HKEY hk = NULL;
    TCHAR szSources[1024];
    DWORD dwNumTimers = 0;
    PPACTIVITY_TIMER ppatList = NULL;

#ifndef SHIP_BUILD
    SETFNAME(_T("ActivityTimerInitList"));
#endif

    wsprintf(szSources, _T("%s\\ActivityTimers"), PWRMGR_REG_KEY);
    dwStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szSources, 0, 0, &hk);
    if(dwStatus == ERROR_SUCCESS) {
        // figure out how many values are associated with the key
        dwStatus = RegQueryInfoKey(hk, NULL, NULL, NULL, &dwNumTimers, NULL, NULL, NULL,
            NULL, NULL, NULL, NULL);
    } else {
        // no timers configured in the registry
        dwNumTimers = 0;
        dwStatus = ERROR_SUCCESS;
    }

    // if there are any values, allocate an array to hold them
    if(dwStatus == ERROR_SUCCESS) {
        ppatList = (PPACTIVITY_TIMER) PmAlloc((dwNumTimers + 1) * sizeof(PACTIVITY_TIMER));
        if(ppatList == NULL) {
            PMLOGMSG(ZONE_WARN, (_T("%s: couldn't allocate %d timers\r\n"), pszFname,
                dwNumTimers));
            dwStatus = ERROR_NOT_ENOUGH_MEMORY;
        } else {
            memset(ppatList, 0, (dwNumTimers + 1) * sizeof(PACTIVITY_TIMER));
            ppatList[dwNumTimers] = NULL;
        }
    }

    // read list of timers
    if(dwStatus == ERROR_SUCCESS && dwNumTimers != 0) {
        DWORD dwIndex = 0;
        do {
            TCHAR szName[256];
            DWORD cbValueName = dim(szName);
            
            dwStatus = RegEnumKeyEx(hk, dwIndex, szName, &cbValueName, NULL,
                NULL, NULL, NULL);
            if(dwStatus == ERROR_SUCCESS) {
                HKEY hkSubKey = NULL;
                
                // open the subkey
                dwStatus = RegOpenKeyEx(hk, szName, 0, 0, &hkSubKey);
                if(dwStatus == ERROR_SUCCESS) {
                    DWORD dwSize, dwType, dwTimeout;
                    LPTSTR pszValueName;

                    // read the timeout, expressed in seconds
                    dwSize = sizeof(dwTimeout);
                    pszValueName = _T("Timeout");
                    dwStatus = RegQueryValueEx(hkSubKey, pszValueName, NULL, &dwType, (LPBYTE) &dwTimeout, 
                        &dwSize);
                    if(dwStatus == ERROR_SUCCESS) {
                        if(dwType != REG_DWORD || dwTimeout > MAXTIMERINTERVAL) {
                            PMLOGMSG(ZONE_WARN, 
                                (_T("%s: RegQueryValueEx('%s'\'%s') or returned invalid type %d or invalid value %d\r\n"),
                                pszFname, szName, pszValueName, dwType, dwTimeout));
                            dwStatus = ERROR_INVALID_DATA;
                        }

                        // convert timeout to milliseconds
                        dwTimeout *= 1000;
                    } else {
                        // no timeout in seconds, try milliseconds
                        dwSize = sizeof(dwTimeout);
                        pszValueName = _T("TimeoutMs");
                        dwStatus = RegQueryValueEx(hkSubKey, pszValueName, NULL, &dwType, (LPBYTE) &dwTimeout, 
                            &dwSize);
                        if(dwStatus != ERROR_SUCCESS || dwType != REG_DWORD || dwTimeout > (MAXTIMERINTERVAL * 1000)) {
                            PMLOGMSG(ZONE_WARN, 
                                (_T("%s: RegQueryValueEx('%s'\'%s') failed %d (or returned invalid type %d or invalid value %d)\r\n"),
                                pszFname, szName, pszValueName, dwStatus, dwType, dwTimeout));
                            dwStatus = ERROR_INVALID_DATA;
                        }
                    }

                    if(dwStatus == ERROR_SUCCESS) {
                        // get wake sources
                        dwSize = sizeof(szSources);
                        pszValueName = _T("WakeSources");
                        dwStatus = RegQueryValueEx(hkSubKey, pszValueName, NULL, &dwType, (LPBYTE) szSources, 
                            &dwSize);
                        if(dwStatus != ERROR_SUCCESS) {
                            // no wake sources
                            szSources[0] = 0;
                            szSources[1] = 0;
                            dwStatus = ERROR_SUCCESS;
                        } else if(dwType != REG_MULTI_SZ) {
                            PMLOGMSG(ZONE_WARN, (_T("%s: invalid type %d for '%s'\'%s'\r\n"), pszFname, dwType,
                                szName, pszValueName));
                            dwStatus = ERROR_INVALID_DATATYPE;
                        } else {
                            szSources[dim(szSources) -1] = szSources[dim(szSources) -2] = 0; // Terminate MultiSZ
                        }
                    }
                    
                    // did we get the parameters?
                    if(dwStatus == ERROR_SUCCESS) {
                        ppatList[dwIndex] = ActivityTimerCreate(szName, dwTimeout, szSources);
                        if(ppatList[dwIndex] == NULL) {
                            dwStatus = ERROR_NOT_ENOUGH_MEMORY;
                        }
                    }
                }
                
                // release the registry key
                RegCloseKey(hkSubKey);
            }
            
            // update the index
            dwIndex++;
        } while(dwStatus == ERROR_SUCCESS && dwIndex < dwNumTimers);

        // did we read all items ok?
        if(dwStatus == ERROR_NO_MORE_ITEMS) {
            dwStatus = ERROR_SUCCESS;
        }

        // terminate the list with a NULL
        ppatList[dwIndex] = NULL;
    }

    // did we succeed?
    if(dwStatus == ERROR_SUCCESS) {
        PMLOCK();
        gppActivityTimers = ppatList;
        PMUNLOCK();
    } else {
        DWORD dwIndex;
        if(ppatList != NULL) {
            for(dwIndex = 0; dwIndex < dwNumTimers; dwIndex++) {
                if(ppatList[dwIndex] != NULL) {
                    ActivityTimerDestroy(ppatList[dwIndex]);
                }
            }
            PmFree(ppatList);
        }
    }

    // release resources
    if(hk != NULL) RegCloseKey(hk);

    PMLOGMSG(dwStatus != ERROR_SUCCESS && ZONE_WARN,
        (_T("%s: returning %d\r\n"), pszFname, dwStatus));
    return dwStatus;
}
Exemple #7
0
int getdefaultgateway(in_addr_t * addr)
{
	HKEY networkCardsKey;
	HKEY networkCardKey;
	HKEY interfacesKey;
	HKEY interfaceKey;
	DWORD i = 0;
	DWORD numSubKeys = 0;
	TCHAR keyName[MAX_KEY_LENGTH];
	DWORD keyNameLength = MAX_KEY_LENGTH;
	TCHAR keyValue[MAX_VALUE_LENGTH];
	DWORD keyValueLength = MAX_VALUE_LENGTH;
	DWORD keyValueType = REG_SZ;
	TCHAR gatewayValue[MAX_VALUE_LENGTH];
	DWORD gatewayValueLength = MAX_VALUE_LENGTH;
	DWORD gatewayValueType = REG_MULTI_SZ;
	int done = 0;

	//const char * networkCardsPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards";
	//const char * interfacesPath = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
#ifdef UNICODE
	LPCTSTR networkCardsPath = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards";
	LPCTSTR interfacesPath = L"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
#define STR_SERVICENAME	 L"ServiceName"
#define STR_DHCPDEFAULTGATEWAY L"DhcpDefaultGateway"
#define STR_DEFAULTGATEWAY	L"DefaultGateway"
#else
	LPCTSTR networkCardsPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards";
	LPCTSTR interfacesPath = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
#define STR_SERVICENAME	 "ServiceName"
#define STR_DHCPDEFAULTGATEWAY "DhcpDefaultGateway"
#define STR_DEFAULTGATEWAY	"DefaultGateway"
#endif
	// The windows registry lists its primary network devices in the following location:
	// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards
	//
	// Each network device has its own subfolder, named with an index, with various properties:
	// -NetworkCards
	//   -5
	//     -Description = Broadcom 802.11n Network Adapter
	//     -ServiceName = {E35A72F8-5065-4097-8DFE-C7790774EE4D}
	//   -8
	//     -Description = Marvell Yukon 88E8058 PCI-E Gigabit Ethernet Controller
	//     -ServiceName = {86226414-5545-4335-A9D1-5BD7120119AD}
	//
	// The above service name is the name of a subfolder within:
	// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
	//
	// There may be more subfolders in this interfaces path than listed in the network cards path above:
	// -Interfaces
	//   -{3a539854-6a70-11db-887c-806e6f6e6963}
	//     -DhcpIPAddress = 0.0.0.0
	//     -[more]
	//   -{E35A72F8-5065-4097-8DFE-C7790774EE4D}
	//     -DhcpIPAddress = 10.0.1.4
	//     -DhcpDefaultGateway = 10.0.1.1
	//     -[more]
	//   -{86226414-5545-4335-A9D1-5BD7120119AD}
	//     -DhcpIpAddress = 10.0.1.5
	//     -DhcpDefaultGateay = 10.0.1.1
	//     -[more]
	//
	// In order to extract this information, we enumerate each network card, and extract the ServiceName value.
	// This is then used to open the interface subfolder, and attempt to extract a DhcpDefaultGateway value.
	// Once one is found, we're done.
	//
	// It may be possible to simply enumerate the interface folders until we find one with a DhcpDefaultGateway value.
	// However, the technique used is the technique most cited on the web, and we assume it to be more correct.

	if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Open registry key or predifined key
	                                 networkCardsPath,   // Name of registry subkey to open
	                                 0,                  // Reserved - must be zero
	                                 KEY_READ,           // Mask - desired access rights
	                                 &networkCardsKey))  // Pointer to output key
	{
		// Unable to open network cards keys
		return -1;
	}

	if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Open registry key or predefined key
	                                 interfacesPath,     // Name of registry subkey to open
	                                 0,                  // Reserved - must be zero
	                                 KEY_READ,           // Mask - desired access rights
	                                 &interfacesKey))    // Pointer to output key
	{
		// Unable to open interfaces key
		RegCloseKey(networkCardsKey);
		return -1;
	}

	// Figure out how many subfolders are within the NetworkCards folder
	RegQueryInfoKey(networkCardsKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

	//printf( "Number of subkeys: %u\n", (unsigned int)numSubKeys);

	// Enumrate through each subfolder within the NetworkCards folder
	for(i = 0; i < numSubKeys && !done; i++)
	{
		keyNameLength = MAX_KEY_LENGTH;
		if(ERROR_SUCCESS == RegEnumKeyEx(networkCardsKey, // Open registry key
		                                 i,               // Index of subkey to retrieve
		                                 keyName,         // Buffer that receives the name of the subkey
		                                 &keyNameLength,  // Variable that receives the size of the above buffer
		                                 NULL,            // Reserved - must be NULL
		                                 NULL,            // Buffer that receives the class string
		                                 NULL,            // Variable that receives the size of the above buffer
		                                 NULL))           // Variable that receives the last write time of subkey
		{
			if(RegOpenKeyEx(networkCardsKey,  keyName, 0, KEY_READ, &networkCardKey) == ERROR_SUCCESS)
			{
				keyValueLength = MAX_VALUE_LENGTH;
				if(ERROR_SUCCESS == RegQueryValueEx(networkCardKey,   // Open registry key
				                                    STR_SERVICENAME,    // Name of key to query
				                                    NULL,             // Reserved - must be NULL
				                                    &keyValueType,    // Receives value type
				                                    (LPBYTE)keyValue, // Receives value
				                                    &keyValueLength)) // Receives value length in bytes
				{
//					printf("keyValue: %s\n", keyValue);
					if(RegOpenKeyEx(interfacesKey, keyValue, 0, KEY_READ, &interfaceKey) == ERROR_SUCCESS)
					{
						gatewayValueLength = MAX_VALUE_LENGTH;
						if(ERROR_SUCCESS == RegQueryValueEx(interfaceKey,         // Open registry key
						                                    STR_DHCPDEFAULTGATEWAY, // Name of key to query
						                                    NULL,                 // Reserved - must be NULL
						                                    &gatewayValueType,    // Receives value type
						                                    (LPBYTE)gatewayValue, // Receives value
						                                    &gatewayValueLength)) // Receives value length in bytes
						{
							// Check to make sure it's a string
							if((gatewayValueType == REG_MULTI_SZ || gatewayValueType == REG_SZ) && (gatewayValueLength > 1))
							{
								//printf("gatewayValue: %s\n", gatewayValue);
								done = 1;
							}
						}
						else if(ERROR_SUCCESS == RegQueryValueEx(interfaceKey,         // Open registry key
						                                    STR_DEFAULTGATEWAY, // Name of key to query
						                                    NULL,                 // Reserved - must be NULL
						                                    &gatewayValueType,    // Receives value type
						                                    (LPBYTE)gatewayValue,// Receives value
						                                    &gatewayValueLength)) // Receives value length in bytes
						{
							// Check to make sure it's a string
							if((gatewayValueType == REG_MULTI_SZ || gatewayValueType == REG_SZ) && (gatewayValueLength > 1))
							{
								//printf("gatewayValue: %s\n", gatewayValue);
								done = 1;
							}
						}
						RegCloseKey(interfaceKey);
					}
				}
				RegCloseKey(networkCardKey);
			}
		}
	}

	RegCloseKey(interfacesKey);
	RegCloseKey(networkCardsKey);

	if(done)
	{
#if UNICODE
		char tmp[32];
		for(i = 0; i < 32; i++) {
			tmp[i] = (char)gatewayValue[i];
			if(!tmp[i])
				break;
		}
		tmp[31] = '\0';
		*addr = inet_addr(tmp);
#else
		*addr = inet_addr(gatewayValue);
#endif
		return 0;
	}

	return -1;
}
// ------------------------------------------------
// 
//  FUNCTION: sys_GetRegEnum( PA_PluginParameters params )
//
//  PURPOSE:  Get a key from the registry.
//        
//	DATE:	  MJG 12/4/03 (3.5.6)
//
void sys_GetRegEnum( PA_PluginParameters params )
{
	LONG_PTR returnValue, regKey, retErr;
	char regSub[MAXBUF];
	LONG_PTR regBufSize = MAX_REG_SIZE;
	CHAR regBuf[MAX_REG_SIZE]; 

	FILETIME ftLastWriteTime;
	HKEY hRootKey;
	HKEY hOpenKey;
	DWORD dwSubKeys;
	DWORD dwValues;
	DWORD i, j;
	PA_Variable paReturnArray1;
	PA_Variable paReturnArray2;

	dwSubKeys = dwValues = 0;
	returnValue = regKey = retErr = 0;
	hRootKey = hOpenKey = 0;
	memset(regSub, 0, MAXBUF);

	// Get the function parameters.
	regKey = PA_GetLongParameter( params, 1 );
	PA_GetTextParameter( params, 2, regSub );
	paReturnArray1 = PA_GetVariableParameter( params, 3 );
	paReturnArray2 = PA_GetVariableParameter( params, 4 );
	
	PA_ResizeArray(&paReturnArray1, 0);
	PA_ResizeArray(&paReturnArray2, 0);

	// Convert the 4d registry constant into a Windows registry key.
	hRootKey = getRootKey( regKey );

	// Open the registry key.
	retErr = RegOpenKeyEx(hRootKey, regSub, 0, KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE , &hOpenKey);
	
	if(retErr == ERROR_SUCCESS){
		
		retErr = RegQueryInfoKey(hOpenKey, NULL, NULL, NULL, &dwSubKeys, NULL, NULL, &dwValues, NULL, NULL, NULL, NULL); 
		
		if( retErr == ERROR_SUCCESS)
		{
			// Enumerate the subkey names.
			
			if (dwSubKeys)
			{
				retErr = ERROR_SUCCESS;
				PA_ResizeArray(&paReturnArray1, dwSubKeys);
				
				for (i=0,j=0; i<dwSubKeys; i++) 
				{ 
					regBufSize = MAX_REG_SIZE;
					retErr = RegEnumKeyEx(hOpenKey, i, regBuf, &regBufSize, NULL, NULL, NULL, &ftLastWriteTime); 
					
					if (retErr == ERROR_SUCCESS) 
					{
						PA_SetTextInArray(paReturnArray1, ++j, regBuf, regBufSize);
					}
				}
			} 
			
			// Enumerate the key value names. 
			if (dwValues) 
			{
				retErr = ERROR_SUCCESS;
				PA_ResizeArray(&paReturnArray2, dwValues);
				
				for (i=0,j=0; i<dwValues; i++) 
				{ 
					regBufSize = MAX_REG_SIZE;
					regBuf[0] = '\0'; 
					retErr = RegEnumValue(hOpenKey, i, regBuf, &regBufSize, NULL, NULL, NULL, NULL);
					
					if (retErr == ERROR_SUCCESS ) 
					{ 
						PA_SetTextInArray(paReturnArray2, ++j, regBuf, regBufSize);
					} 
				}
			}

			returnValue = 1;
		}
	} 
	
	PA_SetVariableParameter( params, 3, paReturnArray1, 0 );
	PA_SetVariableParameter( params, 4, paReturnArray2, 0 );
	
	RegCloseKey( hOpenKey );

	PA_ReturnLong( params, returnValue );
}
Exemple #9
0
bool get_available_wsls(std::vector<std::string>& wsls, std::string& default_wsl) {
    const std::string lxss_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Lxss";

    HKEY hKey;
    
    default_wsl = "";

    LONG lRet = RegOpenKeyEx(HKEY_CURRENT_USER,
        lxss_path.c_str(),
        0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &hKey);
    if (lRet != ERROR_SUCCESS)
        return false;

    const int buf_len = 256;
    char default_wsl_guid[buf_len];
    DWORD default_wsl_guid_len = sizeof(default_wsl_guid);

    lRet = RegQueryValueEx(hKey, "DefaultDistribution", NULL, NULL,
        (LPBYTE)default_wsl_guid, &default_wsl_guid_len);
    if ((lRet != ERROR_SUCCESS) || (default_wsl_guid_len > buf_len))
        return false;
    
    int i = 0;
    while(true) {
        char wsl_guid[buf_len];
        DWORD wsl_guid_len = sizeof(wsl_guid);

        LONG ret = RegEnumKeyEx(hKey, i++, wsl_guid, &wsl_guid_len,
            NULL, NULL, NULL, NULL);
        if (ret != ERROR_SUCCESS) {
            break;
        }

        HKEY hSubKey;
        const std::string sub_key = lxss_path + "\\" + wsl_guid;
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,
            sub_key.c_str(),
            0, KEY_QUERY_VALUE, &hSubKey);
        if (ret != ERROR_SUCCESS) {
            break;
        }

        char wsl_name[buf_len];
        DWORD wsl_name_len = sizeof(wsl_name);
        DWORD wsl_state = 0;
        DWORD wsl_state_len = sizeof(wsl_state);

        ret = RegQueryValueEx(hSubKey, "State", NULL, NULL, (LPBYTE)&wsl_state, &wsl_state_len);
        if (ret != ERROR_SUCCESS || wsl_state != 1) {
            continue;
        }

        ret = RegQueryValueEx(hSubKey, "DistributionName", NULL, NULL,
            (LPBYTE)wsl_name, &wsl_name_len);
        if ((ret == ERROR_SUCCESS) && (wsl_name_len < buf_len)) {
            wsls.push_back(wsl_name);
            if (std::string(wsl_guid) == std::string(default_wsl_guid)) {
                default_wsl = wsl_name;
            }

            RegCloseKey(hSubKey);
        }        
    }

    RegCloseKey(hKey);

    return default_wsl != "";
}
//------------------------------------------------------------------------------
DWORD WINAPI Scan_chrome_history(LPVOID lParam)
{
  FORMAT_CALBAK_READ_INFO data;

  //get child
  HTREEITEM hitem = NULL;
  if (!CONSOL_ONLY)hitem = (HTREEITEM)SendMessage(htrv_files, TVM_GETNEXTITEM,(WPARAM)TVGN_CHILD, (LPARAM)TRV_HTREEITEM_CONF[FILES_TITLE_APPLI]);
  if ((hitem == NULL && LOCAL_SCAN) || CONSOL_ONLY)
  {
    //get path of all profils users
    //HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
    HKEY CleTmp   = 0;
    if (RegOpenKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\",&CleTmp)==ERROR_SUCCESS)
    {
      DWORD i, nbSubKey=0, key_size;
      sqlite3 *db_tmp;

      char tmp_key[MAX_PATH], tmp_key_path[MAX_PATH];
      if (RegQueryInfoKey (CleTmp,0,0,0,&nbSubKey,0,0,0,0,0,0,0)==ERROR_SUCCESS)
      {
        #ifdef CMD_LINE_ONLY_NO_DB
        printf("\"file\";\"parameter\";\"date\";\"id_language_description\";\"session_id\";\"data\";\r\n");
        #endif

        //get subkey
        for(i=0;i<nbSubKey;i++)
        {
          key_size    = MAX_PATH;
          tmp_key[0]  = 0;
          if (RegEnumKeyEx (CleTmp,i,tmp_key,&key_size,0,0,0,0)==ERROR_SUCCESS)
          {
            //generate the key path
            snprintf(tmp_key_path,MAX_PATH,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\%s\\",tmp_key);
            //get profil path
            if (ReadValue(HKEY_LOCAL_MACHINE,tmp_key_path,"ProfileImagePath",tmp_key, MAX_PATH))
            {
              //verify the path if %systemdrive%
              ReplaceEnv("SYSTEMDRIVE",tmp_key,MAX_PATH);


              //search file in this path
              snprintf(tmp_key_path,MAX_PATH,"%s\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\*.*",tmp_key);
              WIN32_FIND_DATA wfd;
              HANDLE hfic = FindFirstFile(tmp_key_path, &wfd);
              if (hfic != INVALID_HANDLE_VALUE)
              {
                do
                {
                  if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){}else
                  {
                    if(wfd.cFileName[0] == '.' && (wfd.cFileName[1] == 0 || wfd.cFileName[1] == '.')){}
                    else
                    {
                      //test all files
                      snprintf(tmp_file_chrome,MAX_PATH,"%s\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\%s",tmp_key,wfd.cFileName);

                      //test to open file
                      if (sqlite3_open(tmp_file_chrome, &db_tmp) == SQLITE_OK)
                      {
                        for (data.type =0;data.type <nb_sql_CHROME && start_scan;data.type = data.type+1)
                        {
                          if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL);
                          sqlite3_exec(db_tmp, sql_CHROME[data.type].sql, callback_sqlite_chrome, &data, NULL);
                          if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL);
                        }
                        sqlite3_close(db_tmp);
                      }
                    }
                  }
                }while(FindNextFile (hfic,&wfd));
              }
            }
          }
        }
      }
      RegCloseKey(CleTmp);
    }
  }else
  {
    sqlite3 *db_tmp;
    #ifdef CMD_LINE_ONLY_NO_DB
    printf("\"Chrome\";\"file\";\"parameter\";\"date\";\"id_language_description\";\"session_id\";\"data\";\r\n");
    #endif
    while(hitem!=NULL)
    {
      //get item txt
      GetTextFromTrv(hitem, tmp_file_chrome, MAX_PATH);
      //test to open file
      if (sqlite3_open(tmp_file_chrome, &db_tmp) == SQLITE_OK)
      {
        for (data.type =0;data.type <nb_sql_CHROME && start_scan;data.type = data.type+1)
        {
          if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL);
          sqlite3_exec(db_tmp, sql_CHROME[data.type].sql, callback_sqlite_chrome, &data, NULL);
          if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL);
        }
        sqlite3_close(db_tmp);
      }
      hitem = (HTREEITEM)SendMessage(htrv_files, TVM_GETNEXTITEM,(WPARAM)TVGN_NEXT, (LPARAM)hitem);
    }
  }

  if (!CONSOL_ONLY)check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
  h_thread_test[(unsigned int)lParam] = 0;
  return 0;
}
Exemple #11
0
bool
CScsiDeviceList::ProcessKey(HKEY hKey, int iLevel, DWORD dwDeviceId)
{
#if defined(_DEBUG)
   switch (iLevel)
   {
   case 3:
      _ftprintf(  stderr, 
                  _T("%-64s\n"), 
                  &m_szLastKey[1]);
      break;

   case 2:
      _ftprintf(  stderr, 
                  _T("%-64s%d\n"), 
                  &m_szLastKey[1], 
                  dwDeviceId & 0xFF);
      break;

   case 1:
      _ftprintf(  stderr, 
                  _T("%-64s%d:%d\n"), 
                  &m_szLastKey[1], 
                  (dwDeviceId >>  8) & 0xFF,
                   dwDeviceId        & 0xFF);
      break;

   case 0:
      _ftprintf(  stderr, 
                  _T("%-64s%d:%d:%d\n"), 
                  &m_szLastKey[1], 
                  (dwDeviceId >>  16) & 0xFF,
                  (dwDeviceId >>  8) & 0xFF,
                   dwDeviceId        & 0xFF);
      break;
   }
#endif

   for (int idxSubkey = 0; ; idxSubkey++) {

      TCHAR szSubkeyName[c_MaxSubkeyLength + 1];
      DWORD dwLength;

      dwLength = sizeof(szSubkeyName);

      m_lLastError = RegEnumKeyEx(  hKey, 
                                    idxSubkey, 
                                    szSubkeyName, 
                                    &dwLength, 
                                    NULL, 
                                    NULL, 
                                    NULL, 
                                    NULL);

      if (m_lLastError == ERROR_NO_MORE_ITEMS) {
         break;
      } else  if (m_lLastError == ERROR_MORE_DATA) {
#if defined(_DEBUG)
         _tcscpy(m_szLastOperation, _T("Enumerating subkeys of "));
         PrintLastError();
#endif
         // Subkey name is too long
         continue;
      } else if (m_lLastError != ERROR_SUCCESS) {
         // Unexpected Error
         _tcscpy(m_szLastOperation, _T("Enumerating subkeys of "));
         return false;
      }

      int   iValue;

      if (_stscanf(szSubkeyName, c_lpszFormatList[iLevel], &iValue) != 1) {
         // Ignore this subkey, it is probably Initiator Id n
         continue;
      }

      m_szLastKey[m_dwLastKeyLength++] = _T('\\');

      DWORD dwSubkeyLength = (DWORD)_tcslen(szSubkeyName);
      memcpy(&m_szLastKey[m_dwLastKeyLength], szSubkeyName, (dwSubkeyLength + 1) * sizeof(TCHAR));
      m_dwLastKeyLength += dwSubkeyLength;

      HKEY  hSubkey;

      m_lLastError = RegOpenKeyEx(hKey, szSubkeyName, 0, KEY_READ, &hSubkey);

      if (m_lLastError != ERROR_SUCCESS) {
         _tcscpy(m_szLastOperation, _T("Opening key "));
         return false;
      }

      if (iLevel == 0) {
#if defined(_DEBUG)
         _ftprintf(  stderr, 
                     _T("%-64s%d:%d:%d:%d\n"), 
                     &m_szLastKey[1], 
                     (dwDeviceId >> 16) & 0xFF,
                     (dwDeviceId >>  8) & 0xFF,
                      dwDeviceId        & 0xFF,
                      iValue);
#endif

         ProcessValues(hSubkey, (dwDeviceId << 8) | iValue);
      } else {
         if (!ProcessKey(hSubkey, iLevel - 1, (dwDeviceId << 8) | iValue)) {
Exemple #12
0
BOOL SelectEmacsen( VOID )
{
  int      nIndex;
  LONG     rret;
  HKEY     hKey,hKey2;
  DWORD    i;
  char     szKeyBuf[260];
  char     szValueBuf[1024];
  DWORD    dwKeyBuf,dwValueBuf;
  FILETIME ft;
  char     *pszEDir;

  /* gathering Emacs infomation... */
  iEmacsenNum=0;
  memset( szEmacsenList, 0, sizeof(szEmacsenList) );

  /* NTEmacs/Meadow */
  pszEDir = getenv("emacs_dir");
  if (pszEDir) {
	  do {
		  /* check NTEmacs */
		  strcpy(szValueBuf, pszEDir);
		  RevConvertPathSeparator(szValueBuf);
		  if (szValueBuf[strlen(szValueBuf)-1] != '\\')
			  strcat(szValueBuf, "\\");
		  strcat(szValueBuf, "bin\\emacs.exe");
		  if (CheckFile(szValueBuf)) {
			  strcpy(szEmacsenList[iEmacsenNum], "NTEmacs (getenv)" );
			  iEmacsenNum++;
		  }
		  /* check Meadow */
		  strcpy(szValueBuf, pszEDir);
		  RevConvertPathSeparator(szValueBuf);
		  if (szValueBuf[strlen(szValueBuf)-1] != '\\')
			  strcat(szValueBuf, "\\");
		  strcat(szValueBuf, "bin\\Meadow.exe");
		  if (CheckFile(szValueBuf)) {
			  strcpy(szEmacsenList[iEmacsenNum], "Meadow (getenv)" );
			  iEmacsenNum++;
		  }
	  } while (0);
  }

  /* NTEmacs */
  rret = RegOpenKey( HKEY_LOCAL_MACHINE,
		     "SOFTWARE\\GNU\\Emacs",
		     &hKey );
  if ( rret == ERROR_SUCCESS ){
    strcpy( szEmacsenList[iEmacsenNum], "NTEmacs" );
    dwValueBuf = sizeof(szValueBuf);
    if ( RegQueryValueEx( hKey,
			  "EMACSPATH",
			  NULL,
			  NULL,
			  szValueBuf,
			  &dwValueBuf ) == ERROR_SUCCESS ){
      dwKeyBuf = sizeof(szKeyBuf);
      if ( RegQueryValueEx( hKey,
			    "emacs_dir",
			    NULL,
			    NULL,
			    szKeyBuf,
			    &dwKeyBuf ) == ERROR_SUCCESS ){
	ReplaceString( szValueBuf, "%emacs_dir%", szKeyBuf );
	RevConvertPathSeparator( szValueBuf );
	strcat( szValueBuf, "\\emacs.exe" );
	if ( CheckFile( szValueBuf ) )
	  iEmacsenNum++;
      }
    } /* if ( RegQueryValueEx( */
    RegCloseKey( hKey );
  }
  /* Meadow */
  i=0;
  rret = RegOpenKey( HKEY_LOCAL_MACHINE,
		     "SOFTWARE\\GNU\\Meadow",
		     &hKey );
  if ( rret == ERROR_SUCCESS ){
    dwKeyBuf = sizeof(szKeyBuf);
    dwValueBuf = sizeof(szValueBuf);
    rret = RegEnumKeyEx( hKey,
			 i++,
			 szKeyBuf,
			 &dwKeyBuf,
			 NULL,
			 szValueBuf,
			 &dwValueBuf,
			 &ft );
    if ( rret == ERROR_SUCCESS ){
      do {
	if ( !strcmp( szKeyBuf, "Environment" ) ){
	  /* 1.00/1.01 */
	  strcpy( szValueBuf, "SOFTWARE\\GNU\\Meadow\\Environment" );
	  strcpy( szEmacsenList[iEmacsenNum], "Meadow 1.00/1.01" );
	} else {
	  /* 1.04a1 or later */
	  sprintf( szValueBuf, "SOFTWARE\\GNU\\Meadow\\%s\\Environment",
		   szKeyBuf);
	  sprintf( szEmacsenList[iEmacsenNum], "Meadow %s", szKeyBuf );
	}
	/* "Meadow.exe" exists? */
	if ( RegOpenKey( HKEY_LOCAL_MACHINE,
			 szValueBuf,
			 &hKey2 ) == ERROR_SUCCESS ){
	  dwKeyBuf = sizeof(szKeyBuf);
	  if ( RegQueryValueEx( hKey2,
				"EMACSPATH",
				NULL,
				NULL,
				szKeyBuf,
				&dwKeyBuf ) == ERROR_SUCCESS ){
	    sprintf( szValueBuf, "%s\\Meadow.exe", szKeyBuf );
	    if ( CheckFile( szValueBuf ) )
	      iEmacsenNum++;
	  } /* if ( RegQueryValueEx( */
	  RegCloseKey( hKey2 );
	} /* if ( RegOpenKey( */
	dwKeyBuf = sizeof(szKeyBuf);
	dwValueBuf = sizeof(szValueBuf);
	if ( iEmacsenNum >= MAX_EMACS ) break;
      } while ( RegEnumKeyEx( hKey,
			      i++,
			      szKeyBuf,
			      &dwKeyBuf,
			      NULL,
			      szValueBuf,
			      &dwValueBuf,
			      &ft ) == ERROR_SUCCESS );
    }
    RegCloseKey( hKey );
  }

  /* IF NOT FOUND ANY EMACSEN */
  if ( iEmacsenNum == 0 ) return ( FALSE );

  if ( iEmacsenNum > 1 ){
    /* select dialog */
    nIndex = DialogBoxParam( hInst,
			     MAKEINTRESOURCE(IDD_SEDIALOG),
			     0,
			     SelectEmacsenDlgProc,
			     0 );
    if ( nIndex < 0 ) return ( FALSE );
  } else {
    /* only one Emacs has found */
    nIndex = 0;
  }
  if (strstr(szEmacsenList[nIndex], "getenv"))
    bNoEmacsRegistry = TRUE;
  if ( ! strncmp( szEmacsenList[nIndex], "NTEmacs", 7 ) ){
    bEmacsType = EMACS_EMACS;
  } else if ( ! strncmp( szEmacsenList[nIndex], "Meadow", 6 ) ){
    bEmacsType = EMACS_MEADOW;
    if ( ! strncmp( szEmacsenList[nIndex], "Meadow 1.00", 11 ) ){
      strcpy( szMeadowVersion, "1.00" );
    } else {
      strcpy( szMeadowVersion, szEmacsenList[nIndex]+7 );
    }
  } else {
    bEmacsType = EMACS_NONE;
  }
  
  /* refrect setting */

  return ( TRUE );
}
Exemple #13
0
int get_regkeys(char *identifier, RegKeys *keys, int *num_keys /* in out */){
  HKEY key,key2;
  int i;
  char knbuff[SMALLBUFSIZ];
  DWORD knlen;
  char cnbuff[SMALLBUFSIZ];
  DWORD cnlen;
  FILETIME ft;
  DWORD type, data, datasiz;

  sprintf(knbuff,"%s\\%s\\%s\\%s", 
	  APP_ROOT_KEY,
	  APP_SUB_KEY,
	  APP_VERSION,
	  identifier);
  if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
		  knbuff, 
		  0,
		  KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
		  &key) != ERROR_SUCCESS){
    if(create_regkeys(identifier)!= 0){
#ifdef HARDDEBUG
      fprintf(stderr,"Failed creating regkeys\n");
#endif
      return -1;
    } else {
      if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
		      knbuff, 
		      0,
		      KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
		      &key) != ERROR_SUCCESS){
#ifdef HARDDEBUG
	fprintf(stderr,"Failed opening regkeys\n");
#endif
	return -1;
      }
    }
  }
  for(i = 0, knlen = SMALLBUFSIZ, cnlen = SMALLBUFSIZ; 
      i < *num_keys &&
	ERROR_SUCCESS == RegEnumKeyEx(key,
				      i,
				      knbuff,
				      &knlen,
				      NULL,
				      cnbuff,
				      &cnlen,
				      &ft);
      ++i, knlen = SMALLBUFSIZ, cnlen = SMALLBUFSIZ){
    if(RegOpenKeyEx(key, 
		    knbuff, 
		    0, 
		    KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
		    &key2) != ERROR_SUCCESS)
      continue;
    strncpy(keys[i].facility_name, knbuff, 
	    MAX_FACILITY_NAME);
    keys[i].facility_name[MAX_FACILITY_NAME - 1] = '\0';
    datasiz = sizeof(DWORD);
    if(RegQueryValueEx(key2, 
		       LATEST_RECORD_NAME,
		       NULL,
		       &type,
		       (BYTE *) &data,
		       &datasiz) != ERROR_SUCCESS)
      keys[i].latest_record = 0;
    else
      keys[i].latest_record = data;
    if(RegQueryValueEx(key2, 
		       LATEST_TIME_NAME,
		       NULL,
		       &type,
		       (BYTE *) &data,
		       &datasiz) != ERROR_SUCCESS)
      keys[i].latest_time = 0;
    else
      keys[i].latest_time = data;
    RegCloseKey(key2);
  }
  *num_keys = i;
  if(!*num_keys){
#ifdef HARDDEBUG
    fprintf(stderr,"get_regkeys got none!\n");
#endif
    return -1;
  }
  return 0;
}
Exemple #14
0
LONG RegEnumKey(HKEY hKey, DWORD dwIndex, LPTSTR ptcsName, DWORD cbName)
{	DWORD cb = cbName; 
return RegEnumKeyEx( hKey, dwIndex, ptcsName, &cb, 0L, NULL, NULL, NULL ); 
}
void QueryKey_All_WSD_Subkey_List(HKEY hKey)
{
    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

    DWORD i, retCode;

    TCHAR  /*achValue[MAX_VALUE_NAME],*/ achValue_single_WSD[MAX_VALUE_NAME];
    //DWORD cchValue = MAX_VALUE_NAME;

    //BYTE  achValue_content[MAX_VALUE_NAME];
    //DWORD  achValue_content;
    //DWORD  dwType, dwSize = MAX_KEY_LENGTH;
    HKEY hKey_WSD_Subkey_List;

    // Get the class name and the value count.
    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);       // last write time

    // Enumerate the subkeys, until RegEnumKeyEx fails.

    if (cSubKeys)
    {
        printf( "\nNumber of subkeys: %d\n", (int)cSubKeys);

        for (i=0; i<cSubKeys; i++)
        {
            cbName = MAX_KEY_LENGTH;
            retCode = RegEnumKeyEx(hKey, i,
                     achKey,
                     &cbName,
                     NULL,
                     NULL,
                     NULL,
                     &ftLastWriteTime);

            //Get single key string
            _tcscpy(achValue_single_WSD, REG_PATH_WSD_DEVICE_UMB);
            _tcscat(achValue_single_WSD, TEXT("\\"));
            _tcscat(achValue_single_WSD, achKey);

            if (retCode == ERROR_SUCCESS)
            {
                _tprintf(TEXT("(%d) %s\n"), (int)(i+1), achKey);

                if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE,
                    achValue_single_WSD,
                    0,
                    KEY_READ,
                    &hKey_WSD_Subkey_List) == ERROR_SUCCESS
                    )
                {
                    QueryValue_Single_WSD_Value_List(hKey_WSD_Subkey_List);
                }
            }
        }
    }

#if 0
    // Enumerate the key values.

    if (cValues)
    {
        printf( "\nNumber of values: %d\n", (int)cValues);

        for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++)
        {
            cchValue = MAX_VALUE_NAME;
            achValue[0] = '\0';
            retCode = RegEnumValue(hKey, i,
                achValue,
                &cchValue,
                NULL,
                NULL,
                NULL,
                NULL);

            if (retCode == ERROR_SUCCESS )
            {
                _tprintf(TEXT("(%d) %s\n"), (int)(i+1), achValue);

                retCode = RegQueryValueEx(hKey, achValue, NULL, &dwType, achValue_content, &dwSize);

                if (dwType == REG_DWORD)
                {
                    //itoa((int)achValue_content, achValue_content, 16);
                    _tprintf(TEXT("The content of value is %s\n"), achValue_content);
                }
                //else if (dwType == REG_SZ)
                //    _tprintf(TEXT("The content of value is %s\n"), achValue_content);
                else
                    _tprintf(TEXT("The content of value is %s\n"), achValue_content);
            }
        }
    }
#endif
}
DEBUG_LOCAL OSStatus MyRegDeleteKey( HKEY hKeyRoot, LPTSTR lpSubKey )
{
    LPTSTR lpEnd;
    OSStatus err;
    DWORD dwSize;
    TCHAR szName[MAX_PATH];
    HKEY hKey;
    FILETIME ftWrite;

    // First, see if we can delete the key without having to recurse.

    err = RegDeleteKey( hKeyRoot, lpSubKey );

    if ( !err )
    {
        goto exit;
    }

    err = RegOpenKeyEx( hKeyRoot, lpSubKey, 0, KEY_READ, &hKey );
    require_noerr( err, exit );

    // Check for an ending slash and add one if it is missing.

    lpEnd = lpSubKey + lstrlen(lpSubKey);

    if ( *( lpEnd - 1 ) != TEXT( '\\' ) )
    {
        *lpEnd =  TEXT('\\');
        lpEnd++;
        *lpEnd =  TEXT('\0');
    }

    // Enumerate the keys

    dwSize = MAX_PATH;
    err = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL, NULL, NULL, &ftWrite);

    if ( !err )
    {
        do
        {
            lstrcpy (lpEnd, szName);

            if ( !MyRegDeleteKey( hKeyRoot, lpSubKey ) )
            {
                break;
            }

            dwSize = MAX_PATH;

            err = RegEnumKeyEx( hKey, 0, szName, &dwSize, NULL, NULL, NULL, &ftWrite );

        }
        while ( !err );
    }

    lpEnd--;
    *lpEnd = TEXT('\0');

    RegCloseKey( hKey );

    // Try again to delete the key.

    err = RegDeleteKey(hKeyRoot, lpSubKey);
    require_noerr( err, exit );

exit:

    return err;
}
Exemple #17
0
int populate_list(HWND hlistview,int resize_window)
{
	HKEY hkey=0;
	int total_width=0;
	ListView_DeleteAllItems(hlistview);
	set_columns(hlistview);
	RegOpenKeyEx(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",0,KEY_READ,&hkey);
	if(hkey!=0){
		int i,count=0,widths[4];
		count=get_subkey_count(hkey);
		memset(widths,0,sizeof(widths));
		get_column_widths(hlistview,widths,sizeof(widths)/sizeof(int));
		for(i=0;i<count;i++){
			char str[512]={0};
			int len=sizeof(str);
			RegEnumKeyEx(hkey,i,str,&len,NULL,NULL,NULL,NULL);
			//RegEnumValue(hkey,i,str,&len,NULL,NULL,NULL,NULL);
			str[sizeof(str)-1]=0;
			if(str[0]!=0){
				int w;
				HKEY hsubkey=0;
				RegOpenKeyEx(hkey,str,0,KEY_READ,&hsubkey);
				if(hsubkey!=0){
					int type=REG_SZ;
					char dispstr[512]={0};
					len=sizeof(dispstr);
					RegQueryValueEx(hsubkey,"DisplayName",NULL,&type,dispstr,&len);
					lv_insert_data(hlistview,i,0,dispstr);
					w=get_str_width(hlistview,dispstr);
					if(widths[0]<w)
						widths[0]=w;
					RegCloseKey(hsubkey);

					lv_insert_data(hlistview,i,1,str);
					w=get_str_width(hlistview,str);
					if(widths[1]<w)
						widths[1]=w;

				}
			}			
		}
		for(i=0;i<4;i++){
			widths[i]+=12;
			ListView_SetColumnWidth(hlistview,i,widths[i]);
			total_width+=widths[i];
		}

		RegCloseKey(hkey);
		if(total_width>0){
			HWND hwnd,hdesk;
			hwnd=GetParent(hlistview);
			hdesk=GetDesktopWindow();
			if(hwnd!=0 && hdesk!=0){
				RECT rect={0};
				int wwin,wdesk,height;
				GetWindowRect(hwnd,&rect);
				wwin=rect.right-rect.left;
				GetWindowRect(hdesk,&rect);
				wdesk=rect.right-rect.left;
				height=rect.bottom-rect.top;
				height=height*2/3;;
				if(total_width>wdesk)
					total_width=wdesk;
				if((total_width>wwin) && resize_window)
					SetWindowPos(hwnd,NULL,0,0,total_width,height,SWP_NOMOVE);
			}
		}
	}
	return total_width;
}
Exemple #18
0
bool ExportRegistryKey(CStdioFile& file, HKEY hKeyRoot, CString keyName)
{
    HKEY hKey = NULL;
    if (RegOpenKeyEx(hKeyRoot, keyName, 0, KEY_READ, &hKey) != ERROR_SUCCESS) {
        return false;
    }

    DWORD subKeysCount = 0, maxSubKeyLen = 0;
    DWORD valuesCount = 0, maxValueNameLen = 0, maxValueDataLen = 0;
    if (RegQueryInfoKey(hKey, NULL, NULL, NULL, &subKeysCount, &maxSubKeyLen,
                        NULL, &valuesCount, &maxValueNameLen, &maxValueDataLen, NULL, NULL) != ERROR_SUCCESS) {
        return false;
    }
    maxSubKeyLen += 1;
    maxValueNameLen += 1;

    CString buffer;

    buffer.Format(_T("[%s\\%s]\n"), GetHiveName(hKeyRoot), keyName);
    file.WriteString(buffer);

    CString valueName;
    DWORD valueNameLen, valueDataLen, type;
    BYTE* data = DEBUG_NEW BYTE[maxValueDataLen];

    for (DWORD indexValue = 0; indexValue < valuesCount; indexValue++) {
        valueNameLen = maxValueNameLen;
        valueDataLen = maxValueDataLen;

        if (RegEnumValue(hKey, indexValue, valueName.GetBuffer(maxValueNameLen),
                         &valueNameLen, NULL, &type, data, &valueDataLen) != ERROR_SUCCESS) {
            return false;
        }

        switch (type) {
            case REG_SZ: {
                CString str((TCHAR*)data);
                str.Replace(_T("\\"), _T("\\\\"));
                str.Replace(_T("\""), _T("\\\""));
                buffer.Format(_T("\"%s\"=\"%s\"\n"), valueName, str);
                file.WriteString(buffer);
            }
            break;
            case REG_BINARY:
                buffer.Format(_T("\"%s\"=hex:%02x"), valueName, data[0]);
                file.WriteString(buffer);
                for (DWORD i = 1; i < valueDataLen; i++) {
                    buffer.Format(_T(",%02x"), data[i]);
                    file.WriteString(buffer);
                }
                file.WriteString(_T("\n"));
                break;
            case REG_DWORD:
                buffer.Format(_T("\"%s\"=dword:%08x\n"), valueName, *((DWORD*)data));
                file.WriteString(buffer);
                break;
            default: {
                CString msg;
                msg.Format(_T("The value \"%s\\%s\\%s\" has an unsupported type and has been ignored.\nPlease report this error to the developers."),
                           GetHiveName(hKeyRoot), keyName, valueName);
                AfxMessageBox(msg, MB_ICONERROR | MB_OK);
            }
            delete [] data;
            return false;
        }
    }

    delete [] data;

    file.WriteString(_T("\n"));

    CString subKeyName;
    DWORD subKeyLen;

    for (DWORD indexSubKey = 0; indexSubKey < subKeysCount; indexSubKey++) {
        subKeyLen = maxSubKeyLen;

        if (RegEnumKeyEx(hKey, indexSubKey, subKeyName.GetBuffer(maxSubKeyLen),
                         &subKeyLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) {
            return false;
        }

        buffer.Format(_T("%s\\%s"), keyName, subKeyName);

        if (!ExportRegistryKey(file, hKeyRoot, buffer)) {
            return false;
        }
    }

    RegCloseKey(hKey);

    return true;
}
int Driver ( vector<tstring> *result,
                 vector<tstring> *descript,
                 vector<tstring> *publisher,
                 vector<tstring> *path)
{
     HKEY hKey;
     LONG lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
                                  "system\\currentcontrolset"
                                  "\\services",
                                  0,
                                  KEY_READ|KEY_WOW64_64KEY, &hKey);
     
     if ( lResult )
         {
          // Check premission Level
          // report the error 
          
          // Not Found Error FILE_NOT_FOUND(2),PATH_NOT_FOUND(3)
          if ( lResult != 5 )                                      
                    return 0;
          // Premission denied Error (5) ---- add read premission
          return 0;
          // Else ? Move on, man!
                                       }

     // Enumerate through the whole subkey
     DWORD i = 0;
     DWORD maxKey = 1024;
     LPTSTR keyName = (LPTSTR)malloc(1024);
     DWORD valueSiz = 1024;
     DWORD type = REG_SZ;
     LPTSTR value = (LPTSTR)malloc(1024);
     DWORD dispSiz = 1024;
     LPTSTR disp = (LPTSTR)malloc(1024);
     vector<tstring> tmp;
     tstring str;
     while ( true )
     {
           keyName[0] = '\0';
           maxKey = 1024;
           if ( RegEnumKeyEx( hKey, i, keyName, &maxKey, NULL, NULL, NULL, NULL))
              break;

           str = keyName;
           tmp.push_back( str );
           i++;
           }

     for (vector<tstring>::iterator it = tmp.begin(); it != tmp.end(); ++it )
     {
           // Open subKey first. Check it's a Service or Driver?
           HKEY subKey = NULL;
           if ( RegOpenKeyEx( hKey, (*it).c_str(), 0, KEY_READ|KEY_WOW64_64KEY, &subKey ) )
                continue;
           if ( RegQueryValueEx( subKey, "ImagePath", NULL, &type, (LPBYTE)value, &valueSiz) )
                { RegCloseKey(subKey); 
                  valueSiz = 1024;
                  value[0] = '\0';
                  continue; }
           if ( RegQueryValueEx( subKey, "DisplayName", NULL, &type, (LPBYTE)disp, &dispSiz) )
                { RegCloseKey(subKey); 
                  dispSiz = 1024;
                  disp[0] = '\0'; }
           str = value;
           
           // Convert to lowCase
           #ifdef UNICODE
                  {
                    int idx = 0;
                    char c;
                    while(str[idx])
                    {  c = str[idx];
                       str[idx] = towlower(c);
                       idx++; }
                   }           
           #else
                  {
                    int idx = 0;
                    char c;
                    while(str[idx])
                    {  c = str[idx];
                       str[idx] = tolower(c);
                       idx++; }
                   }
            #endif
           
           if (str.find("\\drivers\\") != string::npos )
           {    // Is Driver
                // Push back keyName
                str = value;
                path->push_back(str);
                str = (*it);
                result->push_back( str );
                str = disp;
                descript->push_back( str );
                                       }
           else {
                // Not Driver (service)
                // Just Pass~
                }
           
           // TODO: find publisher
           publisher->push_back("");
           
           // CleanUp
           dispSiz = 1024;
           disp[0] = '\0';
           valueSiz = 1024;
           value[0] = '\0';
           }
     
     free(value);
     free(keyName);
     RegCloseKey(hKey);
     return 1;
     }
Exemple #20
0
/*
 * Copyright (c) 2006-2009 Bjorn Andersson <*****@*****.**>, Erik Ekman <*****@*****.**>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifdef WINDOWS32
#include <winsock2.h>
#include <winioctl.h>
#include "windows.h"

HANDLE dev_handle;
struct tun_data data;

static void get_name(char *ifname, int namelen, char *dev_name);

#define TAP_CONTROL_CODE(request,method) CTL_CODE(FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS)
#define TAP_IOCTL_CONFIG_TUN       TAP_CONTROL_CODE(10, METHOD_BUFFERED)
#define TAP_IOCTL_SET_MEDIA_STATUS TAP_CONTROL_CODE(6, METHOD_BUFFERED)

#define TAP_ADAPTER_KEY "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
#define NETWORK_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
#define TAP_DEVICE_SPACE "\\\\.\\Global\\"
#define TAP_VERSION_ID_0801 "tap0801"
#define TAP_VERSION_ID_0901 "tap0901"
#define KEY_COMPONENT_ID "ComponentId"
#define NET_CFG_INST_ID "NetCfgInstanceId"
#else
#include <err.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define TUN_MAX_TRY 50
#endif

#include "tun.h"
#include "common.h"
#include "ipal.h"

char if_name[250];

#ifndef WINDOWS32
#ifdef LINUX

#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/if_tun.h>

int
open_tun(const char *tun_device)
{
    int i;
    int tun_fd;
    struct ifreq ifreq;
    char *tunnel = "/dev/net/tun";

    if ((tun_fd = open(tunnel, O_RDWR)) < 0) {
        warn("open_tun: %s: %s", tunnel, strerror(errno));
        return -1;
    }

    memset(&ifreq, 0, sizeof(ifreq));

    ifreq.ifr_flags = IFF_TUN;

    if (tun_device != NULL) {
        strncpy(ifreq.ifr_name, tun_device, IFNAMSIZ);
        ifreq.ifr_name[IFNAMSIZ-1] = '\0';
        strncpy(if_name, tun_device, sizeof(if_name));
        if_name[sizeof(if_name)-1] = '\0';

        if (ioctl(tun_fd, TUNSETIFF, (void *) &ifreq) != -1) {
            fprintf(stderr, "Opened %s\n", ifreq.ifr_name);
            return tun_fd;
        }

        if (errno != EBUSY) {
            warn("open_tun: ioctl[TUNSETIFF]: %s", strerror(errno));
            return -1;
        }
    } else {
        for (i = 0; i < TUN_MAX_TRY; i++) {
            snprintf(ifreq.ifr_name, IFNAMSIZ, "dns%d", i);

            if (ioctl(tun_fd, TUNSETIFF, (void *) &ifreq) != -1) {
                fprintf(stderr, "Opened %s\n", ifreq.ifr_name);
                snprintf(if_name, sizeof(if_name), "dns%d", i);
                return tun_fd;
            }

            if (errno != EBUSY) {
                warn("open_tun: ioctl[TUNSETIFF]: %s", strerror(errno));
                return -1;
            }
        }

        warn("open_tun: Couldn't set interface name");
    }
    warn("error when opening tun");
    return -1;
}

#else /* BSD */

int
open_tun(const char *tun_device)
{
    int i;
    int tun_fd;
    char tun_name[50];

    if (tun_device != NULL) {
        snprintf(tun_name, sizeof(tun_name), "/dev/%s", tun_device);
        strncpy(if_name, tun_device, sizeof(if_name));
        if_name[sizeof(if_name)-1] = '\0';

        if ((tun_fd = open(tun_name, O_RDWR)) < 0) {
            warn("open_tun: %s: %s", tun_name, strerror(errno));
            return -1;
        }

        fprintf(stderr, "Opened %s\n", tun_name);
        return tun_fd;
    } else {
        for (i = 0; i < TUN_MAX_TRY; i++) {
            snprintf(tun_name, sizeof(tun_name), "/dev/tun%d", i);

            if ((tun_fd = open(tun_name, O_RDWR)) >= 0) {
                fprintf(stderr, "Opened %s\n", tun_name);
                snprintf(if_name, sizeof(if_name), "tun%d", i);
                return tun_fd;
            }

            if (errno == ENOENT)
                break;
        }

        warn("open_tun: Failed to open tunneling device");
    }

    return -1;
}

#endif /* !LINUX */
#else /* WINDOWS32 */
static void
get_device(char *device, int device_len, const char *wanted_dev)
{
    LONG status;
    HKEY adapter_key;
    int index;

    index = 0;
    status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TAP_ADAPTER_KEY, 0, KEY_READ, &adapter_key);

    if (status != ERROR_SUCCESS) {
        warnx("Error opening registry key " TAP_ADAPTER_KEY );
        return;
    }

    while (TRUE) {
        char name[256];
        char unit[256];
        char component[256];

        char cid_string[256] = KEY_COMPONENT_ID;
        HKEY device_key;
        DWORD datatype;
        DWORD len;

        /* Iterate through all adapter of this kind */
        len = sizeof(name);
        status = RegEnumKeyEx(adapter_key, index, name, &len, NULL, NULL, NULL, NULL);
        if (status == ERROR_NO_MORE_ITEMS) {
            break;
        } else if (status != ERROR_SUCCESS) {
            warnx("Error enumerating subkeys of registry key " TAP_ADAPTER_KEY );
            break;
        }

        snprintf(unit, sizeof(unit), TAP_ADAPTER_KEY "\\%s", name);
        status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, unit, 0, KEY_READ, &device_key);
        if (status != ERROR_SUCCESS) {
            warnx("Error opening registry key %s", unit);
            goto next;
        }

        /* Check component id */
        len = sizeof(component);
        status = RegQueryValueEx(device_key, cid_string, NULL, &datatype, (LPBYTE)component, &len);
        if (status != ERROR_SUCCESS || datatype != REG_SZ) {
            goto next;
        }
        if (strncmp(TAP_VERSION_ID_0801, component, strlen(TAP_VERSION_ID_0801)) == 0 ||
                strncmp(TAP_VERSION_ID_0901, component, strlen(TAP_VERSION_ID_0901)) == 0) {
            /* We found a TAP32 device, get its NetCfgInstanceId */
            char iid_string[256] = NET_CFG_INST_ID;

            status = RegQueryValueEx(device_key, iid_string, NULL, &datatype, (LPBYTE) device, (DWORD *) &device_len);
            if (status != ERROR_SUCCESS || datatype != REG_SZ) {
                warnx("Error reading registry key %s\\%s on TAP device", unit, iid_string);
            } else {
                /* Done getting GUID of TAP device,
                 * now check if the name is the requested one */
                if (wanted_dev) {
                    char name[250];
                    get_name(name, sizeof(name), device);
                    if (strncmp(name, wanted_dev, strlen(wanted_dev))) {
                        /* Skip if name mismatch */
                        goto next;
                    }
                }
                /* Get the if name */
                get_name(if_name, sizeof(if_name), device);
                RegCloseKey(device_key);
                return;
            }
        }
next:
        RegCloseKey(device_key);
        index++;
    }
    RegCloseKey(adapter_key);
}
BOOL kull_m_registry_RegEnumKeyEx(IN PKULL_M_REGISTRY_HANDLE hRegistry, IN HKEY hKey, IN DWORD dwIndex, OUT LPWSTR lpName, IN OUT LPDWORD lpcName, IN LPDWORD lpReserved, OUT OPTIONAL LPWSTR lpClass, IN OUT OPTIONAL LPDWORD lpcClass, OUT OPTIONAL PFILETIME lpftLastWriteTime)
{
	BOOL status = FALSE;
	DWORD dwErrCode, szInCar;
	PKULL_M_REGISTRY_HIVE_KEY_NAMED pKn, pCandidateKn;
	PKULL_M_REGISTRY_HIVE_BIN_CELL pHbC;
	PKULL_M_REGISTRY_HIVE_LF_LH pLfLh;
	wchar_t * buffer;

	switch(hRegistry->type)
	{
		case KULL_M_REGISTRY_TYPE_OWN:
			dwErrCode = RegEnumKeyEx(hKey, dwIndex, lpName, lpcName, lpReserved, lpClass, lpcClass, lpftLastWriteTime);
			if(!(status = (dwErrCode == ERROR_SUCCESS)))
				SetLastError(dwErrCode);
			break;
		case KULL_M_REGISTRY_TYPE_HIVE:
			pKn = (PKULL_M_REGISTRY_HIVE_KEY_NAMED) hKey;
			if(pKn->nbSubKeys && (dwIndex < pKn->nbSubKeys) && (pKn->offsetSubKeys != -1))
			{
				pHbC = (PKULL_M_REGISTRY_HIVE_BIN_CELL) (hRegistry->pHandleHive->pStartOf + pKn->offsetSubKeys);
				switch(pHbC->tag)
				{
				case 'fl':
				case 'hl':
					pLfLh = (PKULL_M_REGISTRY_HIVE_LF_LH) pHbC;
					if(pLfLh->nbElements && (dwIndex < pLfLh->nbElements))
					{
						pCandidateKn = (PKULL_M_REGISTRY_HIVE_KEY_NAMED) (hRegistry->pHandleHive->pStartOf + pLfLh->elements[dwIndex].offsetNamedKey);
						if((pCandidateKn->tag == 'kn') && lpName && lpcName)
						{
							if(lpftLastWriteTime)
								*lpftLastWriteTime = pKn->lastModification;
							
							if(pCandidateKn->flags & KULL_M_REGISTRY_HIVE_KEY_NAMED_FLAG_ASCII_NAME)
							{
								szInCar = pCandidateKn->szKeyName;
								if(status = (*lpcName > szInCar))
								{
									if(buffer = kull_m_string_qad_ansi_c_to_unicode((char *) pCandidateKn->keyName, szInCar))
									{
										RtlCopyMemory(lpName, buffer, szInCar * sizeof(wchar_t));
										LocalFree(buffer);
									}
								}
							}
							else
							{
								szInCar = pCandidateKn->szKeyName / sizeof(wchar_t);
								if(status = (*lpcName > szInCar))
									RtlCopyMemory(lpName, pCandidateKn->keyName, pKn->szKeyName);
							}
							if(status)
								lpName[szInCar] = L'\0';
							*lpcName = szInCar;
							
							if(lpcClass)
							{
								szInCar = pCandidateKn->szClassName / sizeof(wchar_t);
								if(lpClass)
								{
									if(status = (*lpcClass > szInCar))
									{
										RtlCopyMemory(lpClass, &((PKULL_M_REGISTRY_HIVE_BIN_CELL) (hRegistry->pHandleHive->pStartOf + pCandidateKn->offsetClassName))->data , pCandidateKn->szClassName);
										lpClass[szInCar] = L'\0';
									}
								}
								*lpcClass = szInCar;
							}
						}
					}
					break;
				case 'il':
				case 'ir':
				default:
					break;
				}
			}
			break;
		default:
			break;
	}
	return status;
}
Exemple #22
0
BOOL CRegistryTool::GetAllSubKey(tstring regPath,VCTSTRING *vctStr)
{
	HKEY hRootKey;
	HKEY hSubKey;
	tstring strSubKey;
	tstring strSubKeyPath;
	int iRetCode;
	BOOL bResult =FALSE;

	TCHAR strClass[MAX_KEY_LENGTH]={0};
	DWORD dwClass = MAX_KEY_LENGTH;
	DWORD dwSubKey;
	DWORD dwMaxSubKeyLen;
	DWORD dwMaxClassLen;
	DWORD dwValues;
	DWORD dwMaxValueNameLen;
	DWORD dwMaxValueLen;
	DWORD dwSecurityDescriptor;
	FILETIME ftLastWriteTime;

	TCHAR strName[MAX_KEY_LENGTH]={0};
	DWORD dwName;



	if(!RegPathToHkeyAndSubKey(regPath,&hRootKey,&strSubKey))
		return FALSE;

	iRetCode = RegOpenKeyEx(
		hRootKey,
		strSubKey.c_str(),
		0,
		KEY_ALL_ACCESS|KEY_WOW64_64KEY,
		&hSubKey
		);
	if(iRetCode==ERROR_SUCCESS)
	{
		iRetCode = RegQueryInfoKey(
			hSubKey,
			strClass,
			&dwClass,
			NULL,
			&dwSubKey,
			&dwMaxSubKeyLen,
			&dwMaxClassLen,
			&dwValues,
			&dwMaxValueNameLen,
			&dwMaxValueLen,
			&dwSecurityDescriptor,
			&ftLastWriteTime
			);

		if(dwSubKey)
		{
			for(int i =0;i<dwSubKey;i++)
			{
				strName[0]='\0';
				dwName = MAX_KEY_LENGTH;
				iRetCode = RegEnumKeyEx(
					hSubKey,
					i,
					strName,
					&dwName,
					NULL,
					NULL,
					NULL,
					&ftLastWriteTime
					);
				strSubKeyPath = regPath;
				strSubKeyPath +="\\";
				strSubKeyPath += strName;
				vctStr->push_back(strSubKeyPath);
			}
		}
		bResult = TRUE;
	}

	RegCloseKey(hSubKey);
	return bResult;
}
Exemple #23
0
/*
 * Gets the current time zone entry in the "Time Zones" registry.
 */
static int getWinTimeZone(char *winZoneName, char *winMapID)
{
    TIME_ZONE_INFORMATION tzi;
    OSVERSIONINFO ver;
    int onlyMapID;
    HANDLE hKey = NULL, hSubKey = NULL;
    LONG ret;
    DWORD nSubKeys, i;
    ULONG valueType;
    TCHAR subKeyName[MAX_ZONE_CHAR];
    TCHAR szValue[MAX_ZONE_CHAR];
    WCHAR stdNameInReg[MAX_ZONE_CHAR];
    TziValue tempTzi;
    WCHAR *stdNamePtr = tzi.StandardName;
    DWORD valueSize;
    DWORD timeType;

    /*
     * Get the current time zone setting of the platform.
     */
    timeType = GetTimeZoneInformation(&tzi);
    if (timeType == TIME_ZONE_ID_INVALID) {
        goto err;
    }

    /*
     * Determine if this is an NT system.
     */
    ver.dwOSVersionInfoSize = sizeof(ver);
    GetVersionEx(&ver);
    isNT = ver.dwPlatformId == VER_PLATFORM_WIN32_NT;

    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_CURRENT_TZ_KEY, 0,
                       KEY_READ, (PHKEY)&hKey);
    if (ret == ERROR_SUCCESS) {
        DWORD val;
        DWORD bufSize;

        /*
         * Determine if auto-daylight time adjustment is turned off.
         */
        valueType = 0;
        bufSize = sizeof(val);
        ret = RegQueryValueExA(hKey, "DisableAutoDaylightTimeSet",
                               NULL, &valueType, (LPBYTE) &val, &bufSize);
        /*
         * Vista uses the different key name.
         */
        if (ret != ERROR_SUCCESS) {
          bufSize = sizeof(val);
            ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled",
                                   NULL, &valueType, (LPBYTE) &val, &bufSize);
        }
        if (ret == ERROR_SUCCESS) {
            if (val == 1) {
                (void) RegCloseKey(hKey);
                customZoneName(tzi.Bias, winZoneName);
                return VALUE_GMTOFFSET;
            }
        }

        /*
         * Vista has the key for the current "Time Zones" entry.
         */
        if (isNT && ver.dwMajorVersion >= 6) {
            valueType = 0;
            bufSize = MAX_ZONE_CHAR;
            ret = RegQueryValueExA(hKey, "TimeZoneKeyName", NULL,
                                   &valueType, (LPBYTE) winZoneName, &bufSize);
            if (ret != ERROR_SUCCESS) {
                goto err;
            }
            (void) RegCloseKey(hKey);
            return VALUE_KEY;
        }

        /*
         * Win32 problem: If the length of the standard time name is equal
         * to (or probably longer than) 32 in the registry,
         * GetTimeZoneInformation() on NT returns a null string as its
         * standard time name. We need to work around this problem by
         * getting the same information from the TimeZoneInformation
         * registry. The function on Win98 seems to return its key name.
         * We can't do anything in that case.
         */
        if (tzi.StandardName[0] == 0) {
            bufSize = sizeof(stdNameInReg);
            ret = getValueInRegistry(hKey, STANDARD_NAME, &valueType,
                                     (LPBYTE) stdNameInReg, &bufSize);
            if (ret != ERROR_SUCCESS) {
                goto err;
            }
            stdNamePtr = stdNameInReg;
        }
        (void) RegCloseKey(hKey);
    }

    /*
     * Open the "Time Zones" registry.
     */
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, NT_TZ_KEY, 0, KEY_READ, (PHKEY)&hKey);
    if (ret != ERROR_SUCCESS) {
        ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_TZ_KEY, 0, KEY_READ, (PHKEY)&hKey);
        /*
         * If both failed, then give up.
         */
        if (ret != ERROR_SUCCESS) {
            return VALUE_UNKNOWN;
        }
    }

    /*
     * Get the number of subkeys of the "Time Zones" registry for
     * enumeration.
     */
    ret = RegQueryInfoKey(hKey, NULL, NULL, NULL, &nSubKeys,
                          NULL, NULL, NULL, NULL, NULL, NULL, NULL);
    if (ret != ERROR_SUCCESS) {
        goto err;
    }

    /*
     * Compare to the "Std" value of each subkey and find the entry that
     * matches the current control panel setting.
     */
    onlyMapID = 0;
    for (i = 0; i < nSubKeys; ++i) {
        DWORD size = sizeof(subKeyName);
        ret = RegEnumKeyEx(hKey, i, subKeyName, &size, NULL, NULL, NULL, NULL);
        if (ret != ERROR_SUCCESS) {
            goto err;
        }
        ret = RegOpenKeyEx(hKey, subKeyName, 0, KEY_READ, (PHKEY)&hSubKey);
        if (ret != ERROR_SUCCESS) {
            goto err;
        }

        size = sizeof(szValue);
        ret = getValueInRegistry(hSubKey, STD_NAME, &valueType,
                                 szValue, &size);
        if (ret != ERROR_SUCCESS) {
            /*
             * NT 4.0 SP3 fails here since it doesn't have the "Std"
             * entry in the Time Zones registry.
             */
            RegCloseKey(hSubKey);
            onlyMapID = 1;
            ret = RegOpenKeyExW(hKey, stdNamePtr, 0, KEY_READ, (PHKEY)&hSubKey);
            if (ret != ERROR_SUCCESS) {
                goto err;
            }
            break;
        }

        if (wcscmp((WCHAR *)szValue, stdNamePtr) == 0) {
            /*
             * Some localized Win32 platforms use a same name to
             * different time zones. So, we can't rely only on the name
             * here. We need to check GMT offsets and transition dates
             * to make sure it's the registry of the current time
             * zone.
             */
            DWORD tziValueSize = sizeof(tempTzi);
            ret = RegQueryValueEx(hSubKey, "TZI", NULL, &valueType,
                                  (unsigned char *) &tempTzi, &tziValueSize);
            if (ret == ERROR_SUCCESS) {
                if ((tzi.Bias != tempTzi.bias) ||
                    (memcmp((const void *) &tzi.StandardDate,
                            (const void *) &tempTzi.stdDate,
                            sizeof(SYSTEMTIME)) != 0)) {
                        goto out;
                }

                if (tzi.DaylightBias != 0) {
                    if ((tzi.DaylightBias != tempTzi.dstBias) ||
                        (memcmp((const void *) &tzi.DaylightDate,
                                (const void *) &tempTzi.dstDate,
                                sizeof(SYSTEMTIME)) != 0)) {
                        goto out;
                    }
                }
            }

            /*
             * found matched record, terminate search
             */
            strcpy(winZoneName, subKeyName);
            break;
        }
    out:
        (void) RegCloseKey(hSubKey);
    }

    /*
     * Get the "MapID" value of the registry to be able to eliminate
     * duplicated key names later.
     */
    valueSize = MAX_MAPID_LENGTH;
    ret = RegQueryValueExA(hSubKey, "MapID", NULL, &valueType, winMapID, &valueSize);
    (void) RegCloseKey(hSubKey);
    (void) RegCloseKey(hKey);

    if (ret != ERROR_SUCCESS) {
        /*
         * Vista doesn't have mapID. VALUE_UNKNOWN should be returned
         * only for Windows NT.
         */
        if (onlyMapID == 1) {
            return VALUE_UNKNOWN;
        }
    }

    return VALUE_KEY;

 err:
    if (hKey != NULL) {
        (void) RegCloseKey(hKey);
    }
    return VALUE_UNKNOWN;
}
Exemple #24
0
/*
===============
PrintCpuInfoFromRegistry
===============
*/
static qboolean PrintCpuInfoFromRegistry( void )
{
	DWORD i, numPrinted;
	HKEY  kCpus;

	char  name_buf[ 256 ];
	DWORD name_buf_len;

	if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, "Hardware\\Description\\System\\CentralProcessor",
	                   0, KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE, &kCpus ) != ERROR_SUCCESS )
	{
		return qfalse;
	}

	numPrinted = 0;

	for ( i = 0; name_buf_len = ARRAY_LEN( name_buf ),
	      RegEnumKeyEx( kCpus, i, name_buf, &name_buf_len,
	                    NULL, NULL, NULL, NULL ) == ERROR_SUCCESS; i++ )
	{
		HKEY   kCpu;

		int    value_buf_i[ 256 ];
		LPBYTE value_buf = ( char * ) value_buf_i;
		DWORD  value_buf_len;

		if ( RegOpenKeyEx( kCpus, name_buf, 0, KEY_QUERY_VALUE, &kCpu ) != ERROR_SUCCESS )
		{
			continue;
		}

		Com_Printf( "    Processor %i:\n", ( int ) i );

		value_buf_len = sizeof( value_buf_i );

		if ( RegQueryValueEx( kCpu, "ProcessorNameString", NULL, NULL, value_buf, &value_buf_len ) == ERROR_SUCCESS )
		{
			Com_Printf( "        Name: %s\n", value_buf );
		}

		value_buf_len = sizeof( value_buf_i );

		if ( RegQueryValueEx( kCpu, "~MHz", NULL, NULL, value_buf, &value_buf_len ) == ERROR_SUCCESS )
		{
			Com_Printf( "        Speed: %i MHz\n", ( int ) * ( DWORD * ) value_buf_i );
		}

		value_buf_len = sizeof( value_buf_i );

		if ( RegQueryValueEx( kCpu, "VendorIdentifier", NULL, NULL, value_buf, &value_buf_len ) == ERROR_SUCCESS )
		{
			Com_Printf( "        Vendor: %s\n", value_buf );
		}

		value_buf_len = sizeof( value_buf_i );

		if ( RegQueryValueEx( kCpu, "Identifier", NULL, NULL, value_buf, &value_buf_len ) == ERROR_SUCCESS )
		{
			Com_Printf( "        Identifier: %s\n", value_buf );
		}

		value_buf_len = sizeof( value_buf_i );

		if ( RegQueryValueEx( kCpu, "FeatureSet", NULL, NULL, value_buf, &value_buf_len ) == ERROR_SUCCESS )
		{
			Com_Printf( "        Feature Bits: %08X\n", ( int ) * ( DWORD * ) value_buf_i );
		}

		RegCloseKey( kCpu );

		numPrinted++;
	}

	RegCloseKey( kCpus );

	return numPrinted > 0;
}
Exemple #25
0
static const char *
identify_system_timezone(void)
{
	int			i;
	char		tzname[128];
	char		localtzname[256];
	time_t		t = time(NULL);
	struct tm  *tm = localtime(&t);
	HKEY		rootKey;
	int			idx;

	if (!tm)
	{
		ereport(LOG,
		  (errmsg("could not identify system time zone: localtime() failed"),
		   errdetail("The PostgreSQL time zone will be set to \"%s\".",
					 "GMT"),
		errhint("You can specify the correct timezone in postgresql.conf.")));
		return NULL;			/* go to GMT */
	}

	memset(tzname, 0, sizeof(tzname));
	strftime(tzname, sizeof(tzname) - 1, "%Z", tm);

	for (i = 0; win32_tzmap[i].stdname != NULL; i++)
	{
		if (strcmp(tzname, win32_tzmap[i].stdname) == 0 ||
			strcmp(tzname, win32_tzmap[i].dstname) == 0)
		{
			elog(DEBUG4, "TZ \"%s\" matches system time zone \"%s\"",
				 win32_tzmap[i].pgtzname, tzname);
			return win32_tzmap[i].pgtzname;
		}
	}

	/*
	 * Localized Windows versions return localized names for the timezone.
	 * Scan the registry to find the English name, and then try matching
	 * against our table again.
	 */
	memset(localtzname, 0, sizeof(localtzname));
	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
			   "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
					 0,
					 KEY_READ,
					 &rootKey) != ERROR_SUCCESS)
	{
		ereport(LOG,
				(errmsg("could not open registry key to identify system time zone: %i",
						(int) GetLastError()),
				 errdetail("The PostgreSQL time zone will be set to \"%s\".",
						   "GMT"),
		errhint("You can specify the correct timezone in postgresql.conf.")));
		return NULL;			/* go to GMT */
	}

	for (idx = 0;; idx++)
	{
		char		keyname[256];
		char		zonename[256];
		DWORD		namesize;
		FILETIME	lastwrite;
		HKEY		key;
		LONG		r;

		memset(keyname, 0, sizeof(keyname));
		namesize = sizeof(keyname);
		if ((r = RegEnumKeyEx(rootKey,
							  idx,
							  keyname,
							  &namesize,
							  NULL,
							  NULL,
							  NULL,
							  &lastwrite)) != ERROR_SUCCESS)
		{
			if (r == ERROR_NO_MORE_ITEMS)
				break;
			ereport(LOG,
					(errmsg_internal("could not enumerate registry subkeys to identify system time zone: %i", (int) r)));
			break;
		}

		if ((r = RegOpenKeyEx(rootKey, keyname, 0, KEY_READ, &key)) != ERROR_SUCCESS)
		{
			ereport(LOG,
					(errmsg_internal("could not open registry subkey to identify system time zone: %i", (int) r)));
			break;
		}

		memset(zonename, 0, sizeof(zonename));
		namesize = sizeof(zonename);
		if ((r = RegQueryValueEx(key, "Std", NULL, NULL, (unsigned char *) zonename, &namesize)) != ERROR_SUCCESS)
		{
			ereport(LOG,
					(errmsg_internal("could not query value for key \"std\" to identify system time zone \"%s\": %i",
									 keyname, (int) r)));
			RegCloseKey(key);
			continue;			/* Proceed to look at the next timezone */
		}
		if (strcmp(tzname, zonename) == 0)
		{
			/* Matched zone */
			strcpy(localtzname, keyname);
			RegCloseKey(key);
			break;
		}
		memset(zonename, 0, sizeof(zonename));
		namesize = sizeof(zonename);
		if ((r = RegQueryValueEx(key, "Dlt", NULL, NULL, (unsigned char *) zonename, &namesize)) != ERROR_SUCCESS)
		{
			ereport(LOG,
					(errmsg_internal("could not query value for key \"dlt\" to identify system time zone \"%s\": %i",
									 keyname, (int) r)));
			RegCloseKey(key);
			continue;			/* Proceed to look at the next timezone */
		}
		if (strcmp(tzname, zonename) == 0)
		{
			/* Matched DST zone */
			strcpy(localtzname, keyname);
			RegCloseKey(key);
			break;
		}

		RegCloseKey(key);
	}

	RegCloseKey(rootKey);

	if (localtzname[0])
	{
		/* Found a localized name, so scan for that one too */
		for (i = 0; win32_tzmap[i].stdname != NULL; i++)
		{
			if (strcmp(localtzname, win32_tzmap[i].stdname) == 0 ||
				strcmp(localtzname, win32_tzmap[i].dstname) == 0)
			{
				elog(DEBUG4, "TZ \"%s\" matches localized system time zone \"%s\" (\"%s\")",
					 win32_tzmap[i].pgtzname, tzname, localtzname);
				return win32_tzmap[i].pgtzname;
			}
		}
	}

	ereport(LOG,
			(errmsg("could not find a match for system time zone \"%s\"",
					tzname),
			 errdetail("The PostgreSQL time zone will be set to \"%s\".",
					   "GMT"),
	   errhint("You can specify the correct timezone in postgresql.conf.")));
	return NULL;				/* go to GMT */
}
Exemple #26
0
INT_PTR CSetPgIntegr::PageDlgProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
	static bool bSkipCbSel = FALSE;
	INT_PTR iRc = 0;

	switch (messg)
	{
	case WM_NOTIFY:
		{
			LPNMHDR phdr = (LPNMHDR)lParam;

			if (phdr->code == TTN_GETDISPINFO)
			{
				return gpSetCls->ProcessTipHelp(hDlg, messg, wParam, lParam);
			}

			break;
		}
	case WM_INITDIALOG:
		{
			bSkipCbSel = true;

			PageDlgProc(hDlg, UM_RELOAD_HERE_LIST, UM_RELOAD_HERE_LIST, 0);

			//-- moved to "ComSpec" page
			//PageDlgProc(hDlg, UM_RELOAD_AUTORUN, UM_RELOAD_AUTORUN, 0);

			// Возвращает NULL, если строка пустая
			wchar_t* pszCurInside = GetDlgItemTextPtr(hDlg, cbInsideName);
			_ASSERTE((pszCurInside==NULL) || (*pszCurInside!=0));
			wchar_t* pszCurHere   = GetDlgItemTextPtr(hDlg, cbHereName);
			_ASSERTE((pszCurHere==NULL) || (*pszCurHere!=0));

			wchar_t szIcon[MAX_PATH+32];
			_wsprintf(szIcon, SKIPLEN(countof(szIcon)) L"%s,0", gpConEmu->ms_ConEmuExe);

			if (pszCurInside)
			{
				bSkipCbSel = false;
				PageDlgProc(hDlg, WM_COMMAND, MAKELONG(cbInsideName,CBN_SELCHANGE), 0);
				bSkipCbSel = true;
			}
			else
			{
				SetDlgItemText(hDlg, cbInsideName, L"ConEmu Inside");
				SetDlgItemText(hDlg, tInsideConfig, L"shell");
				SetDlgItemText(hDlg, tInsideShell, CONEMU_HERE_POSH);
				//SetDlgItemText(hDlg, tInsideIcon, szIcon);
				SetDlgItemText(hDlg, tInsideIcon, L"powershell.exe");
				checkDlgButton(hDlg, cbInsideSyncDir, gpConEmu->mp_Inside && gpConEmu->mp_Inside->mb_InsideSynchronizeCurDir);
				SetDlgItemText(hDlg, tInsideSyncDir, L""); // Auto
			}

			if (pszCurHere)
			{
				bSkipCbSel = false;
				PageDlgProc(hDlg, WM_COMMAND, MAKELONG(cbHereName,CBN_SELCHANGE), 0);
				bSkipCbSel = true;
			}
			else
			{
				SetDlgItemText(hDlg, cbHereName, L"ConEmu Here");
				SetDlgItemText(hDlg, tHereConfig, L"");
				SetDlgItemText(hDlg, tHereShell, CONEMU_HERE_CMD);
				SetDlgItemText(hDlg, tHereIcon, szIcon);
			}

			bSkipCbSel = false;

			SafeFree(pszCurInside);
			SafeFree(pszCurHere);

		}
		break; // WM_INITDIALOG

	case WM_COMMAND:
		switch (HIWORD(wParam))
		{
		case BN_CLICKED:
			{
				WORD CB = LOWORD(wParam);

				switch (CB)
				{
				case cbInsideSyncDir:
					if (gpConEmu->mp_Inside)
					{
						gpConEmu->mp_Inside->mb_InsideSynchronizeCurDir = isChecked(hDlg, CB);
					}
					break;
				case bInsideRegister:
				case bInsideUnregister:
					ShellIntegration(hDlg, ShellIntgr_Inside, CB==bInsideRegister);
					PageDlgProc(hDlg, UM_RELOAD_HERE_LIST, UM_RELOAD_HERE_LIST, 0);
					if (CB==bInsideUnregister)
						PageDlgProc(hDlg, WM_COMMAND, MAKELONG(cbInsideName,CBN_SELCHANGE), 0);
					break;
				case bHereRegister:
				case bHereUnregister:
					ShellIntegration(hDlg, ShellIntgr_Here, CB==bHereRegister);
					PageDlgProc(hDlg, UM_RELOAD_HERE_LIST, UM_RELOAD_HERE_LIST, 0);
					if (CB==bHereUnregister)
						PageDlgProc(hDlg, WM_COMMAND, MAKELONG(cbHereName,CBN_SELCHANGE), 0);
					break;
				}
			}
			break; // BN_CLICKED
		case EN_CHANGE:
			{
				WORD EB = LOWORD(wParam);
				switch (EB)
				{
				case tInsideSyncDir:
					if (gpConEmu->mp_Inside)
					{
						SafeFree(gpConEmu->mp_Inside->ms_InsideSynchronizeCurDir);
						gpConEmu->mp_Inside->ms_InsideSynchronizeCurDir = GetDlgItemTextPtr(hDlg, tInsideSyncDir);
					}
					break;
				}
			}
			break; // EN_CHANGE
		case CBN_SELCHANGE:
			{
				WORD CB = LOWORD(wParam);
				switch (CB)
				{
				case cbInsideName:
				case cbHereName:
					if (!bSkipCbSel)
					{
						wchar_t *pszCfg = NULL, *pszIco = NULL, *pszFull = NULL, *pszDirSync = NULL;
						LPCWSTR pszCmd = NULL;
						INT_PTR iSel = SendDlgItemMessage(hDlg, CB, CB_GETCURSEL, 0,0);
						if (iSel >= 0)
						{
							INT_PTR iLen = SendDlgItemMessage(hDlg, CB, CB_GETLBTEXTLEN, iSel, 0);
							size_t cchMax = iLen+128;
							wchar_t* pszName = (wchar_t*)calloc(cchMax,sizeof(*pszName));
							if ((iLen > 0) && pszName)
							{
								_wcscpy_c(pszName, cchMax, L"Directory\\shell\\");
								SendDlgItemMessage(hDlg, CB, CB_GETLBTEXT, iSel, (LPARAM)(pszName+_tcslen(pszName)));

								HKEY hkShell = NULL;
								if (0 == RegOpenKeyEx(HKEY_CLASSES_ROOT, pszName, 0, KEY_READ, &hkShell))
								{
									DWORD nType;
									DWORD nSize = MAX_PATH*2*sizeof(wchar_t);
									pszIco = (wchar_t*)calloc(nSize+2,1);
									if (0 != RegQueryValueEx(hkShell, L"Icon", NULL, &nType, (LPBYTE)pszIco, &nSize) || nType != REG_SZ)
										SafeFree(pszIco);
									HKEY hkCmd = NULL;
									if (0 == RegOpenKeyEx(hkShell, L"command", 0, KEY_READ, &hkCmd))
									{
										DWORD nSize = MAX_PATH*8*sizeof(wchar_t);
										pszFull = (wchar_t*)calloc(nSize+2,1);
										if (0 != RegQueryValueEx(hkCmd, NULL, NULL, &nType, (LPBYTE)pszFull, &nSize) || nType != REG_SZ)
										{
											SafeFree(pszIco);
										}
										else
										{
											LPCWSTR psz = pszFull;
											LPCWSTR pszPrev = pszFull;
											CEStr szArg;
											while (0 == NextArg(&psz, szArg, &pszPrev))
											{
												if (*szArg != L'/')
													continue;

												if ((lstrcmpi(szArg, L"/inside") == 0)
													|| (lstrcmpi(szArg, L"/here") == 0)
													)
												{
													// Nop
												}
												else if (lstrcmpni(szArg, L"/inside=", 8) == 0)
												{
													pszDirSync = lstrdup(szArg+8); // may be empty!
												}
												else if (lstrcmpi(szArg, L"/config") == 0)
												{
													if (0 != NextArg(&psz, szArg))
														break;
													pszCfg = lstrdup(szArg);
												}
												else if (lstrcmpi(szArg, L"/dir") == 0)
												{
													if (0 != NextArg(&psz, szArg))
														break;
													_ASSERTE(lstrcmpi(szArg, L"%1")==0);
												}
												else //if (lstrcmpi(szArg, L"/cmd") == 0)
												{
													if (lstrcmpi(szArg, L"/cmd") == 0)
														pszCmd = psz;
													else
														pszCmd = pszPrev;
													break;
												}
											}
										}
										RegCloseKey(hkCmd);
									}
									RegCloseKey(hkShell);
								}
							}
							SafeFree(pszName);
						}

						SetDlgItemText(hDlg, (CB==cbInsideName) ? tInsideConfig : tHereConfig,
							pszCfg ? pszCfg : L"");
						SetDlgItemText(hDlg, (CB==cbInsideName) ? tInsideShell : tHereShell,
							pszCmd ? pszCmd : L"");
						SetDlgItemText(hDlg, (CB==cbInsideName) ? tInsideIcon : tHereIcon,
							pszIco ? pszIco : L"");

						if (CB==cbInsideName)
						{
							SetDlgItemText(hDlg, tInsideSyncDir, pszDirSync ? pszDirSync : L"");
							checkDlgButton(hDlg, cbInsideSyncDir, (pszDirSync && *pszDirSync) ? BST_CHECKED : BST_UNCHECKED);
						}

						SafeFree(pszCfg);
						SafeFree(pszFull);
						SafeFree(pszIco);
						SafeFree(pszDirSync);
					}
					break;
				}
			}
			break; // CBN_SELCHANGE
		} // switch (HIWORD(wParam))
		break; // WM_COMMAND

	case UM_RELOAD_HERE_LIST:
		if (wParam == UM_RELOAD_HERE_LIST)
		{
			HKEY hkDir = NULL;
			size_t cchCmdMax = 65535;
			wchar_t* pszCmd = (wchar_t*)calloc(cchCmdMax,sizeof(*pszCmd));
			if (!pszCmd)
				break;

			// Возвращает NULL, если строка пустая
			wchar_t* pszCurInside = GetDlgItemTextPtr(hDlg, cbInsideName);
			_ASSERTE((pszCurInside==NULL) || (*pszCurInside!=0));
			wchar_t* pszCurHere   = GetDlgItemTextPtr(hDlg, cbHereName);
			_ASSERTE((pszCurHere==NULL) || (*pszCurHere!=0));

			bool lbOldSkip = bSkipCbSel; bSkipCbSel = true;

			SendDlgItemMessage(hDlg, cbInsideName, CB_RESETCONTENT, 0, 0);
			SendDlgItemMessage(hDlg, cbHereName, CB_RESETCONTENT, 0, 0);

			if (0 == RegOpenKeyEx(HKEY_CLASSES_ROOT, L"Directory\\shell", 0, KEY_READ, &hkDir))
			{
				for (DWORD i = 0; i < 512; i++)
				{
					wchar_t szName[MAX_PATH+32] = {};
					DWORD cchMax = countof(szName) - 32;
					if (0 != RegEnumKeyEx(hkDir, i, szName, &cchMax, NULL, NULL, NULL, NULL))
						break;
					wchar_t* pszSlash = szName + _tcslen(szName);
					wcscat_c(szName, L"\\command");
					HKEY hkCmd = NULL;
					if (0 == RegOpenKeyEx(hkDir, szName, 0, KEY_READ, &hkCmd))
					{
						DWORD cbMax = (cchCmdMax-2) * sizeof(*pszCmd);
						if (0 == RegQueryValueEx(hkCmd, NULL, NULL, NULL, (LPBYTE)pszCmd, &cbMax))
						{
							pszCmd[cbMax>>1] = 0;
							*pszSlash = 0;
							LPCWSTR pszInside = StrStrI(pszCmd, L"/inside");
							LPCWSTR pszConEmu = StrStrI(pszCmd, L"conemu");
							if (pszConEmu)
							{
								SendDlgItemMessage(hDlg,
									pszInside ? cbInsideName : cbHereName,
									CB_ADDSTRING, 0, (LPARAM)szName);
								if ((pszInside ? pszCurInside : pszCurHere) == NULL)
								{
									if (pszInside)
										pszCurInside = lstrdup(szName);
									else
										pszCurHere = lstrdup(szName);
								}
							}
						}
						RegCloseKey(hkCmd);
					}
				}
				RegCloseKey(hkDir);
			}
Exemple #27
0
bool setup_device(void) {
    HKEY key, key2;
    int i, err;

    char regpath[1024];
    char adapterid[1024];
    char adaptername[1024];
    char tapname[1024];
    char gelukt = 0;
    long len;

    bool found = false;

    get_config_string(lookup_config(config_tree, "Device"), &device);
    get_config_string(lookup_config(config_tree, "Interface"), &iface);

    /* Open registry and look for network adapters */

    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_READ, &key)) {
        logger(LOG_ERR, "Unable to read registry: %s", winerror(GetLastError()));
        return false;
    }

    for (i = 0; ; i++) {
        len = sizeof(adapterid);
        if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL))
            break;

        /* Find out more about this adapter */

        snprintf(regpath, sizeof(regpath), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, adapterid);

        if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2))
            continue;

        len = sizeof(adaptername);
        err = RegQueryValueEx(key2, "Name", 0, 0, adaptername, &len);

        RegCloseKey(key2);

        if(err)
            continue;

        if(device) {
            if(!strcmp(device, adapterid)) {
                found = true;
                break;
            } else
                continue;
        }

        if(iface) {
            if(!strcmp(iface, adaptername)) {
                found = true;
                break;
            } else
                continue;
        }

        snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
        device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);
        if(device_handle != INVALID_HANDLE_VALUE) {
            CloseHandle(device_handle);
            found = true;
            break;
        }
    }

    RegCloseKey(key);

    if(!found) {
        logger(LOG_ERR, "No Windows tap device found!");
        return false;
    }

    if(!device)
        device = xstrdup(adapterid);

    if(!iface)
        iface = xstrdup(adaptername);

    snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, device);

    /* Now we are going to open this device twice: once for reading and once for writing.
       We do this because apparently it isn't possible to check for activity in the select() loop.
       Furthermore I don't really know how to do it the "Windows" way. */

    if(socketpair(AF_UNIX, SOCK_DGRAM, PF_UNIX, sp)) {
        logger(LOG_DEBUG, "System call `%s' failed: %s", "socketpair", strerror(errno));
        return false;
    }

    /* The parent opens the tap device for writing. */

    device_handle = CreateFile(tapname, GENERIC_WRITE,  FILE_SHARE_READ,  0,  OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM , 0);

    if(device_handle == INVALID_HANDLE_VALUE) {
        logger(LOG_ERR, "Could not open Windows tap device %s (%s) for writing: %s", device, iface, winerror(GetLastError()));
        return false;
    }

    device_fd = sp[0];

    /* Get MAC address from tap device */

    if(!DeviceIoControl(device_handle, TAP_IOCTL_GET_MAC, mymac.x, sizeof(mymac.x), mymac.x, sizeof(mymac.x), &len, 0)) {
        logger(LOG_ERR, "Could not get MAC address from Windows tap device %s (%s): %s", device, iface, winerror(GetLastError()));
        return false;
    }

    if(routing_mode == RMODE_ROUTER) {
        overwrite_mac = 1;
    }

    /* Now we start the child */

    reader_pid = fork();

    if(reader_pid == -1) {
        logger(LOG_DEBUG, "System call `%s' failed: %s", "fork", strerror(errno));
        return false;
    }

    if(!reader_pid) {
        /* The child opens the tap device for reading, blocking.
           It passes everything it reads to the socket. */

        char buf[MTU];
        long lenin;

        CloseHandle(device_handle);

        device_handle = CreateFile(tapname, GENERIC_READ, FILE_SHARE_WRITE, 0,  OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);

        if(device_handle == INVALID_HANDLE_VALUE) {
            logger(LOG_ERR, "Could not open Windows tap device %s (%s) for reading: %s", device, iface, winerror(GetLastError()));
            buf[0] = 0;
            write(sp[1], buf, 1);
            exit(1);
        }

        logger(LOG_DEBUG, "Tap reader forked and running.");

        /* Notify success */

        buf[0] = 1;
        write(sp[1], buf, 1);

        /* Pass packets */

        for(;;) {
            ReadFile(device_handle, buf, MTU, &lenin, NULL);
            write(sp[1], buf, lenin);
        }
    }

    read(device_fd, &gelukt, 1);
    if(gelukt != 1) {
        logger(LOG_DEBUG, "Tap reader failed!");
        return false;
    }

    device_info = "Windows tap device";

    logger(LOG_INFO, "%s (%s) is a %s", device, iface, device_info);

    return true;
}
// Workround to enable capture at 30fps for some camera models
// Should be called with administrative rights
// Return 0 if ok, -1 if permission denied
int VfwCamFpsWorkaround ()
{
	HKEY hKey;    
	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 
	DWORD i, retCode;   
   // DWORD cchValue = MAX_VALUE_NAME; 

	// Open key
	retCode= RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\VfWWDM Mapper"), 
							0, KEY_ALL_ACCESS, &hKey);
	if (retCode!= ERROR_SUCCESS) return -1;

	// Get the class name and the value count. 
    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);       // last write time 
 
	// Enumerate the subkeys
	if (cSubKeys) {
		for (i=0; i<cSubKeys; i++) { 
			cbName = MAX_KEY_LENGTH;
			retCode = RegEnumKeyEx(hKey, i,	achKey, &cbName, NULL, 
									NULL, NULL, &ftLastWriteTime); 

			if (retCode == ERROR_SUCCESS) {
				HKEY hKeyValue;

				retCode= RegOpenKeyEx(hKey, achKey, 0, KEY_WRITE, &hKeyValue);
				if (retCode== ERROR_SUCCESS) {
					DWORD value= 333330;
					retCode= RegSetValueEx(hKeyValue, TEXT("AvgTimePerFrame"), 0, REG_DWORD, 
											(const BYTE *) &value, sizeof(DWORD));
				}
				RegCloseKey(hKeyValue);
			}
		}
	} 

	// Close key
	RegCloseKey(hKey);

	return 0;
}
static int get_device_guid(
    char *name,
    int name_size,
    char *actual_name,
    int actual_name_size)
{
    LONG status;
    HKEY control_net_key;
    DWORD len;
    int i = 0;
    int stop = 0;

    status = RegOpenKeyEx(
        HKEY_LOCAL_MACHINE,
        NETWORK_CONNECTIONS_KEY,
        0,
        KEY_READ,
        &control_net_key);

    if (status != ERROR_SUCCESS) {
        return -1;
    }

    while (!stop)
    {
        char enum_name[256];
        char connection_string[256];
        HKEY connection_key;
        char name_data[256];
        DWORD name_type;
        const char name_string[] = "Name";

        len = sizeof (enum_name);
        status = RegEnumKeyEx(
            control_net_key,
            i,
            enum_name,
            &len,
            NULL,
            NULL,
            NULL,
            NULL);

        if (status == ERROR_NO_MORE_ITEMS)
            break;
        else if (status != ERROR_SUCCESS) {
            return -1;
        }

        snprintf(connection_string,
             sizeof(connection_string),
             "%s\\%s\\Connection",
             NETWORK_CONNECTIONS_KEY, enum_name);

        status = RegOpenKeyEx(
            HKEY_LOCAL_MACHINE,
            connection_string,
            0,
            KEY_READ,
            &connection_key);

        if (status == ERROR_SUCCESS) {
            len = sizeof (name_data);
            status = RegQueryValueEx(
                connection_key,
                name_string,
                NULL,
                &name_type,
                (LPBYTE)name_data,
                &len);

            if (status != ERROR_SUCCESS || name_type != REG_SZ) {
                    return -1;
            }
            else {
                if (is_tap_win32_dev(enum_name)) {
                    snprintf(name, name_size, "%s", enum_name);
                    if (actual_name) {
                        if (strcmp(actual_name, "") != 0) {
                            if (strcmp(name_data, actual_name) != 0) {
                                RegCloseKey (connection_key);
                                ++i;
                                continue;
                            }
                        }
                        else {
                            snprintf(actual_name, actual_name_size, "%s", name_data);
                        }
                    }
                    stop = 1;
                }
            }

            RegCloseKey (connection_key);
        }
        ++i;
    }

    RegCloseKey (control_net_key);

    if (stop == 0)
        return -1;

    return 0;
}
static int wpa_config_read_networks(struct wpa_config *config, HKEY hk)
{
	HKEY nhk;
	struct wpa_ssid *ssid, *tail = NULL, *head = NULL;
	int errors = 0;
	LONG ret;
	DWORD i;

	ret = RegOpenKeyEx(hk, TEXT("networks"), 0, KEY_ENUMERATE_SUB_KEYS,
			   &nhk);
	if (ret != ERROR_SUCCESS) {
		wpa_printf(MSG_ERROR, "Could not open wpa_supplicant networks "
			   "registry key");
		return -1;
	}

	for (i = 0; ; i++) {
		TCHAR name[255];
		DWORD namelen;

		namelen = 255;
		ret = RegEnumKeyEx(nhk, i, name, &namelen, NULL, NULL, NULL,
				   NULL);

		if (ret == ERROR_NO_MORE_ITEMS)
			break;

		if (ret != ERROR_SUCCESS) {
			wpa_printf(MSG_DEBUG, "RegEnumKeyEx failed: 0x%x",
				   (unsigned int) ret);
			break;
		}

		if (namelen >= 255)
			namelen = 255 - 1;
		name[namelen] = '\0';

		ssid = wpa_config_read_network(nhk, name, i);
		if (ssid == NULL) {
			wpa_printf(MSG_ERROR, "Failed to parse network "
				   "profile '%s'.", name);
			errors++;
			continue;
		}
		if (head == NULL) {
			head = tail = ssid;
		} else {
			tail->next = ssid;
			tail = ssid;
		}
		if (wpa_config_add_prio_network(config, ssid)) {
			wpa_printf(MSG_ERROR, "Failed to add network profile "
				   "'%s' to priority list.", name);
			errors++;
			continue;
		}
	}

	RegCloseKey(nhk);

	config->ssid = head;

	return errors ? -1 : 0;
}