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

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

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

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

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

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

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

	pEnum->Release();
	SysFreeString(bstrPath);
	SysFreeString(bstrWQL);
	pIWbemServices->Release();
	pIWbemLocator->Release();
	SysFreeString(bstrServer);
	CoUninitialize();
	return retvalue;
}
Example #2
0
static Status Init()
{
	HRESULT hr;

	hr = CoInitialize(0);
	ENSURE(hr == S_OK || hr == S_FALSE);	// S_FALSE => already initialized

	hr = CoInitializeSecurity(0, -1, 0, 0, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, 0, EOAC_NONE, 0);
	if(FAILED(hr))
		WARN_RETURN(ERR::_2);

	{
		IWbemLocatorPtr pLoc = 0;
		hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**)&pLoc);
		if(FAILED(hr))
			WARN_RETURN(ERR::_3);

		hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), 0, 0, 0, 0, 0, 0, &pSvc);
		if(FAILED(hr))
			return ERR::_4;	// NOWARN (happens if WMI service is disabled)
	}

	hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, 0, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, 0, EOAC_NONE);
	if(FAILED(hr))
		WARN_RETURN(ERR::_5);

	return INFO::OK;
}
/**
 * Connect to the DMI server.
 *
 * @returns COM status code.
 * @param   pLocator            The locator.
 * @param   pszServer           The server name.
 * @param   ppServices          Where to return the services interface.
 */
static HRESULT rtSystemDmiWinConnectToServer(IWbemLocator *pLocator, const char *pszServer, IWbemServices **ppServices)
{
    AssertPtr(pLocator);
    AssertPtrNull(pszServer);
    AssertPtr(ppServices);

    BSTR pBStrServer = rtSystemWinBstrFromUtf8(pszServer);
    if (!pBStrServer)
        return E_OUTOFMEMORY;

    HRESULT hrc = pLocator->ConnectServer(pBStrServer,
                                          NULL,
                                          NULL,
                                          0,
                                          NULL,
                                          0,
                                          0,
                                          ppServices);
    if (SUCCEEDED(hrc))
    {
        hrc = CoSetProxyBlanket(*ppServices,
                                RPC_C_AUTHN_WINNT,
                                RPC_C_AUTHZ_NONE,
                                NULL,
                                RPC_C_AUTHN_LEVEL_CALL,
                                RPC_C_IMP_LEVEL_IMPERSONATE,
                                NULL,
                                EOAC_NONE);
        if (FAILED(hrc))
            (*ppServices)->Release();
    }
    SysFreeString(pBStrServer);
    return hrc;
}
/*
================
Sys_GetVideoRam
returns in megabytes
================
*/
int Sys_GetVideoRam(void)
{
#ifdef	ID_DEDICATED
	return 0;
#else
	unsigned int retSize = 64;

	CComPtr<IWbemLocator> spLoc = NULL;
	HRESULT hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_SERVER, IID_IWbemLocator, (LPVOID *) &spLoc);

	if (hr != S_OK || spLoc == NULL) {
		return retSize;
	}

	CComBSTR bstrNamespace(_T("\\\\.\\root\\CIMV2"));
	CComPtr<IWbemServices> spServices;

	// Connect to CIM
	hr = spLoc->ConnectServer(bstrNamespace, NULL, NULL, 0, NULL, 0, 0, &spServices);

	if (hr != WBEM_S_NO_ERROR) {
		return retSize;
	}

	// Switch the security level to IMPERSONATE so that provider will grant access to system-level objects.
	hr = CoSetProxyBlanket(spServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

	if (hr != S_OK) {
		return retSize;
	}

	// Get the vid controller
	CComPtr<IEnumWbemClassObject> spEnumInst = NULL;
	hr = spServices->CreateInstanceEnum(CComBSTR("Win32_VideoController"), WBEM_FLAG_SHALLOW, NULL, &spEnumInst);

	if (hr != WBEM_S_NO_ERROR || spEnumInst == NULL) {
		return retSize;
	}

	ULONG uNumOfInstances = 0;
	CComPtr<IWbemClassObject> spInstance = NULL;
	hr = spEnumInst->Next(10000, 1, &spInstance, &uNumOfInstances);

	if (hr == S_OK && spInstance) {
		// Get properties from the object
		CComVariant varSize;
		hr = spInstance->Get(CComBSTR(_T("AdapterRAM")), 0, &varSize, 0, 0);

		if (hr == S_OK) {
			retSize = varSize.intVal / (1024 * 1024);

			if (retSize == 0) {
				retSize = 64;
			}
		}
	}

	return retSize;
#endif
}
Example #5
0
bool TDBWMI::Initialize(PGLOBAL g)
  {
  if (Init)
    return false;

  // Initialize COM.
  Res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

  if (FAILED(Res)) {
    sprintf(g->Message, "Failed to initialize COM library. " 
            "Error code = %p", Res);
    return true;              // Program has failed.
    } // endif Res

  // Obtain the initial locator to Windows Management
  // on a particular host computer.
  IWbemLocator *loc;        // Initial Windows Management locator

  Res = CoCreateInstance(CLSID_WbemLocator, 0,  CLSCTX_INPROC_SERVER, 
                         IID_IWbemLocator, (LPVOID*) &loc);
 
  if (FAILED(Res)) {
    sprintf(g->Message, "Failed to create Locator. " 
                        "Error code = %p", Res);
    CoUninitialize();
    return true;       // Program has failed.
    }  // endif Res

  // Connect to the specified namespace with the
  // current user and obtain pointer to Svc
  // to make IWbemServices calls.
  Res = loc->ConnectServer(_bstr_t(Nspace),
                             NULL, NULL,0, NULL, 0, 0, &Svc);
  
  if (FAILED(Res)) {
    sprintf(g->Message, "Could not connect. Error code = %p", Res); 
    loc->Release();     
    CoUninitialize();
    return true;                // Program has failed.
    }  // endif hres

  loc->Release();                // Not used anymore

  // Set the IWbemServices proxy so that impersonation
  // of the user (client) occurs.
  Res = CoSetProxyBlanket(Svc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, 
                          NULL, RPC_C_AUTHN_LEVEL_CALL,
                          RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

  if (FAILED(Res)) {
    sprintf(g->Message, "Could not set proxy. Error code = 0x", Res);
    Svc->Release();
    CoUninitialize();
    return true;               // Program has failed.
    }  // endif Res

  Init = true;
  return false;
  } // end of Initialize
Example #6
0
void WMIQuery::initialize() {
	result = CoInitializeEx(0, COINIT_MULTITHREADED);
	result = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
	locator = NULL;
	result = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*) &locator);
	services = NULL;
	result = locator->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &services);
	result = CoSetProxyBlanket(services, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
	enumerator = NULL;
}
Example #7
0
HRESULT GetNamespace(__in PCWSTR pObjectPath, __out IWbemServices** ppNamespace)
{
    HRESULT hr;
    IWbemLocator *pLocator = NULL;
    IWbemServices *pNamespaceLocal = NULL;

    hr = CoCreateInstance(CLSID_WbemLocator,
                          0,
                          CLSCTX_INPROC_SERVER,
                          IID_IWbemLocator,
                          (LPVOID *) &pLocator);
    if(HB_FAILED(hr)) {
        goto cleanexit;
    }

    hr = pLocator->ConnectServer(_bstr_t(pObjectPath),      // Object path of WMI namespace
                                 NULL,                      // User name
                                 NULL,                      // User password
                                 0,                         // Locale
                                 NULL,                      // Security flags
                                 0,                         // Authority
                                 0,                         // Context object
                                 &pNamespaceLocal
                                 );

    if(HB_FAILED(hr)) {
        goto cleanexit;
    }

    hr = CoSetProxyBlanket(pNamespaceLocal,
                           RPC_C_AUTHN_WINNT,
                           RPC_C_AUTHZ_NONE,
                           NULL,
                           RPC_C_AUTHN_LEVEL_CALL,
                           RPC_C_IMP_LEVEL_IMPERSONATE,
                           NULL,
                           EOAC_NONE
                           );
    if(HB_FAILED(hr)) {
        goto cleanexit;
    }

    *ppNamespace = pNamespaceLocal;
    pNamespaceLocal = NULL;

cleanexit:
    HB_SAFE_RELEASE(pLocator);
    HB_SAFE_RELEASE(pNamespaceLocal);

    return hr;
}
HRESULT lvDCOMInterface::setIdentity(COAUTHIDENTITY* pidentity, IUnknown* pUnk)
{
	HRESULT hr;
	if (pidentity != NULL)
	{
		hr = CoSetProxyBlanket(pUnk, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
			RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, pidentity, EOAC_NONE);
		if (FAILED(hr))
		{
			std::cerr << "setIdentity failed" << std::endl;
			return hr;
		}
	}
	return S_OK;
}
Example #9
0
IWbemServices * WbemServices::GetPtr()
{
    if (services_) {
        return services_.p;
    }

    HRESULT retval;
    CComPtr<IWbemLocator> locator_;

    retval = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &locator_);

    if (FAILED(retval))	{
        return NULL;
    }

    retval = locator_->ConnectServer(
        _bstr_t(L"ROOT\\CIMV2"),
        NULL,
        NULL,
        0,
        NULL,
        0,
        0,
        &services_
        );

    if (FAILED(retval)) {
        return NULL;
    }

    CoSetProxyBlanket(
        services_,
        RPC_C_AUTHN_WINNT,
        RPC_C_AUTHZ_NONE,
        NULL,
        RPC_C_AUTHN_LEVEL_CALL,
        RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL,
        EOAC_NONE
        );

    return services_.p;
}
Example #10
0
/* Lookup Administrators group name from winmgmt */
static HRESULT GetAdminName(_bstr_t *name)
{
    HRESULT hr;
    COMPointer<IWbemLocator> pLoc;
    COMPointer<IWbemServices> pSvc;
    COMPointer<IEnumWbemClassObject> pEnum;
    COMPointer<IWbemClassObject> pWobj;
    ULONG returned;
    _variant_t var;

    chk(CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER,
                         IID_IWbemLocator, (LPVOID *)pLoc.replace()));
    chk(pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, NULL,
                            0, 0, 0, pSvc.replace()));
    chk(CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
                          NULL, RPC_C_AUTHN_LEVEL_CALL,
                          RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE));
    chk(pSvc->ExecQuery(_bstr_t(L"WQL"),
                        _bstr_t(L"select * from Win32_Account where "
                                "SID='S-1-5-32-544' and localAccount=TRUE"),
                        WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                        NULL, pEnum.replace()));
    if (!pEnum) {
        hr = E_FAIL;
        errmsg(hr, "Failed to query for Administrators");
        goto out;
    }
    chk(pEnum->Next(WBEM_INFINITE, 1, pWobj.replace(), &returned));
    if (returned == 0) {
        hr = E_FAIL;
        errmsg(hr, "No Administrators found");
        goto out;
    }

    chk(pWobj->Get(_bstr_t(L"Name"), 0, &var, 0, 0));
    try {
        *name = var;
    } catch(...) {
        hr = E_FAIL;
        errmsg(hr, "Failed to get name of Administrators");
        goto out;
    }

out:
    return hr;
}
Example #11
0
HRESULT CConsumer::ConnectToETWNameSpace(BSTR bstrNameSpace)
{
	HRESULT hr = S_OK;
	IWbemLocator *pLocator = NULL;
	hr = CoInitialize(0);
	hr = CoCreateInstance(__uuidof(WbemLocator), 
		0,
		CLSCTX_INPROC_SERVER,
		__uuidof(IWbemLocator),
		(LPVOID*) &pLocator);

	if(FAILED(hr))
	{
		wprintf(L"CoCreateInstance failed with 0x%x\r\n", hr);
		goto cleanup;
	}

	hr = pLocator->ConnectServer(bstrNameSpace,
		NULL,NULL,NULL,0L,NULL,NULL,&g_pServices);

	if(FAILED(hr))
	{
		wprintf(L"Connect toServer Failed with 0x%x\r\n",hr);
		goto cleanup;
	}

	hr = CoSetProxyBlanket(g_pServices,
		RPC_C_AUTHN_WINNT,RPC_C_AUTHN_NONE,
		NULL,
		RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE,
		NULL, EOAC_NONE);

	if(FAILED(hr))
	{
		wprintf(L"CoSetProxBlanket Failed with 0x%x\r\n", hr);
		g_pServices->Release();
		g_pServices = NULL;
	}

cleanup:
	if(pLocator)
		pLocator->Release();

	return hr;
}
Example #12
0
void WMIHelper::initializeWMI(const QString &wmiNamespace)
{
    if(initialized) {
        wbemLocator = 0;
    }
    HRESULT hres;
    wbemLocator = 0;

    QUuid wbemLocatorClsid = "4590f811-1d3a-11d0-891f-00aa004b2e24";
    QUuid wbemLocatorIid = "dc12a687-737f-11cf-884d-00aa004b2e24";

    hres = CoCreateInstance(wbemLocatorClsid,0,CLSCTX_INPROC_SERVER,
                            wbemLocatorIid, (LPVOID *) &wbemLocator);

    if (hres == CO_E_NOTINITIALIZED) { // COM was not initialized
        CoInitializeEx(0, COINIT_MULTITHREADED);
        hres = CoCreateInstance(wbemLocatorClsid,0,CLSCTX_INPROC_SERVER,
                                wbemLocatorIid, (LPVOID *) &wbemLocator);
    }

    if (hres != S_OK) {
       qWarning() << "Failed to create IWbemLocator object." << hres;
        return ;
    }
    wbemServices = 0;
    hres = wbemLocator->ConnectServer(::SysAllocString(wmiNamespace.utf16()),0,0,0,0,0,0,&wbemServices);

    if (hres != WBEM_S_NO_ERROR){
        qWarning() << "Could not connect";
        return ;
    }

    hres = CoSetProxyBlanket( wbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, 0,
                              RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, 0, EOAC_NONE );

    if (hres != S_OK) {
       qWarning() << "Could not set proxy blanket" << hres;
        return ;
    }
    initialized = true;
}
Example #13
0
jobject WMIService::OpenNamespace(JNIEnv* pJavaEnv, LPWSTR nsName, LONG lFlags)
{
	CComPtr<IWbemServices> ptrNamespace;
	HRESULT hres = ptrWbemServices->OpenNamespace(nsName, lFlags, NULL, &ptrNamespace, NULL);
	if (FAILED(hres)) {
		THROW_COMMON_ERROR(L"Can't open namespace", hres);
		return NULL;
	}
    hres = CoSetProxyBlanket(
		ptrNamespace,				 // 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)) {
        THROW_COMMON_ERROR(L"Can't set proxy blanket for opened namespace", hres);
		return NULL;
    }

	JNIMetaData& jniMeta = JNIMetaData::GetMetaData(pJavaEnv);
	
	jobject newServiceObject = pJavaEnv->NewObject(jniMeta.wmiServiceClass, jniMeta.wmiServiceConstructor);
	if (pJavaEnv->ExceptionCheck()) {
		return NULL;
	}
	WMIService* pServiceHandler = new WMIService(pJavaEnv, newServiceObject);
	pServiceHandler->ptrWbemServices = ptrNamespace;

	//WriteLog(pJavaEnv, LT_DEBUG, bstr_t("Connected to WMI namespace ") + nsName);

	return newServiceObject;
}
Example #14
0
int main(int iArgCnt, char ** argv)
{
    HRESULT hres;

    // Step 1: --------------------------------------------------
    // 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.
    }

    // 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 ------------------------

    hres =  CoInitializeSecurity(
        NULL, 
        -1,                          // COM negotiates service
        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 (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 = 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;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

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

    IWbemServices *pSvc = NULL;
	
    // Connect to the local root\cimv2 namespace
    // and obtain pointer pSvc to make IWbemServices calls.
    hres = pLoc->ConnectServer(
        _bstr_t(L"ROOT\\CIMV2"), 
        NULL,
        NULL, 
        0, 
        NULL, 
        0, 
        0, 
        &pSvc
    );
	    
    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 
        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();     
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: -------------------------------------------------
    // Receive event notifications -----------------------------

    // Use an unsecured apartment for security
    IUnsecuredApartment* pUnsecApp = NULL;

    hres = CoCreateInstance(CLSID_UnsecuredApartment, NULL, 
        CLSCTX_LOCAL_SERVER, IID_IUnsecuredApartment, 
        (void**)&pUnsecApp);
 
    EventSink* pSink = new EventSink;
    pSink->AddRef();

    IUnknown* pStubUnk = NULL; 
    pUnsecApp->CreateObjectStub(pSink, &pStubUnk);

    IWbemObjectSink* pStubSink = NULL;
    pStubUnk->QueryInterface(IID_IWbemObjectSink,
        (void **) &pStubSink);

    // The ExecNotificationQueryAsync method will call
    // The EventQuery::Indicate method when an event occurs
    hres = pSvc->ExecNotificationQueryAsync(
        _bstr_t("WQL"), 
        _bstr_t("SELECT * " 
            "FROM Win32_USBHub"), 
        WBEM_FLAG_SEND_STATUS, 
        NULL, 
        pStubSink);

    // Check for errors.
    if (FAILED(hres))
    {
        printf("ExecNotificationQueryAsync failed "
            "with = 0x%X\n", hres);
        pSvc->Release();
        pLoc->Release();
        pUnsecApp->Release();
        pStubUnk->Release();
        pSink->Release();
        pStubSink->Release();
        CoUninitialize();    
        return 1;
    }

    // Wait for the event
    Sleep(10000);
         
    hres = pSvc->CancelAsyncCall(pStubSink);

    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    pUnsecApp->Release();
    pStubUnk->Release();
    pSink->Release();
    pStubSink->Release();
    CoUninitialize();

    return 0;   // Program successfully completed.
	
}
Example #15
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);
}
Example #16
0
HRESULT SetupForIsXInputDevice()
{
	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;

	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	bCleanupCOM = SUCCEEDED(hr);
	
	// Create WMI
	hr = CoCreateInstance( &CLSID_WbemContext,
		NULL,
		CLSCTX_INPROC_SERVER,
		&IID_IWbemContext,
		(LPVOID*) &pIWbemLocator);
	if( FAILED(hr) || pIWbemLocator == NULL )
		goto bail;

	bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );if( bstrNamespace == NULL ) goto bail;
	bstrClassName = SysAllocString( L"Win32_PNPEntity" );   if( bstrClassName == NULL ) goto bail;
	bstrDeviceID  = SysAllocString( L"DeviceID" );          if( bstrDeviceID == NULL )  goto bail;

	// Connect to WMI 	
	hr = IWbemLocator_ConnectServer(pIWbemLocator, bstrNamespace, NULL, NULL, NULL, 
		0L, NULL, NULL, &pIWbemServices );

	if( FAILED(hr) || pIWbemServices == NULL )
		goto bail;

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

	hr = IWbemServices_CreateInstanceEnum( pIWbemServices, bstrClassName, 0, NULL, &pEnumDevices ); 
	if( FAILED(hr) || pEnumDevices == NULL )
		goto bail;

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

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

					strVid = wcsstr( var.bstrVal, L"VID_" );
					if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
						dwVid = 0;
					strPid = wcsstr( var.bstrVal, L"PID_" );
					if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
						dwPid = 0;

					dwVidPid = MAKELONG( dwVid, dwPid );

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

bail:
	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;
}
Example #17
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;  
}
Example #18
0
bool WMIVideoInfo::_initializeWMI()
{
   //// Set security levels 
   //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( FAILED( hr ) )
   //{
   //   Con::errorf( "WMIVideoInfo: Failed to initialize com security." );
   //   return false;
   //}

   // Obtain the locator to WMI 
   HRESULT hr = CoCreateInstance(
      CLSID_WbemLocator,             
      0, 
      CLSCTX_INPROC_SERVER, 
      IID_IWbemLocator, 
      (void**)&mLocator
      );

   if( FAILED( hr ) )
   {
      Con::errorf( "WMIVideoInfo: Failed to create instance of IID_IWbemLocator." );
      return false;
   }

   // Connect to the root\cimv2 namespace with
   // the current user and obtain pointer pSvc
   // to make IWbemServices calls.
   hr = mLocator->ConnectServer(
      BSTR(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 
      &mServices               // pointer to IWbemServices proxy
      );

   if( FAILED( hr ) )
   {
      Con::errorf( "WMIVideoInfo: Connect server failed." );
      return false;
   }


   // Set security levels on the proxy 
   hr = CoSetProxyBlanket(
      mServices,                   // 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( hr ) )
   {
      Con::errorf( "WMIVideoInfo: CoSetProxyBlanket failed" );
      return false;
   }

   return true;
}
Example #19
0
HRESULT WMI::Open(LPCTSTR machine, LPCTSTR user, LPCTSTR pass)
{
    IWbemLocator *locator;
    wchar_t path[MAX_PATH];
    

    if (wbem) {
        result = S_OK;
        return result;
    }

    result =
        CoInitializeSecurity(NULL,                        //Security Descriptor
                             -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 (FAILED(result) && RPC_E_TOO_LATE != result) {
        CoUninitialize();
        return result;
    }

    result = CoCreateInstance(CLSID_WbemLocator,
                              NULL, /* IUnknown */
                              CLSCTX_INPROC_SERVER,
                              IID_IWbemLocator,
                              (LPVOID *)&locator);

    if (FAILED(result)) {
        return result;
    }

    if (machine == NULL) {
        machine = L".";
    }

    wsprintf(path, L"\\\\%S\\ROOT\\CIMV2", machine);

    result = locator->ConnectServer(bstr_t(path), //Object path of WMI namespace
                                    bstr_t(user), //User name. NULL = current user
                                    bstr_t(pass), //User password. NULL = current
                                    NULL,         //Locale. NULL indicates current
                                    0,            //Security flags
                                    NULL,         //Authority (e.g. Kerberos)
                                    NULL,         //Context object
                                    &wbem);       //pointer to IWbemServices proxy

    result = CoSetProxyBlanket(wbem, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
        RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

    if (FAILED(result))
    {
        return result;
    }

    locator->Release();

    return result;
}
Example #20
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());
}
Example #21
0
int wmi_initialize() {

	// Initialize default value
	locator = NULL;
	services = NULL;
	//enumerator = NULL;

	// Initialize COM

	HRESULT result = CoInitializeEx(0, COINIT_MULTITHREADED);
	
	if (FAILED(result)) {
        log_err("Failed to initialize COM library. Error code = %x", result);
        return -1;
    }

	// Set general COM security levels

	result = 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 (FAILED(result)) {
       log_err("Failed to initialize security. Error code = %x", result);
        CoUninitialize();
        return -1;
    }

	// Obtain the initial locator to WMI

	result = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &locator);
 
    if (FAILED(result)) {
       log_err("Failed to create IWbemLocator object. Error code = %x", result);
        CoUninitialize();
        return -1;                 // Program has failed.
    }

	// Connect to WMI through the IWbemLocator::ConnectServer method

	// Connect to the root\cimv2 namespace with
    // the current user and obtain pointer 'services'
    // to make IWbemServices calls.

	result = locator->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 
         &services                // pointer to IWbemServices proxy
    );

	if (FAILED(result)) {
        log_err("Could not connect. Error code = %x", result);
        locator->Release();     
        CoUninitialize();
        return -1;
    }

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

	// Set security levels on the proxy

	result = CoSetProxyBlanket(
       services,                        // 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(result)) {
        log_err("Could not set proxy blanket. Error code = %x", result);
        services->Release();
        locator->Release();     
        CoUninitialize();
        return -1;
    }

	get_initial_values();

	_initialized = 1;
	return 0;
}
Example #22
0
bool WmiClient::initialize()
{
    //	#1, init COM
    HRESULT hres = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (!SUCCEEDED(hres))
    {
        log_err "CoInitializeEx() failed. hres=%u", hres log_end;
        return false;
    }

    //	#2, set general COM security levels
    hres = CoInitializeSecurity(NULL,
                                -1,                             // COM authentication
                                NULL,                           // Authentication services
                                NULL,                           // Reserved
                                RPC_C_AUTHN_LEVEL_DEFAULT,      // Default authentication
                                RPC_C_IMP_LEVEL_IMPERSONATE,    // Default Impoersonation
                                NULL,                           // Authentication info
                                EOAC_NONE,                      // Additional capabilities
                                NULL                            // Reserved
                                );
    if (!SUCCEEDED(hres))
    {
		// 
		//	CoInitializeSecurity() 함수는 프로세스에서 한번만 호출할 수 있다. 
		//	두번호출 되면 RPC_E_TOO_LATE 를 리턴함
		// 
		if (RPC_E_TOO_LATE != hres)
		{
			log_err "CoInitializeSeciruty() failed. hres=%u", hres log_end;
			CoUninitialize();
			return false;
		}
    }

    // #3, Obtain the initial locator to WMI
    hres = CoCreateInstance(CLSID_WbemLocator,
                            0,
                            CLSCTX_INPROC_SERVER,
                            IID_IWbemLocator,
                            (LPVOID*)&_locator
                            );
    if (!SUCCEEDED(hres))
    {
        log_err "CoCreateInstance() failed. hres=%u", hres log_end;
        CoUninitialize();
        return false;
    }

    // #4, Connect to WMI through IWbemLocator::ConnectServer
    // 
    // Connect to the `root\cimv2` namespace with the current user and 
    // obtain pointer _svc to make IWbemServices calls.
    hres = _locator->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,                        // Serucirty flags.
                               0,                           // Authority (for example, Kerberos)
                               0,                           // Context object
                               &_svc                        // Pointer to IWbemServices proxy
                               );
    if (!SUCCEEDED(hres))
    {
        log_err "_locator->ConnectServer() failed. hres=%u", hres log_end;
        _locator->Release(); _locator = NULL;
        CoUninitialize();
        return false;
    }

    log_dbg "Connected to ROOT\\CIMV2 WMI name space." log_end;

    // #5, Security levels on the proxy
    hres = CoSetProxyBlanket(_svc,                          // 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 (!SUCCEEDED(hres))
    {
        log_err "CoSetProxyBlanket() failed. hres=%u", hres log_end;
        _svc->Release(); _svc = NULL;
        _locator->Release(); _locator = NULL;
        CoUninitialize();
        return false;
    }

    _initialized = true;
    return true;
}
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;
}
Example #24
0
//This is copy pasted from Microsoft. pretty poorly written code, 
//-----------------------------------------------------------------------------
// Enum each PNP device using WMI and check each device ID to see if it contains 
// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it's an XInput device
// Unfortunately this information can not be found by just using DirectInput 
//-----------------------------------------------------------------------------
bool IsXInputDevice( const GUID* pGuidProductFromDirectInput )
{
    IWbemLocator*           pIWbemLocator  = NULL;
    IEnumWbemClassObject*   pEnumDevices   = NULL;
    IWbemClassObject*       pDevices[20]   = {0};
    IWbemServices*          pIWbemServices = NULL;
    BSTR                    bstrNamespace  = NULL;
    BSTR                    bstrDeviceID   = NULL;
    BSTR                    bstrClassName  = NULL;
    DWORD                   uReturned      = 0;
    bool                    bIsXinputDevice= false;
    UINT                    iDevice        = 0;
    VARIANT                 var;
    HRESULT                 hr;

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

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

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

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

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

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

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

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

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

    if( bCleanupCOM )
        CoUninitialize();

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

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

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

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

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

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

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

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

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

                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );

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

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

    return hr;
}
BOOL CMemStat::Init()
{
    HRESULT status  = S_OK;
    status = CoInitializeEx(NULL,
                            COINIT_MULTITHREADED);
    if (FAILED(status)) {
        PrintMessage("Cannot initialize COM");
        return status;
    }
    initialized = TRUE;

    status = CoInitializeSecurity(
                             NULL,
                             -1,
                             NULL,
                             NULL,
                             RPC_C_AUTHN_LEVEL_PKT,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE,
                             0
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot initialize security");
        return FALSE;
    }

    status = CoCreateInstance(
                             CLSID_WbemLocator,
                             NULL,
                             CLSCTX_INPROC_SERVER,
                             IID_IWbemLocator,
                             reinterpret_cast< void** >( &locator )
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot create instance");
        return FALSE;
    }

    status = locator->ConnectServer(
                             L"root\\cimv2",
                             NULL,
                             NULL,
                             0L,
                             0L,
                             NULL,
                             NULL,
                             &service
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot connect to wmi server");
        return FALSE;
    }

    status = CoSetProxyBlanket(service,
                             RPC_C_AUTHN_WINNT,
                             RPC_C_AUTHZ_NONE,
                             NULL,
                             RPC_C_AUTHN_LEVEL_CALL,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot set proxy blanket");
        return FALSE;
    }
    return TRUE;
}
/*
================
XInputChecker::XInputChecker
================
*/
XInputChecker::XInputChecker() {
	// CoInit if needed
	HRESULT hr = CoInitialize( OG_NULL );
	bool bCleanupCOM = SUCCEEDED( hr );

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

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

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

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

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

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

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

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

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

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

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

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

	if( bCleanupCOM )
		CoUninitialize();
}
Example #28
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;
}
Example #29
0
int MyMacAddress::WMI_GetMacAddress(int iQueryType, int iSize)
{
	ZeroMemory(PermanentAddress, sizeof(PermanentAddress));
	ZeroMemory(MACAddress, sizeof(MACAddress));
	HRESULT hres;  	int	iTotal = 0;
	if( (iQueryType  < 0) || (iQueryType >= sizeof(szWQLQuery)/sizeof(T_WQL_QUERY)) ) 
	{  		
		return -1;
	}    	
	hres = CoInitializeEx( NULL, COINIT_MULTITHREADED); 
	if( FAILED(hres) )      
	{          
		return -2; 
	}        
	hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
	if( FAILED(hres))
	{          
		CoUninitialize();
		return -2;      
	}        	
	IWbemLocator *pLoc = NULL;
	hres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast <LPVOID*>(&pLoc));
	if( FAILED(hres))
	{  		
		CoUninitialize();
		return -2;      
	}
	IWbemServices *pSvc = NULL;
	hres = pLoc->ConnectServer(_bstr_t( L"ROOT\\CIMV2" ), NULL, NULL, NULL, 0, NULL, NULL, &pSvc);
	if( FAILED(hres))      
	{  		
		pLoc->Release();           
		CoUninitialize();          
		return -2;      
	}    	
	// 设置请求代理的安全级别
	hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
	if(FAILED(hres))
	{          
		pSvc->Release();
		pLoc->Release(); 
		CoUninitialize();  
		return -2;      
	}       
	IEnumWbemClassObject *pEnumerator = NULL;
	hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t( szWQLQuery[iQueryType].szSelect), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);  	
	if(FAILED(hres)) 
	{          
		pSvc->Release();
		pLoc->Release();  
		CoUninitialize();         
		return -3;      
	}        
	while(pEnumerator)
	{  		
		IWbemClassObject *pclsObj = NULL;
		ULONG uReturn = 0;    	
		if(iTotal >= iSize)  
		{  			
			break;  	
		}           
		pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);            
		if( uReturn == 0 )         
		{              
			break;
		}    		
		VARIANT	vtProperty;  	
		TCHAR szProperty[128]; 
		// 获取网卡范例ID		
		VariantInit( &vtProperty);	  	
		pclsObj->Get( szWQLQuery[iQueryType].szProperty, 0, &vtProperty, NULL, NULL );  
		StringCchCopy( szProperty, sizeof(szProperty)/sizeof(TCHAR), W2T(vtProperty.bstrVal) );  
		VariantClear( &vtProperty );    			
		if( GetPNPDeviceID( szProperty))  	
		{  			
			iTotal++;  		
		}  		  		
		pclsObj->Release();  
	}
	// 释放资源  
	pEnumerator->Release(); 
	pSvc->Release();     
	pLoc->Release();   
	CoUninitialize();     
	return iTotal;  
}
bool GpuCapabilitiesWindows::WMIinit() {

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

    if (isWMIinited()) {
        LWARNING("The WMI connection has already been inited.");
        return false;
    }

    HRESULT hRes;

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

    hRes = CoInitializeEx(0, COINIT_APARTMENTTHREADED);
    if (FAILED(hRes)) {
        LWARNING("CoInitializeEx() failed");
        return false;
    }

    // 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 ------------------------

    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
        );

    if (FAILED(hRes)) {

        // Failure of CoInitializeSecurity is not necessarily critical
        // => do not abort initialization

        if (hRes == RPC_E_TOO_LATE) {
            LDEBUG("CoInitializeSecurity failed. HRESULT = RPC_E_TOO_LATE.");
        }
        else if (hRes == RPC_E_NO_GOOD_SECURITY_PACKAGES) {
            LDEBUG("CoInitializeSecurity failed. HRESULT = RPC_E_NO_GOOD_SECURITY_PACKAGES.");
        }
        /*else if (hres == E_OUT_OF_MEMORY) {
            LDEBUG("CoInitializeSecurity failed. HRESULT = E_OUT_OF_MEMORY.");
        } */
        else {
            LDEBUG("CoInitializeSecurity failed. HRESULT = " << hRes);
        }
    }
    else {
        LDEBUG("CoInitializeSecurity successful");

    }

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

    hRes = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pIWbemLocator_);

    if (FAILED(hRes)) {
        LWARNING("Failed to create IWbemLocator object. Err code = 0x" << hRes);
        pIWbemLocator_ = 0;
        CoUninitialize();
        return false;     // error is critical
    }

    LDEBUG("IWbemLocator object successfully created");

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

    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hRes = pIWbemLocator_->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
         &pWbemServices_          // pointer to IWbemServices proxy
         );

    if (FAILED(hRes)) {
        LWARNING("Could not connect to WMI server. Error code = 0x" << hRes);
        pIWbemLocator_->Release();
        CoUninitialize();
        pIWbemLocator_ = 0;
        pWbemServices_ = 0;
        return false;            // error is critical
    }

    LDEBUG("Connected to ROOT\\CIMV2 WMI namespace");


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

    hRes = CoSetProxyBlanket(
       pWbemServices_,              // 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)) {
        LWARNING("Could not set proxy blanket. Error code = 0x" << hRes);
        pWbemServices_->Release();
        pIWbemLocator_->Release();
        CoUninitialize();
        pIWbemLocator_ = 0;
        pWbemServices_ = 0;
        return false;               // error is critical
    }
    LDEBUG("WMI successfully inited");
    return true;

}