Exemple #1
1
// (Usually internal) method to perform usb drive search
bool DeviceFinder::MappingUsbstorToDeviceNumber(std::map<std::string, int>& usbStorToDeviceMap)
{
    HRESULT hr;

    // Clear list of drive names
    usbStorToDeviceMap.clear();

    // Ensure pSvc is initialized
	if (!Initialize()) { Log(0, "ERROR: Unable to initialize for usbstor-deviceNumber mapping.\n");  return false; }

    // Use the IWbemServices pointer to make a WMI request for Win32_SerialPort
    IEnumWbemClassObject* pEnumerator = NULL;
	IWbemServices *pServices = (IWbemServices *)pSvc;	// Cast required as the public API doesn't include the type information
	if (pServices == NULL) { Log(0, "ERROR: Unable to get usbstor-deviceNumber mapping.\n");  return false; }
	hr = pServices->ExecQuery(bstr_t("WQL"), bstr_t("SELECT PNPDeviceID, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
    if (FAILED(hr)) { Log(0, "ERROR: Query for Win32_DiskDrive has failed: 0x%08x\n", hr); return false; }

    // Get the data from the query
    if (pEnumerator)
    {
        for (;;)
        {
            // Get next item in enumeration
            IWbemClassObject *pclsObj;
            ULONG uReturn = 0;
            hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

            // If no more items, exit loop
            if (uReturn == 0) { break; }

            // Get value of the "PNPDeviceID" property
            VARIANT vtProp;
            hr = pclsObj->Get(L"PNPDeviceID", 0, &vtProp, 0, 0);
            char usbstorId[256] = { 0 };
            wcstombs_s(NULL, usbstorId, vtProp.bstrVal, 255);                  // Convert to ASCII
            VariantClear(&vtProp);
//cerr << "[DRIVE:USBSTOR] " << usbstorId << endl;

            // Get value of the "DeviceID" property
            hr = pclsObj->Get(L"DeviceID", 0, &vtProp, 0, 0);
            char deviceId[256] = { 0 };
            wcstombs_s(NULL, deviceId, vtProp.bstrVal, 255);                    // Convert to ASCII
            unsigned int deviceNumber = GetDeviceNumber(vtProp.bstrVal);
            VariantClear(&vtProp);
//cerr << "[DRIVE:DEVICEID] " << deviceId << endl;
//cerr << "[DRIVE:DEVICENUMBER] " << deviceNumber << endl;
            //DiskDriveToLogicalDrive(deviceId);

#ifdef DEBUG_PRINT
            Log(3, "[USBSTOR->DEVICEID->DEVICENUMBER] %s -> %s -> %u\n", usbstorId, deviceId, deviceNumber);
#endif
            usbStorToDeviceMap[usbstorId] = deviceNumber;

            pclsObj->Release();
        }
        pEnumerator->Release();
    }

    return true;
}
Exemple #2
1
// Adapted mostly as-is from http://www.gamedev.net/topic/495075-how-to-retrieve-info-about-videocard/?view=findpost&p=4229170
// so credit goes to that post's author, and in turn, the author of the site mentioned in that post (which seems to be down?).
std::string GetVideoCardDriverVersion() {
	std::string retvalue = "";

	HRESULT hr;
	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	if (FAILED(hr)) {
		return retvalue;
	}

	IWbemLocator *pIWbemLocator = NULL;
	hr = CoCreateInstance(__uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, 
		__uuidof(IWbemLocator), (LPVOID *)&pIWbemLocator);
	if (FAILED(hr)) {
		CoUninitialize();
		return retvalue;
	}

	BSTR bstrServer = SysAllocString(L"\\\\.\\root\\cimv2");
	IWbemServices *pIWbemServices;
	hr = pIWbemLocator->ConnectServer(bstrServer, NULL, NULL, 0L, 0L, NULL,	NULL, &pIWbemServices);
	if (FAILED(hr)) {
		pIWbemLocator->Release();
		SysFreeString(bstrServer);
		CoUninitialize();
		return retvalue;
	}

	hr = CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, 
		NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL,EOAC_DEFAULT);
	
	BSTR bstrWQL = SysAllocString(L"WQL");
	BSTR bstrPath = SysAllocString(L"select * from Win32_VideoController");
	IEnumWbemClassObject* pEnum;
	hr = pIWbemServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);

	ULONG uReturned;
	VARIANT var;
	IWbemClassObject* pObj = NULL;
	if (!FAILED(hr)) {
		hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
	}

	if (!FAILED(hr) && uReturned) {
		hr = pObj->Get(L"DriverVersion", 0, &var, NULL, NULL);
		if (SUCCEEDED(hr)) {
			char str[MAX_PATH];
			WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, str, sizeof(str), NULL, NULL);
			retvalue = str;
		}
	}

	pEnum->Release();
	SysFreeString(bstrPath);
	SysFreeString(bstrWQL);
	pIWbemServices->Release();
	pIWbemLocator->Release();
	SysFreeString(bstrServer);
	CoUninitialize();
	return retvalue;
}
void
IPodDetector::checkConnectedDevices()
{
    IEnumWbemClassObject* currentDevicesEnumerator = NULL;
    queryCurrentlyConnectedDevices( &currentDevicesEnumerator );

    IWbemClassObject* device;
    ULONG returnCount = 0;

    while( currentDevicesEnumerator )
    {
        currentDevicesEnumerator->Next( WBEM_INFINITE,
                                        1,
                                        &device,
                                        &returnCount );
        if( 0 == returnCount )
        {
            break;
        }
        if( returnCount > 0 )
        {
            LOGL( 3, "Detected pre-connected iPod" );
            onDeviceConnected( device );
        }
        device->Release();
    }
    currentDevicesEnumerator->Release();
}
/**
 * Enumerates MSFT_NetIpAddress whose interface index is the same as the
 * adaptor's. Calls stringToAdaptorIP() for each object so that the
 * highest priority IP address is associated with the adaptor.
 */
static void readIpAddressesMsft(IWbemServices *pNamespace, SFLAdaptor *adaptor)
{
	BSTR queryLang = SysAllocString(L"WQL");
	wchar_t *query = L"SELECT * FROM MSFT_NetIpAddress WHERE InterfaceIndex=%u";
	wchar_t ipQuery[70];
	swprintf_s(ipQuery, 70, query, adaptor->ifIndex);
	IEnumWbemClassObject *ipEnum = NULL;
	HRESULT hr = pNamespace->ExecQuery(queryLang, ipQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &ipEnum);
	SysFreeString(queryLang);
	if (!SUCCEEDED(hr)) {
		myLog(LOG_ERR,"readIpAddressesMsft: ExecQuery() failed for query %S error=0x%x", ipQuery, hr);
		return;
	}
	IWbemClassObject *ipObj;
	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		ULONG ipCount = 0;
		hr = ipEnum->Next(WBEM_INFINITE, 1, &ipObj, &ipCount);
		if (ipCount == 0) {
			break;
		}
		VARIANT address;
		hr = ipObj->Get(L"IPAddress", 0, &address, 0, 0);
		if (WBEM_S_NO_ERROR == hr && V_VT(&address) == VT_BSTR)  {
			stringToAdaptorIp(address.bstrVal, adaptor);
		}
		VariantClear(&address);
		ipObj->Release();
	}
	ipEnum->Release();
}
/*
 *	Solution by: Simon Mourier
 *	From: http://stackoverflow.com/questions/5327203/how-to-access-cpus-heat-sensors
 *
 *	For linking use: Wbemuuid.lib
 *	Running info: application must run under administrator privileges!
 */
double SystemInfo::DiagnosticMgr::getCpuTemp()
{
	LONG result;
	LPLONG pTemperature = &result;
	*pTemperature = -1;
	HRESULT ci = CoInitialize(NULL); // needs comdef.h
	HRESULT hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
		RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE,
		NULL, EOAC_NONE, NULL);
	if (SUCCEEDED(hr))
	{
		IWbemLocator *pLocator; // needs Wbemidl.h & Wbemuuid.lib
		hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER , IID_IWbemLocator, (LPVOID*)&pLocator);
		if (SUCCEEDED(hr))
		{
			IWbemServices *pServices;
			BSTR ns = SysAllocString(L"root\\WMI");
			hr = pLocator->ConnectServer(ns, NULL, NULL, NULL, 0, NULL, NULL, &pServices);
			pLocator->Release();
			SysFreeString(ns);
			if (SUCCEEDED(hr))
			{
				BSTR query = SysAllocString(L"SELECT * FROM MSAcpi_ThermalZoneTemperature");
				BSTR wql = SysAllocString(L"WQL");
				IEnumWbemClassObject *pEnum;
				hr = pServices->ExecQuery(wql, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);
				SysFreeString(wql);
				SysFreeString(query);
				pServices->Release();
				if (SUCCEEDED(hr))
				{
					IWbemClassObject *pObject;
					ULONG returned;
					hr = pEnum->Next(-1, 1, &pObject, &returned);
					pEnum->Release();
					if (SUCCEEDED(hr))
					{
						BSTR temp = SysAllocString(L"CurrentTemperature");
						VARIANT v;
						VariantInit(&v);
						hr = pObject->Get(temp, 0, &v, NULL, NULL);
						pObject->Release();
						SysFreeString(temp);
						if (SUCCEEDED(hr))
						{
							*pTemperature = V_I4(&v);
						}
						VariantClear(&v);
					}
				}
			}
			if (ci == S_OK)
			{
				CoUninitialize();
			}
		}
	}
	double tempInTensOfKelvins = (double)*pTemperature;
	return (tempInTensOfKelvins > 0.0) ? ((double)*pTemperature / 10.0) - 273.15 : 0.0;
}
Exemple #6
0
static int get_username() {
	
	IEnumWbemClassObject *enumerator = 0;
	IWbemClassObject * object = 0;

	bool res = false;
	_username = bstr_t();
	enumerator = request(bstr_t("select UserName from Win32_ComputerSystem"));

	VARIANT vUsername;
	VariantInit(&vUsername);

	ULONG uReturn;
	for(;;) {
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(uReturn == 0) {
			break;
		}
		result = object->Get(L"UserName", 0, &vUsername, 0, 0);

		if (SUCCEEDED(result)) {
			_username = GetShortName(vUsername.bstrVal);
			res = true;
		}
		object->Release();
	}

	if (enumerator)
		enumerator->Release();

	//std::cout << "get_username(): " << _username << std::endl;

	return res;
}
Exemple #7
0
int wmi_get_cpu_frequency(float* pcpu_frequency) {

	assert(_initialized);
	assert(pcpu_frequency);

	float& cpu_frequency = *pcpu_frequency;

	IEnumWbemClassObject *enumerator = 0;
	IWbemClassObject * object = 0;

	// Use the IWbemServices pointer to make requests of WMI ----
	static const bstr_t WQL = bstr_t("WQL");
	static const bstr_t Query = bstr_t("SELECT CurrentClockSpeed FROM Win32_Processor");

	HRESULT result = services->ExecQuery(WQL,
		Query,
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&enumerator
	);

	if (FAILED(result)) {
		log_err("Query for operating system name failed."
					 " Error code = %d \n", result);
        services->Release();
        locator->Release();
        CoUninitialize();

		//TODO return valid error
        return -1;
    }

	VARIANT variant;
	ULONG uReturn;

	for(;;)
	{
		result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
			
		if(0 == uReturn) {
			break;
		}

		VariantInit(&variant);

		result = object->Get(L"CurrentClockSpeed", 0, &variant, 0, 0);
		if (result == WBEM_S_NO_ERROR) {
				//Variant::Print(variant);
				cpu_frequency = (float)variant.iVal;
		}


		object->Release();
	}

	if (enumerator)
		enumerator->Release();	

	return 0;
}
Exemple #8
0
bool CHardwareMonitor::IsOHMRunning()
{
	if ((m_pServicesOHM == NULL) || (m_pServicesSystem == NULL))
		return false;
	bool bOHMRunning = false;
	IEnumWbemClassObject* pEnumerator = NULL;
	HRESULT hr;
	hr = m_pServicesSystem->ExecQuery(L"WQL", L"Select * from win32_Process WHERE Name='OpenHardwareMonitor.exe'" , WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);  
	if (SUCCEEDED(hr))  
	{
		IWbemClassObject *pclsObj=NULL;  
		ULONG uReturn = 0;  
		hr = pEnumerator->Next(WBEM_INFINITE, 1,  &pclsObj, &uReturn);  
		if ((FAILED(hr)) || (0 == uReturn))
		{
			pEnumerator->Release();
			return false;
		}
		VARIANT vtProp;  
		VariantInit(&vtProp);  
		hr = pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);  
		int procId = static_cast<int>(vtProp.iVal);
		if (procId) {
			bOHMRunning = true;
		}
		pclsObj->Release();
		pEnumerator->Release();
	}
	return bOHMRunning;
}
 /**
 * Finds the associated Win32_NetworkAdapterConfiguration for Win32_NetworkAdapter adapterObj.
 * Iterates through the IP addresses associated with the adapter calling
 * stringToAdaptorIp() to choose the highest priority address (according to EnumIPSelectionPriority)
 * as the adapter address which is used to populate adapter->userData->ipAddr.
 * If two addresses have the same highest priority, then the first one seen is chosen.
 */
static void readIpAddressesWin32(IWbemServices *pNamespace, IWbemClassObject *adapterObj, SFLAdaptor *adaptor)
{
	IEnumWbemClassObject *configEnum;
	HRESULT hr = associatorsOf(pNamespace, adapterObj,
							   L"Win32_NetworkAdapterSetting",
							   L"Win32_NetworkAdapterConfiguration",
							   L"Setting", &configEnum);
	if (SUCCEEDED(hr)) {
		IWbemClassObject *configObj;
		ULONG configCount;
		hr = configEnum->Next(WBEM_INFINITE, 1, &configObj, &configCount);
		if (SUCCEEDED(hr) && configCount == 1) {
			VARIANT addresses;
			hr = configObj->Get(L"IPAddress", 0, &addresses, 0, 0);
			if (WBEM_S_NO_ERROR == hr && addresses.vt == (VT_ARRAY | VT_BSTR))  {
				SAFEARRAY *sa = V_ARRAY(&addresses);
				LONG lstart, lend;
				hr = SafeArrayGetLBound(sa, 1, &lstart);
				hr = SafeArrayGetUBound(sa, 1, &lend);
				BSTR *pbstr;
				hr = SafeArrayAccessData(sa, (void HUGEP **)&pbstr);
				if (SUCCEEDED(hr)) {
					for (LONG idx=lstart; idx <= lend; idx++) {		
						PCWSTR addrStr = pbstr[idx];
						stringToAdaptorIp(addrStr, adaptor);
					}
					SafeArrayUnaccessData(sa);
				}
			}
			VariantClear(&addresses);
			configObj->Release();
		}
		configEnum->Release();
	}
}
Exemple #10
0
static int get_num_core() {
	IEnumWbemClassObject *enumerator = 0;
	IWbemClassObject * object = 0;

	int res = -1;
	_num_core = 0;
	enumerator = request(bstr_t("select NumberOfCores from Win32_Processor"));

	VARIANT vUsername;
	VariantInit(&vUsername);

	ULONG uReturn;
	for(;;) {
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(uReturn == 0) {
			break;
		}
		result = object->Get(L"NumberOfCores", 0, &vUsername, 0, 0);

		if (SUCCEEDED(result)) {
			_num_core = vUsername.uiVal;
			res = 0;
		}
		object->Release();
	}

	if (enumerator)
		enumerator->Release();

	//std::cout << "get_num_core(): " << _num_core << std::endl;

	return res;
}
VARIANT* GpuCapabilitiesWindows::WMIquery(std::string wmiClass, std::string attribute) {

    // Code based upon:  "Example: Getting WMI Data from the Local Computer"
    // http://msdn2.microsoft.com/en-us/library/aa390423.aspx

    if (!isWMIinited()) {
        LWARNING("WMI not initiated");
        return 0;
    }

    HRESULT hres;
    VARIANT* result = 0;

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----
    IEnumWbemClassObject* pEnumerator = NULL;
    std::string query = "SELECT " + attribute + " FROM " + wmiClass;
    hres = pWbemServices_->ExecQuery(
        bstr_t("WQL"),
        bstr_t(query.c_str()),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        NULL,
        &pEnumerator);

    if (FAILED(hres)) {
        LWARNING("ERROR: WMI query failed: " << query);
        return 0;
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------

    IWbemClassObject* pclsObj = 0;
    ULONG uReturn = 0;

    if (pEnumerator) {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if (uReturn) {
            // Get the value of the attribute and store it in result
            result = new VARIANT;
            hr = pclsObj->Get(LPCWSTR(str2wstr(attribute).c_str()), 0, result, 0, 0);
        }
    }

    if (!result) {
        LWARNING("No WMI query result");
    }

    // Clean enumerator and pclsObject
    if (pEnumerator)
        pEnumerator->Release();
    if (pclsObj)
        pclsObj->Release();

    return result;

}
Exemple #12
0
/* Return the CPU usage in percent of this process */
int getcpu()
{
	HRESULT hres;
	int cpu = -1;

	/* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
	IEnumWbemClassObject* pEnumerator = NULL;

	BSTR Language = SysAllocString(L"WQL");
	BSTR Query    = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");

	hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);

	/* Query didn't work */
	if (!FAILED(hres))
	{
		IWbemClassObject *pclsObj = NULL;
		ULONG uReturn = 0;

		/* Iterate the query results */
		while (pEnumerator)
		{
			VARIANT vtProp;
			VariantInit(&vtProp);
			/* Next item */
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

			/* No more items left */
			if (uReturn == 0)
				break;

			/* Find process ID */
			hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
			if (!FAILED(hr))
			{
				/* Matches our process ID? */
				UINT pid = vtProp.uintVal;
				VariantClear(&vtProp);
				if (pid == GetCurrentProcessId())
				{					
					/* Get CPU percentage for this process */
					hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
					if (!FAILED(hr))
					{
						/* Deal with wide string ickyness. Who in their right
						 * mind puts a number in a bstrVal wide string item?!
						 */
						cpu = 0;
						std::wstringstream out(vtProp.bstrVal);
						out >> cpu;
						VariantClear(&vtProp);
					}
					pclsObj->Release();
					break;
				}
std::shared_ptr<CHardware> CHardwareFactory::newOpticalDiscDrive() const
{
    /*
    * IWbemServices::ExecQuery              http://msdn.microsoft.com/en-us/library/windows/desktop/aa392107%28v=VS.85%29.aspx
    * IWbemClassObject::Next                http://msdn.microsoft.com/en-us/library/windows/desktop/aa391453%28v=VS.85%29.aspx
    * IWbemClassObject::Get                 http://msdn.microsoft.com/en-us/library/windows/desktop/aa391442%28v=VS.85%29.aspx
    * Win32_CDROMDrive class                http://msdn.microsoft.com/en-us/library/windows/desktop/aa394081%28v=VS.85%29.aspx
    *
    * Creating a WMI Application Using C++  http://msdn.microsoft.com/en-us/library/windows/desktop/aa389762%28v=VS.85%29.aspx
    */

    IEnumWbemClassObject* enumerator = 0;

    HRESULT hr = mWbemServices->ExecQuery(BSTR(L"WQL"), BSTR(L"SELECT * FROM Win32_CDROMDrive"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 0, &enumerator);
    
    if (FAILED(hr))
    {
        throw CBasicException("ExecQuery failed");
    }

    std::list<std::string> opticalDriveList;

    while(enumerator)
    {
        IWbemClassObject* obj = 0;
        ULONG ret = 0;
        hr = enumerator->Next(WBEM_INFINITE, 1, &obj, &ret);

        if (ret == 0 || FAILED(hr))
        {
            break;
        }
        
        VARIANT vtProp;

        hr = obj->Get(L"Caption", 0, &vtProp, 0, 0);

        if (FAILED(hr))
        {
            continue;
        }

        opticalDriveList.push_back(CUtils::str2utf8(vtProp.bstrVal));

        VariantClear(&vtProp);

        obj->Release();
    }

    enumerator->Release();

    return std::shared_ptr<CHardware>(new CHardware(CHardware::OPTICALDISCDRIVE, opticalDriveList));
}
Exemple #14
0
/*
Check VMWare bios using WMI 
*/
BOOL vmware_wmi()
{
	IWbemServices *pSvc = NULL;
	IWbemLocator *pLoc = NULL;
	IEnumWbemClassObject* pEnumerator = NULL;
	BOOL bStatus = FALSE;
	HRESULT hr;

	// Init WMI
	bStatus = InitWMI(&pSvc, &pLoc);

	if (bStatus)
	{
		// If success, execute the desired query
		bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_PnPEntity"));
		if (bStatus)
		{
			// Get the data from the query
			IWbemClassObject *pclsObj = NULL;
			ULONG uReturn = 0;
			VARIANT vtProp;

			while (pEnumerator)
			{
				hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
				if (0 == uReturn)
					break;


				// Get the value of the Name property
				hr = pclsObj->Get(_T("DeviceId"), 0, &vtProp, 0, 0);
				//_tprintf(_T("DeviceId : %s"), vtProp.bstrVal);

				// release the current result object
				VariantClear(&vtProp);
				pclsObj->Release();

			}
		}
	}

	// Cleanup
	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();
	CoUninitialize();

	return TRUE;

}
static bool TryAddress(const std::string& ipAddress)
{
    IEnumWbemClassObject* enumerator = 0;

    std::wstring query(L"SELECT * FROM Win32_PingStatus WHERE (Address=\"");
    query.append(::UTF8ToWide(ipAddress));
    query.append(L"\")");
    BSTR queryBstr = SysAllocString(query.c_str());

    HRESULT result = service->ExecQuery(L"WQL", queryBstr,
        WBEM_FLAG_FORWARD_ONLY, 0, &enumerator);
    SysFreeString(queryBstr);

    if (FAILED(result))
    {
        HandleHResultError("Failed to execute address query", result);
        return false;
    }

    ULONG count;
    IWbemClassObject* ping = 0;
    result = enumerator->Next(WBEM_INFINITE, 1L, &ping, &count);
    if (FAILED(result))
    {
        HandleHResultError("Failed to get ping data", result);
        enumerator->Release();
        return false;
    }

    if (count < 1)
    {
        LogError("Did not find ping result");
        enumerator->Release();
        ping->Release();
        return false;
    }

    variant_t pingValue;
    result = ping->Get(L"StatusCode", 0, &pingValue, 0, 0);
    if (FAILED(result))
    {
        HandleHResultError("Could not get ping StatusCode value", result);
        enumerator->Release();
        ping->Release();
        return false;
    }

    ping->Release();
    return static_cast<int>(pingValue) == 0;
}
Exemple #16
0
/**
 * Test to see whether we are running on a system with Hyper-V enabled.
 * We consider Hyper-V to be running (and can export per vm stats) if
 * the Hyper-V related services (nvspwmi, vmm, vhdsvc) are running and
 * we can access the WMI namespace root\virtualization (ie v1 for Win 2008).
 * We do not check for the v2 namespace, since this is not required for 
 * per vm stats.
 * The ability connect to the sFlow filter for export of packet samples 
 * and counter samples for the virtual switch is made separately.
 */
BOOL testForHyperv()
{
	BSTR path = SysAllocString(WMI_CIMV2_NS);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	SysFreeString(path);
	if (WBEM_S_NO_ERROR != hr) {
		myLog(LOG_ERR,"testForHyperv: connectToWMI failed for namespace %S", path);
		return false;
	}
	//Test for Hyper-V services
	BOOL gotHyperV = false;
	BSTR queryLang = SysAllocString(L"WQL");
	BSTR query = SysAllocString(L"SELECT * FROM Win32_Service WHERE Name=\"nvspwmi\" OR Name=\"vmms\" OR Name=\"vhdsvc\"");
	IEnumWbemClassObject *serviceEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &serviceEnum);
	SysFreeString(query);
	SysFreeString(queryLang);
	if (WBEM_S_NO_ERROR != hr) {
		myLog(LOG_ERR, "testForHyperv: ExecQuery() failed for %S error=0x%x", query, hr);
	} else {
		IWbemClassObject *serviceObj = NULL;
		ULONG uReturned = 0;
		BOOL gotHyperVSvc = false;
		hr = serviceEnum->Next(WBEM_INFINITE, 1, &serviceObj, &uReturned);
		if (SUCCEEDED(hr)) {
			if (uReturned == 1) {
				gotHyperVSvc = true;
				serviceObj->Release();
			}
		}
		serviceEnum->Release();
		pNamespace->Release();
		if (gotHyperVSvc) { //now check that we have the v1 virtualization namespace
			CoUninitialize();
			path = SysAllocString(WMI_VIRTUALIZATION_NS_V1);
			hr = connectToWMI(path, &pNamespace);
			SysFreeString(path);
			if (WBEM_NO_ERROR == hr) {
				gotHyperV = true;
				pNamespace->Release();
			}
		}
	}
	CoUninitialize();
	myLog(LOG_INFO, "testForHyperv: HyperV=%u", gotHyperV);
	return gotHyperV;
}
Exemple #17
0
int getTimeProcessors(IWbemServices *pSvc,ULONG *ulVal ,int n)
{
	int nError = 0;
    IEnumWbemClassObject* pEnumerator = NULL;
    HRESULT hres = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_PerfRawData_PerfOS_Processor",
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);

    if (FAILED(hres))
    {
        ShowMessage("Query for operating system name failed.");
        return 1;
    }

    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;
	int nCtr = 0;

    while (nCtr<n)
    {
        pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;
        VariantInit(&vtProp);

		pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
		ulVal[nCtr] = _wtol(vtProp.bstrVal);
        VariantClear(&vtProp);
		pclsObj->Get(L"TimeStamp_Sys100NS", 0, &vtProp, 0, 0);// время в милисекундах прошедших с получночи 1 января 1970 года
		ulVal[nCtr+1] = _wtol(vtProp.bstrVal);
		VariantClear(&vtProp);
		nCtr+=2;
    }
	pclsObj->Release();
	pEnumerator->Release();

	return nError;
}
void ListClasses(IWbemServices *pNamespace)
{
    HRESULT hr;
    IEnumWbemClassObject *pEnum = NULL;

    hr = pNamespace->CreateClassEnum(NULL, 0, NULL, &pEnum);
    if(SUCCEEDED(hr))
    {

        // Note that even though security was set on the namespace pointer, it must 
        // also be set on this pointer since COM will revert back to the default
        // settings for any new pointers!

        hr = SetProxySecurity(pEnum);
        if(SUCCEEDED(hr))
        {
            IWbemClassObject* Array[1];
            Array[0] = NULL;
            ULONG uRet = 0;
            while (SUCCEEDED(hr = pEnum->Next(10000, 1, Array, &uRet)) && Array[0])
            {
                // Note that IWbemClassObjects are inproc and thus have no proxy.
                // Therefore, they never need CoSetProxyBlanket.

                BSTR strText;
                IWbemClassObject* pObj = Array[0];
                hr = pObj->GetObjectText(0, &strText);

                if(SUCCEEDED(hr) && strText)
                {
                    printf("\nGot class %S", strText);
                    SysFreeString(strText);
                }
                pObj->Release();
                Array[0] = NULL;
            }
        }
        else
            printf("\nFAILED TO SET SECURITY FOR ENUMERATOR!!!!! hr = 0x%x", hr);
        pEnum->Release();
    }
}
Exemple #19
0
void WMIMonitor(ScriptValue &s, ScriptValue *args) {
	HRESULT hr;
	int i;
	for (i=0; i<numWmiServers; i++) {
		if (!scriptstrcmp(args[0].stringVal, wmiServers[i].name)) break;
	}
	if (i == numWmiServers) {
		if (!srealloc(wmiServers, sizeof(WMIServer)*(numWmiServers+1))) return;

		InitCom();
		if (FAILED(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_SECURE_REFS, NULL))) {
			return;
		}

		IWbemLocator *locator;
		hr = CoCreateInstance(CLSID_WbemLocator, 0, 
			CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &locator);
	 
		if (FAILED(hr)) {
			locator = 0;
			UninitCom();
			return;
		}

		wmiServers[i].name = args[0].stringVal;

		BSTR bstr = UTF8toBSTR(args[0].stringVal->value, &args[0].stringVal->len);
		if (!bstr) {
			locator->Release();
			UninitCom();
			return;
		}
		wmiServers[i].services = 0;
		hr = locator->ConnectServer(bstr, 0, 0, 0, WBEM_FLAG_CONNECT_USE_MAX_WAIT, 0, 0, &wmiServers[i].services);
		freeBSTR(bstr);
		if (FAILED(hr)) {
			locator->Release();
			UninitCom();
			return;
		}

		args[0].stringVal->AddRef();
		numWmiServers++;
	}
	wmiServers[i].refs++;
	BSTR bstr = UTF8toBSTR(args[1].stringVal->value, &args[1].stringVal->len);
	if (bstr) {
		IEnumWbemClassObject *penum;
		HRESULT res = wmiServers[i].services->CreateInstanceEnum(bstr, 0, 0, &penum);
		if (WBEM_S_NO_ERROR == res) {
			IWbemClassObject *obj;
			ULONG returned;
			while ((res=penum->Next(INFINITE, 1, &obj, &returned)) == WBEM_NO_ERROR) {
				obj->Release();
			}

			penum->Release();
		}
		//wmiServers[i].services->GetObjectW(bstr, 0, 0, 
		freeBSTR(bstr);
	}
}
Exemple #20
0
int MyMacAddress::WMI_GetMacAddress(int iQueryType, int iSize)
{
	ZeroMemory(PermanentAddress, sizeof(PermanentAddress));
	ZeroMemory(MACAddress, sizeof(MACAddress));
	HRESULT hres;  	int	iTotal = 0;
	if( (iQueryType  < 0) || (iQueryType >= sizeof(szWQLQuery)/sizeof(T_WQL_QUERY)) ) 
	{  		
		return -1;
	}    	
	hres = CoInitializeEx( NULL, COINIT_MULTITHREADED); 
	if( FAILED(hres) )      
	{          
		return -2; 
	}        
	hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
	if( FAILED(hres))
	{          
		CoUninitialize();
		return -2;      
	}        	
	IWbemLocator *pLoc = NULL;
	hres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast <LPVOID*>(&pLoc));
	if( FAILED(hres))
	{  		
		CoUninitialize();
		return -2;      
	}
	IWbemServices *pSvc = NULL;
	hres = pLoc->ConnectServer(_bstr_t( L"ROOT\\CIMV2" ), NULL, NULL, NULL, 0, NULL, NULL, &pSvc);
	if( FAILED(hres))      
	{  		
		pLoc->Release();           
		CoUninitialize();          
		return -2;      
	}    	
	// 设置请求代理的安全级别
	hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
	if(FAILED(hres))
	{          
		pSvc->Release();
		pLoc->Release(); 
		CoUninitialize();  
		return -2;      
	}       
	IEnumWbemClassObject *pEnumerator = NULL;
	hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t( szWQLQuery[iQueryType].szSelect), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);  	
	if(FAILED(hres)) 
	{          
		pSvc->Release();
		pLoc->Release();  
		CoUninitialize();         
		return -3;      
	}        
	while(pEnumerator)
	{  		
		IWbemClassObject *pclsObj = NULL;
		ULONG uReturn = 0;    	
		if(iTotal >= iSize)  
		{  			
			break;  	
		}           
		pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);            
		if( uReturn == 0 )         
		{              
			break;
		}    		
		VARIANT	vtProperty;  	
		TCHAR szProperty[128]; 
		// 获取网卡范例ID		
		VariantInit( &vtProperty);	  	
		pclsObj->Get( szWQLQuery[iQueryType].szProperty, 0, &vtProperty, NULL, NULL );  
		StringCchCopy( szProperty, sizeof(szProperty)/sizeof(TCHAR), W2T(vtProperty.bstrVal) );  
		VariantClear( &vtProperty );    			
		if( GetPNPDeviceID( szProperty))  	
		{  			
			iTotal++;  		
		}  		  		
		pclsObj->Release();  
	}
	// 释放资源  
	pEnumerator->Release(); 
	pSvc->Release();     
	pLoc->Release();   
	CoUninitialize();     
	return iTotal;  
}
Exemple #21
0
//This is copy pasted from Microsoft. pretty poorly written code, 
//-----------------------------------------------------------------------------
// Enum each PNP device using WMI and check each device ID to see if it contains 
// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it's an XInput device
// Unfortunately this information can not be found by just using DirectInput 
//-----------------------------------------------------------------------------
bool IsXInputDevice( const GUID* pGuidProductFromDirectInput )
{
    IWbemLocator*           pIWbemLocator  = NULL;
    IEnumWbemClassObject*   pEnumDevices   = NULL;
    IWbemClassObject*       pDevices[20]   = {0};
    IWbemServices*          pIWbemServices = NULL;
    BSTR                    bstrNamespace  = NULL;
    BSTR                    bstrDeviceID   = NULL;
    BSTR                    bstrClassName  = NULL;
    DWORD                   uReturned      = 0;
    bool                    bIsXinputDevice= false;
    UINT                    iDevice        = 0;
    VARIANT                 var;
    HRESULT                 hr;

    // CoInit if needed
    hr = CoInitialize(NULL);
    bool bCleanupCOM = SUCCEEDED(hr);

    // Create WMI
    hr = CoCreateInstance( __uuidof(WbemLocator),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof(IWbemLocator),
                           (LPVOID*) &pIWbemLocator);
    if( FAILED(hr) || pIWbemLocator == NULL )
        goto LCleanup;

    bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto LCleanup;        
    bstrClassName = SysAllocString( L"Win32_PNPEntity" );   if( bstrClassName == NULL ) goto LCleanup;        
    bstrDeviceID  = SysAllocString( L"DeviceID" );          if( bstrDeviceID == NULL )  goto LCleanup;        
    
    // Connect to WMI 
    hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L, 
                                       0L, NULL, NULL, &pIWbemServices );
    if( FAILED(hr) || pIWbemServices == NULL )
        goto LCleanup;

    // Switch security level to IMPERSONATE. 
    CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
                       RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );                    

    hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices ); 
    if( FAILED(hr) || pEnumDevices == NULL )
        goto LCleanup;

    // Loop over all devices
    for( ;; )
    {
        // Get 20 at a time
        hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );
        if( FAILED(hr) )
            goto LCleanup;
        if( uReturned == 0 )
            break;

        for( iDevice=0; iDevice<uReturned; iDevice++ )
        {
            // For each device, get its device ID
            hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL );
            if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )
            {
                // Check if the device ID contains "IG_".  If it does, then it's an XInput device
				    // This information can not be found from DirectInput 
                if( wcsstr( var.bstrVal, L"IG_" ) )
                {
                    // If it does, then get the VID/PID from var.bstrVal
                    DWORD dwPid = 0, dwVid = 0;
                    WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );
                    if( strVid && swscanf_s( strVid, L"VID_%4X", &dwVid ) != 1 )
                        dwVid = 0;
                    WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
                    if( strPid && swscanf_s( strPid, L"PID_%4X", &dwPid ) != 1 )
                        dwPid = 0;

                    // Compare the VID/PID to the DInput device
                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );
                    if( dwVidPid == pGuidProductFromDirectInput->Data1 )
                    {
                        bIsXinputDevice = true;
                        goto LCleanup;
                    }
                }
            }   
            SAFE_RELEASE( pDevices[iDevice] );
        }
    }

LCleanup:
    if(bstrNamespace)
        SysFreeString(bstrNamespace);
    if(bstrDeviceID)
        SysFreeString(bstrDeviceID);
    if(bstrClassName)
        SysFreeString(bstrClassName);
    for( iDevice=0; iDevice<20; iDevice++ )
        SAFE_RELEASE( pDevices[iDevice] );
    SAFE_RELEASE( pEnumDevices );
    SAFE_RELEASE( pIWbemLocator );
    SAFE_RELEASE( pIWbemServices );

    if( bCleanupCOM )
        CoUninitialize();

    return bIsXinputDevice;
}
/*
================
XInputChecker::XInputChecker
================
*/
XInputChecker::XInputChecker() {
	// CoInit if needed
	HRESULT hr = CoInitialize( OG_NULL );
	bool bCleanupCOM = SUCCEEDED( hr );

	// Create WMI
	IWbemLocator* pIWbemLocator = OG_NULL;
	hr = CoCreateInstance( __uuidof( WbemLocator ), OG_NULL, CLSCTX_INPROC_SERVER, __uuidof( IWbemLocator ), ( LPVOID* )&pIWbemLocator );
	if( FAILED( hr ) || pIWbemLocator == OG_NULL ) {
		if( bCleanupCOM )
			CoUninitialize();
		return;
	}

	IEnumWbemClassObject* pEnumDevices = OG_NULL;
	IWbemServices* pIWbemServices = OG_NULL;
	IWbemClassObject* pDevices[20] = {0};

	BSTR bstrDeviceID = OG_NULL;
	BSTR bstrClassName = OG_NULL;
	BSTR bstrNamespace = OG_NULL;

	// Do just once
	do {
		bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );	if( bstrNamespace == OG_NULL )	break;
		bstrDeviceID = SysAllocString( L"DeviceID" );				if( bstrDeviceID == OG_NULL )	break;
		bstrClassName = SysAllocString( L"Win32_PNPEntity" );		if( bstrClassName == OG_NULL )	break;

		// Connect to WMI
		hr = pIWbemLocator->ConnectServer( bstrNamespace, OG_NULL, OG_NULL, 0L, 0L, OG_NULL, OG_NULL, &pIWbemServices );
		if( FAILED( hr ) || pIWbemServices == OG_NULL )
			break;

		// Switch security level to IMPERSONATE
		CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, OG_NULL,
						   RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, OG_NULL, 0 );

		// Get list of Win32_PNPEntity devices
		hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, OG_NULL, &pEnumDevices );
		if( FAILED( hr ) || pEnumDevices == OG_NULL )
			break;

		// Loop over all devices
		DWORD uReturned = 0;
		VARIANT var;
		for( ; ; ) {
			// Get 20 at a time
			hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );
			if( FAILED( hr ) || uReturned == 0 )
				break;

			for( int i = 0; i < uReturned; i++ ) {
				// For each device, get its device ID
				hr = pDevices[i]->Get( bstrDeviceID, 0L, &var, OG_NULL, OG_NULL );
				if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != OG_NULL ) {
					// Check if the device ID contains "IG_".  If it does, then it’s an XInput device
					// Unfortunately this information can not be found by just using DirectInput
					if( wcsstr( var.bstrVal, L"IG_" ) ) {
						// If it does, then get the VID/PID from var.bstrVal
						DWORD dwPid = 0, dwVid = 0;
						WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );
						if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
							dwVid = 0;
						WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
						if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
							dwPid = 0;

						listIds.Alloc() = MAKELONG( dwVid, dwPid );
					}
				}
				SAFE_RELEASE( pDevices[i] );
			}
		}
	}
	while( 0 ); // Do just once

	if( bstrNamespace )
		SysFreeString( bstrNamespace );
	if( bstrDeviceID )
		SysFreeString( bstrDeviceID );
	if( bstrClassName )
		SysFreeString( bstrClassName );

	for( int i=0; i<20; i++ )
		SAFE_RELEASE( pDevices[i] );
	SAFE_RELEASE( pEnumDevices );
	SAFE_RELEASE( pIWbemLocator );
	SAFE_RELEASE( pIWbemServices );

	if( bCleanupCOM )
		CoUninitialize();
}
Exemple #23
0
//-----------------------------------------------------------------------------
// Enum each PNP device using WMI and check each device ID to see if it contains 
// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then itӳ an XInput device
// Unfortunately this information can not be found by just using DirectInput.
// Checking against a VID/PID of 0x028E/0x045E won't find 3rd party or future 
// XInput devices.
//
// This function stores the list of xinput devices in a linked list 
// at g_pXInputDeviceList, and IsXInputDevice() searchs that linked list
//-----------------------------------------------------------------------------
HRESULT SetupForIsXInputDevice()
{
    IWbemServices* pIWbemServices = NULL;
    IEnumWbemClassObject* pEnumDevices = NULL;
    IWbemLocator* pIWbemLocator = NULL;
    IWbemClassObject* pDevices[20] = {0};
    BSTR bstrDeviceID = NULL;
    BSTR bstrClassName = NULL;
    BSTR bstrNamespace = NULL;
    DWORD uReturned = 0;
    bool bCleanupCOM = false;
    UINT iDevice = 0;
    VARIANT var;
    HRESULT hr;

    // CoInit if needed
    hr = CoInitialize( NULL );
    bCleanupCOM = SUCCEEDED( hr );

    // Create WMI
    hr = CoCreateInstance( __uuidof( WbemLocator ),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof( IWbemLocator ),
                           ( LPVOID* )&pIWbemLocator );
    if( VP_FAILED( hr ) || pIWbemLocator == NULL )
        goto LCleanup;

    // Create BSTRs for WMI
    bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" ); if( bstrNamespace == NULL ) goto LCleanup;
    bstrDeviceID = SysAllocString( L"DeviceID" );           if( bstrDeviceID == NULL )  goto LCleanup;
    bstrClassName = SysAllocString( L"Win32_PNPEntity" );    if( bstrClassName == NULL ) goto LCleanup;

    // Connect to WMI 
    hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L,
                                       0L, NULL, NULL, &pIWbemServices );
    if( VP_FAILED( hr ) || pIWbemServices == NULL )
        goto LCleanup;

    // Switch security level to IMPERSONATE
    CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
                       RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0 );

    // Get list of Win32_PNPEntity devices
    hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices );
    if( VP_FAILED( hr ) || pEnumDevices == NULL )
        goto LCleanup;

    // Loop over all devices
    for(; ; )
    {
        // Get 20 at a time
        hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );
        if( VP_FAILED( hr ) )
            goto LCleanup;
        if( uReturned == 0 )
            break;

        for( iDevice = 0; iDevice < uReturned; iDevice++ )
        {
            // For each device, get its device ID
            hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL );
            if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )
            {
                // Check if the device ID contains "IG_".  If it does, then itӳ an XInput device
                // Unfortunately this information can not be found by just using DirectInput 
                if( wcsstr( var.bstrVal, L"IG_" ) )
                {
                    // If it does, then get the VID/PID from var.bstrVal
                    DWORD dwPid = 0, dwVid = 0;
                    WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );
                    if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
                        dwVid = 0;
                    WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
                    if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
                        dwPid = 0;

                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );

                    // Add the VID/PID to a linked list
                    XINPUT_DEVICE_NODE* pNewNode = new XINPUT_DEVICE_NODE;
                    if( pNewNode )
                    {
                        pNewNode->dwVidPid = dwVidPid;
                        pNewNode->pNext = g_pXInputDeviceList;
                        g_pXInputDeviceList = pNewNode;
                    }
                }
            }
            SAFE_RELEASE( pDevices[iDevice] );
        }
    }

LCleanup:
    if( bstrNamespace )
        SysFreeString( bstrNamespace );
    if( bstrDeviceID )
        SysFreeString( bstrDeviceID );
    if( bstrClassName )
        SysFreeString( bstrClassName );
    for( iDevice = 0; iDevice < 20; iDevice++ )
    SAFE_RELEASE( pDevices[iDevice] );
    SAFE_RELEASE( pEnumDevices );
    SAFE_RELEASE( pIWbemLocator );
    SAFE_RELEASE( pIWbemServices );

    return hr;
}
void EnumSerialFromWMI(std::vector<int> &ports, std::vector<std::string> &friendlyNames)
{
	ports.clear();
	friendlyNames.clear();

	HRESULT hr;
	IWbemLocator *pLocator = NULL;
	IWbemServices *pServicesSystem = NULL;

	hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLocator);
	if (FAILED(hr))
	{
		return;
	}
	hr = pLocator->ConnectServer(L"root\\CIMV2", NULL, NULL, NULL, 0, NULL, NULL, &pServicesSystem);
	if (pServicesSystem == NULL)
	{
		pLocator->Release();
		return;
	}

	int dindex = 0;
	std::string query = "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"";
	IEnumWbemClassObject* pEnumerator = NULL;
	hr = pServicesSystem->ExecQuery(L"WQL", bstr_t(query.c_str()), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
	if (!FAILED(hr))
	{
		// Get the data from the query
		IWbemClassObject *pclsObj = NULL;
		while (pEnumerator)
		{
			ULONG uReturn = 0;
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
			if (FAILED(hr) || (0 == uReturn))
			{
				break;
			}

			VARIANT vtProp;
			VariantInit(&vtProp);
			HRESULT hrGet = pclsObj->Get(L"Name", 0, &vtProp, NULL, NULL);
			if (SUCCEEDED(hrGet) && (vtProp.vt == VT_BSTR) && (wcslen(vtProp.bstrVal) > 3))
			{
				std::string itemName = _bstr_t(vtProp.bstrVal);
				VariantClear(&vtProp);

				size_t spos = itemName.find("(COM");
				if (spos != std::string::npos)
				{
					std::string tmpstr = itemName.substr(spos + 4);
					spos = tmpstr.find(")");
					if (spos != std::string::npos)
					{
						tmpstr = tmpstr.substr(0, spos);
						int nPort = atoi(tmpstr.c_str());
						ports.push_back(nPort);
						friendlyNames.push_back(itemName);
					}
				}
			}
			pclsObj->Release();
		}
		pEnumerator->Release();
	}
	pServicesSystem->Release();
	pLocator->Release();
}
Exemple #25
0
void QtWMI::OnQueryWMI()
{		
	CString strQuery;
	strQuery.Format(L"select * from Win32_%s", ui.cboWMIClasses->currentText().toStdWString().c_str() );	
	IWbemLocator *pLoc = NULL;	
	IWbemServices *pSvc = NULL;
	IEnumWbemClassObject* pEnumerator = NULL;
	IWbemClassObject *pclsObj=NULL;
	HRESULT hr=E_FAIL;

	do 
	{
		hr=CoCreateInstance(CLSID_WbemLocator,0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
		if (FAILED(hr) )		break;

		hr=pLoc->ConnectServer(	_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
		if (FAILED(hr) )		break;

		hr=CoSetProxyBlanket( pSvc,  RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
			RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );
		if (FAILED(hr) )		break;

		hr=pSvc->ExecQuery( _bstr_t(L"WQL"),  bstr_t(strQuery), 
			WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,  NULL, &pEnumerator);
		if (FAILED(hr) )		break;

		ULONG		uReturn=0;
		variant_t		vtProp;	
		vtProp.Clear();						
		SAFEARRAY* psaNames=NULL;
		LONG nLower=0, nUpper=0;		
		_bstr_t		PropName;
		CString s;

		while (pEnumerator)
		{
			pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
			if(!uReturn)     break;   

			hr=pclsObj->GetNames(NULL, WBEM_FLAG_ALWAYS | WBEM_FLAG_NONSYSTEM_ONLY, NULL, &psaNames);
			if (hr==WBEM_S_NO_ERROR )
			{
				nLower=nUpper=0;

				SafeArrayGetLBound(psaNames, 1, &nLower);
				SafeArrayGetUBound(psaNames, 1, &nUpper);
				ui.lbDebug->clear();

				for (long i = nLower; i <= nUpper; i++) 
				{					
					SafeArrayGetElement(psaNames, &i, &PropName);	
					s.Format(L"%s", PropName);							
					hr = pclsObj->Get(s, 0, &vtProp, 0, 0);					
					if (hr==WBEM_S_NO_ERROR)																
						DisplayVariantValues(s, vtProp);	
					vtProp.Clear();						
				}					
			}
			if (psaNames)
				::SafeArrayDestroy(psaNames);	
			SAFE_RELEASE(pclsObj);	
		}		

	} while (0);

	SAFE_RELEASE(pEnumerator);
	SAFE_RELEASE(pclsObj);	
	SAFE_RELEASE(pSvc);
	SAFE_RELEASE(pLoc);
}
int main(int argc, char **argv)
{
    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x"
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------

    hres = CoInitializeSecurity(
        nullptr,
        -1,                          // COM authentication
        nullptr,                        // Authentication services
        nullptr,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        nullptr,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        nullptr                         // Reserved
        );


    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;                    // Program has failed.
    }

    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = nullptr;

    hres = CoCreateInstance(
        CLSID_WbemLocator,
        nullptr,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, reinterpret_cast<LPVOID *>(&pLoc));

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: -----------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = nullptr;

    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hres = pLoc->ConnectServer(
        _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
        nullptr,                    // User name. NULL = current user
        nullptr,                    // User password. NULL = current
        nullptr,                       // Locale. NULL indicates current
        NULL,                    // Security flags.
        nullptr,                       // Authority (for example, Kerberos)
        nullptr,                       // Context object 
        &pSvc                    // pointer to IWbemServices proxy
        );

    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x"
            << hex << hres << endl;
        pLoc->Release();
        CoUninitialize();
        return 1;                // Program has failed.
    }

    //cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    hres = CoSetProxyBlanket(
        pSvc,                        // Indicates the proxy to set
        RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
        nullptr,                        // Server principal name 
        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
        nullptr,                        // client identity
        EOAC_NONE                    // proxy capabilities 
        );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    IEnumWbemClassObject* pEnumerator = nullptr;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"),
        bstr_t("SELECT * FROM Win32_Process"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        nullptr,
        &pEnumerator);

    if (FAILED(hres))
    {
        cout << "Query for processes failed."
            << " Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------

    IWbemClassObject *pclsObj = nullptr;
    ULONG uReturn = 0;
    int i = 0;
    while (pEnumerator)
    {
        i++;
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if (0 == uReturn)
        {
            break;
        }

        VARIANT vtId;
        pclsObj->Get(L"ProcessId", 0, &vtId, nullptr, nullptr);
        wprintf_s(L"%d\n", vtId.intVal);
        VARIANT vtName;
        pclsObj->Get(L"Name", 0, &vtName, nullptr, nullptr);
        if (vtName.bstrVal != nullptr)
            wprintf_s(L"%ls\n", vtName.bstrVal);
        else
            wprintf_s(L"\n");
        VARIANT vtCmd;
        pclsObj->Get(L"CommandLine", 0, &vtCmd, nullptr, nullptr);
        if (vtCmd.bstrVal != nullptr)
            wprintf_s(L"%ls\n", vtCmd.bstrVal);
        else
            wprintf_s(L"\n");
        VariantClear(&vtId);
        VariantClear(&vtName);
        VariantClear(&vtCmd);

        pclsObj->Release();
    }
    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    CoUninitialize();
    return 0;   // Program successfully completed.
}
Exemple #27
0
	tstring CCliMgr::GetWmiInfo( LPCTSTR lpszClass,LPCTSTR lpszField)
	{
		tstring SysInfo,strtmp;
		HRESULT ret;
		ret = CoInitialize(NULL);
		ret = CoInitializeSecurity( NULL,
			-1,
			NULL,
			NULL,
			RPC_C_AUTHN_LEVEL_PKT,
			RPC_C_IMP_LEVEL_IMPERSONATE,
			NULL,
			EOAC_NONE,
			0
			);
		if (ret == S_OK || ret== RPC_E_TOO_LATE )
		{
			IWbemLocator * pIWbemLocator = NULL;
			IWbemServices * pWbemServices = NULL;
			IEnumWbemClassObject * pEnumObject  = NULL;
			BSTR bstrNamespace = (L"root\\cimv2");// 通过 IWbemLocator 和 IWbemServices 这两个 COM 接口访问 WMI, 获取系统信息
			if(CoCreateInstance (CLSID_WbemAdministrativeLocator, NULL,
				CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_IUnknown ,(void**)&pIWbemLocator) 
				== S_OK)
			{
				if(pIWbemLocator->ConnectServer(
					bstrNamespace,  // Namespace
					NULL,			// Userid
					NULL,           // PW
					NULL,           // Locale
					0,              // flags
					NULL,           // Authority
					NULL,           // Context
					&pWbemServices
					) == S_OK)
				{
					HRESULT hRes;
					_bstr_t strQuery = (L"Select * from Win32_OperatingSystem");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "操作系统的名称: "+_getWmiInfo(pClassObject,"Caption")+"\r\n";
								SysInfo = SysInfo + strtmp;
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_DiskDrive");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "硬盘的Model: "+_getWmiInfo(pClassObject,"Model")+"\r\n";
								SysInfo = SysInfo + strtmp;
								m_pLogger->WriteLog(LM_INFO, TEXT("硬盘的Model: %s"),_getWmiInfo(pClassObject,"Model").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}					
					strQuery = (L"Select * from Win32_LogicalDisk");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							while( pEnumObject->Next( WBEM_INFINITE, 
								uCount, &pClassObject, &uReturned) == S_OK )
							{
								if (atoi(_getWmiInfo(pClassObject,"DriveType").c_str()) != 3)
									continue;
								tstring str;
								str =_getWmiInfo(pClassObject,"Name");
								strtmp = "盘符: " +str+"    ";
								m_pLogger->WriteLog(LM_INFO, TEXT("盘符: %s"),str.c_str());
								tstring drv;
								drv += toupper(str[0]);										
								if(m_Hy.IsDriverProtected((char *)drv.c_str()))
								{
									strtmp = strtmp+ "还原状态: 保护 ";
									m_pLogger->WriteLog(LM_INFO, TEXT("还原状态: 保护 "));
								}
								else
								{
									strtmp = strtmp+ "还原状态: 未保护 ";
									m_pLogger->WriteLog(LM_INFO, TEXT("还原状态: 未保护 "));	
								}
								strtmp = strtmp+ "  剩余空间: "+_getWmiInfo(pClassObject,"FreeSpace")+"\r\n";
								SysInfo = SysInfo + strtmp;
								m_pLogger->WriteLog(LM_INFO, TEXT("剩余空间: %s"),_getWmiInfo(pClassObject,"FreeSpace").c_str());
								
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_processor");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "处理器的制造厂商: "+_getWmiInfo(pClassObject,"Manufacturer") + "\r\n";
								strtmp = strtmp + "处理器的名称: "+_getWmiInfo(pClassObject,"Caption") + "\r\n";
								SysInfo = SysInfo + strtmp;

								m_pLogger->WriteLog(LM_INFO, TEXT("处理器的制造厂商: %s"),_getWmiInfo(pClassObject,"Manufacturer").c_str());
								m_pLogger->WriteLog(LM_INFO, TEXT("处理器的名称: %s"),_getWmiInfo(pClassObject,"Caption").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_LogicalMemoryConfiguration");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "物理内存大小: "+_getWmiInfo(pClassObject,"TotalPhysicalMemory") + "\r\n";
								strtmp = strtmp + "页面文件大小: "+_getWmiInfo(pClassObject,"TotalPageFileSpace") + "\r\n";
								strtmp = strtmp + "虚拟内存大小: "+_getWmiInfo(pClassObject,"TotalVirtualMemory") + "\r\n";
								SysInfo = SysInfo + strtmp;

								m_pLogger->WriteLog(LM_INFO, TEXT("物理内存大小: %s"),_getWmiInfo(pClassObject,"TotalPhysicalMemory").c_str());
								m_pLogger->WriteLog(LM_INFO, TEXT("页面文件大小: %s"),_getWmiInfo(pClassObject,"TotalPageFileSpace").c_str());
								m_pLogger->WriteLog(LM_INFO, TEXT("虚拟内存大小: %s"),_getWmiInfo(pClassObject,"TotalVirtualMemory").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_VideoController");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "显卡名称: "+_getWmiInfo(pClassObject,"Name") + "\r\n";
								SysInfo = SysInfo + strtmp;
								m_pLogger->WriteLog(LM_INFO, TEXT("显卡名称: %s"),_getWmiInfo(pClassObject,"Name").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_NetworkAdapter where (Netconnectionstatus = 2)");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							while( pEnumObject->Next( WBEM_INFINITE, 
								uCount, &pClassObject, &uReturned) == S_OK )
							{
								tstring str;
								str =_getWmiInfo(pClassObject,"MACAddress");
								if (!str.empty())
								{
									str =_getWmiInfo(pClassObject,"PNPDeviceID");
									size_t pos =  str.find("PCI",0);
									if (pos != tstring::npos)
									{
										tstring str = _getWmiInfo(pClassObject,"Caption");
										size_t pos = str.find(']');
										if (pos != tstring::npos)
											str = str.substr(pos+1);
										strtmp = "网卡名称: "+str + "\r\n";
										SysInfo = SysInfo + strtmp;
										m_pLogger->WriteLog(LM_INFO,  "网卡名称: %s" , str.c_str()) ;	
									}
								}
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
				}
			}
			if (pIWbemLocator)
				pIWbemLocator->Release();
			if (pWbemServices)
				pWbemServices->Release();
			if (pEnumObject)
				pEnumObject->Release();
		}
		CoUninitialize();
		if (!SysInfo.empty())
		{
			m_SysInfo = SysInfo;
		}
		return SysInfo;
	}
/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	BSTR path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	if (FAILED(hr)) {
		//only try the v2 namespace since this will only be present
		//with the extensible switch that supports sampling.
	    //don't try to get counters if there is no sampling.
		SysFreeString(path);
		myLog(LOG_INFO, "readWMISwitchPorts: virtualization namespace v2 not found");
		return;
	} else {
		SysFreeString(path);
	}

	BSTR queryLang = SysAllocString(L"WQL");
	wchar_t *query = L"SELECT * FROM Msvm_EthernetSwitchPort";
	IEnumWbemClassObject *switchPortEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &switchPortEnum);
	SysFreeString(queryLang);
	if (FAILED(hr)) {
		myLog(LOG_ERR,"readWMISwitchPorts: ExecQuery() failed for query %S error=0x%x", query, hr);
		pNamespace->Release();
		return;
	}

	if (sp->vAdaptorList == NULL) {
		sp->vAdaptorList = adaptorListNew();
	}
	IWbemClassObject *switchPortObj = NULL;

	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		SFLAdaptor *vAdaptor = NULL;
		ULONG uReturned = 1;
		hr = switchPortEnum->Next(WBEM_INFINITE, 1, &switchPortObj, &uReturned);
		if (0 == uReturned) {
			break;
		}
		wchar_t *guidString = stringFromWMIProperty(switchPortObj, PROP_NAME);
		if (guidString != NULL) {
			char portGuid[FORMATTED_GUID_LEN+1];
			guidToString(guidString, (UCHAR *)portGuid, FORMATTED_GUID_LEN);
			myLog(LOG_INFO, "readWMISwitchPorts: portGuid=%s", portGuid);
			my_free(guidString);
			vAdaptor = adaptorListGet(sp->vAdaptorList, portGuid);
		}
		if (vAdaptor != NULL) {
			HVSVPortInfo *portInfo = (HVSVPortInfo *)vAdaptor->userData;
			wchar_t *switchName = stringFromWMIProperty(switchPortObj, PROP_SYSTEM_NAME);
			if (switchName != NULL) {
				if (portInfo->switchName != NULL) {
					my_free(portInfo->switchName);
				}
				portInfo->switchName = switchName;
			}
			wchar_t *friendlyName = stringFromWMIProperty(switchPortObj, PROP_ELEMENT_NAME);
			if (friendlyName != NULL) {
				if (portInfo->portFriendlyName != NULL) {
					my_free(portInfo->portFriendlyName);
				}
				portInfo->portFriendlyName = friendlyName;
			}
			setPortCountersInstance(vAdaptor);
			wchar_t *speedString = stringFromWMIProperty(switchPortObj, PROP_SPEED);
			if (speedString != NULL) {
				ULONGLONG ifSpeed = _wcstoui64(speedString, NULL, 10);
				vAdaptor->ifSpeed = ifSpeed;
				my_free(speedString);
			}
			//could also get ifDirection but FullDuplex=True always

			//Get the MACs and VM system name when we enumerate the vms.
			myLog(LOG_INFO, 
				  "readWMISwitchPorts: updated switch port %s %S portId=%u ifIndex=%u ifSpeed=%llu counterName=%S", 
				  vAdaptor->deviceName, portInfo->portFriendlyName, portInfo->portId, vAdaptor->ifIndex, 
				  vAdaptor->ifSpeed, portInfo->portCountersInstance);
		} else {
			myLog(LOG_INFO, "readWMISwitchPorts: vAdapter not found");
		}
		switchPortObj->Release();
	}
	switchPortEnum->Release();
	pNamespace->Release();
}
Exemple #29
0
void CHardwareMonitor::RunWMIQuery(const char* qTable, const std::string &qType)
{
	if ((m_pServicesOHM == NULL) || (m_pServicesSystem == NULL))
		return;
	HRESULT hr;
	int dindex = 0;
	std::string query = "SELECT * FROM ";
	query.append(qTable);
	query.append(" WHERE SensorType = '");
	query.append(qType);
	query.append("'");
	IEnumWbemClassObject* pEnumerator = NULL; 
	hr = m_pServicesOHM->ExecQuery(L"WQL", bstr_t(query.c_str()), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
	if (!FAILED(hr))
	{
		// Get the data from the query
		IWbemClassObject *pclsObj = NULL;
		while (pEnumerator)
		{
			ULONG uReturn = 0;
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
			if (FAILED(hr) || (0 == uReturn))
			{
				break;
			}

			VARIANT vtProp;

			hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
			if (SUCCEEDED(hr))
			{
				std::string itemName = _bstr_t(vtProp.bstrVal);
				stdreplace(itemName, "#", "");
				VariantClear(&vtProp);

				hr = pclsObj->Get(L"Value", 0, &vtProp, 0, 0);
				if (SUCCEEDED(hr))
				{
					float fItemValue = float(vtProp.fltVal);
					std::ostringstream itemValue;
					if ((qType == "Load") || (qType == "Temperature")) {
						itemValue.precision(3);
					}
					itemValue << fItemValue;
					VariantClear(&vtProp);

					//hr = pclsObj->Get(L"InstanceId", 0, &vtProp, 0, 0);
					hr = pclsObj->Get(L"Identifier", 0, &vtProp, 0, 0); // instance id seems to drift
					if (SUCCEEDED(hr))
					{
						std::string itemId = _bstr_t(vtProp.bstrVal);
						if (itemId.find("/hdd") != std::string::npos)
						{
							itemName = itemId + " " + itemName;
						}
						//itemId = "WMI"+itemId;
						//_log.Log(LOG_NORM, "Hardware Monitor: %s, %s, %s",itemId.c_str(), itemName.c_str(),itemValue.str().c_str());
						UpdateSystemSensor(qType, dindex, itemName, itemValue.str());
						VariantClear(&vtProp);
						dindex++;
					}
				}
			}
			pclsObj->Release();
		}
		pEnumerator->Release();
	}
}
Exemple #30
-1
bool 
IPodDetector::doesIpodExist(IPod *ipod)
{
    IEnumWbemClassObject* enumerator = NULL;
    std::stringstream output;

    for( size_t i = 0; i < ipod->serial().length(); ++i )
    {
        output << (char)ipod->serial().c_str()[i];
    }
    queryByDeviceID( output.str(), &enumerator );
    
    IWbemClassObject* object;
    ULONG count;

    enumerator->Next( WBEM_INFINITE, 1, &object, &count );
    
    enumerator->Release();

    if( count > 0 )
    {
        object->Release();
        return true;
    }
    return false;
}