Ejemplo n.º 1
0
int ui_doinstall(HANDLE hFile,int offset,header *head, section *sec, entry *ent, uninstall_header *uhead)
{
  TCHAR tmpbuf[MAX_PATH];
  int ret = 3;
  m_hFile=hFile;
  m_offset=offset;
  m_section=sec;
  m_entry=ent;
  m_header=head;

  if (!uhead) {
	  if (noisy) {
		  noisy=!(head->silent_install);
	  } else {
		  head->silent_install = !noisy;
	  }
	  /* Setup localized strings */
	  if ((g_strings = getStrings(NULL)) == NULL) {
		  GETRESOURCE(tmpbuf, JAVAWS_ERROR_STRINGTABLE);
		  if (noisy) MessageBox(NULL,tmpbuf,g_caption,MB_OK|MB_ICONWARNING);
	  }
	  _tcscpy(tmpbuf, m_header->name);
	  process_string(m_header->name, tmpbuf, NULL);
	  _tcscpy(tmpbuf, m_header->licensetext);
	  process_string(m_header->licensetext, tmpbuf, NULL);
	  _tcscpy(tmpbuf, m_header->componenttext);
	  process_string(m_header->componenttext, tmpbuf, NULL);
	  _tcscpy(tmpbuf, m_header->text);
	  process_string(m_header->text, tmpbuf, NULL);
  }

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
  m_uninstheader=uhead;
  if (uhead)
  {
	  INT32 args[] = { (INT32)m_uninstheader->name };
	  g_strings = getStrings(NULL);
	  _tcscpy(tmpbuf, m_uninstheader->uninstalltext);
	  process_string(m_uninstheader->uninstalltext, tmpbuf, NULL);
	  GETRESOURCE2(tmpbuf, JAVAWS_MESSAGE_UNINSTALL, args);
      wsprintf(g_caption,tmpbuf);
      return DialogBox(g_hInstance,MAKEINTRESOURCE(IDD_INST),GetDesktopWindow(),DialogProcUninstall);
  }
  else
#endif
  {
    TCHAR buf[MAX_PATH];
    int st=0;

    state_install_directory[0]=0;
    if (head->install_reg_key[0])
    {
      HKEY hKey;
		  if ( RegOpenKeyEx((HKEY)head->install_reg_rootkey,head->install_reg_key,0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
			  int l = sizeof(buf);
			  int t=REG_SZ;
        if (RegQueryValueEx(hKey,head->install_reg_value,NULL,&t,buf,&l ) == ERROR_SUCCESS && t == REG_SZ && buf[0])
			  {
          LPTSTR e;
          LPTSTR p=buf;
          while (*p && *p != _T('\"')) p=CharNext(p);
          if (*p)
          {
            LPTSTR p2;
			p=CharNext(p);
			p2 = p;
            while (*p2 && *p2 != _T('\"')) p2=CharNext(p2);
            if (*p2)
            {
              *p2=0;
            }
            else p=buf;
          }
          else p=buf; 
          // p is the path now, check for .exe extension
          e=p;
          while (*e) e=CharNext(e);
          while (e>p && *e != _T('.') && *e != _T('\\')) e=CharPrev(p, e);
          if (*e ==_T('.'))
          {
            if ((e[1] == _T('e') || e[1]==_T('E')) &&
                (e[2] == _T('x') || e[2]==_T('X')) &&
                (e[3] == _T('e') || e[3]==_T('E')))        // check extension
            {
              DWORD d;
              e[4]=0;
              d=GetFileAttributes(p);               // get the file attributes
              if (d == 0xFFFFFFFFF || !(d&FILE_ATTRIBUTE_DIRECTORY)) // if not exists, or not directory, then remove suffix
              {
				while (e>p && *e != _T('\\')) e=CharPrev(p, e);
                if (*e == _T('\\')) *e=0;
              }
            }
          }


          _tcscpy(state_install_directory,buf);
        }
			  RegCloseKey(hKey);
      }
    }

    if (!state_install_directory[0]) 
    {
      _tcscpy(state_install_directory,head->install_directory);
#ifdef NSIS_CONFIG_WINAMPHACKCHECK
#warning NSIS_CONFIG_WINAMPHACKCHECK defined, this section NOT internationalized, proceed with caution!
      if (!mini_stricmp(state_install_directory,"$PROGRAMFILES\\Winamp"))
      {
        HKEY hKey;
		    if ( RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Winamp",0,KEY_READ,&hKey) == ERROR_SUCCESS)
		    {
			    int l = sizeof(buf);
			    int t=REG_SZ;
			    if (RegQueryValueEx(hKey,"UninstallString",NULL,&t,buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
			    {
				    char *p=buf+mini_strlen(buf);
				    while (p >= buf && *p != '\\') p--;
				    if ( p >= buf)
				    {
					    char *i=buf;
					    *p=0;
					    while (*i == ' ' || *i == '\"') i++;
					    mini_strcpy(state_install_directory,i);
              st=1;
				    }
			    }
			    RegCloseKey(hKey);
		    }
      }
#endif

      if (!st && !process_string(buf,state_install_directory,NULL)) {
        _tcscpy(state_install_directory,buf);
	  }
    }

	{
		INT32 args[] = { (INT32)head->name };
		GETRESOURCE2(tmpbuf, JAVAWS_MESSAGE_SETUP, args);
		wsprintf(g_caption,"%s Setup",head->name);
	}
#ifdef NSIS_CONFIG_LOG
    if (head->silent_install==2) 
    {
      wsprintf(g_log_file,"%s%sinstall.log",state_install_directory,state_install_directory[mini_strlen(state_install_directory)-1]=='\\'?"":"\\");    
      log_dolog=1;
    }
#endif

    if (!head->silent_install && autoinstall != 1) {
      ret = DialogBox(g_hInstance,MAKEINTRESOURCE(IDD_INST),
		       GetDesktopWindow(),DialogProc);
      /* if ret was 3 we only showed the license agreement, */
      /* so continue as if we are doing an autoinstall and  */
      /* run the install thread without a UI.               */
      if (ret != 3) return ret;
    }
    m_section[0].default_state=0x80000000;
    return install_thread(NULL);
  }
}
Ejemplo n.º 2
0
  int readCpuCounters(SFLHost_cpu_counters *cpu) {
    int gotData = NO;
	uint32_t i = 0;
	PPDH_RAW_COUNTER_ITEM thread = NULL, processor = NULL;
	DWORD dwRet,cbData = sizeof(DWORD);
	HKEY hkey;

	cpu->cpu_user = (uint32_t)readSingleCounter("\\Processor(_Total)\\% User Time");
	cpu->cpu_system = (uint32_t)readSingleCounter("\\Processor(_Total)\\% Privileged Time");
	cpu->cpu_idle = (uint32_t)readSingleCounter("\\Processor(_Total)\\% Idle Time");
	cpu->cpu_intr = (uint32_t)readSingleCounter("\\Processor(_Total)\\% Interrupt Time");
	cpu->interrupts = (uint32_t)readSingleCounter("\\Processor(_Total)\\Interrupts/sec");
	cpu->contexts = (uint32_t)readSingleCounter("\\System\\Context Switches/sec");
	cpu->uptime = (uint32_t)readFormattedCounter("\\System\\System Up Time");
	cpu->cpu_num = readMultiCounter("\\Processor(*)\\% Processor Time",&processor);

	// see http://support.microsoft.com/kb/888282 for ways to determine CPU speed
	dwRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
						"hardware\\description\\system\\centralprocessor\\0",
						0,
						KEY_QUERY_VALUE,
						&hkey);

	if(dwRet == ERROR_SUCCESS) {
		dwRet = RegQueryValueEx( hkey,
			                     "~MHz",
			                     NULL,
								 NULL,
			                     (LPBYTE) &cpu->cpu_speed,
			                     &cbData );
		if(dwRet != ERROR_SUCCESS) cpu->cpu_speed = -1;
	}

	cpu->proc_total = readMultiCounter("\\Thread(*)\\Thread State",&thread);
	cpu->proc_run = 0;
	if(thread){
		for(i = 0; i < cpu->proc_total; i++){
			if(thread[i].RawValue.FirstValue == 2 && strncmp("Idle",thread[i].szName,4) != 0){
				cpu->proc_run++;
			}
		}
	}

	//These have no obvious Windows equivalent
	cpu->cpu_sintr = UNKNOWN_COUNTER;
	cpu->cpu_nice = UNKNOWN_COUNTER;
	cpu->cpu_wio = UNKNOWN_COUNTER;
	cpu->load_one = UNKNOWN_FLOAT;
	cpu->load_five = UNKNOWN_FLOAT;
	cpu->load_fifteen = UNKNOWN_FLOAT;
	
	MyLog(LOG_INFO,"readCpuCounters:\n\tuptime:\t\t%lus\n\tcpu_num:\t%d\n\tcpu speed:\t%d MHz\n\tuser: %lu\n\tsystem: %lu\n\tidle: %lu\n\tirq: %lu\n\tthreads_total: %lu\n\tthreads_running: %lu\n",
			cpu->uptime,cpu->cpu_num,cpu->cpu_speed,cpu->cpu_user,cpu->cpu_system,cpu->cpu_idle,cpu->cpu_intr,cpu->proc_total,cpu->proc_run);

	if(thread){ 
		free(thread);
	}
	if(processor){
		free(processor);
	}

	gotData = YES;

    return gotData;
  }
Ejemplo n.º 3
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, 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, 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 */
}
Ejemplo n.º 4
0
void CPythonEngine::init()
{
    if (!initialised)
    {
        initialised = 1;

        /* Initialize the Python interpreter.*/
        Py_Initialize();
        PyEval_InitThreads();


        PyGILState_STATE gstate;
        gstate = PyGILState_Ensure();

        /* Initialize TA Python env. */
        Py_InitModule("tibiaauto", Methods_tibiaauto);
        Py_InitModule("tareader", Methods_tareader);
        Py_InitModule("tasender", Methods_tasender);
        Py_InitModule("tamap", Methods_tamap);
        Py_InitModule("taregexp", Methods_taregexp);
        Py_InitModule("taalice", Methods_taalice);
        Py_InitModule("taitem", Methods_taitem);
        Py_InitModule("tacrstat", Methods_tacrstat);
        Py_InitModule("takernel", Methods_takernel);
        Py_InitModule("tapacket", Methods_tapacket);
        PyRun_SimpleString("import tibiaauto");
        PyRun_SimpleString("import tareader");
        PyRun_SimpleString("import tasender");
        PyRun_SimpleString("import tamap");
        PyRun_SimpleString("import taregexp");
        PyRun_SimpleString("import taalice");
        PyRun_SimpleString("import taitem");
        PyRun_SimpleString("import tacrstat");
        PyRun_SimpleString("import takernel");
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("import time");


        char installPath[1024];
        unsigned long installPathLen = 1023;
        installPath[0] = '\0';
        HKEY hkey = NULL;
        if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Tibia Auto\\", 0, KEY_READ, &hkey))
        {
            RegQueryValueEx(hkey, TEXT("Install_Dir"), NULL, NULL, (unsigned char *)installPath, &installPathLen);
            RegCloseKey(hkey);
        }
        if (!strlen(installPath))
        {
            ::MessageBox(0, "ERROR! Unable to read TA install directory! Please reinstall!", "ERROR", 0);
            PostQuitMessage(-1);
            return;
        }

        char pathBuf[2048];
        sprintf(pathBuf, "%s\\tascripts\\tautil.py", installPath);

        // load tautil.py
        FILE *f = fopen(pathBuf, "r");
        if (f)
        {
            fseek(f, 0, SEEK_END);
            int fileSize = ftell(f);
            fseek(f, 0, SEEK_SET);
            char *fileBuf = (char *)malloc(fileSize + 1);
            memset(fileBuf, 0, fileSize + 1);
            fread(fileBuf, 1, fileSize, f);

            int ret = PyRun_SimpleString(fileBuf);
            if (ret == -1)
                AfxMessageBox("Loading tautil.py script failed!");
            fclose(f);
        }
        else
        {
            AfxMessageBox("Unable to find tascripts\\tautil.py!");
        }

        PyGILState_Release(gstate);

        InitializeCriticalSection(&ScriptEngineCriticalSection);


        // now load all scripts from 'tascripts' subdirectory
        sprintf(pathBuf, "%s\\tascripts\\*.py", installPath);
        WIN32_FIND_DATA findFileData;
        HANDLE hFind = FindFirstFile(pathBuf, &findFileData);
        if (hFind != INVALID_HANDLE_VALUE)
        {
            char buf[1024];

            do
            {
                snprintf(buf, 1023, "%s\\tascripts\\%s", installPath, findFileData.cFileName);
                // tautil.py will be loaded in a special way
                if (!strstr(buf, "tascripts\\tautil.py"))
                    loadScript(buf);
            }
            while (FindNextFile(hFind, &findFileData));
            FindClose(hFind);
        }
    }
}
Ejemplo n.º 5
0
int smpd_get_all_smpd_data(smpd_data_t **data)
{
#ifdef HAVE_WINDOWS_H
    HKEY tkey;
    DWORD result;
    LONG enum_result;
    char name[SMPD_MAX_NAME_LENGTH], value[SMPD_MAX_VALUE_LENGTH];
    DWORD name_length, value_length, index;
    smpd_data_t *list, *item;
    char err_msg[512];

    smpd_enter_fn(FCNAME);

    if (data == NULL)
    {
	smpd_exit_fn(FCNAME);
	return SMPD_FAIL;
    }

    result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, SMPD_REGISTRY_KEY, 0, KEY_READ, &tkey);
    if (result != ERROR_SUCCESS)
    {
	/* No key therefore no settings */
	/* No access to the key, therefore no soup for you */
	*data = NULL;
	smpd_exit_fn(FCNAME);
	return SMPD_SUCCESS;
    }

    list = NULL;
    index = 0;
    name_length = SMPD_MAX_NAME_LENGTH;
    value_length = SMPD_MAX_VALUE_LENGTH;
    enum_result = RegEnumValue(tkey, index, name, &name_length, NULL, NULL, (LPBYTE)value, &value_length);
    while (enum_result == ERROR_SUCCESS)
    {
	item = (smpd_data_t*)MPIU_Malloc(sizeof(smpd_data_t));
	if (item == NULL)
	{
	    *data = NULL;
	    result = RegCloseKey(tkey);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	memcpy(item->name, name, SMPD_MAX_NAME_LENGTH);
	memcpy(item->value, value, SMPD_MAX_VALUE_LENGTH);
	item->next = list;
	list = item;
	index++;
	name_length = SMPD_MAX_NAME_LENGTH;
	value_length = SMPD_MAX_VALUE_LENGTH;
	enum_result = RegEnumValue(tkey, index, name, &name_length, NULL, NULL, (LPBYTE)value, &value_length);
    }

    result = RegCloseKey(tkey);
    if (result != ERROR_SUCCESS)
    {
	smpd_translate_win_error(result, err_msg, 512, "Unable to close the HKEY_LOCAL_MACHINE\\" SMPD_REGISTRY_KEY " registry key, error %d: ", result);
	smpd_err_printf("%s\n", err_msg);
	smpd_exit_fn(FCNAME);
	return SMPD_FAIL;
    }

    *data = list;
    smpd_exit_fn(FCNAME);
    return SMPD_SUCCESS;
#else
    smpd_enter_fn(FCNAME);
    if (data == NULL)
    {
	smpd_exit_fn(FCNAME);
	return SMPD_FAIL;
    }
    *data = NULL;
    smpd_exit_fn(FCNAME);
    return SMPD_FAIL;
#endif
}
Ejemplo n.º 6
0
int EDT_UtilReg_LogPermissions(HKEY hRootKey, const wchar_t *wzKey)
{
	int iReturnCode = EDT_OK;
	int err = ERROR_SUCCESS;

	HKEY hRegKey;
	LOG_ENTER();
	LOG_TIME(L"registry key (%ls\\%ls) --> \n",hRootKey==HKEY_CURRENT_USER?L"HKCU":L"HKLM",wzKey);

	if(ERROR_SUCCESS != (err = RegOpenKeyEx(hRootKey, wzKey, 0L, KEY_READ , &hRegKey)))
	{
		if(err != ERROR_FILE_NOT_FOUND)
		{
			LOG_ERRORCODE(L"RegOpenKeyEx failed",err);
			return EDT_ERR_REGISTRY_READ_FAILED;
		}
		else
		{
			LOG_EXIT(L"NOT FOUND\n");
			return EDT_ERR_REGISTRY_NOT_FOUND;
		}
	}
	PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
	DWORD lcbSecurityDescriptor = 0;

	if(ERROR_INSUFFICIENT_BUFFER == (err = RegGetKeySecurity(hRegKey, DACL_SECURITY_INFORMATION, pSecurityDescriptor, &lcbSecurityDescriptor)))
	{     
		pSecurityDescriptor = (PSECURITY_DESCRIPTOR)malloc(lcbSecurityDescriptor);

		if(ERROR_SUCCESS != (err = RegGetKeySecurity(hRegKey, DACL_SECURITY_INFORMATION, pSecurityDescriptor, &lcbSecurityDescriptor)))
		{
			LOG_ERRORCODE(L"RegQueryValueEx failed",err);
			iReturnCode = EDT_ERR_REGISTRY_READ_FAILED;
		}
		else
		{
			BOOL bDaclPresent = FALSE;
			BOOL bDaclDefaulted = FALSE;
			PACL pDacl = NULL;

			GetSecurityDescriptorDacl(pSecurityDescriptor, &bDaclPresent, &pDacl, &bDaclDefaulted);
			if(bDaclPresent == TRUE)
			{
				if(pDacl == NULL)
				{
					LOG(L"A NULL discretionary access control list (DACL) found \nA NULL DACL implicitly allows all access to an object.\n");
				}
				else
				{
					LOG(L"A discretionary access control list (DACL) was found with Length = %d\n",pDacl->AclSize);
					LOG(L"Number of Access Control Elements (ACE's): %d\n",pDacl->AceCount);
					registryLogAces(pDacl);
				}
			}
			else
			{
				LOG(L"No discretionary access control list (DACL) found \n");
			}

			LPTSTR StringSecurityDescriptor;
			ULONG StringSecurityDescriptorLen;

			ConvertSecurityDescriptorToStringSecurityDescriptor(pSecurityDescriptor,SDDL_REVISION_1,DACL_SECURITY_INFORMATION,
				&StringSecurityDescriptor,&StringSecurityDescriptorLen);


			LOG(L"%s\n",(const wchar_t*)StringSecurityDescriptor);
			//parse info see http://msdn.microsoft.com/en-us/library/aa379570%28v=vs.85%29.aspx

			LocalFree(StringSecurityDescriptor);

		}
		free(pSecurityDescriptor);
	}
	else
	{
		LOG_ERRORCODE(L"RegGetKeySecurity failed",err);
	}

	if(ERROR_SUCCESS != (err = RegCloseKey(hRegKey)))
	{
		LOG_ERRORCODE(L"RegCloseKey failed",err);
	}

	LOG_EXIT(iReturnCode);
	return iReturnCode;
} 
Ejemplo n.º 7
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_win_getversion                                               *
 *                                                                            *
 * Purpose: get Windows version information                                   *
 *                                                                            *
 ******************************************************************************/
const OSVERSIONINFOEX		*zbx_win_getversion()
{
#	define ZBX_REGKEY_VERSION		"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
#	define ZBX_REGVALUE_CURRENTVERSION	"CurrentVersion"
#	define ZBX_REGVALUE_CURRENTBUILDNUMBER	"CurrentBuildNumber"
#	define ZBX_REGVALUE_CSDVERSION		"CSDVersion"

#	define ZBX_REGKEY_PRODUCT		"System\\CurrentControlSet\\Control\\ProductOptions"
#	define ZBX_REGVALUE_PRODUCTTYPE		"ProductType"

	static OSVERSIONINFOEX	vi = {sizeof(OSVERSIONINFOEX)};

	OSVERSIONINFOEX		*pvi = NULL;
	HKEY			h_key_registry = NULL;
	wchar_t			*key_value = NULL, *ptr;

	if (0 != vi.dwMajorVersion)
		return &vi;

	if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(ZBX_REGKEY_VERSION), 0, KEY_READ, &h_key_registry))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "failed to open registry key '%s'", ZBX_REGKEY_VERSION);
		goto out;
	}

	if (NULL == (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_CURRENTVERSION))))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "failed to read registry value '%s'", ZBX_REGVALUE_CURRENTVERSION);
		goto out;
	}

	if (NULL != (ptr = wcschr(key_value, TEXT('.'))))
	{
		*ptr++ = L'\0';
		vi.dwMinorVersion = _wtoi(ptr);
	}

	vi.dwMajorVersion = _wtoi(key_value);

	zbx_free(key_value);

	if (6 > vi.dwMajorVersion || 2 > vi.dwMinorVersion)
	{
		GetVersionEx((OSVERSIONINFO *)&vi);
	}
	else
	{
		if (NULL != (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_CSDVERSION))))
		{
			wcscpy_s(vi.szCSDVersion, sizeof(vi.szCSDVersion) / sizeof(*vi.szCSDVersion), key_value);

			zbx_free(key_value);
		}

		if (NULL == (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_CURRENTBUILDNUMBER))))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "failed to read registry value '%s'",
					ZBX_REGVALUE_CURRENTBUILDNUMBER);
			goto out;
		}

		vi.dwBuildNumber = _wtoi(key_value);
		zbx_free(key_value);

		RegCloseKey(h_key_registry);
		h_key_registry = NULL;

		if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(ZBX_REGKEY_PRODUCT), 0, KEY_READ,
				&h_key_registry))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "failed to open registry key '%s'", ZBX_REGKEY_PRODUCT);
			goto out;
		}

		if (NULL == (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_PRODUCTTYPE))))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "failed to read registry value '%s'", ZBX_REGVALUE_PRODUCTTYPE);
			goto out;
		}

		if (0 == wcscmp(key_value, L"WinNT"))
			vi.wProductType = 1;
		else if (0 == wcscmp(key_value, L"LenmanNT"))
			vi.wProductType = 2;
		else if (0 == wcscmp(key_value, L"ServerNT"))
			vi.wProductType = 3;

		zbx_free(key_value);

		vi.dwPlatformId = VER_PLATFORM_WIN32_NT;
	}

	pvi = &vi;
out:
	if (NULL != h_key_registry)
		RegCloseKey(h_key_registry);

	return pvi;
}
Ejemplo n.º 8
0
Archivo: tun.c Proyecto: Churro/iodine
/*
 * 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>

#ifndef IFCONFIGPATH
#define IFCONFIGPATH "PATH=/sbin:/bin "
#endif

#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 <netinet/in.h>
#include <arpa/inet.h>

#define TUN_MAX_TRY 50
#endif

#include "tun.h"
#include "common.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;
#ifdef ANDROID
	char *tunnel = "/dev/tun";
#else
	char *tunnel = "/dev/net/tun";
#endif

	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);
}
static String platformGetFontPath(const String& faceName) {
	static const LPWSTR fontRegistryPath = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
	HKEY hKey;
	LONG result;
	std::wstring wsFaceName(faceName.begin(), faceName.end());

	// Open Windows font registry key
	result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, fontRegistryPath, 0, KEY_READ, &hKey);
	if (result != ERROR_SUCCESS) {
		throw std::runtime_error("Cant open registry!");
	}

	DWORD maxValueNameSize, maxValueDataSize;
	result = RegQueryInfoKey(hKey, 0, 0, 0, 0, 0, 0, 0, &maxValueNameSize, &maxValueDataSize, 0, 0);

	if (result != ERROR_SUCCESS) {
		throw std::runtime_error("Cant query registry!");
	}

	DWORD valueIndex = 0;
	LPWSTR valueName = new WCHAR[maxValueNameSize];
	LPBYTE valueData = new BYTE[maxValueDataSize];
	DWORD valueNameSize, valueDataSize, valueType;
	std::wstring wsFontFile;

	// Look for a matching font name
	do {
		wsFontFile.clear();
		valueDataSize = maxValueDataSize;
		valueNameSize = maxValueNameSize;

		result = RegEnumValue(hKey, valueIndex, valueName, &valueNameSize, 0, &valueType, valueData, &valueDataSize);

		valueIndex++;

		if (result != ERROR_SUCCESS || valueType != REG_SZ) {
			continue;
		}

		std::wstring wsValueName(valueName, valueNameSize);

		// Found a match
		if (_wcsnicmp(wsFaceName.c_str(), wsValueName.c_str(), wsFaceName.size()) == 0) {
			wsFontFile.assign((LPWSTR)valueData, valueDataSize);
			break;
		}
	} while (result != ERROR_NO_MORE_ITEMS);

	delete[] valueName;
	delete[] valueData;

	RegCloseKey(hKey);

	if (wsFontFile.empty()) {
		throw std::runtime_error("Did not find matching font!");
	}

	// Build full font file path
	WCHAR winDir[MAX_PATH];
	GetWindowsDirectory(winDir, MAX_PATH);

	std::wstringstream ss;
	ss << winDir << "\\Fonts\\" << wsFontFile;
	wsFontFile = ss.str();

	return String(wsFontFile.begin(), wsFontFile.end());
}
Ejemplo n.º 10
0
HRESULT TffdshowVideoInputPin::CheckMediaType(const CMediaType* mt)
{
    if (mt->majortype != MEDIATYPE_Video && !(mt->majortype == MEDIATYPE_DVD_ENCRYPTED_PACK && supdvddec)) {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    if (mt->subtype == MEDIASUBTYPE_DVD_SUBPICTURE) {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    BITMAPINFOHEADER *hdr = NULL, hdr0;

    if (mt->formattype == FORMAT_VideoInfo) {
        VIDEOINFOHEADER *vih = (VIDEOINFOHEADER*)mt->pbFormat;
        hdr = &vih->bmiHeader;
        fixMPEGinAVI(hdr->biCompression);
    } else if (mt->formattype == FORMAT_VideoInfo2) {
        VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2*)mt->pbFormat;
        hdr = &vih2->bmiHeader;
        fixMPEGinAVI(hdr->biCompression);
    } else if (mt->formattype == FORMAT_MPEGVideo) {
        MPEG1VIDEOINFO *mpeg1info = (MPEG1VIDEOINFO*)mt->pbFormat;
        hdr = &(hdr0 = mpeg1info->hdr.bmiHeader);
        hdr->biCompression = FOURCC_MPG1;
    } else if (mt->formattype == FORMAT_MPEG2Video) {
        MPEG2VIDEOINFO *mpeg2info = (MPEG2VIDEOINFO*)mt->pbFormat;
        hdr = &(hdr0 = mpeg2info->hdr.bmiHeader);
        if (hdr->biCompression == 0 || hdr->biCompression == 0x0038002d) {
            if (mt->subtype == MEDIASUBTYPE_H264_TRANSPORT) {
                hdr->biCompression = FOURCC_H264;
            } else if (mt->subtype == MEDIASUBTYPE_AVC1 || mt->subtype == MEDIASUBTYPE_avc1 || mt->subtype == MEDIASUBTYPE_H264 || mt->subtype == MEDIASUBTYPE_h264 || mt->subtype == MEDIASUBTYPE_CCV1) {
                hdr->biCompression = FOURCC_H264;
            } else {
                hdr->biCompression = FOURCC_MPG2;
            }
        }
    } else if (mt->formattype == FORMAT_TheoraIll) {
        sTheoraFormatBlock *oggFormat = (sTheoraFormatBlock*)mt->pbFormat;
        hdr = &hdr0;
        hdr->biWidth = oggFormat->width;
        hdr->biHeight = oggFormat->height;
        hdr->biCompression = FOURCC_THEO;
    } else if (mt->formattype == FORMAT_RLTheora) {
        hdr = &hdr0;
        hdr->biCompression = FOURCC_THEO;
    } else {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    char_t pomS[60];
    DPRINTF(_l("TffdshowVideoInputPin::CheckMediaType: %s, %i, %i"), fourcc2str(hdr2fourcc(hdr, &mt->subtype), pomS, 60), hdr->biWidth, hdr->biHeight);

    /* Information : WMP 11 and Media Center under Vista do not check for uncompressed format anymore, so no way to get
       ffdshow raw video decoder for postprocessing on uncompressed.
       So instead of saying "Media Type not supported", we says it is but only if there is an existing filter that can
       take this format in charge, and then ffdshow will be plugged after this codec (plug is done by TffdshowDecVideo::ConnectCompatibleFilter). */
    int res = getVideoCodecId(hdr, &mt->subtype, NULL);

    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);
    ffstring exeFilename(fv->getExefilename());
    exeFilename.ConvertToLowerCase();

    if (res == 0 && pCompatibleFilter == NULL &&
            fv->deci->getParam2(IDFF_alternateUncompressed) == 1 && // Enable WMP11 postprocessing
            fv->deci->getParam2(IDFF_rawv) != 0 && // Raw video not on disabled
            (exeFilename == _l("wmplayer.exe") ||
             exeFilename == _l("ehshell.exe"))) { // Only WMP and Media Center are concerned
        bool doPostProcessing = false;
        if (osvi.dwMajorVersion > 5) { // OS >= VISTA
            doPostProcessing = true;
        } else if (osvi.dwMajorVersion == 5 // If OS=XP, check version of WMP
                   && exeFilename == _l("ehshell.exe")) { // But only for Media Center
            // Read WMP version from the aRegistry
            HKEY hKey = NULL;
            LONG regErr;

            // Read WMP version from the following registry key
            regErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _l("SOFTWARE\\Microsoft\\MediaPlayer\\Setup\\Installed Versions"), 0, KEY_READ, &hKey);
            if (regErr != ERROR_SUCCESS) {
                return res == AV_CODEC_ID_NONE ? VFW_E_TYPE_NOT_ACCEPTED : S_OK;
            }

            DWORD dwType;
            BYTE buf[4096] = { '\0' };   // make it big enough for any kind of values
            DWORD dwSize = sizeof(buf);
            regErr = RegQueryValueEx(hKey, _T("wmplayer.exe"), 0, &dwType, buf, &dwSize);

            if (hKey) {
                RegCloseKey(hKey);
            }

            if (regErr != ERROR_SUCCESS || dwType != REG_BINARY) {
                return res == AV_CODEC_ID_NONE ? VFW_E_TYPE_NOT_ACCEPTED : S_OK;
            }

            if (buf[2] >= 0x0b) { // Third byte is the major version number
                doPostProcessing = true;
            }
        }


        if (doPostProcessing) {
            DPRINTF(_l("TffdshowVideoInputPin::CheckMediaType: input format disabled or not supported. Trying to maintain in the graph..."));
            IFilterMapper2 *pMapper = NULL;
            IEnumMoniker *pEnum = NULL;

            HRESULT hr = CoCreateInstance(CLSID_FilterMapper2,
                                          NULL, CLSCTX_INPROC, IID_IFilterMapper2,
                                          (void **) &pMapper);

            if (FAILED(hr)) {
                // Error handling omitted for clarity.
            }

            GUID arrayInTypes[2];
            arrayInTypes[0] = mt->majortype;//MEDIATYPE_Video;
            arrayInTypes[1] = mt->subtype;//MEDIASUBTYPE_dvsd;

            hr = pMapper->EnumMatchingFilters(
                     &pEnum,
                     0,                  // Reserved.
                     TRUE,               // Use exact match?
                     MERIT_DO_NOT_USE + 1, // Minimum merit.
                     TRUE,               // At least one input pin?
                     1,                  // Number of major type/subtype pairs for input.
                     arrayInTypes,       // Array of major type/subtype pairs for input.
                     NULL,               // Input medium.
                     NULL,               // Input pin category.
                     FALSE,              // Must be a renderer?
                     TRUE,               // At least one output pin?
                     0,                  // Number of major type/subtype pairs for output.
                     NULL,               // Array of major type/subtype pairs for output.
                     NULL,               // Output medium.
                     NULL);              // Output pin category.

            // Enumerate the monikers.
            IMoniker *pMoniker;
            ULONG cFetched;

            while (pEnum->Next(1, &pMoniker, &cFetched) == S_OK) {
                IPropertyBag *pPropBag = NULL;
                hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
                                             (void **)&pPropBag);

                if (SUCCEEDED(hr)) {
                    // To retrieve the friendly name of the filter, do the following:
                    VARIANT varName;
                    VariantInit(&varName);
                    hr = pPropBag->Read(L"FriendlyName", &varName, 0);
                    if (SUCCEEDED(hr)) {
                        if (varName.pbstrVal == NULL || _strnicmp(FFDSHOW_NAME_L, varName.bstrVal, 22) != 0) {
                            // Display the name in your UI somehow.
                            DPRINTF(_l("TffdshowVideoInputPin::CheckMediaType: compatible filter found (%s)"), varName.pbstrVal);
                            hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pCompatibleFilter);
                        }
                    }

                    // Now add the filter to the graph. Remember to release pFilter later.
                    IFilterGraph *pGraph = NULL;
                    fv->deci->getGraph(&pGraph);

                    IGraphBuilder *pGraphBuilder = NULL;
                    hr = pGraph->QueryInterface(IID_IGraphBuilder, (void **)&pGraphBuilder);
                    if (hr == S_OK) {
                        pGraphBuilder->AddFilter(pCompatibleFilter, varName.bstrVal);
                    } else {
                        pCompatibleFilter->Release();
                        pCompatibleFilter = NULL;
                    }

                    // Clean up.
                    VariantClear(&varName);
                    pGraphBuilder->Release();
                    pPropBag->Release();
                }
                pMoniker->Release();
                if (pCompatibleFilter != NULL) {
                    break;
                }
            }

            // Clean up.
            pMapper->Release();
            pEnum->Release();
        }
    }
    if (pCompatibleFilter != NULL) {
        return S_OK;
    }
    return res == AV_CODEC_ID_NONE ? VFW_E_TYPE_NOT_ACCEPTED : S_OK;
}
Ejemplo n.º 11
0
LRESULT decompress_begin(CODEC * codec, BITMAPINFO * lpbiInput, BITMAPINFO * lpbiOutput)
{
	BITMAPINFOHEADER * inhdr = &lpbiInput->bmiHeader;
	xvid_gbl_init_t init;
	xvid_gbl_info_t info;
	xvid_dec_create_t create;
	HKEY hKey;

	if (init_dll(codec) != 0) return ICERR_ERROR;

	memset(&init, 0, sizeof(init));
	init.version = XVID_VERSION;
	init.cpu_flags = codec->config.cpu;
	init.debug = codec->config.debug;
	codec->xvid_global_func(0, XVID_GBL_INIT, &init, NULL);

	memset(&info, 0, sizeof(info));
	info.version = XVID_VERSION;
	codec->xvid_global_func(0, XVID_GBL_INFO, &info, NULL);

	memset(&create, 0, sizeof(create));
	create.version = XVID_VERSION;
	create.width = lpbiInput->bmiHeader.biWidth;
	create.height = lpbiInput->bmiHeader.biHeight;
	create.fourcc = inhdr->biCompression;

    /* Decoder threads */
    if (codec->config.cpu & XVID_CPU_FORCE)
		create.num_threads = codec->config.num_threads;
	else 
        create.num_threads = info.num_threads; /* Autodetect */

	switch(codec->xvid_decore_func(0, XVID_DEC_CREATE, &create, NULL)) 
	{
	case XVID_ERR_FAIL :
		return ICERR_ERROR;

	case XVID_ERR_MEMORY :
		return ICERR_MEMORY;

	case XVID_ERR_FORMAT :
		return ICERR_BADFORMAT;

	case XVID_ERR_VERSION :
		return ICERR_UNSUPPORTED;
	}

	codec->dhandle = create.handle;

	RegOpenKeyEx(XVID_REG_KEY, XVID_REG_PARENT "\\" XVID_REG_CHILD, 0, KEY_READ, &hKey);

	REG_GET_N("Brightness", pp_brightness, 0);
	REG_GET_N("Deblock_Y",  pp_dy, 0);
	REG_GET_N("Deblock_UV", pp_duv, 0);
	REG_GET_N("Dering_Y",  pp_dry, 0);
	REG_GET_N("Dering_UV", pp_druv, 0);
	REG_GET_N("FilmEffect", pp_fe, 0);

	RegCloseKey(hKey);

	return ICERR_OK;
}
Ejemplo n.º 12
0
static char *DigiCrypt_GetFirstAllowedCSPNameNew(void)
{
  char *psRes = NULL;
  HKEY  hKey = NULL;
  LONG  lRet=0;
  DWORD dwIndex = 0;
  BOOL  fRes;
  char sProvName[dSTRING_ITEM_LEN+1];
  char sKeyNameBuf[dSTRING_ITEM_LEN+1];
  HCRYPTPROV hProvide = 0;
  DWORD dwBufLen;
  FILETIME oTime;
  //char buff[200];
  BYTE pbData[dNAME_ITEM_LEN+1];
  DWORD cbData=dNAME_ITEM_LEN+1;
  //
  DWORD dwProvType;

  strncpy(sKeyNameBuf, psData_CSP_Path, sizeof(sKeyNameBuf));
  lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,sKeyNameBuf,0, KEY_READ, &hKey);

  while (lRet == ERROR_SUCCESS)  {
    dwBufLen = dSTRING_ITEM_LEN;
    lRet = RegEnumKeyEx(hKey,dwIndex,sProvName,&dwBufLen,NULL,NULL,0,&oTime);
    if (lRet == ERROR_SUCCESS) {
      if (lstrcmp(sProvName,psData_Ignore_CSP_Name) != 0) {
	dwProvType = DigiCrypt_FindContext_GetCSPType(sProvName);
	LOG("CSP %s",sProvName);
	//printf("%s :",sProvName);
	if ((lstrcmp(sProvName,psData_Extra_CSP_Name) != 0) && (lstrcmp(sProvName,"Belgium Identity Card CSP")!=0)) {
        //fRes = OpenProvider(&hProvide, sProvName, CRYPT_SILENT);
	  fRes = CryptAcquireContext(&hProvide,NULL,sProvName,dwProvType, CRYPT_SILENT);
	  fRes=CryptGetProvParam(hProvide, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
	  //	  printf("X\n");
	} else {
	  //fRes = OpenProvider(&hProvide, sProvName, CRYPT_VERIFYCONTEXT);
	  //fRes = CryptAcquireContext(&hProvide,"SetCARDKeyContainer",sProvName,dwProvType, CRYPT_SILENT);
	  fRes = CryptAcquireContext(&hProvide,NULL,sProvName,dwProvType, CRYPT_VERIFYCONTEXT);
	  if (fRes == TRUE) {
	    //the extra csp might give wrong answer. We should ask from provider, why.
	    //The following is the work-around -- try to lookup key container from the card.
	    //if the result is negative this is a not the csp what is needed.
     	    fRes=CryptGetProvParam(hProvide, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
	    if (fRes == TRUE)
	      fRes=CryptAcquireContext(&hProvide,(char*)pbData,sProvName,dwProvType, CRYPT_SILENT);
	  }
	}
	//printf("fRes: %x\n",GetLastError());
	if (fRes == TRUE) { // && dwProvType == 2) 
	  //  printf("OK %d %s\n",cbData, pbData);
	  //set global values
	  LOG("CSP %s accepted",sProvName);
	  //is it hardware token?
	  cbData=dNAME_ITEM_LEN+1;
	  if (CryptGetProvParam(hProvide, PP_IMPTYPE, pbData, &cbData, 0)) {
	    //printf("implementat: %d\n",pbData[0]);
	    if((pbData[0] & 1))  // hardware token
	      {
		strncpy(oG_sCSPName, sProvName, sizeof(oG_sCSPName));
		//CryptReleaseContext(hProvide, 0);
		psRes = oG_sCSPName;
		break;
	      }
	  }
	}
      }
    }
    //hProvide = 0;
    CryptReleaseContext(hProvide, 0);
    dwIndex++;
  }
  if (hKey != NULL)
    RegCloseKey(hKey);
  return(psRes);
}
Ejemplo n.º 13
0
BOOL EnumImageHijack( AUTORUN_CALLBACK pfnCallback, LPVOID lpParam )
{
	CHKey hKey;
	DWORD dwResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, 
						"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options",
						0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, (PHKEY)&hKey );
	if(ERROR_SUCCESS != dwResult ) {
		SetLastError( dwResult );
		return FALSE;
	}

	//查询子键数量
	DWORD cSubKey = 0;
	dwResult = RegQueryInfoKey( hKey.GetHandle(), NULL, NULL, 0, &cSubKey, NULL,NULL, NULL, NULL, NULL, NULL, NULL );
	if( ERROR_SUCCESS != dwResult )	{
		SetLastError( dwResult );
		return FALSE;
	}

	LPCTSTR lpszSystemDir = getenv( "SystemRoot" );
	if( lpszSystemDir == NULL ) 
		return FALSE;

	for( DWORD i=0; i < cSubKey; i++ ) {

		AUTORUN_ITEM Item = {0};
		dwResult = RegEnumKey( hKey.GetHandle(), i, Item.Name, sizeof( Item.Name ) );
		if( ERROR_SUCCESS != dwResult ) {
			SetLastError( dwResult );
			continue;
		}
		
		//打开子键
		CHKey hSubKey ;
		dwResult = RegOpenKeyEx( hKey.GetHandle(), Item.Name, 0, KEY_QUERY_VALUE, (PHKEY)&hSubKey );
		if( ERROR_SUCCESS != dwResult ){
			SetLastError( dwResult );
			continue;
		}

		char Buffer[512] = {0};
		DWORD cbSize = sizeof( Buffer );
		dwResult = RegQueryValueEx( hSubKey.GetHandle(), "Debugger", NULL, NULL, (PUCHAR)Buffer, &cbSize );
		if( dwResult != ERROR_SUCCESS ) {
			SetLastError( dwResult );
			continue;
		}

		strncpy( Item.ImagePath, lpszSystemDir, sizeof( Item.ImagePath ) - 1 );
		PathAddBackslash( Item.ImagePath );
		strncat( Item.ImagePath, "System32\\", sizeof( Item.ImagePath ) - strlen( Item.ImagePath ) - 1 );
		strncat( Item.ImagePath, Buffer, sizeof( Item.ImagePath ) - strlen( Item.ImagePath ) - 1 );

		//去掉删除
		PathRemoveArgs( Item.ImagePath );
		PathAddExtension( Item.ImagePath, ".exe" );

		if( !pfnCallback( AUTORUN_IMAGE_HIJACK, &Item, lpParam ) ) {
			SetLastError( ERROR_CANCELLED );
			return FALSE;
		}	
	}

	return TRUE;
}
Ejemplo n.º 14
0
/*----------------------------------------------------------------------
 Get info about JRE from registry.
----------------------------------------------------------------------*/
static int findJreInfoFromRegistry(char *path, char *args) {
	INT	   i;
	HKEY   hKey;				/* Key handle of NetShell */
	CHAR   ValueName[MAX_PATH]; /* Name of value. */
	DWORD  cbValueName;			/* Size of value name. */
	DWORD  dwType;     			/* Type of data. */
	CHAR   bData[MAX_PATH];   	/* Data buffer. */
	DWORD  cbData;  		  	/* Size of data buffer. */
	DWORD  retCode;
	CHAR   *Param;
	BOOL   found = FALSE;		/* We have found info in the registry */

	/* Open the key for jre and get info about it. */
	retCode = RegOpenKeyEx(hKeyRoot, SubKey, 0, KEY_EXECUTE, &hKey);
	if (retCode != ERROR_SUCCESS) {
		DPRINT(("stub: RegOpenKeyEx error for hKey = %d\n",
				retCode));
		return FALSE;
	}
	for (i = 0; retCode == ERROR_SUCCESS; i++) {
		bData[0] = '\0';
		ValueName[0] = '\0';
		cbData = MAX_PATH;
		cbValueName = MAX_PATH;
		/* Enumerate the key values. */
		retCode = RegEnumValue(hKey, i, ValueName, &cbValueName,
								NULL, &dwType, bData, &cbData);
		if (retCode != ERROR_SUCCESS) {
			if (dwType < REG_FULL_RESOURCE_DESCRIPTOR &&
								retCode != ERROR_NO_MORE_ITEMS) {
				DPRINT(("stub: ERROR, RegEnumValue = %d cbData = %d line %d\n"
					   , retCode, cbData, __LINE__));
 				return FALSE;
			}
		}
		DPRINT(("stub.findJreInfo...: i=%d, ValueName=%s, cbValueName=%d, dwType=%d,\n\t bData=%s, cbData=%d; retCode=%d\n", i, ValueName, cbValueName, dwType, bData, cbData, retCode));
		/* Process the value accordingly. */
		Param = _strlwr(ValueName);
		if(!strcmp("javahome", Param)) {
			DPRINT(("stub.findJreInfo...: Setting path and args to %s\n",bData));
			strcat(path, bData);
			strcat(args, bData);
			found = TRUE;
		}
		if(!strcmp("microversion", Param)) {
			DPRINT(("stub.findJreInfo...: found JRE 1.1.%s\n",bData));
			if(atoi(bData) < 6) {
				CHAR title[TITLELEN];
				CHAR msg[MSGLEN];
				LoadString(NULL, IDS_OLD_JRE_TITLE, title, TITLELEN);
				LoadString(NULL, IDS_OLD_JRE_MSG, msg, MSGLEN);
				MessageBox(NULL, msg, title,
					MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND);
				DPRINT(("stub: version of jre is too old"));
				return FALSE;
			}
		}
	}
	DPRINT(("stub.findJreInfo...: done, found=%d",found));
	return found;
}
Ejemplo n.º 15
0
int xmi_registry_win_query(int kind, char **regcontents) {

	LONG RegRV;
	DWORD QueryRV;
	LPTSTR subKey;
	HKEY key;
    	DWORD BufferSize = TOTALBYTES;
        DWORD cbdata;
	PPERF_DATA_BLOCK PerfData;
	char stringkey[1024];


	strcpy(stringkey,"Software\\XMI-MSIM\\");
	switch (kind) {
		case XMI_REGISTRY_WIN_DATA:
			strcat(stringkey,"data");
			break;
		case XMI_REGISTRY_WIN_SHARE:
			strcat(stringkey,"share");
			break;
		case XMI_REGISTRY_WIN_XMSO2XMSI:
			strcat(stringkey,"xmso2xmsi");
			break;
		case XMI_REGISTRY_WIN_XMSO2SVG:
			strcat(stringkey,"xmso2svg");
			break;
		case XMI_REGISTRY_WIN_XMSO2SPE:
			strcat(stringkey,"xmso2spe");
			break;
		case XMI_REGISTRY_WIN_XMSO2CSV:
			strcat(stringkey,"xmso2csv");
			break;
		case XMI_REGISTRY_WIN_XMSO2HTM:
			strcat(stringkey,"xmso2htm");
			break;
		case XMI_REGISTRY_WIN_LOGO:
			strcat(stringkey,"icon");
			break;
		case XMI_REGISTRY_WIN_OPENCL_CODE:
			strcat(stringkey,"openclcode");
			break;
		case XMI_REGISTRY_WIN_OPENCL_LIB:
			strcat(stringkey,"opencllib");
			break;
		case XMI_REGISTRY_WIN_XMSA2XMSO:
			strcat(stringkey,"xmsa2xmso");
			break;
		default:
			fprintf(stderr,"Invalid kind in xmi_registry_win_query\n");
			return 0;
	}


	//Windows mode: query registry
	RegRV = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(stringkey), 0, KEY_READ,&key);
	if (RegRV != ERROR_SUCCESS) {
		fprintf(stderr,"Error opening key %s in registry\n",stringkey);
		return 0;
	}
	PerfData = (PPERF_DATA_BLOCK) g_malloc( BufferSize );
	cbdata = BufferSize;


	QueryRV = RegQueryValueExA(key,TEXT(""), NULL, NULL, (LPBYTE) PerfData,&cbdata);
	while( QueryRV == ERROR_MORE_DATA ) {
	        // Get a buffer that is big enough.
		BufferSize += BYTEINCREMENT;
		PerfData = (PPERF_DATA_BLOCK) g_realloc( PerfData, BufferSize );
		cbdata = BufferSize;
		QueryRV = RegQueryValueExA(key,TEXT(""), NULL, NULL, (LPBYTE) PerfData,&cbdata);
	}
	if (QueryRV != ERROR_SUCCESS) {
		fprintf(stderr,"Error querying key %s in registry\n",stringkey);
		return 0;
	}


#if DEBUG == 1
		fprintf(stdout,"KeyValue: %s, bytes %i cbdata %i\n",(char *) PerfData,strlen((char *) PerfData), (int) cbdata);
#endif



	RegCloseKey(key);

	*regcontents = (char *) PerfData;
	return 1;
}
Ejemplo n.º 16
0
// query com ports on:
//		Windows 2000 - XP - Vista - 7
//
int GetPortNumXP2000Vista(WORD vid, WORD pid, char* ser)
{
	//Variables used for Registry access
	HKEY tmpKey, tmpSubKey, tmpPortKey;
	CString portKeyString;
	DWORD valtype;
	char* portString;
	DWORD length = 100;
	portString = new char[101];

	//Set portnum to -1, so if there is an error we will
	//know by returning a negative port value
	int portNum = -1;

	//  Open keys to get to the key where the port number is located. This key is:
	//  HKLM\System\CurrentControlSet\Enum\USB\Vid_xxxx&Pid_yyyy&Mi_00\zzzz_00\DeviceParameters\PortName
	if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\", 0, KEY_READ, &tmpKey))
	{
		if (ERROR_SUCCESS == RegOpenKey(tmpKey, "Enum\\USB\\", &tmpSubKey))
		{
			//Loop through and replace spaces for WinXP2000Vista
			int i = 0;
			while (ser[i] != '\0')
			{
				if (ser[i] == 0x20)
					ser[i] = '_';
				i++;
			}

			//The portkey string should look like this
			//"Vid_XXXX&Pid_XXXX&MI_00\\XXXX_00" where the XXXX's are Vid, Pid and serial string - version less than 5.0
			//"Vid_XXXX&Pid_XXXX\\XXXX" where the XXXX's are Vid, Pid and serial string - version greater than or equal to 5.0
			portKeyString.Format("Vid_%04x&Pid_%04x&Mi_00\\%s_00\\Device Parameters\\", vid, pid, ser);

			//If the portkey string is in the registry, then go ahead and open the portname
			if (ERROR_SUCCESS == RegOpenKeyEx(tmpSubKey, portKeyString, 0, KEY_READ, &tmpPortKey))
			{
				if (ERROR_SUCCESS == RegQueryValueEx(tmpPortKey, "PortName", NULL, &valtype, (unsigned char *)portString, &length))
				{
					// When we obtain this key, it will be in string format of
					// "COMXX" where XX is the port. Simply make the first three
					// elements of the string 0, and call the atoi function to obtain
					// the number of the port.
					portString[0] = '0';
					portString[1] = '0';
					portString[2] = '0';
					portNum = atoi(portString);
				}
				//Make sure to close all open keys for cleanup
				RegCloseKey(tmpPortKey);
			}
			else
			{
				portKeyString.Format("Vid_%04x&Pid_%04x\\%s\\Device Parameters\\", vid, pid, ser);

				//If the portkey string is in the registry, then go ahead and open the portname
				if (ERROR_SUCCESS == RegOpenKeyEx(tmpSubKey, portKeyString, 0, KEY_READ, &tmpPortKey))
				{
					if (ERROR_SUCCESS == RegQueryValueEx(tmpPortKey, "PortName", NULL, &valtype, (unsigned char *)portString, &length))
					{
						// When we obtain this key, it will be in string format of
						// "COMXX" where XX is the port. Simply make the first three
						// elements of the string 0, and call the atoi function to obtain
						// the number of the port.
						portString[0] = '0';
						portString[1] = '0';
						portString[2] = '0';
						portNum = atoi(portString);
					}
					//Make sure to close all open keys for cleanup
					RegCloseKey(tmpPortKey);
				}
			}

			RegCloseKey(tmpSubKey);
		}
		RegCloseKey(tmpKey);
	}
	RegCloseKey(HKEY_LOCAL_MACHINE);

	delete portString;

	// Return the number of the port the device is connected too
	return portNum;
}
Ejemplo n.º 17
0
LIST*
builtin_system_registry(
    PARSE    *parse,
    FRAME    *frame )
{
    char const* path = lol_get(frame->args, 0)->string;
    LIST* result = L0;
    HKEY key = get_key(&path);

    if (
        key != 0
        && ERROR_SUCCESS == RegOpenKeyEx(key, path, 0, KEY_QUERY_VALUE, &key)
    )
    {
        DWORD  type;
        BYTE   data[MAX_REGISTRY_DATA_LENGTH];
        DWORD  len = sizeof(data);
        LIST const* const field = lol_get(frame->args, 1);

        if ( ERROR_SUCCESS ==
             RegQueryValueEx(key, field ? field->string : 0, 0, &type, data, &len) )
        {
            switch (type)
            {

             case REG_EXPAND_SZ:
                 {
                     long len;
                     string expanded[1];
                     string_new(expanded);

                     while (
                         (len = ExpandEnvironmentStrings(
                             (LPCSTR)data, expanded->value, expanded->capacity))
                         > expanded->capacity
                     )
                         string_reserve(expanded, len);

                     expanded->size = len - 1;

                     result = list_new( result, newstr(expanded->value) );
                     string_free( expanded );
                 }
                 break;

             case REG_MULTI_SZ:
                 {
                     char* s;

                     for (s = (char*)data; *s; s += strlen(s) + 1)
                         result = list_new( result, newstr(s) );

                 }
                 break;

             case REG_DWORD:
                 {
                     char buf[100];
                     sprintf( buf, "%u", *(PDWORD)data );
                     result = list_new( result, newstr(buf) );
                 }
                 break;

             case REG_SZ:
                 result = list_new( result, newstr((char*)data) );
                 break;
            }
        }
        RegCloseKey(key);
    }
    return  result;
}
Ejemplo n.º 18
0
static jboolean
GetPublicJREHome(char *buf, jint bufsize)
{
    HKEY key, subkey;
    char version[MAXPATHLEN];

    /*
     * Note: There is a very similar implementation of the following
     * registry reading code in the Windows java control panel (javacp.cpl).
     * If there are bugs here, a similar bug probably exists there.  Hence,
     * changes here require inspection there.
     */

    /* Find the current version of the JRE */
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) {
        fprintf(stderr, "Error opening registry key '" JRE_KEY "'\n");
        return JNI_FALSE;
    }

    if (!GetStringFromRegistry(key, "CurrentVersion",
                               version, sizeof(version))) {
        fprintf(stderr, "Failed reading value of registry key:\n\t"
                JRE_KEY "\\CurrentVersion\n");
        RegCloseKey(key);
        return JNI_FALSE;
    }

    if (strcmp(version, DOTRELEASE) != 0) {
        fprintf(stderr, "Registry key '" JRE_KEY "\\CurrentVersion'\nhas "
                "value '%s', but '" DOTRELEASE "' is required.\n", version);
        RegCloseKey(key);
        return JNI_FALSE;
    }

    /* Find directory where the current version is installed. */
    if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) {
        fprintf(stderr, "Error opening registry key '"
                JRE_KEY "\\%s'\n", version);
        RegCloseKey(key);
        return JNI_FALSE;
    }

    if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) {
        fprintf(stderr, "Failed reading value of registry key:\n\t"
                JRE_KEY "\\%s\\JavaHome\n", version);
        RegCloseKey(key);
        RegCloseKey(subkey);
        return JNI_FALSE;
    }

    if (_launcher_debug) {
        char micro[MAXPATHLEN];
        if (!GetStringFromRegistry(subkey, "MicroVersion", micro,
                                   sizeof(micro))) {
            printf("Warning: Can't read MicroVersion\n");
            micro[0] = '\0';
        }
        printf("Version major.minor.micro = %s.%s\n", version, micro);
    }

    RegCloseKey(key);
    RegCloseKey(subkey);
    return JNI_TRUE;
}
Ejemplo n.º 19
0
////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// PUBLIC FUNCTIONS /////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
int EDT_UtilReg_LogKeyTree(HKEY hrootKey,const wchar_t* keyName, int flags,int recursion)
{
	HKEY hSubKey;

	if(recursion > 8)
	{
		LOG(L"Recursion greater then 8, won't go any deeper\n");
		return EDT_OK;
	}
	LOG_ENTER();
	if(recursion == 0)
		LOG(L"LogKeyTree (%ls\\%ls) \n",hrootKey==HKEY_CURRENT_USER?L"HKCU":L"HKLM",keyName);

	if( RegOpenKeyEx( hrootKey,keyName,0,KEY_READ,&hSubKey) == ERROR_SUCCESS)
	{
		TCHAR    subKeyName[MAX_KEY_LENGTH];
		DWORD    subKeyNameLen=MAX_KEY_LENGTH;  
		DWORD    nrOfSubKeys;
		DWORD    maxSubKeySize;
		DWORD    nrOfValues;
		DWORD    maxValueSize;
		DWORD    maxValueDataSize;
		FILETIME lastWriteTime;

		DWORD i, retVal; 

		retVal = RegQueryInfoKey(
			hSubKey,                // key handle 
			NULL,					// buffer for class name 
			NULL,					// size of class string 
			NULL,                   // reserved 
			&nrOfSubKeys,           // number of subkeys 
			&maxSubKeySize,         // longest subkey size 
			NULL,					// longest class string 
			&nrOfValues,            // number of values this key contains
			&maxValueSize,          // longest value name size
			&maxValueDataSize,      // longest value data size
			NULL,					// security descriptor 
			NULL);					// last write time 

		// Enumerate subKeys 
		if (nrOfSubKeys)
		{
			LOG( L"Number of subkeys: %d\n", nrOfSubKeys);

			for (i=0; i<nrOfSubKeys; i++) 
			{ 
				subKeyNameLen=MAX_KEY_LENGTH;
				retVal = RegEnumKeyEx(hSubKey,i,subKeyName,&subKeyNameLen,NULL,NULL,NULL,&lastWriteTime); 
				if (retVal == ERROR_SUCCESS) 
				{
					switch(flags)
					{
					case EDTREGFLAG_EIDMW_ONLY:
						if(EDT_UtilReg_IsEidmwKeyName(subKeyName) == FALSE)
						{
							break;
						}						
					default:
						recursion++;
						LOG(L"%d)subKeyName: %s\n",i+1,subKeyName);
						EDT_UtilReg_LogKeyTree(hSubKey,subKeyName,flags,recursion);
						recursion--;
						break;
					}
				}
				else
				{
					LOG(L"%d)RegEnumKeyEx failed with %d \n",i+1,retVal);
				}
			}
		}
		// Enumerate key values 
		if (nrOfValues) 
		{
			LOG( L"Number of values: %d\n", nrOfValues);
			DWORD valueBufferLenInChars =(maxValueSize+1);//1 extra for terminating null character//buffersize in characters
			wchar_t *valueBuffer = (wchar_t*)malloc(sizeof(wchar_t)*valueBufferLenInChars);

			if(valueBuffer != NULL)
			{
				DWORD valueDataBufferLen = maxValueDataSize+4;//4 extra for 2 terminating null characters (unicode)
				BYTE *valueDataBuffer = (BYTE*)malloc(valueDataBufferLen);

				if (valueDataBuffer != NULL)
				{
					retVal=ERROR_SUCCESS;
					for ( i=0; i < nrOfValues; i++ ) 
					{ 
						valueBufferLenInChars = (maxValueSize+1);//1 extra for terminating null character
						retVal = RegEnumValue(hSubKey,i,valueBuffer,&valueBufferLenInChars,NULL,NULL,NULL,NULL);
						if (retVal == ERROR_SUCCESS ) 
						{ 							
							DWORD dwType = REG_NONE;
							valueDataBufferLen = maxValueDataSize+4;//4 extra for 2 terminating null characters (unicode)
							retVal = RegQueryValueEx(hSubKey, valueBuffer, 0L, &dwType, valueDataBuffer, &valueDataBufferLen);
							if(retVal != ERROR_SUCCESS)
							{     
								LOG(L"(%d)(???) %s: \n", i+1, valueBuffer); 
								LOG(L"RegQueryValueEx failed %d\n",retVal);
							}
							else
							{
								EDT_UtilReg_LogValueData(valueBuffer, valueDataBuffer, valueDataBufferLen,  dwType);
							}
						}
						else
						{
							LOG(L"(%d) RegEnumValue failed\n",i+1);
						}
					}
					free(valueDataBuffer);
				}		
				else
				{
					LOG_ERROR(L"malloc valueDataBuffer failed\n");
				}
				free(valueBuffer);
			}
			else
			{
				LOG_ERROR(L"malloc valueBuffer failed\n");
			}
		}
		RegCloseKey(hSubKey);
	}
	LOG_EXIT(EDT_OK);
	return EDT_OK;
}
Ejemplo n.º 20
0
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;
}
Ejemplo n.º 21
0
LONG CFBPanel::OnDblclk(HWND hwndCPl, UINT /*uAppNum*/, LONG /*lData*/)
{

	AFX_MANAGE_STATE(AfxGetStaticModuleState());

    // Create the dialog box using the parent window handle
    CFBDialog dlg(CWnd::FromHandle(hwndCPl));

	try {
		// Check if Firebird is installed by reading the registry
		HKEY hkey;
		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_KEY_ROOT_INSTANCES, 0, KEY_QUERY_VALUE, &hkey)
			== ERROR_SUCCESS)
		{
			char rootpath[MAX_PATH - 2];
			DWORD buffer_size = sizeof(rootpath);
			if (RegQueryValueEx(hkey, FB_DEFAULT_INSTANCE, NULL, NULL, LPBYTE(rootpath), &buffer_size)
				== ERROR_SUCCESS)
			{
				PathAddBackslash(rootpath);
				dlg.m_Root_Path = rootpath;
			}

			RegCloseKey(hkey);

			dlg.m_FB_Version = "not known";
			CString afilename = dlg.m_Root_Path + "bin\\gbak.exe";
			buffer_size = GetFileVersionInfoSize( (LPCTSTR) afilename, 0);
			void* VersionInfo = new char [buffer_size];
			void* ProductVersion = 0;
			void* SpecialBuild = 0;
			void* PrivateBuild = 0;
			UINT ValueSize;
			if ( GetFileVersionInfo((LPCTSTR) afilename, 0, buffer_size, VersionInfo) )
			{
				VerQueryValue( VersionInfo, "\\StringFileInfo\\040904E4\\ProductVersion",
								&ProductVersion, &ValueSize);
				if (ValueSize)
				{
					dlg.m_FB_Version = "Version ";
					dlg.m_FB_Version += (char*) ProductVersion;
				}
				VerQueryValue( VersionInfo, "\\StringFileInfo\\040904E4\\SpecialBuild",
								&SpecialBuild, &ValueSize);
				if (ValueSize)
				{
					dlg.m_FB_Version += " ";
					dlg.m_FB_Version += (char*) SpecialBuild;
				}
				VerQueryValue( VersionInfo, "\\StringFileInfo\\040904E4\\PrivateBuild",
								&PrivateBuild, &ValueSize);
				if (ValueSize)
				{
					dlg.m_FB_Version += " ";
					dlg.m_FB_Version += (char*) PrivateBuild;
				}
/**/
			}
			delete[] (char*) VersionInfo;

			// Show the dialog box
			if (dlg.DoModal() != IDOK)
				return 0;
		}
	}
	catch ( ... )
	{
		//raise an error
		dlg.MessageBox("Firebird does not appear to be installed correctly.", "Installation Error", MB_OK);
	}
    return 0;
}
Ejemplo n.º 22
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;
}
Ejemplo n.º 23
0
int smpd_get_smpd_data(const char *key, char *value, int value_len)
{
#ifdef HAVE_WINDOWS_H
    HKEY tkey;
    DWORD len, result;
    char err_msg[512];

    smpd_enter_fn(FCNAME);

    if (smpd_get_smpd_data_from_environment(key, value, value_len) == SMPD_TRUE)
    {
	smpd_exit_fn(FCNAME);
	return SMPD_SUCCESS;
    }

    result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, SMPD_REGISTRY_KEY, 0, KEY_READ, &tkey);
    if (result != ERROR_SUCCESS)
    {
	if (smpd_get_smpd_data_default(key, value, value_len) != SMPD_SUCCESS)
	{
	    smpd_dbg_printf("Unable to get the data for the key '%s'\n", key);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	smpd_exit_fn(FCNAME);
	return SMPD_SUCCESS;
    }

    len = value_len;
    result = RegQueryValueEx(tkey, key, 0, NULL, (unsigned char *)value, &len);
    if (result != ERROR_SUCCESS)
    {
	RegCloseKey(tkey);
	if (smpd_get_smpd_data_default(key, value, value_len) != SMPD_SUCCESS)
	{
	    smpd_dbg_printf("Unable to get the data for the key '%s'\n", key);
	    smpd_exit_fn(FCNAME);
	    return SMPD_FAIL;
	}
	smpd_exit_fn(FCNAME);
	return SMPD_SUCCESS;
    }

    result = RegCloseKey(tkey);
    if (result != ERROR_SUCCESS)
    {
	smpd_translate_win_error(result, err_msg, 512, "Unable to close the HKEY_LOCAL_MACHINE\\" SMPD_REGISTRY_KEY " registry key, error %d: ", result);
	smpd_err_printf("%s\n", err_msg);
	smpd_exit_fn(FCNAME);
	return SMPD_FAIL;
    }

    smpd_exit_fn(FCNAME);
    return SMPD_SUCCESS;
#else
    int result;
    smpd_data_t *list = NULL, *node;
    int num_bytes;

    smpd_enter_fn(FCNAME);

    smpd_dbg_printf("getting smpd data: %s\n", key);

    if (smpd_get_smpd_data_from_environment(key, value, value_len) == SMPD_TRUE)
    {
	smpd_exit_fn(FCNAME);
	return SMPD_SUCCESS;
    }

    list = smpd_parse_smpd_file();

    if (list)
    {
	int found = 0;
	while (list)
	{
	    node = list;
	    list = list->next;
	    if (strcmp(key, node->name) == 0)
	    {
		strcpy(value, node->value);
		smpd_dbg_printf("smpd data: %s=%s\n", key, value);
		found = 1;
	    }
	    MPIU_Free(node);
	}
	if (found)
	{
	    smpd_exit_fn(FCNAME);
	    return SMPD_SUCCESS;
	}
    }

    result = smpd_get_smpd_data_default(key, value, value_len);
    if (result == SMPD_SUCCESS)
    {
	smpd_dbg_printf("smpd data: %s=%s\n", key, value);
    }
    else
    {
	smpd_dbg_printf("smpd data: failed to get %s\n", key);
    }

    smpd_exit_fn(FCNAME);
    return result;
#endif
}
Ejemplo n.º 24
0
void CSysInfo::GetOSInfo (void)
{
	m_mapOS.clear ();

	m_mapOS[ "Language" ] = (string)m_system->m_szLanguagesEnglish; // 현재 언어.

	OSVERSIONINFOEX osvi;
	BOOL bOsVersionInfoEx;

	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

	if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
	{
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) 
			return;
	}

	switch (osvi.dwPlatformId)
	{
		// Test for the Windows NT product family.
	case VER_PLATFORM_WIN32_NT:

		// Test for the specific product family.
		if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 )
			m_mapOS[ "Name" ] = "Microsoft Windows Server 2003 family";
		else if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 )
			m_mapOS[ "Name" ] = "Microsoft Windows XP ";
		else if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
			m_mapOS[ "Name" ] = "Microsoft Windows 2000 ";
		else if ( osvi.dwMajorVersion <= 4 )
			m_mapOS[ "Name" ] = "Microsoft Windows NT ";

		// Test for specific product on Windows NT 4.0 SP6 and later.
		if( bOsVersionInfoEx )
		{
			// Test for the workstation type.
			if ( osvi.wProductType == VER_NT_WORKSTATION )
			{
				if( osvi.dwMajorVersion == 4 )
					m_mapOS[ "Edition" ] = "Workstation 4.0 ";
				else if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
					m_mapOS[ "Edition" ] = "Home Edition ";
				else
					m_mapOS[ "Edition" ] = "Professional ";
			}
			// Test for the server type.
			else if ( osvi.wProductType == VER_NT_SERVER )
			{
				if( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 )
				{
					if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
						m_mapOS[ "Edition" ] = "Datacenter Edition " ;
					else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
						m_mapOS[ "Edition" ] = "Enterprise Edition " ;
					else if ( osvi.wSuiteMask == VER_SUITE_BLADE )
						m_mapOS[ "Edition" ] = "Web Edition " ;
					else
						m_mapOS[ "Edition" ] = "Standard Edition " ;
				}
				else if( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
				{
					if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
						m_mapOS[ "Edition" ] = "Datacenter Server " ;
					else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
						m_mapOS[ "Edition" ] = "Advanced Server " ;
					else
						m_mapOS[ "Edition" ] = "Server " ;
				}
				else  // Windows NT 4.0 
				{
					if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
						m_mapOS[ "Edition" ] = "Server 4.0, Enterprise Edition ";
					else
						m_mapOS[ "Edition" ] = "Server 4.0 ";
				}
			}
		}
		else  // Test for specific product on Windows NT 4.0 SP5 and earlier
		{
			HKEY hKey;
			char szProductType[BUFSIZE];
			DWORD dwBufLen=BUFSIZE;
			LONG lRet;

			lRet = RegOpenKeyEx (HKEY_LOCAL_MACHINE
							, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions"
							, 0
							, KEY_QUERY_VALUE
							, &hKey );
			if( lRet == ERROR_SUCCESS )
			{

				lRet = RegQueryValueEx ( hKey
							, "ProductType"
							, NULL
							, NULL
							, (LPBYTE) szProductType
							, &dwBufLen);
				if( (lRet == ERROR_SUCCESS) && (dwBufLen <= BUFSIZE) )
				{
					RegCloseKey( hKey );

					string strEdition;
					if ( lstrcmpi( "WINNT", szProductType) == 0 )
						strEdition = "Workstation ";
					if ( lstrcmpi( "LANMANNT", szProductType) == 0 )
						strEdition = "Server ";
					if ( lstrcmpi( "SERVERNT", szProductType) == 0 )
						strEdition = "Advanced Server ";

					char buff[ 32 ];
					sprintf (buff, "%d.%d ", osvi.dwMajorVersion, osvi.dwMinorVersion );
					m_mapOS[ "Edition" ] = strEdition + buff;
				}
			}
		}

		// Display service pack (if any) and build number.
		char szSrvPack[ 255 ];
		if( osvi.dwMajorVersion == 4 && 
			lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 )
		{
			HKEY hKey;
			LONG lRet;

			// Test for SP6 versus SP6a.
			lRet = RegOpenKeyEx (HKEY_LOCAL_MACHINE
								, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009"
								, 0
								, KEY_QUERY_VALUE
								, &hKey );
			if( lRet == ERROR_SUCCESS )
				sprintf (szSrvPack, "Service Pack 6a (Build %d)", osvi.dwBuildNumber & 0xFFFF );         
			else // Windows NT 4.0 prior to SP6a
			{
				sprintf (szSrvPack, "%s (Build %d)"
						, osvi.szCSDVersion
						, osvi.dwBuildNumber & 0xFFFF);
			}

			RegCloseKey( hKey );

			m_mapOS[ "Service Pack" ] = szSrvPack;
		}
		else // Windows NT 3.51 and earlier or Windows 2000 and later
		{
			sprintf (szSrvPack, "%s (Build %d)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
			m_mapOS[ "Service Pack" ] = szSrvPack;
		}


		break;

		// Test for the Windows 95 product family.
	case VER_PLATFORM_WIN32_WINDOWS:

		if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
		{
			m_mapOS[ "Name" ] = "Microsoft Windows 95 ";
			if ( osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B' )
				m_mapOS[ "Name" ] += "OSR2 ";
		} 

		if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
		{
			m_mapOS[ "Name" ] = "Microsoft Windows 98 ";
			if ( osvi.szCSDVersion[1] == 'A' )
				m_mapOS[ "Name" ] += "SE ";
		} 

		if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
		{
			m_mapOS[ "Name" ] = "Microsoft Windows Millennium Edition";
		} 
		break;

	case VER_PLATFORM_WIN32s:

		m_mapOS[ "Name" ] = "Microsoft Win32s";
		break;
	}
}
Ejemplo n.º 25
0
static void
slow_gatherer_windowsNT( void (*add)(const void*, size_t, int), int requester )
{
    static int is_initialized = 0;
    static NETSTATISTICSGET pNetStatisticsGet = NULL;
    static NETAPIBUFFERSIZE pNetApiBufferSize = NULL;
    static NETAPIBUFFERFREE pNetApiBufferFree = NULL;
    static int is_workstation = 1;

    static int cbPerfData = PERFORMANCE_BUFFER_SIZE;
    PERF_DATA_BLOCK *pPerfData;
    HANDLE hDevice, hNetAPI32 = NULL;
    DWORD dwSize, status;
    int nDrive;

    if ( !is_initialized ) {
	HKEY hKey;

	if ( debug_me )
	    log_debug ("rndw32#slow_gatherer_nt: init toolkit\n" );
	/* Find out whether this is an NT server or workstation if necessary */
	if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
			  "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
			  0, KEY_READ, &hKey) == ERROR_SUCCESS) {
	    BYTE szValue[32];
	    dwSize = sizeof (szValue);

	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: check product options\n" );
	    status = RegQueryValueEx (hKey, "ProductType", 0, NULL,
				      szValue, &dwSize);
	    if (status == ERROR_SUCCESS && stricmp (szValue, "WinNT")) {
		/* Note: There are (at least) three cases for ProductType:
		 * WinNT = NT Workstation, ServerNT = NT Server, LanmanNT =
		 * NT Server acting as a Domain Controller */
		is_workstation = 0;
		if ( debug_me )
		    log_debug ("rndw32: this is a NT server\n");
	    }
	    RegCloseKey (hKey);
	}

	/* Initialize the NetAPI32 function pointers if necessary */
	if ( (hNetAPI32 = LoadLibrary ("NETAPI32.DLL")) ) {
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: netapi32 loaded\n" );
	    pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32,
						       "NetStatisticsGet");
	    pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32,
						       "NetApiBufferSize");
	    pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32,
						       "NetApiBufferFree");

	    if ( !pNetStatisticsGet
		 || !pNetApiBufferSize || !pNetApiBufferFree ) {
		FreeLibrary (hNetAPI32);
		hNetAPI32 = NULL;
		g10_log_debug ("rndw32: No NETAPI found\n" );
	    }
	}

	is_initialized = 1;
    }

    /* Get network statistics.	Note: Both NT Workstation and NT Server by
     * default will be running both the workstation and server services.  The
     * heuristic below is probably useful though on the assumption that the
     * majority of the network traffic will be via the appropriate service.
     * In any case the network statistics return almost no randomness */
    {	LPBYTE lpBuffer;
	if (hNetAPI32 && !pNetStatisticsGet (NULL,
			   is_workstation ? L"LanmanWorkstation" :
			   L"LanmanServer", 0, 0, &lpBuffer) ) {
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: get netstats\n" );
	    pNetApiBufferSize (lpBuffer, &dwSize);
	    (*add) ( lpBuffer, dwSize,requester );
	    pNetApiBufferFree (lpBuffer);
	}
    }

    /* Get disk I/O statistics for all the hard drives */
    for (nDrive = 0;; nDrive++) {
	DISK_PERFORMANCE diskPerformance;
	char szDevice[50];

	/* Check whether we can access this device */
	sprintf (szDevice, "\\\\.\\PhysicalDrive%d", nDrive);
	hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
			      NULL, OPEN_EXISTING, 0, NULL);
	if (hDevice == INVALID_HANDLE_VALUE)
	    break;

	/* Note: This only works if you have turned on the disk performance
	 * counters with 'diskperf -y'.  These counters are off by default */
	if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
			     &diskPerformance, sizeof (DISK_PERFORMANCE),
			     &dwSize, NULL))
	{
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: iostats drive %d\n",
								  nDrive );
	    (*add) ( &diskPerformance, dwSize, requester );
	}
	else {
	    log_info ("NOTE: you should run 'diskperf -y' "
		      "to enable the disk statistics\n");
	}
	CloseHandle (hDevice);
    }

  #if 0 /* we don't need this in GnuPG  */
    /* Wait for any async keyset driver binding to complete.  You may be
     * wondering what this call is doing here... the reason it's necessary is
     * because RegQueryValueEx() will hang indefinitely if the async driver
     * bind is in progress.  The problem occurs in the dynamic loading and
     * linking of driver DLL's, which work as follows:
     *
     * hDriver = LoadLibrary( DRIVERNAME );
     * pFunction1 = ( TYPE_FUNC1 ) GetProcAddress( hDriver, NAME_FUNC1 );
     * pFunction2 = ( TYPE_FUNC1 ) GetProcAddress( hDriver, NAME_FUNC2 );
     *
     * If RegQueryValueEx() is called while the GetProcAddress()'s are in
     * progress, it will hang indefinitely.  This is probably due to some
     * synchronisation problem in the NT kernel where the GetProcAddress()
     * calls affect something like a module reference count or function
     * reference count while RegQueryValueEx() is trying to take a snapshot
     * of the statistics, which include the reference counts.  Because of
     * this, we have to wait until any async driver bind has completed
     * before we can call RegQueryValueEx() */
    waitSemaphore (SEMAPHORE_DRIVERBIND);
  #endif

    /* Get information from the system performance counters.  This can take
     * a few seconds to do.  In some environments the call to
     * RegQueryValueEx() can produce an access violation at some random time
     * in the future, adding a short delay after the following code block
     * makes the problem go away.  This problem is extremely difficult to
     * reproduce, I haven't been able to get it to occur despite running it
     * on a number of machines.  The best explanation for the problem is that
     * on the machine where it did occur, it was caused by an external driver
     * or other program which adds its own values under the
     * HKEY_PERFORMANCE_DATA key.  The NT kernel calls the required external
     * modules to map in the data, if there's a synchronisation problem the
     * external module would write its data at an inappropriate moment,
     * causing the access violation.  A low-level memory checker indicated
     * that ExpandEnvironmentStrings() in KERNEL32.DLL, called an
     * interminable number of calls down inside RegQueryValueEx(), was
     * overwriting memory (it wrote twice the allocated size of a buffer to a
     * buffer allocated by the NT kernel).  This may be what's causing the
     * problem, but since it's in the kernel there isn't much which can be
     * done.
     *
     * In addition to these problems the code in RegQueryValueEx() which
     * estimates the amount of memory required to return the performance
     * counter information isn't very accurate, since it always returns a
     * worst-case estimate which is usually nowhere near the actual amount
     * required.  For example it may report that 128K of memory is required,
     * but only return 64K of data */
    {	pPerfData =  m_alloc (cbPerfData);
	for (;;) {
	    dwSize = cbPerfData;
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: get perf data\n" );
	    status = RegQueryValueEx (HKEY_PERFORMANCE_DATA, "Global", NULL,
				      NULL, (LPBYTE) pPerfData, &dwSize);
	    if (status == ERROR_SUCCESS) {
		if (!memcmp (pPerfData->Signature, L"PERF", 8)) {
		    (*add) ( pPerfData, dwSize, requester );
		}
		else
		    g10_log_debug ( "rndw32: no PERF signature\n");
		break;
	    }
	    else if (status == ERROR_MORE_DATA) {
		cbPerfData += PERFORMANCE_BUFFER_STEP;
		pPerfData = m_realloc (pPerfData, cbPerfData);
	    }
	    else {
		g10_log_debug ( "rndw32: get performance data problem\n");
		break;
	    }
	}
	m_free (pPerfData);
    }
    /* Although this isn't documented in the Win32 API docs, it's necessary
       to explicitly close the HKEY_PERFORMANCE_DATA key after use (it's
       implicitly opened on the first call to RegQueryValueEx()).  If this
       isn't done then any system components which provide performance data
       can't be removed or changed while the handle remains active */
    RegCloseKey (HKEY_PERFORMANCE_DATA);
}
Ejemplo n.º 26
0
LONG
    VcdPmGetPortArray(
        VOID
    )
/*++

Routine Description:

    Use the registry enteries in HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM
    to simulate the Virtual Comm Device API: VCD_PM_Get_Port_Array. See VCD.ASM
    in the Win 3.1 DDK.


Arguments:

    None

Return Value:

    Port Array in LOWORD. Bit array of valid ports:

    Bit Set   -> Port valid
    Bit clear -> Port invalid

    Bit 0 -> COM1, Bit 1 -> COM2, Bit 2 -> COM3...

--*/
{
    HKEY        hSerialCommKey;
    DWORD       dwPortArray;
    DWORD       dwPortNum;
    DWORD       cbPortName;
    DWORD       cbPortValue;
    CHAR        szPortName[16];
    CHAR        szPortValue[16];
    LONG        iPort;
    LONG        iStatus;

    dwPortArray = 0;
    if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
                      "HARDWARE\\DEVICEMAP\\SERIALCOMM",
                      0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
                      &hSerialCommKey) == ERROR_SUCCESS){

        cbPortName  = sizeof(szPortName);
        cbPortValue = sizeof(szPortValue);
        for (iPort = 0;
             (iStatus = RegEnumValue(hSerialCommKey,
                                     iPort, szPortName, &cbPortName,
                                     NULL, NULL, szPortValue,
                                     &cbPortValue)) != ERROR_NO_MORE_ITEMS;
             iPort++)
        {
            if ((iStatus == ERROR_SUCCESS) && (cbPortValue > 3)) {

                if (NT_SUCCESS(RtlCharToInteger(szPortValue+3,10,&dwPortNum))) {
                    dwPortArray |= (1 << (dwPortNum - 1));
                }

            }
            cbPortName  = sizeof(szPortName);
            cbPortValue = sizeof(szPortValue);
        }
    // WOW only supports 9 ports. See WU32OPENCOM in WUCOMM.C.
    dwPortArray &= 0x1FF;
    RegCloseKey(hSerialCommKey);
    }
    return(dwPortArray);
}
Ejemplo n.º 27
0
svn_error_t *
svn_config__parse_registry(svn_config_t *cfg, const char *file,
                           svn_boolean_t must_exist, apr_pool_t *pool)
{
  apr_pool_t *subpool;
  svn_stringbuf_t *section, *option, *value;
  svn_error_t *svn_err = SVN_NO_ERROR;
  HKEY base_hkey, hkey;
  DWORD index;
  LONG err;

  if (0 == strncmp(file, SVN_REGISTRY_HKLM, SVN_REGISTRY_HKLM_LEN))
    {
      base_hkey = HKEY_LOCAL_MACHINE;
      file += SVN_REGISTRY_HKLM_LEN;
    }
  else if (0 == strncmp(file, SVN_REGISTRY_HKCU, SVN_REGISTRY_HKCU_LEN))
    {
      base_hkey = HKEY_CURRENT_USER;
      file += SVN_REGISTRY_HKCU_LEN;
    }
  else
    {
      return svn_error_createf(SVN_ERR_BAD_FILENAME, NULL,
                               "Unrecognised registry path '%s'",
                               svn_path_local_style(file, pool));
    }

  err = RegOpenKeyEx(base_hkey, file, 0,
                     KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
                     &hkey);
  if (err != ERROR_SUCCESS)
    {
      const int is_enoent = APR_STATUS_IS_ENOENT(APR_FROM_OS_ERROR(err));
      if (!is_enoent)
        return svn_error_createf(SVN_ERR_BAD_FILENAME, NULL,
                                 "Can't open registry key '%s'",
                                 svn_path_local_style(file, pool));
      else if (must_exist && is_enoent)
        return svn_error_createf(SVN_ERR_BAD_FILENAME, NULL,
                                 "Can't find registry key '%s'",
                                 svn_path_local_style(file, pool));
      else
        return SVN_NO_ERROR;
    }


  subpool = svn_pool_create(pool);
  section = svn_stringbuf_create("", subpool);
  option = svn_stringbuf_create("", subpool);
  value = svn_stringbuf_create("", subpool);

  /* The top-level values belong to the [DEFAULT] section */
  svn_err = parse_section(cfg, hkey, SVN_CONFIG__DEFAULT_SECTION,
                          option, value);
  if (svn_err)
    goto cleanup;

  /* Now enumerate the rest of the keys. */
  svn_stringbuf_ensure(section, SVN_REG_DEFAULT_NAME_SIZE);
  for (index = 0; ; ++index)
    {
      DWORD section_len = section->blocksize;
      FILETIME last_write_time;
      HKEY sub_hkey;

      err = RegEnumKeyEx(hkey, index, section->data, &section_len,
                         NULL, NULL, NULL, &last_write_time);
      if (err == ERROR_NO_MORE_ITEMS)
          break;
      if (err == ERROR_MORE_DATA)
        {
          svn_stringbuf_ensure(section, section_len);
          err = RegEnumKeyEx(hkey, index, section->data, &section_len,
                             NULL, NULL, NULL, &last_write_time);
        }
      if (err != ERROR_SUCCESS)
        {
          svn_err =  svn_error_create(SVN_ERR_MALFORMED_FILE, NULL,
                                      "Can't enumerate registry keys");
          goto cleanup;
        }

      err = RegOpenKeyEx(hkey, section->data, 0,
                         KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
                         &sub_hkey);
      if (err != ERROR_SUCCESS)
        {
          svn_err =  svn_error_create(SVN_ERR_MALFORMED_FILE, NULL,
                                      "Can't open existing subkey");
          goto cleanup;
        }

      svn_err = parse_section(cfg, sub_hkey, section->data, option, value);
      RegCloseKey(sub_hkey);
      if (svn_err)
        goto cleanup;
    }

 cleanup:
  RegCloseKey(hkey);
  svn_pool_destroy(subpool);
  return svn_err;
}
Ejemplo n.º 28
0
HRESULT CoCreateInstanceWithoutModel( REFCLSID rclsid, REFIID riid, void **ppv )
{
    HKEY key;
    DWORD len;
    LONG result;
    HRESULT hr = S_OK;
    OLECHAR guidString[128];

	wchar_t keyString[1024];
    wchar_t dllName[MAX_PATH];

    StringFromGUID2( rclsid, guidString, NumItems( guidString ) );

#ifndef _UNICODE
    wchar_t szID[64];              // the class ID to register.

    WideCharToMultiByte( CP_ACP, 0, guidString, -1, szID, sizeof( szID ), NULL, NULL );
    _stprintf_s( keyString, 1024, _T("CLSID\\%s\\InprocServer32"), szID );
#else
    _stprintf_s( keyString, 1024, _T("CLSID\\%s\\InprocServer32"), guidString );
#endif

    // Lets grab the DLL name now.
    result = RegOpenKeyEx( HKEY_CLASSES_ROOT, keyString, 0, KEY_READ, &key );
    if ( result == ERROR_SUCCESS )
    {
        DWORD type;
        result = RegQueryValueEx( key, NULL, NULL, &type, NULL, &len );
        if ((result == ERROR_SUCCESS) && ((type == REG_SZ) || (type == REG_EXPAND_SZ)))
        {
            result = RegQueryValueEx( key, NULL, NULL, &type, (BYTE*) dllName, &len );
            if (result == ERROR_SUCCESS)
            {
                // We've got the name of the DLL to load, so load it.
                HINSTANCE dll;

                dll = LoadLibraryEx( dllName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
                if ( dll != NULL )
                {
                    // We've loaded the DLL, so find the DllGetClassObject function.
                    FARPROC func;

                    func = GetProcAddress( dll, "DllGetClassObject" );
                    if ( func != NULL )
                    {
                        // Cool, lets call the function to get a class factory for
                        // the rclsid passed in.
                        IClassFactory *classFactory;
                        DLLGETCLASSOBJECT *dllGetClassObject = (DLLGETCLASSOBJECT*)func;

                        hr = dllGetClassObject( rclsid, IID_ICF, (void**)&classFactory );
                        if ( SUCCEEDED( hr ) )
                        {
                            //
                            // Ask the class factory to create an instance of the
                            // necessary object.
                            //
                            hr = classFactory->CreateInstance( NULL, riid, ppv );

                            // Release that class factory!
                            classFactory->Release();
                        }
                    }
                    else
                        hr = HRESULT_FROM_WIN32( GetLastError() );
                }
                else
                    hr = HRESULT_FROM_WIN32( GetLastError() );
            }
            else
                hr = HRESULT_FROM_WIN32( GetLastError() );
        }
        else
            hr = HRESULT_FROM_WIN32( GetLastError() );
        RegCloseKey( key );
    }
    else
        hr = HRESULT_FROM_WIN32( GetLastError() );
    return hr;
}
Ejemplo n.º 29
0
//----------------------------------------------------------------------------
// Fetch the user's default browser.
//----------------------------------------------------------------------------
bool GetBrowserCommandLineFromRegistry(std::string& sBrowser)
{
	LONG  nLong;
	HKEY  hKey;
	TCHAR sValue[MAX_PATH];
	DWORD nValueLength = sizeof(sValue);
	TCHAR sShortPath[MAX_PATH];

	sBrowser = TEXT("");

	// Find out what the preferred browser is by looking to see if .html is 
	// associated with NetscapeMarkup or htmlfile.
	if (RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT(".html"), 0, KEY_QUERY_VALUE, &hKey)  != ERROR_SUCCESS)
		return false;

	nLong = RegQueryValueEx(hKey, TEXT(""), NULL, NULL, (LPBYTE) sValue, &nValueLength);
	RegCloseKey(hKey);
	if (nLong != ERROR_SUCCESS)
		return false;

	string sTemp = sValue;
	sTemp += TEXT("\\shell\\open\\command");
	if (RegOpenKeyEx(HKEY_CLASSES_ROOT, sTemp.c_str(), 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
		return false;

	nValueLength = sizeof(sValue);
	nLong = RegQueryValueEx(hKey, "", NULL, NULL, (LPBYTE)sValue, &nValueLength);
	RegCloseKey(hKey);
	if (nLong != ERROR_SUCCESS)
		return false;

	sTemp = sValue;
	int nLocation = (int)(sTemp.find('\"'));
	if (nLocation == 0)
	{
		sTemp.erase(0, 1); // Remove the leading quote.
		nLocation = (int)(sTemp.find('\"', 1));
		if (nLocation != -1)
			sTemp.erase(nLocation, sTemp.length() - nLocation); // Remove the traling quote (and anything following it).

		DWORD nRetValue = GetShortPathName(sTemp.c_str(), sShortPath, MAX_PATH);
		if (nRetValue == 0 || nRetValue >= MAX_PATH)
			return false;
		else
			sBrowser = sShortPath;
	}
	else if (nLocation != -1)
	{
		sBrowser = sTemp;
		sBrowser.erase(0, nLocation);

		UINT nLen = sBrowser.length();
		while (nLen > 0 && (sBrowser[nLen - 1] == ' ' || 
			sBrowser[nLen - 1] == '\t' || sBrowser[nLen - 1] == '\n'))
		{
			sBrowser.erase(nLen - 1);
			nLen = sBrowser.length();
		}
	}

	return sBrowser.length() > 0;
}
Ejemplo n.º 30
0
void RepeatSysIdleTimerResetThread()
{
	HKEY hKey = NULL;
	DWORD dwBattSuspendTimeout = 0;
	DWORD dwACSuspendTimeout = 0;
	DWORD dwIdleTimerResetPeriod = 0;

	// Timer 백업 및 Unattendedmode 에서 Sleep 진입 되지 않도록 Timer Reset Thread 생성
	if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, RK_SYSTEM_TIMEOUT_PATH, 0, 0, &hKey) == ERROR_SUCCESS )
	{
		DWORD dwData = 0;
		DWORD dwDataSize = sizeof(dwData);

		if( RegQueryValueEx(hKey, RV_BATT_SUSPEND_TIMEOUT, NULL, NULL, (LPBYTE)&dwData, &dwDataSize) == ERROR_SUCCESS)
		{
			dwBattSuspendTimeout = dwData;
		}

		dwData = 0;
		if( RegQueryValueEx(hKey, RV_AC_SUSPEND_TIMEOUT, NULL, NULL, (LPBYTE)&dwData, &dwDataSize) == ERROR_SUCCESS)
		{
			dwACSuspendTimeout = dwData;
		}

		RegCloseKey(hKey);
		hKey = NULL;
	}

	RETAILMSG(1, (TEXT("[WSM] dwBattSuspendTimeout : %d \r\n"), dwBattSuspendTimeout ));
	RETAILMSG(1, (TEXT("[WSM] dwACSuspendTimeout : %d \r\n"), dwACSuspendTimeout ));


	dwIdleTimerResetPeriod = (dwBattSuspendTimeout < dwACSuspendTimeout)? dwBattSuspendTimeout:dwACSuspendTimeout;


	RETAILMSG(1, (TEXT("[WSM] dwIdleTimerResetPeriod : %d \r\n"), dwIdleTimerResetPeriod ));



	while(g_bRunningRepeatSysIdleTimerResetThread)
	{
		// dwIdleTimerResetPeriod 나누기 2 주기마다 리셋 시켜줌

		for(DWORD dwIdx = 0; dwIdx < dwIdleTimerResetPeriod / 2; dwIdx++)
		{
			if(g_bRunningRepeatSysIdleTimerResetThread == FALSE)
			{
				goto Exit;
			}
			Sleep(1000);
		}

		RETAILMSG(1, (TEXT("[WSM] System Idle Timer Reset! \r\n") ));
		SystemIdleTimerReset();
		
	}


Exit:

	RETAILMSG(1, (TEXT("[WSM] RepeatSysIdleTimerResetThread End \r\n") ));

	return;

}