Ejemplo n.º 1
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
 * and v2 for Win 2012).
 * We need to check for the v2 namespace and use in preference to v1, 
 * since v1 was deprecated and all classes removed in Win 2012 R2. So
 * we also set the global variable wmiVirtNs to the preferred namespace.
 * 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 v2 virtualization namespace
			CoUninitialize();
			path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
			hr = connectToWMI(path, &pNamespace);
			SysFreeString(path);
			if (WBEM_NO_ERROR == hr) {
				gotHyperV = true;
				wmiVirtNsVer = 2;
				pNamespace->Release();
			} else {
				CoUninitialize();
				path = SysAllocString(WMI_VIRTUALIZATION_NS_V1);
				hr = connectToWMI(path, &pNamespace);
				SysFreeString(path);
				if (WBEM_NO_ERROR == hr) {
					gotHyperV = true;
					wmiVirtNsVer = 1;
					pNamespace->Release();
				}
			}
			if (!(wmiVirtNsVer == 1 || wmiVirtNsVer == 2)) {
				myLog(LOG_ERR, "testForHyperv: unknown wmiVirtNsVer=%u", wmiVirtNsVer);
			}
		}
	}
	CoUninitialize();
	myLog(LOG_INFO, "testForHyperv: HyperV=%u wmiVirtNsVer=%u", gotHyperV, wmiVirtNsVer);
	return gotHyperV;
}
Ejemplo n.º 2
0
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.
}
Ejemplo n.º 3
0
/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	myLog(LOG_INFO, "entering readWMISwitchPorts");
	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();
}
Ejemplo n.º 4
0
HRESULT
ExecuteMethodsInClass(
    __in     IWbemServices* WbemServices,
    __in_opt PWCHAR UserId,
    __in_opt PWCHAR Password,
    __in_opt PWCHAR DomainName
    )

/*++

Routine Description:

    This routine enumerates the instances of the Toaster method class and
    executes the methods in the class for each instance.

Arguments:

    WbemServices - Pointer to the WBEM services interface used for accessing
        the WMI services.

    UserId - Pointer to the user id information or NULL.

    Password - Pointer to password or NULL. If the user id is not specified,
        this parameter is ignored.

    DomainName - Pointer to domain name or NULL. If the user id is not specified,
        this parameter is ignored.

Return Value:

    HRESULT Status code.

--*/

{
    HRESULT status = S_OK;

    IEnumWbemClassObject* enumerator  = NULL;
    IWbemClassObject* classObj        = NULL;
    IWbemClassObject* instanceObj     = NULL;

    const BSTR className   = SysAllocString(TOASTER_METHOD_CLASS);

    VARIANT pathVariable;
    _bstr_t instancePath;
    ULONG   nbrObjsSought = 1;
    ULONG   nbrObjsReturned;

    //
    // Create an Enumeration object to enumerate the instances of the given class.
    //
    status = WbemServices->CreateInstanceEnum(className,
                                              WBEM_FLAG_SHALLOW | WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                                              NULL,
                                              &enumerator);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set authentication information for the interface.
    //
    status = SetInterfaceSecurity(enumerator, UserId, Password, DomainName);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Get the class object for the method definition.
    //
    status = WbemServices->GetObject(className, 0, NULL, &classObj, NULL);
    if (FAILED(status)) {
        goto exit;
    }

    do {

        //
        // Get the instance object for each instance of the class.
        //
        status = enumerator->Next(WBEM_INFINITE,
                                  nbrObjsSought,
                                  &instanceObj,
                                  &nbrObjsReturned);

        if (status == WBEM_S_FALSE) {
            status = S_OK;
            break;
        }

        if (FAILED(status)) {
            if (status == WBEM_E_INVALID_CLASS) {
                printf("ERROR: Toaster driver may not be active on the system.\n");
            }
            goto exit;
        }

        //
        // To obtain the object path of the object for which the method has to be
        // executed, query the "__PATH" property of the WMI instance object.
        //
        status = instanceObj->Get(_bstr_t(L"__PATH"), 0, &pathVariable, NULL, NULL);
        if (FAILED(status)) {
            goto exit;
        }

        instancePath = pathVariable.bstrVal;
        instanceObj->Release();
        instanceObj = NULL;

        //
        // Execute the methods in this instance of the class.
        //
        status = ExecuteMethod1InInstance(WbemServices, classObj, instancePath, IN_DATA1_VALUE);
        if (FAILED(status)) {
            goto exit;
        }

        status = ExecuteMethod2InInstance(WbemServices, classObj, instancePath, IN_DATA1_VALUE, IN_DATA2_VALUE);
        if (FAILED(status)) {
            goto exit;
        }

        status = ExecuteMethod3InInstance(WbemServices, classObj, instancePath, IN_DATA1_VALUE, IN_DATA2_VALUE);
        if (FAILED(status)) {
            goto exit;
        }
    } while (!FAILED(status));

exit:

    if (className != NULL) {
        SysFreeString(className);
    }

    if (classObj != NULL) {
        classObj->Release();
    }

    if (enumerator != NULL) {
        enumerator->Release();
    }

    if (instanceObj != NULL) {
        instanceObj->Release();
    }

    return status;
}
Ejemplo n.º 5
0
void CHardwareMonitor::RunWMIQuery(const char* qTable, const std::string &qType)
{
	if (pServicesOHM && pServicesSystem)
	{
		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 = 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();
		}
	}
	else {
		//_log.Log(LOG_NORM, "Hardware Monitor: pservices null");
	}
}
Ejemplo n.º 6
0
int wmi_get_battery_info() {

	std::cout << "wmi_get_battery_info" << std::endl;

	//assert(_initialized);
	//assert(pcpu_load_comp);
	//assert(pcpu_load_user);
	//assert(pcpu_load_sys);

	//float& cpu_load_comp = *pcpu_load_comp;
	//float& cpu_load_user = *pcpu_load_user;
	//float& cpu_load_sys = *pcpu_load_sys;

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

	//cpu_load_comp = 0;
	//cpu_load_user = 0;

	bool user_logged = false;

	long long current_process_id = _current_process_id;

	
	enumerator = request(
		// uint16, uint32, uint16, uint32... 
		bstr_t("SELECT"
		" Availability, BatteryRechargeTime, BatteryStatus,"
		"Caption, DesignCapacity, DesignVoltage, FullChargeCapacity"
		" FROM  Win32_Battery")
	);
		
	
	ULONG uReturn;
	for(;;) {
		
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(0 == uReturn) {
			break;
		}

		VARIANT var;
		VariantInit(&var);
		result = object->Get(L"Voltage", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned short v = var.uiVal;
			//std::cout << "Availability: " << v << std::endl; 
		}
		
		VariantInit(&var);
		result = object->Get(L"DischargeRate", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "BatteryRechargeTime: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"Caption", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "BatteryRechargeTime: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"DesignCapacity", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "DesignCapacity: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"DesignVoltage", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned long long v = var.ullVal;
			//std::cout << "DesignVoltage: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"FullChargeCapacity", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "FullChargeCapacity: " << v << std::endl; 
		}


		object->Release();
	} // for(;;)

	if (enumerator)
		enumerator->Release();

	return 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’s 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 CDirectInput8Manager::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( 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( 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( 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
                // 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 = m_pXInputDeviceList;
                        m_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;
}
Ejemplo n.º 8
0
HRESULT GetVideoMemoryViaWMI( WCHAR* strInputDeviceID, DWORD* pdwAdapterRam )
{
	HRESULT hr;
	bool bGotMemory = false;
	HRESULT hrCoInitialize = S_OK;
	IWbemLocator* pIWbemLocator = nullptr;
	IWbemServices* pIWbemServices = nullptr;
	BSTR pNamespace = nullptr;

	*pdwAdapterRam = 0;
	hrCoInitialize = CoInitialize( 0 );

	hr = CoCreateInstance( CLSID_WbemLocator,
						   nullptr,
						   CLSCTX_INPROC_SERVER,
						   IID_IWbemLocator,
						   ( LPVOID* )&pIWbemLocator );
#ifdef PRINTF_DEBUGGING
	if( FAILED( hr ) ) wprintf( L"WMI: CoCreateInstance failed: 0x%0.8x\n", hr );
#endif

	if( SUCCEEDED( hr ) && pIWbemLocator )
	{
		// Using the locator, connect to WMI in the given namespace.
		pNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );

		hr = pIWbemLocator->ConnectServer( pNamespace, nullptr, nullptr, 0L,
										   0L, nullptr, nullptr, &pIWbemServices );
#ifdef PRINTF_DEBUGGING
		if( FAILED( hr ) ) wprintf( L"WMI: pIWbemLocator->ConnectServer failed: 0x%0.8x\n", hr );
#endif
		if( SUCCEEDED( hr ) && pIWbemServices != 0 )
		{
			HINSTANCE hinstOle32 = nullptr;

			hinstOle32 = LoadLibraryW( L"ole32.dll" );
			if( hinstOle32 )
			{
				PfnCoSetProxyBlanket pfnCoSetProxyBlanket = nullptr;

				pfnCoSetProxyBlanket = ( PfnCoSetProxyBlanket )GetProcAddress( hinstOle32, "CoSetProxyBlanket" );
				if( pfnCoSetProxyBlanket != 0 )
				{
					// Switch security level to IMPERSONATE.
					pfnCoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr,
										  RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, 0 );
				}

				FreeLibrary( hinstOle32 );
			}

			IEnumWbemClassObject* pEnumVideoControllers = nullptr;
			BSTR pClassName = nullptr;

			pClassName = SysAllocString( L"Win32_VideoController" );

			hr = pIWbemServices->CreateInstanceEnum( pClassName, 0,
													 nullptr, &pEnumVideoControllers );
#ifdef PRINTF_DEBUGGING
			if( FAILED( hr ) ) wprintf( L"WMI: pIWbemServices->CreateInstanceEnum failed: 0x%0.8x\n", hr );
#endif

			if( SUCCEEDED( hr ) && pEnumVideoControllers )
			{
				IWbemClassObject* pVideoControllers[10] = {0};
				DWORD uReturned = 0;
				BSTR pPropName = nullptr;

				// Get the first one in the list
				pEnumVideoControllers->Reset();
				hr = pEnumVideoControllers->Next( 5000,             // timeout in 5 seconds
												  10,                  // return the first 10
												  pVideoControllers,
												  &uReturned );
#ifdef PRINTF_DEBUGGING
				if( FAILED( hr ) ) wprintf( L"WMI: pEnumVideoControllers->Next failed: 0x%0.8x\n", hr );
				if( uReturned == 0 ) wprintf( L"WMI: pEnumVideoControllers uReturned == 0\n" );
#endif

				VARIANT var;
				if( SUCCEEDED( hr ) )
				{
					bool bFound = false;
					for( UINT iController = 0; iController < uReturned; iController++ )
					{
						if ( !pVideoControllers[iController] )
							continue;

						pPropName = SysAllocString( L"PNPDeviceID" );
						hr = pVideoControllers[iController]->Get( pPropName, 0L, &var, nullptr, nullptr );
#ifdef PRINTF_DEBUGGING
						if( FAILED( hr ) )
							wprintf( L"WMI: pVideoControllers[iController]->Get PNPDeviceID failed: 0x%0.8x\n", hr );
#endif
						if( SUCCEEDED( hr ) )
						{
							if( wcsstr( var.bstrVal, strInputDeviceID ) != 0 )
								bFound = true;
						}
						VariantClear( &var );
						if( pPropName ) SysFreeString( pPropName );

						if( bFound )
						{
							pPropName = SysAllocString( L"AdapterRAM" );
							hr = pVideoControllers[iController]->Get( pPropName, 0L, &var, nullptr, nullptr );
#ifdef PRINTF_DEBUGGING
							if( FAILED( hr ) )
								wprintf( L"WMI: pVideoControllers[iController]->Get AdapterRAM failed: 0x%0.8x\n",
										 hr );
#endif
							if( SUCCEEDED( hr ) )
							{
								bGotMemory = true;
								*pdwAdapterRam = var.ulVal;
							}
							VariantClear( &var );
							if( pPropName ) SysFreeString( pPropName );
							break;
						}
						SAFE_RELEASE( pVideoControllers[iController] );
					}
				}
				SAFE_RELEASE(pEnumVideoControllers);
			}

			if( pClassName )
				SysFreeString( pClassName );
		}

		if( pNamespace )
			SysFreeString( pNamespace );
		SAFE_RELEASE( pIWbemServices );
	}

	SAFE_RELEASE( pIWbemLocator );

	if( SUCCEEDED( hrCoInitialize ) )
		CoUninitialize();

	if( bGotMemory )
		return S_OK;
	else
		return E_FAIL;
}
Ejemplo n.º 9
0
static unsigned int getclock(void)
{
	unsigned int clock;
#ifdef KONOHA_ON_MACOSX
	int cpu_sels[2] = { CTL_HW, HW_CPU_FREQ };
	size_t len = sizeof(int);
	sysctl(cpu_sels, 2, &clock, &len, NULL, 0);
	clock = (unsigned int) clock / (1000 * 1000);
#elif defined(KONOHA_ON_WINDOWS)
	HRESULT hres;
	hres = CoInitializeEx(0, COINIT_MULTITHREADED);
	hres = CoInitializeSecurity(
		NULL,
		-1,                          // COM authentication
		NULL,                        // Authentication services
		NULL,                        // Reserved
		RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
		RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
		NULL,                        // Authentication info
		EOAC_NONE,                   // Additional capabilities
		NULL                         // Reserved
		);
	IWbemLocator *pLoc = NULL;
	hres = CoCreateInstance(
		CLSID_WbemLocator,
		0,
		CLSCTX_INPROC_SERVER, 
		IID_IWbemLocator, (LPVOID *) &pLoc);
	IWbemServices *pSvc = NULL;
	hres = pLoc->ConnectServer(
		_bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
		NULL,                    // User name. NULL = current user
		NULL,                    // User password. NULL = current
		0,                       // Locale. NULL indicates current
		NULL,                    // Security flags.
		0,                       // Authority (e.g. Kerberos)
		0,                       // Context object
		&pSvc                    // pointer to IWbemServices 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
		NULL,                        // Server principal name
		RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
		RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
		NULL,                        // client identity
		EOAC_NONE                    // proxy capabilities
		);
	IEnumWbemClassObject* pEnumerator = NULL;
	hres = pSvc->ExecQuery(
		bstr_t("WQL"),
		bstr_t("SELECT * FROM Win32_Processor"),
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&pEnumerator);
	IWbemClassObject *pclsObj;
	ULONG uReturn = 0;
	
	while (pEnumerator) {
		HRESULT hr = pEnumerator->Next(
			WBEM_INFINITE,
			1,
			&pclsObj,
			&uReturn
			);
		if (uReturn == 0) { break; }
		VARIANT vtProp;
		hr = pclsObj->Get(L"MaxClockSpeed", 0, &vtProp, 0, 0);
		clock = (unsigned int)vtProp.bstrVal;
		VariantClear(&vtProp);
		pclsObj->Release();
	}
	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();
	CoUninitialize();
#elif defined(KONOHA_ON_LINUX)
	char buf[64] = {'\0'}, *data = buf;
	const char *cpumhz = "cpu MHz";
	size_t len = strlen(cpumhz);
	FILE *fp = fopen("/proc/cpuinfo","r");
	while (fgets( buf, 64, fp ) != NULL){
		if ( strncmp(buf, cpumhz, len) == 0){
			data = strstr(buf, cpumhz);
			break;
		}
	}
	while (!isdigit(*data)) {
		data++;
	}
	clock = (unsigned int) atoi(data) / 1000;
	fclose(fp);

#else
	TODO();
#endif
	return clock;
}
Ejemplo n.º 10
0
int readSystemUUID(u_char *uuidbuf){
	int	                    gotData = NO;
	BSTR                    path = SysAllocString(L"root\\wmi");
	BSTR                    className = SysAllocString(L"MSSmBios_RawSMBiosTables");
	BSTR                    propName = SysAllocString(L"SMBiosData");
	ULONG                   uReturned = 1;
	HRESULT                 hr = S_FALSE;
	IWbemLocator            *pLocator = NULL;
	IWbemServices           *pNamespace = NULL;
	IEnumWbemClassObject    *pEnumSMBIOS = NULL;
	IWbemClassObject        *pSmbios = NULL;
	CIMTYPE                 type;
	VARIANT                 pVal;
	SAFEARRAY               *pArray = NULL;
	smbiosHeader            *smbiosData;
	u_char                  *uuidPtr;
	DWORD                   smbufSize;

	hr =  CoInitializeEx(0, COINIT_MULTITHREADED);
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to initialize COM");
		gotData = NO;
		goto Cleanup;
	}
	
	hr =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,EOAC_NONE,NULL);
	hr = CoCreateInstance( CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLocator );
	if(! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to create WMI instance");
		gotData = NO;
		goto Cleanup;
	}

	hr = pLocator->ConnectServer(path, NULL, NULL, NULL, 0, NULL, NULL, &pNamespace );
	pLocator->Release();
	if( WBEM_S_NO_ERROR != hr ){
		myLog(LOG_ERR,"getSystemUUID: ConnectServer() failed for namespace");
		gotData = NO;
		goto Cleanup;
	}

	hr = pNamespace->CreateInstanceEnum(className, 0, NULL, &pEnumSMBIOS );
	pNamespace->Release();
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"getSystemUUID: CreateInstanceEnum() failed for MSSmBios_RawSMBiosTables");
		gotData = NO;
		goto Cleanup;
	}

	hr = pEnumSMBIOS->Next(4000, 1, &pSmbios, &uReturned );
	pEnumSMBIOS->Release();
	if ( 1 != uReturned ){
		myLog(LOG_ERR,"getSystemUUID: Next() failed for pEnumSMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	
	pSmbios->Get(propName,0L,&pVal,&type,NULL);
	if ( ( VT_UI1 | VT_ARRAY) != pVal.vt){
		myLog(LOG_ERR,"getSystemUUID: Get() failed for pSmbios");
	    gotData = NO;
		goto Cleanup;
	}

	pArray = V_ARRAY(&pVal);
	smbufSize = pArray->rgsabound[0].cElements;
	smbiosData = (smbiosHeader*)my_calloc(smbufSize);
	if(!smbiosData){
		myLog(LOG_ERR,"getSystemUUID: failed to allocate buffer for smbiosData");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)smbiosData,pArray->pvData,smbufSize);
	uuidPtr = (u_char*)getUUIDPtr(smbufSize,smbiosData);
	if(!uuidPtr){
		myLog(LOG_ERR,"getSystemUUID: failed to find UUID in SMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)uuidbuf,uuidPtr,16);
	gotData = YES;

Cleanup:
	SysFreeString(propName);
	SysFreeString(className);
	SysFreeString(path);
	if(smbiosData) my_free(smbiosData);

	return gotData;
}
Ejemplo n.º 11
0
BOOL CEnumerateSerial::UsingWMI(CSimpleArray<UINT>& ports, CSimpleArray<CString>& friendlyNames)
#endif
{
  //Make sure we clear out any elements which may already be in the array(s)
#if defined CENUMERATESERIAL_USE_STL
  ports.clear();
  friendlyNames.clear();
#else
  ports.RemoveAll();
  friendlyNames.RemoveAll();
#endif  

  //What will be the return value
  BOOL bSuccess = FALSE;

  //Create the WBEM locator
  IWbemLocator* pLocator = NULL;
  HRESULT hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&pLocator));
  if (SUCCEEDED(hr))
  {
    IWbemServices* pServices = NULL;
    hr = pLocator->ConnectServer(_bstr_t("\\\\.\\root\\cimv2"), NULL, NULL, NULL, 0, NULL, NULL, &pServices);
    if (SUCCEEDED(hr))
    {
      //Execute the query
      IEnumWbemClassObject* pClassObject = NULL;
      hr = pServices->CreateInstanceEnum(_bstr_t("Win32_SerialPort"), WBEM_FLAG_RETURN_WBEM_COMPLETE, NULL, &pClassObject);
      if (SUCCEEDED(hr))
      {
        bSuccess = TRUE;

        //Now enumerate all the ports
        hr = WBEM_S_NO_ERROR;

        //Final Next will return WBEM_S_FALSE
        while (hr == WBEM_S_NO_ERROR)
        {
          ULONG uReturned = 0;
          IWbemClassObject* apObj[10];
          memset(apObj, 0, sizeof(apObj));
          hr = pClassObject->Next(WBEM_INFINITE, 10, reinterpret_cast<IWbemClassObject**>(apObj), &uReturned);
          if (SUCCEEDED(hr))
          {
            for (ULONG n=0; n<uReturned; n++)
            {
              VARIANT varProperty1;
              VariantInit(&varProperty1);
              HRESULT hrGet = apObj[n]->Get(L"DeviceID", 0, &varProperty1, NULL, NULL);
              if (SUCCEEDED(hrGet) && (varProperty1.vt == VT_BSTR) && (wcslen(varProperty1.bstrVal) > 3))
              {
                //If it looks like "COMX" then add it to the array which will be returned
                if ((_wcsnicmp(varProperty1.bstrVal, L"COM", 3) == 0) && IsNumeric(&(varProperty1.bstrVal[3]), TRUE))
                {
                  //Work out the port number
                  int nPort = _wtoi(&(varProperty1.bstrVal[3]));
                #if defined CENUMERATESERIAL_USE_STL
                  ports.push_back(nPort);
                #else
                  ports.Add(nPort);
                #endif

                  //Also get the friendly name of the port
                  VARIANT varProperty2;
                  VariantInit(&varProperty2);
                  if (SUCCEEDED(apObj[n]->Get(L"Name", 0, &varProperty2, NULL, NULL)) && (varProperty2.vt == VT_BSTR))
                  {  
                #if defined CENUMERATESERIAL_USE_STL
                  #if defined _UNICODE  
                    std::wstring szName(varProperty2.bstrVal);
                  #else
                    CAutoHeapAlloc szAsciiValue;
                    int nLengthA = WideCharToMultiByte(CP_ACP, 0, varProperty2.bstrVal, -1, NULL, 0, NULL, NULL);
                    if (nLengthA)
                    {
                      if (szAsciiValue.Allocate(nLengthA))
                        WideCharToMultiByte(CP_ACP, 0, varProperty2.bstrVal, -1, static_cast<LPSTR>(szAsciiValue.m_pData), nLengthA, NULL, NULL);
                    }

                    std::string szName(static_cast<LPSTR>(szAsciiValue.m_pData));
                  #endif
                    friendlyNames.push_back(szName);
                  #else
                    friendlyNames.Add(CString(varProperty2.bstrVal));    
                  #endif
                  }
                  else
                  {
                  #if defined CENUMERATESERIAL_USE_STL
                    friendlyNames.push_back(_T(""));
                  #else
                    friendlyNames.Add(_T(""));
                  #endif  
                  }

                  //Free up the variant;
                  VariantClear(&varProperty2);
                }
              }

              //Free up the variant;
              VariantClear(&varProperty1);

              //Free up each COM interface
              apObj[n]->Release();
            }
          }
        }

        //Free up the COM interface
        pClassObject->Release();
      }

      //Free up the COM interface
      pServices->Release();
    }

    //Free up the COM interface
    pLocator->Release();
  }
  
  return bSuccess;
}
Ejemplo n.º 12
0
/////////////////////////////////////////////////////////////////////////////
//++
//
//  CPartitionInfo:HrGetLogicalDisks
//
//  Description:
//      Get the logical disks for the passed in partition.
//
//  Arguments:
//      pPartitionIn
//          WMI partition object to query on.
//
//  Return Value:
//      S_OK
//          Success
//
//      S_FALSE
//          The file system was not NTFS.
//
//      Other
//          An error occurred.
//
//  Remarks:
//      None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPartitionInfo::HrGetLogicalDisks(
    IWbemClassObject * pPartitionIn
    )
{
    HRESULT                 hr;
    VARIANT                 var;
    WCHAR                   szBuf[ 256 ];
    IEnumWbemClassObject *  pLogicalDisks = NULL;
    IWbemClassObject *      pLogicalDisk = NULL;
    ULONG                   ulReturned;
    BSTR                    bstrQuery = NULL;
    BSTR                    bstrWQL = NULL;

    VariantInit( &var );

    bstrWQL = SysAllocString( L"WQL" );
    if ( bstrWQL == NULL )
    {
        hr = E_OUTOFMEMORY;
        STATUS_REPORT_REF(
                  TASKID_Major_Find_Devices
                , TASKID_Minor_HrGetLogicalDisks
                , IDS_ERROR_OUTOFMEMORY
                , IDS_ERROR_OUTOFMEMORY_REF
                , hr
                );
        goto Cleanup;
    } // if:

    //
    //  Need to enum the logical disk(s) of this partition to determine if it is booted
    //  bootable.
    //
    hr = HrGetWMIProperty( pPartitionIn, L"DeviceID", VT_BSTR, &var );
    if ( FAILED( hr ) )
    {
        goto Cleanup;
    } // if:

    hr = StringCchPrintfW(
                      szBuf
                    , RTL_NUMBER_OF( szBuf )
                    , L"Associators of {Win32_DiskPartition.DeviceID='%ws'} where AssocClass=Win32_LogicalDiskToPartition"
                    , var.bstrVal
                    );
    if ( FAILED( hr ) )
    {
        goto Cleanup;
    } // if:

    bstrQuery = SysAllocString( szBuf );
    if ( bstrQuery == NULL )
    {
        hr = E_OUTOFMEMORY;
        STATUS_REPORT_REF(
                  TASKID_Major_Find_Devices
                , TASKID_Minor_HrGetLogicalDisks
                , IDS_ERROR_OUTOFMEMORY
                , IDS_ERROR_OUTOFMEMORY_REF
                , hr
                );
        goto Cleanup;
    } // if:

    hr = m_pIWbemServices->ExecQuery( bstrWQL, bstrQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pLogicalDisks );
    if ( FAILED( hr ) )
    {
        STATUS_REPORT_REF(
              TASKID_Major_Find_Devices
            , TASKID_Minor_WMI_Logical_Disks_Qry_Failed
            , IDS_ERROR_WMI_DISKS_QRY_FAILED
            , IDS_ERROR_WMI_DISKS_QRY_FAILED_REF
            , hr
            );
        goto Cleanup;
    } // if:

    for ( ; ; )
    {
        hr = pLogicalDisks->Next( WBEM_INFINITE, 1, &pLogicalDisk, &ulReturned );
        if ( ( hr == S_OK ) && ( ulReturned == 1 ) )
        {
            HrLogLogicalDiskInfo( pLogicalDisk, var.bstrVal );
            hr = HrAddLogicalDiskToArray( pLogicalDisk );
            if ( FAILED( hr ) )
            {
                goto Cleanup;
            } // if:

            pLogicalDisk->Release();
            pLogicalDisk = NULL;
        } // if:
        else if ( ( hr == S_FALSE ) && ( ulReturned == 0 ) )
        {
            hr = S_OK;
            break;
        } // else if:
        else
        {
            STATUS_REPORT_STRING_REF(
                      TASKID_Major_Find_Devices
                    , TASKID_Minor_HrGetLogicalDisks_Next
                    , IDS_ERROR_WQL_QRY_NEXT_FAILED
                    , bstrQuery
                    , IDS_ERROR_WQL_QRY_NEXT_FAILED_REF
                    , hr
                    );
            goto Cleanup;
        } // else:
    } // for:

Cleanup:

    VariantClear( &var );

    SysFreeString( bstrQuery );
    SysFreeString( bstrWQL );

    if ( pLogicalDisk != NULL )
    {
        pLogicalDisk->Release();
    } // if:

    if ( pLogicalDisks != NULL )
    {
        pLogicalDisks->Release();
    } // if:

    return hr;

} //*** CPartitionInfo::HrGetLogicalDisks
Ejemplo n.º 13
0
//
//   函数: GetOSName(PWSTR, DWORD)
//
//   目的: 获取当前操作系统的名字(例如:"Microsoft Windows 7 企业版").
//
//   参数:
//   * pszName - 存放操作系统名的缓冲区. 
//   * cch - 由pszName所指向的缓冲区大小,以字符形式.
//
//   返回值: 如果函数成功返回TRUE.
//
BOOL GetOSName(PWSTR pszName, DWORD cch)
{
    HRESULT hr = S_OK;
    IWbemLocator *pLoc = NULL;
    IWbemServices *pSvc = NULL;
    IEnumWbemClassObject *pEnumerator = NULL;
    PCWSTR pszMachineName = L".";

    // 通过调用 CoInitializeEx初始化COM参数.
    hr = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hr))
    {
        return FALSE;
    }

    // 通过调用CoInitializeSecurity初始化COM进程安全. 
    hr = CoInitializeSecurity(
        NULL, 
        -1,                             // COM 认证
        NULL,                           // 认证服务
        NULL,                           // 保留
        RPC_C_AUTHN_LEVEL_DEFAULT,      // 默认认证
        RPC_C_IMP_LEVEL_IDENTIFY,       // 默认身份 
        NULL,                           // 认证信息
        EOAC_NONE,                      // 额外的能力
        NULL                            // 保留
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 通过调用CoCreateInstance获得WMI的初始定位器. 
    hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, reinterpret_cast<LPVOID *>(&pLoc));
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 通过IWbemLocator::ConnectServer连接到WMI.
    wchar_t szPath[200];
    hr = StringCchPrintf(szPath, ARRAYSIZE(szPath), L"\\\\%s\\root\\cimv2", 
        pszMachineName);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    hr = pLoc->ConnectServer(
        bstr_t(szPath),                 // WMI名空间的路径
        NULL,                           // 用户名
        NULL,                           // 用户密码
        NULL,                           // 本地
        NULL,                           // 安全标志
        NULL,                           // 权限
        NULL,                           // 上下文对象
        &pSvc                           // IWbemServices 代理
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 在WMI连接中设置安全级别.
    hr = CoSetProxyBlanket(
        pSvc,                           // 指明代理来设置
        RPC_C_AUTHN_DEFAULT,            // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_DEFAULT,            // RPC_C_AUTHZ_xxx
        COLE_DEFAULT_PRINCIPAL,         // 主要服务器名字
        RPC_C_AUTHN_LEVEL_PKT_PRIVACY,  // RPC_C_AUTHN_LEVEL_xxx 
        RPC_C_IMP_LEVEL_IMPERSONATE,    // RPC_C_IMP_LEVEL_xxx
        NULL,                           // 客户身份
        EOAC_NONE                       // 代理功能 
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 使用IWbemServices指针提出WMI请求. 
    // 查询指明当前操作系统名的Win32_OperatingSystem.Caption.
    hr = pSvc->ExecQuery(bstr_t(L"WQL"), 
        bstr_t(L"SELECT Caption FROM Win32_OperatingSystem"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL, &pEnumerator);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 确保枚举代理.
    hr = CoSetProxyBlanket(
        pEnumerator,                    // 指明代理来设置
        RPC_C_AUTHN_DEFAULT,            // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_DEFAULT,            // RPC_C_AUTHZ_xxx
        COLE_DEFAULT_PRINCIPAL,         // 主要服务器名字
        RPC_C_AUTHN_LEVEL_PKT_PRIVACY,  // RPC_C_AUTHN_LEVEL_xxx 
        RPC_C_IMP_LEVEL_IMPERSONATE,    // RPC_C_IMP_LEVEL_xxx
        NULL,                           // 客户身份
        EOAC_NONE                       // 代理功能 
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 通过以上的查询来获取数据.
    IWbemClassObject *pclsObj = NULL;
    ULONG uReturn = 0;

    while (pEnumerator)
    {
        // 获得一个对象.
        HRESULT hrTmp = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

        if (0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        // 获取Win32_OperatingSystem.Caption属性的值.
        hrTmp = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);
        if (SUCCEEDED(hrTmp))
        {
            hr = StringCchCopy(pszName, cch, vtProp.bstrVal);

            VariantClear(&vtProp);
        }

        pclsObj->Release();
        pclsObj = NULL;
    }

Cleanup:
    // 集中清理所以的已分配资源.
    if (pLoc)
    {
        pLoc->Release();
        pLoc = NULL;
    }
    if (pSvc)
    {
        pSvc->Release();
        pSvc = NULL;
    }
    if (pEnumerator)
    {
        pEnumerator->Release();
        pEnumerator = NULL;
    }

    CoUninitialize();

    return SUCCEEDED(hr);
}
RTDECL(int) RTSystemQueryDmiString(RTSYSDMISTR enmString, char *pszBuf, size_t cbBuf)
{
    AssertPtrReturn(pszBuf, VERR_INVALID_POINTER);
    AssertReturn(cbBuf > 0, VERR_INVALID_PARAMETER);
    *pszBuf = '\0';
    AssertReturn(enmString > RTSYSDMISTR_INVALID && enmString < RTSYSDMISTR_END, VERR_INVALID_PARAMETER);

    /*
     * Figure the property name before we start.
     */
    const char *pszPropName;
    switch (enmString)
    {
        case RTSYSDMISTR_PRODUCT_NAME:      pszPropName = "Name"; break;
        case RTSYSDMISTR_PRODUCT_VERSION:   pszPropName = "Version"; break;
        case RTSYSDMISTR_PRODUCT_UUID:      pszPropName = "UUID"; break;
        case RTSYSDMISTR_PRODUCT_SERIAL:    pszPropName = "IdentifyingNumber"; break;
        case RTSYSDMISTR_MANUFACTURER:      pszPropName = "Vendor"; break;

        default:
            return VERR_NOT_SUPPORTED;
    }

    /*
     * Before we do anything with COM, we have to initialize it.
     */
    HRESULT hrc = rtSystemDmiWinInitialize();
    if (FAILED(hrc))
        return VERR_NOT_SUPPORTED;

    int rc = VERR_NOT_SUPPORTED;
    BSTR pBstrPropName = rtSystemWinBstrFromUtf8(pszPropName);
    if (pBstrPropName)
    {
        /*
         * Instantiate the IWbemLocator, whatever that is and connect to the
         * DMI serve.
         */
        IWbemLocator *pLoc;
        hrc = CoCreateInstance(CLSID_WbemLocator,
                               0,
                               CLSCTX_INPROC_SERVER,
                               IID_IWbemLocator,
                               (LPVOID *)&pLoc);
        if (SUCCEEDED(hrc))
        {
            IWbemServices *pServices;
            hrc = rtSystemDmiWinConnectToServer(pLoc, "ROOT\\CIMV2", &pServices);
            if (SUCCEEDED(hrc))
            {
                /*
                 * Enumerate whatever it is we're looking at and try get
                 * the desired property.
                 */
                BSTR pBstrFilter = rtSystemWinBstrFromUtf8("Win32_ComputerSystemProduct");
                if (pBstrFilter)
                {
                    IEnumWbemClassObject *pEnum;
                    hrc = pServices->CreateInstanceEnum(pBstrFilter, 0, NULL, &pEnum);
                    if (SUCCEEDED(hrc))
                    {
                        do
                        {
                            IWbemClassObject *pObj;
                            ULONG cObjRet;
                            hrc = pEnum->Next(WBEM_INFINITE, 1, &pObj, &cObjRet);
                            if (   SUCCEEDED(hrc)
                                && cObjRet >= 1)
                            {
                                VARIANT Var;
                                VariantInit(&Var);
                                hrc = pObj->Get(pBstrPropName, 0, &Var, 0, 0);
                                if (   SUCCEEDED(hrc)
                                    && V_VT(&Var) == VT_BSTR)
                                {
                                    /*
                                     * Convert the BSTR to UTF-8 and copy it
                                     * into the return buffer.
                                     */
                                    char *pszValue;
                                    rc = RTUtf16ToUtf8(Var.bstrVal, &pszValue);
                                    if (RT_SUCCESS(rc))
                                    {
                                        rc = RTStrCopy(pszBuf, cbBuf, pszValue);
                                        RTStrFree(pszValue);
                                        hrc = WBEM_S_FALSE;
                                    }
                                }
                                VariantClear(&Var);
                                pObj->Release();
                            }
                        } while (hrc != WBEM_S_FALSE);

                        pEnum->Release();
                    }
                    SysFreeString(pBstrFilter);
                }
                else
                    hrc = E_OUTOFMEMORY;
                pServices->Release();
            }
            pLoc->Release();
        }
        SysFreeString(pBstrPropName);
    }
    else
        hrc = E_OUTOFMEMORY;
    rtSystemDmiWinTerminate();
    if (FAILED(hrc) && rc == VERR_NOT_SUPPORTED)
        rc = VERR_NOT_SUPPORTED;
    return rc;
}
Ejemplo n.º 15
0
HRESULT
GetAndSetValuesInClass(
    _In_     IWbemServices* WbemServices,
    _In_opt_ PWSTR UserId,
    _In_opt_ PWSTR Password,
    _In_opt_ PWSTR DomainName
    )

/*++

Routine Description:

    This routine enumerates the instances of the Toaster Device Information
    class and gets/sets the value of one of its Properties.

Arguments:

    WbemServices - Pointer to the WBEM services interface used for accessing
        the WMI services.

    UserId - Pointer to the user id information or NULL.

    Password - Pointer to password or NULL. If the user id is not specified,
        this parameter is ignored.

    DomainName - Pointer to domain name or NULL. If the user id is not specified,
        this parameter is ignored.

Return Value:

    HRESULT Status code.

--*/

{
    HRESULT status = S_OK;

    IEnumWbemClassObject* enumerator  = NULL;
    IWbemClassObject* classObj        = NULL;
    IWbemClassObject* instanceObj     = NULL;

    const BSTR className   = SysAllocString(TOASTER_DEVICE_INFO_CLASS);

    VARIANT instProperty;
    ULONG   nbrObjsSought = 1;
    ULONG   nbrObjsReturned;

    //
    // Create an Enumeration object to enumerate the instances of the given class.
    //
    status = WbemServices->CreateInstanceEnum(className,
                                              WBEM_FLAG_SHALLOW | WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                                              NULL,
                                              &enumerator);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set authentication information for the interface.
    //
    status = SetInterfaceSecurity(enumerator, UserId, Password, DomainName);
    if (FAILED(status)) {
        goto exit;
    }

    do {

        //
        // Get the instance object for each instance of the class.
        //
        status = enumerator->Next(WBEM_INFINITE,
                                  nbrObjsSought,
                                  &instanceObj,
                                  &nbrObjsReturned);

        if (status == WBEM_S_FALSE) {
            status = S_OK;
            break;
        }

        if (FAILED(status)) {
            if (status == WBEM_E_INVALID_CLASS) {
                printf("ERROR: Toaster driver may not be active on the system.\n");
            }
            goto exit;
        }

        //
        // To obtain the object path of the object for which the method has to be
        // executed, query the "__PATH" property of the WMI instance object.
        //
        status = instanceObj->Get(_bstr_t(L"__PATH"), 0, &instProperty, 0, 0);
        if (FAILED(status)) {
            goto exit;
        }

        printf("\n");
        printf("Instance Path .: %ws\n", (wchar_t*)instProperty.bstrVal);

        //
        // Get the current value of the DummyValue property.
        //
        status = instanceObj->Get(TOASTER_VAR1, 0, &instProperty, NULL, NULL);
        if (FAILED(status)) {
            goto exit;
        }

        printf("  Property ....: %ws\n", TOASTER_VAR1);
        printf("  Old Value ...: %d\n", instProperty.lVal);

        //
        // Set a new value for the DummyValue property.
        //
        instProperty.lVal++;

        status = instanceObj->Put(TOASTER_VAR1, 0, &instProperty, 0);
        if (FAILED(status)) {
            goto exit;
        }

        status = WbemServices->PutInstance(instanceObj,
                                           WBEM_FLAG_UPDATE_ONLY,
                                           NULL,
                                           NULL);
        if (FAILED(status)) {
            goto exit;
        }

        status = instanceObj->Get(_bstr_t(TOASTER_VAR1), 0, &instProperty, NULL, NULL);
        if (FAILED(status)) {
            goto exit;
        }

        printf("  New Value ...: %d\n", instProperty.lVal);

        instanceObj->Release();
        instanceObj = NULL;

    } while (!FAILED(status));

exit:

    if (className != NULL) {
        SysFreeString(className);
    }

    if (classObj != NULL) {
        classObj->Release();
    }

    if (enumerator != NULL) {
        enumerator->Release();
    }

    if (instanceObj != NULL) {
        instanceObj->Release();
    }

    return status;
}
Ejemplo n.º 16
0
//===============================================
//XInputの設定
//===============================================
//[input]
//
//[return]
//	hr
//===============================================
HRESULT CInput::SetupXInputDevice()
{
	IWbemServices *pIWbemServices = NULL;
	IEnumWbemClassObject *pEnumDevices = NULL;
	IWbemLocator *pIWbemLocator = NULL;
	IWbemClassObject *pDevice[20] = {0};
	BSTR bstrDeviceID = NULL;
	BSTR bstrClassName = NULL;
	BSTR bstrNamespace = NULL;
	DWORD Returned = 0;
	bool IsCleanupCOM = false;
	UINT Device = 0;
	VARIANT var;
	HRESULT hr;
	
	hr = CoInitialize(NULL);
	IsCleanupCOM = SUCCEEDED(hr);
	
	/*WMIの生成*/
	hr = CoCreateInstance(__uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&pIWbemLocator);
	
	if(FAILED(hr) || pIWbemLocator == NULL)
	{
		goto LCleanUp;
	}
	
	/*BSTRの生成*/
	bstrNamespace = SysAllocString(L"\\\\.\\root\\cimv2");
	bstrDeviceID  = SysAllocString(L"DeviceID");
	bstrClassName = SysAllocString(L"Win32_PNPEntity");
	
	if(bstrNamespace == NULL)
	{
		goto LCleanUp;
	}
	
	if(bstrDeviceID == NULL)
	{
		goto LCleanUp;
	}
	
	if(bstrClassName == NULL)
	{
		goto LCleanUp;
	}
	
	/*WMIへの接続*/
	hr = pIWbemLocator->ConnectServer(bstrNamespace, NULL, NULL, 0L, 0L, NULL, NULL, &pIWbemServices);
	
	if(FAILED(hr) || pIWbemServices == NULL)
	{
		goto LCleanUp;
	}
	
	/*セキュリティーレベルの切替*/
	//CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
	//					RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0); 
						
	/*リストを得る*/
	hr = pIWbemServices->CreateInstanceEnum(bstrClassName, 0, NULL, &pEnumDevices);
	
	if(FAILED(hr) )
	{
		goto LCleanUp;
	}
	
	for(;;)
	{
		hr = pEnumDevices->Next(10000, 20, pDevice, &Returned);
		
		if(FAILED(hr) )
		{
			goto LCleanUp;
		}
		
		if(Returned == 0)
		{
			break;
		}
		
		for(Device = 0;Device < Returned;Device++)
		{
			hr = pDevice[Device]->Get(bstrDeviceID, 0L, &var, NULL, NULL);
			
			if(SUCCEEDED(hr) )
			{
				if(wcsstr(var.bstrVal, L"IG_") )
				{
					DWORD dwPid = 0;
					DWORD dwVid = 0;
					
					WCHAR *pstrVid = wcsstr(var.bstrVal, L"VID_" );
					
					if(pstrVid && swscanf_s(pstrVid, L"VID_%4X", &dwVid) != 1)
					{
						dwVid = 0;
					}
					
					WCHAR *pstrPid = wcsstr(var.bstrVal, L"PID_");
					
					if(pstrPid && swscanf_s(pstrPid, L"PID_%4L", &dwPid) != 1)
					{
						dwPid = 0;
					}
					
					DWORD dwVidPid = MAKELONG(dwVid, dwPid); 
					
					XINPUT_DEVICE_NODE *pNewNode = new XINPUT_DEVICE_NODE;
					
					if(pNewNode)
					{
						pNewNode->dwVidPid = dwVidPid;
					}
					
				}
			}
			
			RELEASE(pDevice[Device] );
		}
	}
	
LCleanUp:
	if(bstrNamespace)
	{
		SysFreeString(bstrNamespace);
	}	
	
	if(bstrDeviceID)
	{
		SysFreeString(bstrDeviceID);
	}
	
	if(bstrClassName)
	{
		SysFreeString(bstrClassName);
	}
	
	for(Device = 0;Device < 20;Device++)
	{
		RELEASE(pDevice[Device]);
	}
	
	RELEASE(pEnumDevices);
	RELEASE(pIWbemLocator);
	RELEASE(pIWbemServices);
	
	return hr;
	
}
Ejemplo n.º 17
0
int wmi_get_cpu_comp_user_sys(float* pcpu_load_comp, float* pcpu_load_user, float* pcpu_load_sys) {

	assert(_initialized);
	assert(pcpu_load_comp);
	assert(pcpu_load_user);
	assert(pcpu_load_sys);

	float& cpu_load_comp = *pcpu_load_comp;
	float& cpu_load_user = *pcpu_load_user;
	float& cpu_load_sys = *pcpu_load_sys;

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

	cpu_load_comp = 0;
	cpu_load_user = 0;

	bool user_logged = false;

	long long current_process_id = _current_process_id;

	enumerator = request(
		bstr_t("SELECT Name, IDProcess, PercentProcessorTime FROM Win32_PerfFormattedData_PerfProc_Process WHERE PercentUserTime > 0")
	);
		
	VARIANT var;
	VARIANT var_name;
	VARIANT user;

	ULONG uReturn;
	for(;;) {
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);

		if(0 == uReturn) {
			break;
		}
			
		VariantInit(&var);
		// Get Process ID of object - Required for Get Owner Input
		result = object->Get(L"IDProcess", 0, &var, NULL, NULL );
		long long process_id = var.iVal;

		// Get total cpu load
		VariantInit(&var);
		result = object->Get(L"PercentProcessorTime", 0, &var, NULL, NULL );
		long long process_cpu_load = _wtoi(var.bstrVal);

		//std::wcout << "process_cpu_load: " << process_cpu_load << " var.bstrVal : " << var.bstrVal << " app name: " << var_name.bstrVal << std::endl;

		//std::cout << "app name: " << wtoa(var_name.bstrVal) << std::endl;
		//std::cout << "process_cpu_load: " << process_cpu_load << std::endl;
		if (process_id == 0) {

			// Process id 0 = System Idle Process
			continue;

		} else if (process_id == current_process_id) {

			//std::cout << "COMP test:" << process_cpu_load << std::endl;
			cpu_load_comp = (float)process_cpu_load;

		} else if(user_proc_set.find(process_id) != user_proc_set.end()) {

			//std::cout << "user fnd:" << process_id << '\n';
			//Print(std::wcout, var_name);
			cpu_load_user += (float)process_cpu_load;

		} else if(system_proc_set.find(process_id) != system_proc_set.end()) {

			//std::cout << "sys Fnd:" << process_id << '\n';
			//Print(std::wcout, var_name);
			cpu_load_sys += (float)process_cpu_load;

		} else {
			//std::cout << "TEST: " << process_id << '\n';
					// Declare
			IWbemClassObject* pwcrGetOwnerIn = NULL;
			IWbemClassObject* pwcrGetOwnerOut = NULL;
			IWbemClassObject* pOutParams = NULL;
			result = services->ExecMethod(bstr_t("Win32_Process.Handle=") + bstr_t(process_id), bstr_t(L"GetOwner"), 0, NULL, pwcrGetOwnerIn, &pOutParams, NULL);
				
			VariantInit(&user);
			if (pOutParams) {
				result = pOutParams->Get(L"User", 0, &user, 0, 0);
				pOutParams->Release();
			}
			//std::cout << "result: " << result << std::endl;
			if (SUCCEEDED(result) && user.vt == VT_BSTR) {
				const bstr_t& process_owner = user.bstrVal;
				if (process_owner.length() && process_owner == _username) { 
					//std::cout << "user Insrt: " << process_id << " <_> " << process_cpu_load << '\n';
					//Print(std::wcout, var_name);
					user_proc_set.insert(process_id);
					cpu_load_user += (float)process_cpu_load;
				}
			} else {

				// Get process name
				{
					result = object->Get(L"Name", 0, &var_name, NULL, NULL);
					//std::cout << "Name: " << wtoa(var_name.bstrVal) << std::endl;
				}

				if (bstr_t(var_name.bstrVal) != bstr_t("_Total")) {
					//std::cout << "OTHER test: " << process_cpu_load << std::endl;
					//std::cout << "system Insrt:" << process_id << " <_> " << process_cpu_load << '\n';
					//Print(std::wcout, var_name);
					system_proc_set.insert(process_id);
					cpu_load_sys += (float)process_cpu_load;
				}
			}

			//pOutParams->Release();
		}

		object->Release();
	} // for(;;)


	VariantClear(&var);
    VariantClear(&var_name);
	VariantClear(&user);

	// Normalize value
	float total_cpu_load = cpu_load_comp + cpu_load_user + cpu_load_sys;
	if (total_cpu_load > 100) {
		cpu_load_comp = (cpu_load_comp / total_cpu_load) * 100;
		cpu_load_user = (cpu_load_user / total_cpu_load) * 100;
		cpu_load_sys = (cpu_load_sys / total_cpu_load) * 100;
	}
	//std::cout << "cpu_load_comp f: " << cpu_load_comp << std::endl;
	//std::cout << "cpu_load_user f: " << cpu_load_user << std::endl;
	//std::cout << "cpu_load_sys f: " << cpu_load_sys << std::endl;

	if (enumerator)
		enumerator->Release();

	return 0;	
}
Ejemplo n.º 18
0
HRESULT QuerySecurityCenterProducts(char *query, list<struct productInfo> *productList, WHISKER_PRODUCT_TYPE productType) {
    HRESULT hres;
    
    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
        return hres;                 // Program has failed.
    }

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

    IWbemServices *pSvc = NULL;
	
    // 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\\SECURITYCENTER"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (e.g. Kerberos)
         0,                       // Context object 
         &pSvc                    // pointer to IWbemServices proxy
         );
    
    if (FAILED(hres))
    {
        cout << "Could not connect to ROOT\\SECURITYCENTER. Error code = 0x" 
             << hex << hres << endl;
        pLoc->Release();     
        return hres;                // Program has failed.
    }

    //cout << "Connected to ROOT\\SECURITYCENTER 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
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // 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();     
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"), 
        bstr_t(query),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL,
        &pEnumerator);
    
    if (FAILED(hres))
    {
        cout << "Query '" << query << "' failed."
            << " Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        return hres;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------
    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;
   
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, 
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
		}

		// A place to store our product data.
		struct productInfo product;
		memset(&product, 0x0, sizeof(struct productInfo));

        VARIANT vtProp;

        // Get the value of the Name property
        hr = pclsObj->Get(L"displayName", 0, &vtProp, 0, 0);
        wcout << "Product Name: " << vtProp.bstrVal << endl;

		product.displayName = vtProp.bstrVal;

        VariantClear(&vtProp);

		hr = pclsObj->Get(L"instanceGuid", 0, &vtProp, 0, 0);
		//wcout << "Instance GUID: " << vtProp.bstrVal << endl;

		product.instanceGuid = vtProp.bstrVal;

		VariantClear(&vtProp);

        hr = pclsObj->Get(L"companyName", 0, &vtProp, 0, 0);
        wcout << "Company Name: " << vtProp.bstrVal << endl;

		product.companyName = vtProp.bstrVal;

        VariantClear(&vtProp);

		hr = pclsObj->Get(L"productEnabled", 0, &vtProp, 0, 0);
		wcout << "Product Enabled: " << (vtProp.boolVal ? L"Yes" : L"No") << endl;

		product.productEnabled = (vtProp.boolVal != 0);

		VariantClear(&vtProp);

		hr = pclsObj->Get(L"productHasNotifiedUser", 0, &vtProp, 0, 0);
		wcout << "Product Has Notified User: "******"Yes" : L"No") << endl;

		product.productHasNotifiedUser = (vtProp.boolVal != 0);

		VariantClear(&vtProp);

		hr = pclsObj->Get(L"productUptoDate", 0, &vtProp, 0, 0);
		wcout << "Product Up to Date: " << (vtProp.boolVal ? L"Yes" : L"No") << endl;

		product.productUptoDate = (vtProp.boolVal != 0);

		VariantClear(&vtProp);

		hr = pclsObj->Get(L"productWantWscNotifications", 0, &vtProp, 0, 0);
		wcout << "Product Wants WSC Notifications: " << (vtProp.boolVal ? L"Yes" : L"No") << endl;

		product.productWantsWscNotifications = (vtProp.boolVal != 0);

		VariantClear(&vtProp);

		hr = pclsObj->Get(L"versionNumber", 0, &vtProp, 0, 0);
		wcout << "Version Number: " << vtProp.bstrVal << endl;

		product.versionNumber = vtProp.bstrVal;

		VariantClear(&vtProp);

		hr = pclsObj->Get(L"productState", 0, &vtProp, 0, 0);

		int byte4 = (vtProp.intVal & 0xFF000000) >> 24;
		int byte3 = (vtProp.intVal & 0x00FF0000) >> 16;
		int byte2 = (vtProp.intVal & 0x0000FF00) >> 8;
		int byte1 = (vtProp.intVal & 0x000000FF);

		wcout << "Legacy WSC State" << endl;
		wcout << "Product State: " << dec << vtProp.intVal << endl;
		wcout << "Product State (hex): " << hex << vtProp.intVal << endl;
		wcout << "Byte 4: " << hex << byte4 << endl;
		wcout << "Byte 3: " << hex << byte3 << endl;
		wcout << "Byte 2: " << hex << byte2 << endl;
		wcout << "Byte 1: " << hex << byte1 << endl;
		wcout << "Product Type (Legacy):  " << securityProviderGuess(vtProp.intVal).c_str() << endl;
		wcout << "Realtime Protection (Legacy): " << scannerActiveGuess(vtProp.intVal).c_str() << endl;
		wcout << "DAT File (Legacy): " << datFileGuess(vtProp.intVal).c_str() << endl;

		product.legacyProductState = vtProp.intVal;

		product.productType = productType;

		productList->push_back(product);

		VariantClear(&vtProp);

		// Hack together a product state that is compatible with newer WSC:
		switch(product.productType) {
			case PRODUCT_TYPE_AV:
				product.productState = WSC_SECURITY_PROVIDER_ANTIVIRUS << 16;
				break;
			case PRODUCT_TYPE_AS:
				product.productState = WSC_SECURITY_PROVIDER_ANTISPYWARE << 16;
				break;
			case PRODUCT_TYPE_FW:
				product.productState = WSC_SECURITY_PROVIDER_FIREWALL << 16;
				break;
		};

		if(product.productEnabled) {
			product.productState += REAL_TIME_PROTECTION_ENABLED;
		}

		if(product.productUptoDate == false) {
			product.productState += DAT_FILE_OUT_OF_DATE;

		}

		byte4 = (product.productState & 0xFF000000) >> 24;
		byte3 = (product.productState & 0x00FF0000) >> 16;
		byte2 = (product.productState & 0x0000FF00) >> 8;
		byte1 = (product.productState & 0x000000FF);

		wcout << "New WSC State" << endl;
		wcout << "Product State: " << dec << product.productState << endl;
		wcout << "Product State (hex): " << hex << product.productState << endl;
		wcout << "Byte 4: " << hex << byte4 << endl;
		wcout << "Byte 3: " << hex << byte3 << endl;
		wcout << "Byte 2: " << hex << byte2 << endl;
		wcout << "Byte 1: " << hex << byte1 << endl;
		wcout << "Product Type:  " << securityProviderGuess(product.productState).c_str() << endl;
		wcout << "Realtime Protection: " << scannerActiveGuess(product.productState).c_str() << endl;
		wcout << "DAT File: " << datFileGuess(product.productState).c_str() << endl;

        pclsObj->Release();
    }

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

	return S_OK;
}
// **************************************************************************
//
//	CAdvClientDlg::OnEnumdisks()
//
// Description:
//		Enumerates all the disks on a machine. Demonstrates getting
//		known properties directly.
//
// Parameters:
//		None.
//
// Returns:
//		Nothing.
//
// Globals accessed:
//		None.
//
// Globals modified:
//		None.
//
//===========================================================================
void CAdvClientDlg::OnEnumdisks() 
{
	// these are for enumerating.
	HRESULT  hRes;
	ULONG uReturned;
	IWbemClassObject *pStorageDev = NULL;
	IEnumWbemClassObject *pEnumStorageDevs = NULL;

	// these help get properties.
	VARIANT pVal;
	BSTR propName = NULL;
    CString buf;

	// here's what we're looking for.
	// NOTE: make sure you specify a class that has a Provider()
	//	specified for it in the mof file. All other classes are
	//	abstract and wont be found using HMM_FLAG_SHALLOW. They
	//	will be found using HMM_FLAG_DEEP.
	BSTR className = SysAllocString(L"Win32_LogicalDisk");
	if (!className)
	{		
		TRACE(_T("SysAllocString failed: not enough memory\n"));
		return;
	}

	// setup for the "__RELPATH" system property.
	propName = SysAllocString(L"__RELPATH");
	if (!propName)
	{		
		SysFreeString(className);
		TRACE(_T("SysAllocString failed: not enough memory\n"));
		return;
	}

	VariantInit(&pVal);

	m_outputList.ResetContent();
	m_outputList.AddString(_T("working..."));

	TRACE(_T("Going for class\n"));

	//---------------------------
	// get the list of logical storage devices.
    if ((hRes = m_pIWbemServices->CreateInstanceEnum(className,
												WBEM_FLAG_SHALLOW, 
												NULL,
												&pEnumStorageDevs)) == S_OK) 
	{
		TRACE(_T("good enumerator\n"));

		m_outputList.ResetContent();

		uReturned = 1;
		while(uReturned == 1)
		{
			//---------------------------
			// enumerate through the resultset.
			hRes = pEnumStorageDevs->Next(TIMEOUT,
										1,
										&pStorageDev,
										&uReturned);

			TRACE(_T("Next() %d:%s\n"), uReturned, ErrorString(hRes));

			// was one found?
			if((hRes == S_OK) && (uReturned == 1))
			{

				TRACE(_T("Got a device class\n"));

				VariantClear(&pVal);

			
				// Add the path
				if (pStorageDev->Get(propName, 
										0L, 
										&pVal, 
										NULL, NULL) == S_OK) 
				{
					TRACE(_T("Got a device path\n"));
					 buf = V_BSTR(&pVal);
				} 

				// add to the output listbox.
				m_outputList.AddString(buf);

				// cleanup for next loop
				VariantInit(&pVal);

				// Done with this object.
				if (pStorageDev)
				{ 
					pStorageDev->Release();

					// NOTE: pStorageDev MUST be set to NULL for the next all to Next().
					pStorageDev = NULL;
				} 

			} // endif (hRes == S_OK)

        } // endwhile

		TRACE(_T("done enumming: %s\n"), ErrorString(hRes));

		// Done with this enumerator.
		if (pEnumStorageDevs)
		{ 
			pEnumStorageDevs->Release(); 
			pEnumStorageDevs = NULL;
		}
    } 
	else // CreateInstanceEnum() failed.
	{
		TRACE(_T("CreateInstanceEnum() failed: %s\n"), ErrorString(hRes));

	} // endif CreateInstanceEnum()

	TRACE(_T("returning\n"));
}
Ejemplo n.º 20
0
static char *
getWmiInfo (int mode)
{
	/* for more details about this wonderful API, see 
	http://msdn.microsoft.com/en-us/site/aa394138
	http://msdn.microsoft.com/en-us/site/aa390423
	http://msdn.microsoft.com/en-us/library/windows/desktop/aa394138%28v=vs.85%29.aspx
	http://social.msdn.microsoft.com/forums/en-US/vcgeneral/thread/d6420012-e432-4964-8506-6f6b65e5a451
	*/

	char *buffer = (char *) malloc (128);
	HRESULT hres;
	HRESULT hr;
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	IEnumWbemClassObject *pEnumerator = NULL;
	IWbemClassObject *pclsObj;
	ULONG uReturn = 0;

	hres =  CoInitializeEx (0, COINIT_APARTMENTTHREADED | COINIT_SPEED_OVER_MEMORY);

	if (FAILED (hres))
	{
		strcpy (buffer, "Error Code 0");
		return buffer;
	}

	hres =  CoInitializeSecurity (NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);

	/* mysteriously failing after the first execution, but only when used as a plugin, skip it */
	/*if (FAILED (hres))
	{
		CoUninitialize ();
		strcpy (buffer, "Error Code 1");
		return buffer;
	}*/

	hres = CoCreateInstance (CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

	if (FAILED (hres))
	{
		CoUninitialize ();
		strcpy (buffer, "Error Code 2");
		return buffer;
	}

	hres = pLoc->ConnectServer (_bstr_t (L"root\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);

	if (FAILED (hres))
	{
		pLoc->Release ();
		CoUninitialize ();
		strcpy (buffer, "Error Code 3");
		return buffer;
	}

	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 ();
		strcpy (buffer, "Error Code 4");
		return buffer;
	}

	switch (mode)
	{
		case 0:
			hres = pSvc->ExecQuery (_bstr_t ("WQL"), _bstr_t ("SELECT * FROM Win32_OperatingSystem"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
			break;
		case 1:
			hres = pSvc->ExecQuery (_bstr_t ("WQL"), _bstr_t ("SELECT * FROM Win32_Processor"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
			break;
		case 2:
			hres = pSvc->ExecQuery (_bstr_t ("WQL"), _bstr_t ("SELECT * FROM Win32_VideoController"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
			break;

	}

	if (FAILED (hres))
	{
		pSvc->Release ();
		pLoc->Release ();
		CoUninitialize ();
		strcpy (buffer, "Error Code 5");
		return buffer;
	}

	while (pEnumerator)
	{
		hr = pEnumerator->Next (WBEM_INFINITE, 1, &pclsObj, &uReturn);
		if (0 == uReturn)
		{
			break;
		}
		VARIANT vtProp;
		switch (mode)
		{
			case 0:
				hr = pclsObj->Get (L"Caption", 0, &vtProp, 0, 0);
				break;
			case 1:
				hr = pclsObj->Get (L"Name", 0, &vtProp, 0, 0);
				break;
			case 2:
				hr = pclsObj->Get (L"Name", 0, &vtProp, 0, 0);
				break;
		}
		WideCharToMultiByte (CP_ACP, 0, vtProp.bstrVal, -1, buffer, SysStringLen (vtProp.bstrVal)+1, NULL, NULL);
		VariantClear (&vtProp);
    }

	pSvc->Release ();
	pLoc->Release ();
	pEnumerator->Release ();
	pclsObj->Release ();
	CoUninitialize ();
	return buffer;
}
Ejemplo n.º 21
0
bool WMIVideoInfo::_queryPropertyWMI( const PVIQueryType queryType, const U32 adapterId, String *outValue )
{
   if( mServices == NULL )
      return false;

   BSTR bstrWQL  = SysAllocString(L"WQL");
   BSTR bstrPath = SysAllocString(L"select * from Win32_VideoController");
   IEnumWbemClassObject* enumerator;
   
   // Use the IWbemServices pointer to make requests of WMI
   HRESULT hr = mServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator);

   if( FAILED( hr ) )
      return false;

   IWbemClassObject *adapter = NULL;   
   ULONG uReturned;

   // Get the appropriate adapter.
   for ( S32 i = 0; i <= adapterId; i++ )
   {
      hr = enumerator->Next(WBEM_INFINITE, 1, &adapter, &uReturned );

      if ( FAILED( hr ) || uReturned == 0 )
      {
         enumerator->Release();
         return false;         
      }
   }

   // Now get the property
   VARIANT v;
   hr = adapter->Get( smPVIQueryTypeToWMIString[queryType], 0, &v, NULL, NULL );

   bool result = SUCCEEDED( hr );

   if ( result )
   {
      switch( v.vt )
      {
      case VT_I4:
         {
            LONG longVal = v.lVal;

            if( queryType == PVI_VRAM )
               longVal = longVal >> 20; // Convert to megabytes

            *outValue = String::ToString( (S32)longVal );
            break;
         }

      case VT_UI4:
         {
            *outValue = String::ToString( (U32)v.ulVal );
            break;
         }

      case VT_BSTR:
         {
            *outValue = String( v.bstrVal );
            break;
         }            
      case VT_LPSTR:
      case VT_LPWSTR:
         break;
      }


   }                  

   // Cleanup      
   adapter->Release();   
   enumerator->Release();

   return result;
}
Ejemplo n.º 22
0
LRESULT CALLBACK  //static
IPodDetector::WindowProc(  HWND hwnd,
                           UINT uMsg,
                           WPARAM wParam,
                           LPARAM lParam
                         )
{
    IPodDetector* ipd = s_hwndMap[ hwnd ];

    switch( uMsg )
    {
        case WM_DEVICECHANGE:
        {
            HRESULT result = PostMessage( hwnd, WM_USER, wParam, lParam );
            if( FAILED( result ) )
                LOGL( 3, "error: PostMessage WM_USER failed: " << ::GetLastError() )

        }
        break;

        case WM_USER:
            switch( wParam )
            {
                case DBT_DEVICEARRIVAL:
                {
                    std::string deviceId = ipd->getDBTDeviceInfo( lParam );
                    LOGL( 3, "Device arrived - id: " << deviceId )
                    IEnumWbemClassObject* enumerator;
                    ipd->queryByDeviceID( deviceId, &enumerator );
                    
                    IWbemClassObject* object;
                    ULONG retCount;

                    int count = 0;
                    while( enumerator )
                    {
                        enumerator->Next( WBEM_INFINITE,
                                          1,
                                          &object,
                                          &retCount );

                        if( 0 == retCount )
                            break;

                        ipd->onDeviceConnected( object );
                        object->Release();
                        count++;
                    }
                    if( count > 0 )
                    {
                        LOGL( 3, count << " ipods found with this deviceId" );
                    }
                    else
                    {
                        LOGL( 3, "no ipods found with this deviceid - presumeably a non-ipod has been plugged in!" )
                    }
                    enumerator->Release();
                }
                break;

                case DBT_DEVICEREMOVECOMPLETE:
                {
                    //std::string deviceId = ipd->getDBTDeviceInfo( lParam );
                    LOGL( 3, "DBT device removal detected - checking for disconnected iPod.." );
                    ipd->onDeviceRemoved();
                }
                break;

                default:
                {
        //            LOGL( 3, "Unknown WM_DEVICECHANGE wParam: " << wParam );
                }
                break;
            }
        break;

        default:
            return DefWindowProc( hwnd, uMsg, wParam, lParam );
        break;
    }
    return 0;
}
Ejemplo n.º 23
0
bool CSMBiosTable::FetchSMBiosDataByCom( unsigned char ** p )
{
	BOOL bRet = FALSE;   
	HRESULT hres;   

	// Initialize COM.    
	hres =  CoInitializeEx( 0, COINIT_MULTITHREADED );    
	if( FAILED(hres) )   
	{   
		return FALSE;              // Program has failed.    
	}   

	// Obtain the initial locator to Windows Management    
	// on a particular host computer.    
	IWbemLocator *pLoc = 0;   
	hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc );   
	if( FAILED(hres) )   
	{   
		CoUninitialize();   
		return FALSE;       // Program has failed.    
	}   

	IWbemServices *pSvc = 0;   

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

	if( FAILED(hres) )   
	{   
		pLoc->Release();        
		CoUninitialize();   
		return FALSE;                // Program has failed.    
	}   

	// Set the IWbemServices proxy so that impersonation    
	// of the user (client) occurs.    
	hres = CoSetProxyBlanket(   
		pSvc,                         // the proxy to set    
		RPC_C_AUTHN_WINNT,            // authentication service    
		RPC_C_AUTHZ_NONE,             // authorization service    
		NULL,                         // Server principal name    
		RPC_C_AUTHN_LEVEL_CALL,       // authentication level    
		RPC_C_IMP_LEVEL_IMPERSONATE,  // impersonation level    
		NULL,                         // client identity     
		EOAC_NONE                     // proxy capabilities         
		);   

	if( FAILED(hres) )   
	{   
		pSvc->Release();   
		pLoc->Release();        
		CoUninitialize();   
		return FALSE;               // Program has failed.    
	}   

	IEnumWbemClassObject* pEnumerator = NULL;   
	hres = pSvc->CreateInstanceEnum( L"MSSMBios_RawSMBiosTables", 0, NULL, &pEnumerator);
	if( FAILED(hres) )   
	{   
		pSvc->Release();   
		pLoc->Release();        
		CoUninitialize();   
		return FALSE;               // Program has failed.    
	}   
	else   
	{    
		do   
		{   
			IWbemClassObject* pInstance = NULL;   
			ULONG dwCount = NULL;   

			hres = pEnumerator->Next( WBEM_INFINITE, 1, &pInstance, &dwCount);         
			if( SUCCEEDED(hres) )   
			{   
				VARIANT varBIOSData;   
				VariantInit(&varBIOSData);   
				CIMTYPE  type;   

				hres = pInstance->Get(bstr_t("SmbiosMajorVersion"),0,&varBIOSData,&type,NULL);   
				if( FAILED(hres) )   
				{   
					VariantClear(&varBIOSData);   
				}   
				else   
				{   
					m_smbiosbuffer.nSMBIOSMajorVersion = varBIOSData.iVal;   
					VariantInit(&varBIOSData);   
					hres = pInstance->Get( bstr_t("SmbiosMinorVersion"), 0, &varBIOSData, &type, NULL );   
					if( FAILED(hres) )   
					{   
						VariantClear( &varBIOSData );   
					}   
					else   
					{   
						m_smbiosbuffer.nSMBIOSMinorVersion = varBIOSData.iVal;   
						VariantInit(&varBIOSData);   
						hres = pInstance->Get( bstr_t("SMBiosData"), 0, &varBIOSData, &type, NULL );   
						if( SUCCEEDED(hres) )   
						{   
							if( ( VT_UI1 | VT_ARRAY  ) != varBIOSData.vt )   
							{   
							}   
							else   
							{   
								SAFEARRAY           *parray = NULL;   
								parray = V_ARRAY(&varBIOSData);   
								BYTE* pbData = (BYTE*)parray->pvData;   

								m_smbiosbuffer.nLength = parray->rgsabound[0].cElements;   
								(*p) = new unsigned char[m_smbiosbuffer.nLength];   
								memcpy_s( (*p), m_smbiosbuffer.nLength, pbData, m_smbiosbuffer.nLength );
								bRet = TRUE;   
							}   
						}   
						VariantClear( &varBIOSData );   
					}   
				}   
				break;   
			}   

		}while( hres == WBEM_S_NO_ERROR );   
	}   

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

	return bRet;  
}
Ejemplo n.º 24
0
unsigned long long loadngo::data::GetMachineId()
{
	// Step 1: --------------------------------------------------
	// Initialize COM. ------------------------------------------
//	HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
//	if (hr == S_OK)
//	{
		BSTR objectPath = SysAllocString(L"ROOT\\CIMV2");
		std::vector<char> container;
		// Step 2: --------------------------------------------------
		// Set general COM security levels --------------------------
		// Note: If you are using Windows 2000, you need to specify -
		// the default authentication credentials for a user by using
		// a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
		// parameter of CoInitializeSecurity ------------------------

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


		if (hr == S_OK)
		{

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

			IWbemLocator *pLoc = NULL;

			hr = CoCreateInstance(
				CLSID_WbemLocator,
				0,
				CLSCTX_INPROC_SERVER,
				IID_IWbemLocator, (LPVOID *)&pLoc);

			if (hr == S_OK)
			{

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

				IWbemServices *pSvc = NULL;

				// Connect to the root\cimv2 namespace with
				// the current user and obtain pointer pSvc
				// to make IWbemServices calls.
				hr = pLoc->ConnectServer(
					objectPath, // Object path of WMI namespace
					NULL,                    // User name. NULL = current user
					NULL,                    // User password. NULL = current
					0,                       // Locale. NULL indicates current
					NULL,                    // Security flags.
					0,                       // Authority (e.g. Kerberos)
					0,                       // Context object 
					&pSvc                    // pointer to IWbemServices proxy
					);

				if (hr == S_OK)
				{

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

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

					if (hr == S_OK)
					{
						// Step 6: --------------------------------------------------
						// Use the IWbemServices pointer to make requests of WMI ----
						BSTR wql = SysAllocString(L"WQL");
						BSTR query = SysAllocString(L"SELECT * FROM Win32_BIOS");
						// For example, get the name of the operating system
						IEnumWbemClassObject* pEnumerator = NULL;
						hr = pSvc->ExecQuery(
							wql,
							query,
							WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
							NULL,
							&pEnumerator);

						if (hr == S_OK)
						{
							// Step 7: -------------------------------------------------
							// Get the data from the query in step 6 -------------------

							IWbemClassObject *pclsObj = NULL;
							ULONG uReturn = 0;

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

								if (0 == uReturn)
								{
									break;
								}

								if(pclsObj->BeginEnumeration(0) == S_OK)
								{
									BSTR name = nullptr;
									VARIANT var;
									while (pclsObj->Next(0, &name, &var, nullptr, nullptr) == WBEM_S_NO_ERROR)
									{
										Insert(container, name);
										SysFreeString(name);
										InsertVariant(container, var);
										VariantClear(&var);
									}
								}

								pclsObj->Release();
							}
						}
						pEnumerator->Release();
					}
					pSvc->Release();
					pSvc = 0;
				}
				pLoc->Release();
			}
		}
		SysFreeString(objectPath);
	//	CoUninitialize();
	//}
	return util::FNV1a(&container[0], container.size());
}
Ejemplo n.º 25
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;
	}
Ejemplo n.º 26
0
/**
 * Enumerates the adapters for this host from WMI Win32_NetworkAdapter
 * where NetConnectionStatus=2 (to exclude tunnels, ras, wan miniports etc).
 * Uses the information to populate the sp->adaptorList structure.
 * adapter->deviceName = Win32_NetworkAdapter.GUID (converted to 
 * lowercase char with enclosing {} removed)
 * adapter->ifIndex = Win32_NetworkAdapter.InterfaceIndex
 * this is the interface index used in the route table (rather than Index
 * which is the index for the interface in the registry).
 * adapter->userData->countersInstance = Win32_NetworkAdapter.Name 
 * (with reserved chars replaced) 
 * adapter->userData->isVirtual = (Win32_NetworkAdapter.ServiceName == "VMSMP")
 * Optionally gets the IP address (v4 and/or v6) from the associated
 * Win32_NetworkAdapterConfiguration. This is only required when trying
 * to identify the IP addresses that could be used as the agent address.
 * Returns true on success, false on failure.
 */
static BOOL readInterfacesWin32(SFLAdaptorList *adaptorList, BOOL getIpAddr)
{
	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,"readInterfacesWin32: connectToWMI failed for namespace %S", path);
		return FALSE;
	}
	BSTR queryLang = SysAllocString(L"WQL");
	BSTR query = SysAllocString(L"SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus=2");
	IEnumWbemClassObject *adapterEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &adapterEnum);
	SysFreeString(queryLang);
	if (!SUCCEEDED(hr)) {
		myLog(LOG_ERR,"readInterfacesWin32: ExecQuery() failed for query %S error=0x%x", query, hr);
		SysFreeString(query);
		pNamespace->Release();
		return FALSE;
	}
	SysFreeString(query);
	IWbemClassObject *adapterObj = NULL;
	VARIANT ifIndexVal;
	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		ULONG adapterCount = 1;
		hr = adapterEnum->Next(WBEM_INFINITE, 1, &adapterObj, &adapterCount);
		if (0 == adapterCount) {
			break;
		}
		wchar_t *guidString = stringFromWMIProperty(adapterObj, PROP_GUID);
		wchar_t *macString = stringFromWMIProperty(adapterObj, PROP_MAC);
		if (guidString != NULL && macString != NULL) {
			u_char deviceName[FORMATTED_GUID_LEN+1];
			guidToString(guidString, deviceName, FORMATTED_GUID_LEN);
			u_char mac[13];
			wchexToBinary(macString, mac, 13);
			SFLAdaptor *adaptor = adaptorListAdd(adaptorList, 
												(char *)deviceName, mac, 
												sizeof(HSPAdaptorNIO));
			// clear the mark so we don't free it later
			adaptor->marked = FALSE;
			if (WBEM_S_NO_ERROR == adapterObj->Get(PROP_IFINDEX, 0, &ifIndexVal, 0, 0) &&
				(V_VT(&ifIndexVal) == VT_I4 || V_VT(&ifIndexVal) == VT_UI4)) {
				adaptor->ifIndex = ifIndexVal.ulVal;
			}
			HSPAdaptorNIO *userData = (HSPAdaptorNIO *)adaptor->userData;
			if (userData->countersInstance != NULL) {
				my_free(userData->countersInstance);
			}
			wchar_t *counterName = stringFromWMIProperty(adapterObj, PROP_NAME);
			if (counterName != NULL) {
				cleanCounterName(counterName, UTNETWORK_INTERFACE);
				userData->countersInstance = counterName;
			}
			wchar_t *svcName = stringFromWMIProperty(adapterObj, PROP_SVC_NAME);
			if (svcName != NULL) {
				userData->isVirtual = (_wcsicmp(VMSMP, svcName) == 0);
				my_free(svcName);
			}
			if (getIpAddr) {
				userData->ipPriority = IPSP_NONE;
				readIpAddressesWin32(pNamespace, adapterObj, adaptor);
			}
			myLog(LOG_INFO,"ReadInterfacesWin32:\n\tAdapterName:\t%s\n\tifIndex:\t%lu\n\tCounterName:\t%S\n\tisVirtual\t%u",
				adaptor->deviceName, adaptor->ifIndex, userData->countersInstance, userData->isVirtual);
		}
		if (guidString != NULL) {
			my_free(guidString);
		}
		if (macString != NULL) {
			my_free(macString);
		}
		adapterObj->Release();
		VariantClear(&ifIndexVal);
	}
	adapterEnum->Release();
	pNamespace->Release();
	return TRUE;
}
Ejemplo n.º 27
0
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 ) )
            {
				if(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 && wscanf(strVid, L"VID_%4X", &dwVid) != 1)
							dwVid = 0;
						WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
						if (strPid && wscanf(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;
						}
					}
				}
				VariantClear(&var);
            }   
            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;
}
Ejemplo n.º 28
0
int main(int argc, char **argv)
{
    HRESULT hres;

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

    // Initialize
    hres =  CoInitializeSecurity(
        NULL,
        -1,      // COM negotiates service
        NULL,    // Authentication services
        NULL,    // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,    // authentication
        RPC_C_IMP_LEVEL_IMPERSONATE,  // Impersonation
        NULL,             // Authentication info
        EOAC_NONE,        // Additional capabilities
        NULL              // Reserved
        );


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

    // Obtain the initial locator to Windows Management
    // on a particular host computer.
    IWbemLocator *pLoc = 0;

    hres = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pLoc);

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

    IWbemServices *pSvc = 0;

    // 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"), // WMI namespace
        NULL,                    // User name
        NULL,                    // User password
        0,                       // Locale
        NULL,                    // Security flags
        0,                       // Authority
        0,                       // Context object
        &pSvc                    // 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;

    // Set the IWbemServices proxy so that impersonation
    // of the user (client) occurs.
    hres = CoSetProxyBlanket(

       pSvc,                         // the proxy to set
       RPC_C_AUTHN_WINNT,            // authentication service
       RPC_C_AUTHZ_NONE,             // authorization service
       NULL,                         // Server principal name
       RPC_C_AUTHN_LEVEL_CALL,       // authentication level
       RPC_C_IMP_LEVEL_IMPERSONATE,  // impersonation level
       NULL,                         // 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.
    }


    // Use the IWbemServices pointer to make requests of WMI.
    // Make requests here:

    // For example, query for all the running processes
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"),
        bstr_t("SELECT * FROM Win32_Process"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        NULL,
        &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.
    }
    else
    {
        IWbemClassObject *pclsObj;
        ULONG uReturn = 0;

        while (pEnumerator)
        {
            hres = pEnumerator->Next(WBEM_INFINITE, 1,
                &pclsObj, &uReturn);

            if(0 == uReturn)
            {
                break;
            }

            VARIANT vtProp;

            // Get the value of the Name property
            hres = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
            wcout << "Process Name : " << vtProp.bstrVal << endl;
            VariantClear(&vtProp);
        }

    }

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

    return 0;   // Program successfully completed.
}
Ejemplo n.º 29
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);
}
Ejemplo n.º 30
0
JSON* GetSystemSpecs() {
  JSON* specs = JSON::CreateObject();
  HRESULT hres;

  IWbemLocator* pLoc = NULL;

  hres = CoCreateInstance(
      CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);

  if (FAILED(hres)) {
    return specs; // Program has failed.
  }

  IWbemServices* pSvc = NULL;

  // 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
      NULL, // User name. NULL = current user
      NULL, // User password. NULL = current
      0, // Locale. NULL indicates current
      NULL, // Security flags.
      0, // Authority (for example, Kerberos)
      0, // Context object
      &pSvc // pointer to IWbemServices proxy
  );

  if (FAILED(hres)) {
    pLoc->Release();
    return specs; // Program has failed.
  }

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

  if (FAILED(hres)) {
    pSvc->Release();
    pLoc->Release();
    return specs; // Program has failed.
  }

  IEnumWbemClassObject* pEnumerator = NULL;
  hres = pSvc->ExecQuery(
      bstr_t("WQL"),
      bstr_t("SELECT Caption FROM Win32_OperatingSystem"),
      WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
      NULL,
      &pEnumerator);

  if (FAILED(hres)) {
    pSvc->Release();
    pLoc->Release();
    return specs; // Program has failed.
  }

  IWbemClassObject* pclsObj;
  ULONG uReturn = 0;

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

    if (0 == uReturn) {
      break;
    }

    VARIANT vtProp;

    // Get the value of the Name property
    hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);
    specs->AddStringItem("Operating System", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
    VariantClear(&vtProp);

    pclsObj->Release();
  }
  pEnumerator = NULL;
  hres = pSvc->ExecQuery(
      bstr_t("WQL"),
      bstr_t("SELECT Name FROM Win32_processor"),
      WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
      NULL,
      &pEnumerator);

  if (FAILED(hres)) {
    pSvc->Release();
    pLoc->Release();
    return specs; // Program has failed.
  }

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

    if (0 == uReturn) {
      break;
    }

    VARIANT vtProp;

    // Get the value of the Name property
    hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
    specs->AddStringItem("Processor", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
    VariantClear(&vtProp);

    pclsObj->Release();
  }

  pEnumerator = NULL;
  hres = pSvc->ExecQuery(
      bstr_t("WQL"),
      bstr_t(
          "SELECT Name , AdapterRam, DriverVersion, VideoModeDescription FROM Win32_VideoController"),
      WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
      NULL,
      &pEnumerator);

  if (FAILED(hres)) {
    pSvc->Release();
    pLoc->Release();
    return specs; // Program has failed.
  }

  JSON* graphicsadapters = JSON::CreateArray();

  uReturn = 0;
  while (pEnumerator) {
    JSON* graphicscard = JSON::CreateObject();
    HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

    if (0 == uReturn) {
      break;
    }

    VARIANT vtProp;

    // Get the value of the Name property
    hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
    graphicscard->AddStringItem("Name", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
    VariantClear(&vtProp);

    // Get the value of the Name property
    hr = pclsObj->Get(L"AdapterRam", 0, &vtProp, 0, 0);
    uint32_t capacity = vtProp.uintVal;
    graphicscard->AddNumberItem("Video Controller RAM (MB)", capacity / 1048576);
    VariantClear(&vtProp);

    // get driver version
    hr = pclsObj->Get(L"DriverVersion", 0, &vtProp, 0, 0);
    graphicscard->AddStringItem("Driver Version", WCHAR_TO_OVR_STRING(vtProp.bstrVal));

    // get resolution
    hr = pclsObj->Get(L"VideoModeDescription", 0, &vtProp, 0, 0);
    graphicscard->AddStringItem("Video Mode", WCHAR_TO_OVR_STRING(vtProp.bstrVal));

    VariantClear(&vtProp);
    pclsObj->Release();

    graphicsadapters->AddArrayElement(graphicscard);
  }

  specs->AddItem("Graphics Adapters", graphicsadapters);

  pEnumerator = NULL;
  hres = pSvc->ExecQuery(
      bstr_t("WQL"),
      bstr_t("SELECT Capacity FROM Win32_PhysicalMemory"),
      WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
      NULL,
      &pEnumerator);

  if (FAILED(hres)) {
    pSvc->Release();
    pLoc->Release();
    return specs; // Program has failed.
  }

  uint64_t totalram = 0;
  uReturn = 0;
  while (pEnumerator) {
    HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

    if (0 == uReturn) {
      break;
    }

    VARIANT vtProp;

    // Get the value of the Name property
    hr = pclsObj->Get(L"Capacity", 0, &vtProp, 0, 0);
    uint64_t capacity = QString::fromWCharArray(vtProp.bstrVal).toLongLong();
    totalram += capacity;
    VariantClear(&vtProp);
    pclsObj->Release();
  }

  specs->AddNumberItem("Total RAM (GB)", totalram / 1073741824.0);

  JSON* usbtree = JSON::CreateArray();

  QMap<QString, QStringList> antecedents;

  pEnumerator = NULL;
  hres = pSvc->ExecQuery(
      bstr_t("WQL"),
      bstr_t("SELECT Antecedent,Dependent FROM Win32_USBControllerDevice"),
      WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
      NULL,
      &pEnumerator);

  if (FAILED(hres)) {
    pSvc->Release();
    pLoc->Release();
    return specs; // Program has failed.
  }

  VARIANT vtProp;

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

    if (0 == uReturn) {
      break;
    }

    // Get the reference value of the Antecedent property.  There is not a function to dereference
    // the value.
    hr = pclsObj->Get(L"Antecedent", 0, &vtProp, 0, 0);
    BSTR name = vtProp.bstrVal;
    // sanitize the string input to just the output
    QString antecedent = QString::fromWCharArray(name).split("=")[1].replace("\"", "");
    VariantClear(&vtProp);

    // Get the reference value of the Dependent property.  There is not a function to dereference
    // the value.
    hr = pclsObj->Get(L"Dependent", 0, &vtProp, 0, 0);
    name = vtProp.bstrVal;
    // sanitize the string input to just the output
    QString dependent = QString::fromWCharArray(name).split("=")[1].replace("\"", "");
    antecedents[antecedent].append(dependent);
    VariantClear(&vtProp);
  }
  for (int ant = 0; ant < antecedents.size(); ant++) {
    QString antecedent_name = antecedents.keys()[ant];
    // get antecedent object in a new enumerator
    IEnumWbemClassObject* pEnumerator2 = NULL;
    IWbemClassObject* pclsObj2;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"),
        bstr_t(
            "SELECT Manufacturer, Name, DeviceID, Caption FROM WIN32_USBController where deviceid = '") +
            bstr_t(antecedent_name.toUtf8()) + bstr_t("'"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        NULL,
        &pEnumerator2);
    if (FAILED(hres)) {
      pSvc->Release();
      pLoc->Release();
      return specs; // Program has failed.
    }

    JSON* USBAntecedent = JSON::CreateObject();

    while (pEnumerator2) {
      HRESULT hr = pEnumerator2->Next(WBEM_INFINITE, 1, &pclsObj2, &uReturn);

      if (0 == uReturn) {
        break;
      }

      VARIANT vtProp;

      // Get the value of the Name property
      hr = pclsObj2->Get(L"Name", 0, &vtProp, 0, 0);
      USBAntecedent->AddStringItem("name", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
      VariantClear(&vtProp);

      // Get the value of the DeviceID property
      hr = pclsObj2->Get(L"DeviceID", 0, &vtProp, 0, 0);
      USBAntecedent->AddStringItem("deviceid", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
      VariantClear(&vtProp);

      // Get the value of the caption property
      hr = pclsObj2->Get(L"Caption", 0, &vtProp, 0, 0);
      USBAntecedent->AddStringItem("caption", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
      VariantClear(&vtProp);

      // Get the value of the manufacturer property
      hr = pclsObj2->Get(L"Manufacturer", 0, &vtProp, 0, 0);
      USBAntecedent->AddStringItem("manufacturer", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
      VariantClear(&vtProp);

      pclsObj2->Release();
    }
    JSON* devices = JSON::CreateArray();
    for (int dev = 0; dev < antecedents[antecedent_name].size(); ++dev) {
      // get antecedent object in a new enumerator
      pEnumerator2 = NULL;
      if (!pclsObj2)
        pclsObj2->Release();
      hres = pSvc->ExecQuery(
          bstr_t("WQL"),
          bstr_t("SELECT Manufacturer,Name FROM Win32_PnPEntity where DeviceID = '") +
              bstr_t(antecedents[antecedent_name][dev].toUtf8()) + bstr_t("'"),
          WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
          NULL,
          &pEnumerator2);
      if (FAILED(hres)) {
        pSvc->Release();
        pLoc->Release();
        return specs; // Program has failed.
      }

      while (pEnumerator2) {
        HRESULT hr = pEnumerator2->Next(WBEM_INFINITE, 1, &pclsObj2, &uReturn);

        if (0 == uReturn) {
          break;
        }

        VARIANT vtProp;

        JSON* properties = JSON::CreateObject();

        // Get the value of the Manufacturer property
        hr = pclsObj2->Get(L"Manufacturer", 0, &vtProp, 0, 0);
        properties->AddStringItem("manufacturer", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
        VariantClear(&vtProp);

        // Get the value of the Manufacturer property
        hr = pclsObj2->Get(L"Name", 0, &vtProp, 0, 0);
        properties->AddStringItem("name", WCHAR_TO_OVR_STRING(vtProp.bstrVal));
        VariantClear(&vtProp);

        pclsObj2->Release();
        devices->AddArrayElement(properties);
      }
    }

    USBAntecedent->AddItem("Devices", devices);
    usbtree->AddArrayElement(USBAntecedent);
  }

  specs->AddItem("USB Tree", usbtree);

  // Cleanup
  // ========
  pSvc->Release();
  pLoc->Release();
  pEnumerator->Release();
  if (!pclsObj)
    pclsObj->Release();
  return specs;
}