HRESULT HealthBloodPressureServiceContent::SetCCCD( ) { HRESULT hr = S_OK; // // Client configuration Descriptor // PBTH_LE_GATT_DESCRIPTOR descriptors = NULL; USHORT numDesc = 0; USHORT numDescsActual = 0; BOOLEAN isFoundClientConfigDesc = FALSE; USHORT clientConfigDescIndex = 0; BTH_LE_GATT_DESCRIPTOR_VALUE clientConfigValue; ::ZeroMemory(&clientConfigValue, sizeof(clientConfigValue)); // // Find the Client configuration descriptor // if (SUCCEEDED(hr)) { // First call to determine buffer size. hr = BluetoothGATTGetDescriptors( m_hDeviceHandle, &m_BloodPressureMeasurementCharacteristic, 0, NULL, &numDesc, BLUETOOTH_GATT_FLAG_NONE); if (HRESULT_FROM_WIN32(ERROR_MORE_DATA) == hr) { hr = S_OK; } else { CHECK_HR(hr, "Failed to get the Descriptor count - changing to E_FAIL"); hr = E_FAIL; } } if (SUCCEEDED(hr)) { // Allocate memory for the descriptors buffer. descriptors = new BTH_LE_GATT_DESCRIPTOR[numDesc]; if (NULL == descriptors) { hr = E_OUTOFMEMORY; } else { ::ZeroMemory(descriptors, numDesc * sizeof(BTH_LE_GATT_DESCRIPTOR)); } CHECK_HR(hr, "Failed to allocate the descriptor buffer"); } if (SUCCEEDED(hr)) { // Second call to retrieve the descriptors. hr = BluetoothGATTGetDescriptors( m_hDeviceHandle, &m_BloodPressureMeasurementCharacteristic, numDesc, descriptors, &numDescsActual, BLUETOOTH_GATT_FLAG_NONE); CHECK_HR(hr, "Failed to get the descriptors"); } if (SUCCEEDED(hr)) { if (numDesc != numDescsActual) { hr = E_FAIL; } CHECK_HR(hr, "Number of descriptors do not match"); } if (SUCCEEDED(hr)) { // Loop through the list of descriptors to see if the Client Characteristic // Configuration descriptor is present. for (USHORT i = 0; i < numDesc; i++) { if (ClientCharacteristicConfiguration == descriptors[i].DescriptorType) { isFoundClientConfigDesc = true; clientConfigDescIndex = i; break; } } if (!isFoundClientConfigDesc) { hr = E_INVALIDARG; } CHECK_HR(hr, "Client Config descriptor not found"); } if (SUCCEEDED(hr)) { // // Set the client config descriptor to register for indications // clientConfigValue.DescriptorType = ClientCharacteristicConfiguration; clientConfigValue.ClientCharacteristicConfiguration .IsSubscribeToIndication = TRUE; hr = BluetoothGATTSetDescriptorValue( m_hDeviceHandle, &descriptors[clientConfigDescIndex], &clientConfigValue, BLUETOOTH_GATT_FLAG_NONE); CHECK_HR(hr, "Failed to set the client config descriptor"); } // // Cleanup // if (NULL != descriptors) { delete [] descriptors; } return hr; }
//////////////////////////////////////////////////////////// /// /// @brief 设置当前Windows下的电源使用方案 /// /// @param __in ULONG nStandby = PWR_NEVER 系统挂起时间,默认值为0 /// @param __in ULONG nHibernate = PWR_NEVER 系统待机时间,默认值为0 /// @param __in ULONG& nSpindownTime = PWR_NEVER 关闭硬盘时间,默认值为0 /// @param __in ULONG nVedioOffTime = PWR_NEVER 关闭监视器时间,默认值为0 /// /// @return HRESULT /// /// @retval S_OK 正常返回 /// @retval 通过GetLastError()返回 /// //////////////////////////////////////////////////////////// HRESULT WindowsPowerLW::UpdateCurrentPowerScheme( __in ULONG nStandby, __in ULONG nHibernate, __in ULONG nSpindowTime, __in ULONG nVideoOffTime ) { DEBUG_XCOVER_MARK_LINE; /// 分为直流电源和交流电源 if (SystemPowerStatus.ACLineStatus) /// 交流电源 { DEBUG_XCOVER_MARK_LINE; if (!nStandby && !nHibernate) { DEBUG_XCOVER_MARK_LINE; pwrPolicy.user.IdleTimeoutAc = 0; pwrPolicy.mach.DozeS4TimeoutAc = 0; pwrPolicy.user.IdleAc.Action = PowerActionNone; } else if (!nStandby && nHibernate) { DEBUG_XCOVER_MARK_LINE; pwrPolicy.user.IdleTimeoutAc = nHibernate; pwrPolicy.mach.DozeS4TimeoutAc = 0; pwrPolicy.user.IdleAc.Action = PowerActionHibernate; } else { DEBUG_XCOVER_MARK_LINE; pwrPolicy.user.IdleTimeoutAc = nStandby; pwrPolicy.mach.DozeS4TimeoutAc = 0; if (nHibernate > nStandby) { DEBUG_XCOVER_MARK_LINE; pwrPolicy.mach.DozeS4TimeoutAc = nHibernate - nStandby; } pwrPolicy.user.IdleAc.Action = PowerActionSleep; } pwrPolicy.user.SpindownTimeoutAc = nSpindowTime; pwrPolicy.user.VideoTimeoutAc = nVideoOffTime; } else /// 直流电源 { DEBUG_XCOVER_MARK_LINE; if (!nStandby && !nHibernate) { DEBUG_XCOVER_MARK_LINE; pwrPolicy.user.IdleTimeoutDc = 0; pwrPolicy.mach.DozeS4TimeoutDc = 0; pwrPolicy.user.IdleDc.Action = PowerActionNone; } else if (!nStandby && nHibernate) { DEBUG_XCOVER_MARK_LINE; pwrPolicy.user.IdleTimeoutDc = nHibernate; pwrPolicy.mach.DozeS4TimeoutDc = 0; pwrPolicy.user.IdleDc.Action = PowerActionHibernate; } else { DEBUG_XCOVER_MARK_LINE; pwrPolicy.user.IdleTimeoutDc = nStandby; pwrPolicy.mach.DozeS4TimeoutDc = 0; if (nHibernate > nStandby) { DEBUG_XCOVER_MARK_LINE; pwrPolicy.mach.DozeS4TimeoutDc = nHibernate - nStandby; } pwrPolicy.user.IdleDc.Action = PowerActionSleep; } pwrPolicy.user.SpindownTimeoutDc = nSpindowTime; pwrPolicy.user.VideoTimeoutDc = nVideoOffTime; } DEBUG_XCOVER_MARK_LINE; if (!SetActivePwrScheme(nIndex,NULL,&pwrPolicy)) { return HRESULT_FROM_WIN32(GetLastError()); } DEBUG_XCOVER_MARK_LINE; return S_OK; }
/******************************************************************** WcaCaScriptReadAsCustomActionData() - read the ca script into a format that is useable by other CA data functions. ********************************************************************/ extern "C" HRESULT WIXAPI WcaCaScriptReadAsCustomActionData( __in WCA_CASCRIPT_HANDLE hScript, __out LPWSTR* ppwzCustomActionData ) { HRESULT hr = S_OK; LARGE_INTEGER liScriptSize = { 0 }; BYTE* pbData = NULL; DWORD cbData = 0; if (!::GetFileSizeEx(hScript->hScriptFile, &liScriptSize)) { ExitWithLastError(hr, "Failed to get size of ca script file."); } if (0 != liScriptSize.HighPart || 0 != (liScriptSize.LowPart % sizeof(WCHAR))) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); ExitOnFailure(hr, "Invalid data read from ca script."); } cbData = liScriptSize.LowPart; pbData = static_cast<BYTE*>(MemAlloc(cbData, TRUE)); ExitOnNull(pbData, hr, E_OUTOFMEMORY, "Failed to allocate memory to read in ca script."); if (INVALID_SET_FILE_POINTER == ::SetFilePointer(hScript->hScriptFile, 0, NULL, FILE_BEGIN)) { ExitWithLastError(hr, "Failed to reset to beginning of ca script."); } DWORD cbTotalRead = 0; DWORD cbRead = 0; do { if (!::ReadFile(hScript->hScriptFile, pbData + cbTotalRead, cbData - cbTotalRead, &cbRead, NULL)) { ExitWithLastError(hr, "Failed to read from ca script."); } cbTotalRead += cbRead; } while (cbRead && cbTotalRead < cbData); if (cbTotalRead != cbData) { hr = E_UNEXPECTED; ExitOnFailure(hr, "Failed to completely read ca script."); } // Add one to the allocated space because the data stored in the script is not // null terminated. After copying the memory over, we'll ensure the string is // null terminated. DWORD cchData = cbData / sizeof(WCHAR) + 1; hr = StrAlloc(ppwzCustomActionData, cchData); ExitOnFailure(hr, "Failed to copy ca script."); CopyMemory(*ppwzCustomActionData, pbData, cbData); (*ppwzCustomActionData)[cchData - 1] = L'\0'; LExit: ReleaseMem(pbData); return hr; }
/*********************************************************************** * register_coclasses */ static HRESULT register_coclasses(struct regsvr_coclass const *list) { LONG res = ERROR_SUCCESS; HKEY coclass_key; res = RegCreateKeyExW(HKEY_CLASSES_ROOT, clsid_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &coclass_key, NULL); if (res != ERROR_SUCCESS) goto error_return; for (; res == ERROR_SUCCESS && list->clsid; ++list) { WCHAR buf[39]; HKEY clsid_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &clsid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; if (list->name) { res = RegSetValueExA(clsid_key, NULL, 0, REG_SZ, (CONST BYTE*)(list->name), strlen(list->name) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->ips) { res = register_key_defvalueA(clsid_key, ips_keyname, list->ips); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->ips32) { HKEY ips32_key; res = RegCreateKeyExW(clsid_key, ips32_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &ips32_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = RegSetValueExA(ips32_key, NULL, 0, REG_SZ, (CONST BYTE*)list->ips32, lstrlenA(list->ips32) + 1); if (res == ERROR_SUCCESS && list->ips32_tmodel) res = RegSetValueExA(ips32_key, tmodel_valuename, 0, REG_SZ, (CONST BYTE*)list->ips32_tmodel, strlen(list->ips32_tmodel) + 1); RegCloseKey(ips32_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->progid) { res = register_key_defvalueA(clsid_key, progid_keyname, list->progid); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = register_progid(buf, list->progid, NULL, list->name, list->progid_extra); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->viprogid) { res = register_key_defvalueA(clsid_key, viprogid_keyname, list->viprogid); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = register_progid(buf, list->viprogid, list->progid, list->name, list->progid_extra); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } error_close_clsid_key: RegCloseKey(clsid_key); } error_close_coclass_key: RegCloseKey(coclass_key); error_return: return res != ERROR_SUCCESS ? HRESULT_FROM_WIN32(res) : S_OK; }
// Collect the username and password into a serialized credential for the correct usage scenario // (logon/unlock is what's demonstrated in this sample). LogonUI then passes these credentials // back to the system to log on. HRESULT CardUnlockCredential::GetSerialization( CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* pcpgsr, CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs, PWSTR* ppwszOptionalStatusText, CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon ) { //while (!_pListener->GetConnectedStatus()); //SetUserData(_pListener->GetUserName(), _pListener->GetPassword()); UNREFERENCED_PARAMETER(ppwszOptionalStatusText); UNREFERENCED_PARAMETER(pcpsiOptionalStatusIcon); KERB_INTERACTIVE_LOGON kil; ZeroMemory(&kil, sizeof(kil)); HRESULT hr; WCHAR wsz[MAX_COMPUTERNAME_LENGTH+1]; DWORD cch = ARRAYSIZE(wsz); if (GetComputerNameW(wsz, &cch)) { PWSTR pwzProtectedPassword; hr = ProtectIfNecessaryAndCopyPassword(_rgFieldStrings[SFI_PASSWORD], _cpus, &pwzProtectedPassword); if (SUCCEEDED(hr)) { KERB_INTERACTIVE_UNLOCK_LOGON kiul; // Initialize kiul with weak references to our credential. hr = KerbInteractiveUnlockLogonInit(wsz, _rgFieldStrings[SFI_USERNAME], pwzProtectedPassword, _cpus, &kiul); if (SUCCEEDED(hr)) { // We use KERB_INTERACTIVE_UNLOCK_LOGON in both unlock and logon scenarios. It contains a // KERB_INTERACTIVE_LOGON to hold the creds plus a LUID that is filled in for us by Winlogon // as necessary. hr = KerbInteractiveUnlockLogonPack(kiul, &pcpcs->rgbSerialization, &pcpcs->cbSerialization); if (SUCCEEDED(hr)) { ULONG ulAuthPackage; hr = RetrieveNegotiateAuthPackage(&ulAuthPackage); if (SUCCEEDED(hr)) { pcpcs->ulAuthenticationPackage = ulAuthPackage; pcpcs->clsidCredentialProvider = CLSID_CardUnlockProvider; // At this point the credential has created the serialized credential used for logon // By setting this to CPGSR_RETURN_CREDENTIAL_FINISHED we are letting logonUI know // that we have all the information we need and it should attempt to submit the // serialized credential. *pcpgsr = CPGSR_RETURN_CREDENTIAL_FINISHED; } } } CoTaskMemFree(pwzProtectedPassword); } } else { DWORD dwErr = GetLastError(); hr = HRESULT_FROM_WIN32(dwErr); } return hr; }
bool pal::load_library(const string_t* in_path, dll_t* dll) { string_t path = *in_path; // LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR: // In framework-dependent apps, coreclr would come from another directory than the host, // so make sure coreclr dependencies can be resolved from coreclr.dll load dir. if (LongFile::IsPathNotFullyQualified(path)) { if (!pal::realpath(&path)) { trace::error(_X("Failed to load the dll from [%s], HRESULT: 0x%X"), path.c_str(), HRESULT_FROM_WIN32(GetLastError())); return false; } } //Adding the assert to ensure relative paths which are not just filenames are not used for LoadLibrary Calls assert(!LongFile::IsPathNotFullyQualified(path) || !LongFile::ContainsDirectorySeparator(path)); *dll = ::LoadLibraryExW(path.c_str(), NULL, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); if (*dll == nullptr) { trace::error(_X("Failed to load the dll from [%s], HRESULT: 0x%X"), path.c_str(), HRESULT_FROM_WIN32(GetLastError())); return false; } // Pin the module HMODULE dummy_module; if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, path.c_str(), &dummy_module)) { trace::error(_X("Failed to pin library [%s] in [%s]"), path.c_str(), _STRINGIFY(__FUNCTION__)); return false; } if (trace::is_enabled()) { string_t buf; GetModuleFileNameWrapper(*dll, &buf); trace::info(_X("Loaded library from %s"), buf.c_str()); } return true; }
/*********************************************************************** * register_coclasses */ static HRESULT register_coclasses(struct regsvr_coclass const *list) { LONG res = ERROR_SUCCESS; HKEY coclass_key; res = RegCreateKeyExW(HKEY_CLASSES_ROOT, clsid_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &coclass_key, NULL); if (res != ERROR_SUCCESS) goto error_return; for (; res == ERROR_SUCCESS && list->clsid; ++list) { WCHAR buf[39]; HKEY clsid_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &clsid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; if (list->name) { res = RegSetValueExA(clsid_key, NULL, 0, REG_SZ, (CONST BYTE*)(list->name), strlen(list->name) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->idName) { char buffer[64] = "@%SYSTEMROOT%\\system32\\shell32.dll,-"; sprintf(buffer+strlen(buffer), "%u", list->idName); res = RegSetValueExA(clsid_key, localized_valuename, 0, REG_EXPAND_SZ, (CONST BYTE*)(buffer), strlen(buffer)+1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->idDefaultIcon) { HKEY icon_key; char buffer[64] = "%SYSTEMROOT%\\system32\\shell32.dll,-"; res = RegCreateKeyExW(clsid_key, defaulticon_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &icon_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; sprintf(buffer+strlen(buffer), "%u", list->idDefaultIcon); res = RegSetValueExA(icon_key, NULL, 0, REG_EXPAND_SZ, (CONST BYTE*)(buffer), strlen(buffer)+1); RegCloseKey(icon_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->ips) { res = register_key_defvalueA(clsid_key, ips_keyname, list->ips); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->ips32) { HKEY ips32_key; res = RegCreateKeyExW(clsid_key, ips32_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &ips32_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = RegSetValueExA(ips32_key, NULL, 0, REG_SZ, (CONST BYTE*)list->ips32, lstrlenA(list->ips32) + 1); if (res == ERROR_SUCCESS && list->ips32_tmodel) res = RegSetValueExA(ips32_key, tmodel_valuename, 0, REG_SZ, (CONST BYTE*)list->ips32_tmodel, strlen(list->ips32_tmodel) + 1); RegCloseKey(ips32_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->flags & SHELLEX_MAYCHANGEDEFAULTMENU) { HKEY shellex_key, mcdm_key; res = RegCreateKeyExW(clsid_key, shellex_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &shellex_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = RegCreateKeyExW(shellex_key, mcdm_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &mcdm_key, NULL); RegCloseKey(shellex_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; RegCloseKey(mcdm_key); } if (list->flags & (SHELLFOLDER_WANTSFORPARSING|SHELLFOLDER_ATTRIBUTES|SHELLFOLDER_CALLFORATTRIBUTES)) { HKEY shellfolder_key; res = RegCreateKeyExW(clsid_key, shellfolder_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &shellfolder_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; if (list->flags & SHELLFOLDER_WANTSFORPARSING) res = RegSetValueExA(shellfolder_key, wfparsing_valuename, 0, REG_SZ, (LPBYTE)"", 1); if (list->flags & SHELLFOLDER_ATTRIBUTES) res = RegSetValueExA(shellfolder_key, attributes_valuename, 0, REG_DWORD, (LPBYTE)&list->dwAttributes, sizeof(DWORD)); if (list->flags & SHELLFOLDER_CALLFORATTRIBUTES) res = RegSetValueExA(shellfolder_key, cfattributes_valuename, 0, REG_DWORD, (LPBYTE)&list->dwCallForAttributes, sizeof(DWORD)); RegCloseKey(shellfolder_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->clsid_str) { res = register_key_defvalueA(clsid_key, clsid_keyname, list->clsid_str); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->progid) { HKEY progid_key; res = register_key_defvalueA(clsid_key, progid_keyname, list->progid); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = RegCreateKeyExA(HKEY_CLASSES_ROOT, list->progid, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &progid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = register_key_defvalueW(progid_key, clsid_keyname, buf); RegCloseKey(progid_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } error_close_clsid_key: RegCloseKey(clsid_key); } error_close_coclass_key: RegCloseKey(coclass_key); error_return: return res != ERROR_SUCCESS ? HRESULT_FROM_WIN32(res) : S_OK; }
static HRESULT WINAPI DEVENUM_IPropertyBag_Read( LPPROPERTYBAG iface, LPCOLESTR pszPropName, VARIANT* pVar, IErrorLog* pErrorLog) { LPVOID pData = NULL; DWORD received; DWORD type = 0; RegPropBagImpl *This = impl_from_IPropertyBag(iface); HRESULT res = S_OK; LONG reswin32; TRACE("(%p)->(%s, %p, %p)\n", This, debugstr_w(pszPropName), pVar, pErrorLog); if (!pszPropName || !pVar) return E_POINTER; reswin32 = RegQueryValueExW(This->hkey, pszPropName, NULL, NULL, NULL, &received); res = HRESULT_FROM_WIN32(reswin32); if (SUCCEEDED(res)) { pData = HeapAlloc(GetProcessHeap(), 0, received); /* work around a GCC bug that occurs here unless we use the reswin32 variable as well */ reswin32 = RegQueryValueExW(This->hkey, pszPropName, NULL, &type, pData, &received); res = HRESULT_FROM_WIN32(reswin32); } if (SUCCEEDED(res)) { res = E_INVALIDARG; /* assume we cannot coerce into right type */ TRACE("Read %d bytes (%s)\n", received, type == REG_SZ ? debugstr_w(pData) : "binary data"); switch (type) { case REG_SZ: switch (V_VT(pVar)) { case VT_LPWSTR: V_UNION(pVar, bstrVal) = CoTaskMemAlloc(received); memcpy(V_UNION(pVar, bstrVal), pData, received); res = S_OK; break; case VT_EMPTY: V_VT(pVar) = VT_BSTR; /* fall through */ case VT_BSTR: V_UNION(pVar, bstrVal) = SysAllocStringLen(pData, received/sizeof(WCHAR) - 1); res = S_OK; break; } break; case REG_DWORD: TRACE("REG_DWORD: %x\n", *(DWORD *)pData); switch (V_VT(pVar)) { case VT_EMPTY: V_VT(pVar) = VT_I4; /* fall through */ case VT_I4: case VT_UI4: V_UNION(pVar, ulVal) = *(DWORD *)pData; res = S_OK; break; } break; case REG_BINARY: { SAFEARRAYBOUND bound; void * pArrayElements; bound.lLbound = 0; bound.cElements = received; TRACE("REG_BINARY: len = %d\n", received); switch (V_VT(pVar)) { case VT_EMPTY: V_VT(pVar) = VT_ARRAY | VT_UI1; /* fall through */ case VT_ARRAY | VT_UI1: if (!(V_UNION(pVar, parray) = SafeArrayCreate(VT_UI1, 1, &bound))) res = E_OUTOFMEMORY; else res = S_OK; break; } if (res == E_INVALIDARG) break; res = SafeArrayAccessData(V_UNION(pVar, parray), &pArrayElements); if (FAILED(res)) break; CopyMemory(pArrayElements, pData, received); res = SafeArrayUnaccessData(V_UNION(pVar, parray)); break; } } if (res == E_INVALIDARG) FIXME("Variant type %x not supported for regtype %x\n", V_VT(pVar), type); } HeapFree(GetProcessHeap(), 0, pData); TRACE("<- %x\n", res); return res; }
static HRESULT do_process_key(LPCOLESTR *pstr, HKEY parent_key, strbuf *buf, BOOL do_register) { LPCOLESTR iter = *pstr; HRESULT hres; LONG lres; HKEY hkey = 0; strbuf name; enum { NORMAL, NO_REMOVE, IS_VAL, FORCE_REMOVE, DO_DELETE } key_type = NORMAL; static const WCHAR wstrNoRemove[] = {'N','o','R','e','m','o','v','e',0}; static const WCHAR wstrForceRemove[] = {'F','o','r','c','e','R','e','m','o','v','e',0}; static const WCHAR wstrDelete[] = {'D','e','l','e','t','e',0}; static const WCHAR wstrval[] = {'v','a','l',0}; iter = *pstr; hres = get_word(&iter, buf); if(FAILED(hres)) return hres; strbuf_init(&name); while(buf->str[1] || buf->str[0] != '}') { key_type = NORMAL; if(!lstrcmpiW(buf->str, wstrNoRemove)) key_type = NO_REMOVE; else if(!lstrcmpiW(buf->str, wstrForceRemove)) key_type = FORCE_REMOVE; else if(!lstrcmpiW(buf->str, wstrval)) key_type = IS_VAL; else if(!lstrcmpiW(buf->str, wstrDelete)) key_type = DO_DELETE; if(key_type != NORMAL) { hres = get_word(&iter, buf); if(FAILED(hres)) break; } TRACE("name = %s\n", debugstr_w(buf->str)); if(do_register) { if(key_type == IS_VAL) { hkey = parent_key; strbuf_write(buf->str, &name, -1); }else if(key_type == DO_DELETE) { TRACE("Deleting %s\n", debugstr_w(buf->str)); RegDeleteTreeW(parent_key, buf->str); }else { if(key_type == FORCE_REMOVE) RegDeleteTreeW(parent_key, buf->str); lres = RegCreateKeyW(parent_key, buf->str, &hkey); if(lres != ERROR_SUCCESS) { WARN("Could not create(open) key: %08x\n", lres); hres = HRESULT_FROM_WIN32(lres); break; } } }else if(key_type != IS_VAL && key_type != DO_DELETE) { strbuf_write(buf->str, &name, -1); lres = RegOpenKeyW(parent_key, buf->str, &hkey); if(lres != ERROR_SUCCESS) WARN("Could not open key %s: %08x\n", debugstr_w(name.str), lres); } if(key_type != DO_DELETE && *iter == '=') { iter++; hres = get_word(&iter, buf); if(FAILED(hres)) break; if(buf->len != 1) { WARN("Wrong registry type: %s\n", debugstr_w(buf->str)); hres = DISP_E_EXCEPTION; break; } if(do_register) { switch(buf->str[0]) { case 's': hres = get_word(&iter, buf); if(FAILED(hres)) break; lres = RegSetValueExW(hkey, name.len ? name.str : NULL, 0, REG_SZ, (PBYTE)buf->str, (lstrlenW(buf->str)+1)*sizeof(WCHAR)); if(lres != ERROR_SUCCESS) { WARN("Could set value of key: %08x\n", lres); hres = HRESULT_FROM_WIN32(lres); break; } break; case 'd': { DWORD dw; hres = get_word(&iter, buf); if(FAILED(hres)) break; dw = atoiW(buf->str); lres = RegSetValueExW(hkey, name.len ? name.str : NULL, 0, REG_DWORD, (PBYTE)&dw, sizeof(dw)); if(lres != ERROR_SUCCESS) { WARN("Could set value of key: %08x\n", lres); hres = HRESULT_FROM_WIN32(lres); break; } break; } case 'b': { BYTE *bytes; DWORD count; DWORD i; hres = get_word(&iter, buf); if(FAILED(hres)) break; count = (lstrlenW(buf->str) + 1) / 2; bytes = HeapAlloc(GetProcessHeap(), 0, count); if(bytes == NULL) { hres = E_OUTOFMEMORY; break; } for(i = 0; i < count && buf->str[2*i]; i++) { WCHAR digits[3]; if(!isxdigitW(buf->str[2*i]) || !isxdigitW(buf->str[2*i + 1])) { hres = E_FAIL; break; } digits[0] = buf->str[2*i]; digits[1] = buf->str[2*i + 1]; digits[2] = 0; bytes[i] = (BYTE) strtoulW(digits, NULL, 16); } if(SUCCEEDED(hres)) { lres = RegSetValueExW(hkey, name.len ? name.str : NULL, 0, REG_BINARY, bytes, count); if(lres != ERROR_SUCCESS) { WARN("Could not set value of key: 0x%08x\n", lres); hres = HRESULT_FROM_WIN32(lres); } } HeapFree(GetProcessHeap(), 0, bytes); break; } default: WARN("Wrong resource type: %s\n", debugstr_w(buf->str)); hres = DISP_E_EXCEPTION; }; if(FAILED(hres)) break; }else { if(*iter == '-') iter++; hres = get_word(&iter, buf); if(FAILED(hres)) break; } }else if(key_type == IS_VAL) { WARN("value not set!\n"); hres = DISP_E_EXCEPTION; break; } if(key_type != IS_VAL && key_type != DO_DELETE && *iter == '{' && isspaceW(iter[1])) { hres = get_word(&iter, buf); if(FAILED(hres)) break; hres = do_process_key(&iter, hkey, buf, do_register); if(FAILED(hres)) break; } TRACE("%x %x\n", do_register, key_type); if(!do_register && (key_type == NORMAL || key_type == FORCE_REMOVE)) { TRACE("Deleting %s\n", debugstr_w(name.str)); RegDeleteKeyW(parent_key, name.str); } if(hkey && key_type != IS_VAL) RegCloseKey(hkey); hkey = 0; name.len = 0; hres = get_word(&iter, buf); if(FAILED(hres)) break; } HeapFree(GetProcessHeap(), 0, name.str); if(hkey && key_type != IS_VAL) RegCloseKey(hkey); *pstr = iter; return hres; }
HRESULT CNodeFactory::ProcessAssemblyIdentityTag(XML_NODE_INFO **aNodeInfo, USHORT cNumRecs) { HRESULT hr = S_OK; LPWSTR pwzAttributeNS = NULL; USHORT idx = 1; ASSERT(aNodeInfo && cNumRecs && _pAsmInfo); while (idx < cNumRecs) { if (aNodeInfo[idx]->dwType == XML_ATTRIBUTE) { // Found an attribute. Find out which one, and extract the data. // Note: ::ExtractXMLAttribute increments idx. hr = ApplyNamespace(aNodeInfo[idx], &pwzAttributeNS, 0); if (FAILED(hr)) { goto Exit; } if (!lstrcmpW(pwzAttributeNS, XML_ATTRIBUTE_NAME)) { if (!_pAsmInfo->_pwzName) { hr = ::ExtractXMLAttribute(&(_pAsmInfo->_pwzName), aNodeInfo, &idx, cNumRecs); if (FAILED(hr)) { SAFEDELETEARRAY(pwzAttributeNS); goto Exit; } } else { DEBUGOUT(_pdbglog, 1, ID_FUSLOG_XML_MULTIPLE_IDENTITIES); hr = E_FAIL; goto Exit; } } else if (!lstrcmpW(pwzAttributeNS, XML_ATTRIBUTE_PUBLICKEYTOKEN)) { if (!_pAsmInfo->_pwzPublicKeyToken) { hr = ::ExtractXMLAttribute(&(_pAsmInfo->_pwzPublicKeyToken), aNodeInfo, &idx, cNumRecs); if (FAILED(hr)) { SAFEDELETEARRAY(pwzAttributeNS); goto Exit; } } else { DEBUGOUT(_pdbglog, 1, ID_FUSLOG_XML_MULTIPLE_IDENTITIES); hr = E_FAIL; goto Exit; } } else if (!lstrcmpW(pwzAttributeNS, XML_ATTRIBUTE_CULTURE)) { if (!_pAsmInfo->_pwzCulture) { hr = ::ExtractXMLAttribute(&(_pAsmInfo->_pwzCulture), aNodeInfo, &idx, cNumRecs); if (FAILED(hr)) { SAFEDELETEARRAY(pwzAttributeNS); goto Exit; } // Change all synonyms for culture=neutral/"" to unset if (!lstrlenW(_pAsmInfo->_pwzCulture) || !lstrcmpiW(_pAsmInfo->_pwzCulture, CFG_CULTURE_NEUTRAL)) { SAFEDELETEARRAY(_pAsmInfo->_pwzCulture); } } else { DEBUGOUT(_pdbglog, 1, ID_FUSLOG_XML_MULTIPLE_IDENTITIES); hr = E_FAIL; goto Exit; } } else { idx++; } SAFEDELETEARRAY(pwzAttributeNS); } else { idx++; } } if (!_pAsmInfo->_pwzName) { // Data was incomplete. hr = HRESULT_FROM_WIN32(ERROR_TAG_NOT_PRESENT); goto Exit; } Exit: return hr; }
LRESULT CVideoViewControl::OnTimer(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { HandleError(HRESULT_FROM_WIN32(ERROR_PROCESS_ABORTED)); return 0; }
HRESULT CNodeFactory::ProcessQualifyAssemblyTag(XML_NODE_INFO **aNodeInfo, USHORT cNumRecs) { HRESULT hr = S_OK; USHORT idx = 1; LPWSTR pwzAttributeNS = NULL; LPWSTR pwzPartialName = NULL; LPWSTR pwzFullName = NULL; CQualifyAssembly *pqa = NULL; IAssemblyName *pNameFull = NULL; IAssemblyName *pNamePartial = NULL; IAssemblyName *pNameQualified = NULL; LPWSTR wzCanonicalDisplayName=NULL; ASSERT(aNodeInfo && cNumRecs); while (idx < cNumRecs) { if (aNodeInfo[idx]->dwType == XML_ATTRIBUTE) { // Found an attribute. Find out which one, and extract the data. // Node: ::ExtractXMLAttribute increments idx. hr = ApplyNamespace(aNodeInfo[idx], &pwzAttributeNS, 0); if (FAILED(hr)) { goto Exit; } if (!lstrcmpW(pwzAttributeNS, XML_ATTRIBUTE_PARTIALNAME)) { SAFEDELETEARRAY(pwzAttributeNS); if (pwzPartialName) { // Ignore duplicate attribute idx++; } else { hr = ::ExtractXMLAttribute(&pwzPartialName, aNodeInfo, &idx, cNumRecs); if (FAILED(hr)) { goto Exit; } } } else if (!lstrcmpW(pwzAttributeNS, XML_ATTRIBUTE_FULLNAME)) { SAFEDELETEARRAY(pwzAttributeNS); if (pwzFullName) { // Ignore duplicate attribute idx++; } else { hr = ::ExtractXMLAttribute(&pwzFullName, aNodeInfo, &idx, cNumRecs); if (FAILED(hr)) { goto Exit; } } } else { SAFEDELETEARRAY(pwzAttributeNS); idx++; } } else { idx++; } } if (pwzPartialName && pwzFullName) { DWORD dwSize; DWORD adwProperties[] = { ASM_NAME_NAME, ASM_NAME_MAJOR_VERSION, ASM_NAME_MINOR_VERSION, ASM_NAME_BUILD_NUMBER, ASM_NAME_REVISION_NUMBER, ASM_NAME_CULTURE, ASM_NAME_PUBLIC_KEY_TOKEN }; DWORD adwCmpFlags[] = { ASM_CMPF_NAME, ASM_CMPF_MAJOR_VERSION, ASM_CMPF_MINOR_VERSION, ASM_CMPF_BUILD_NUMBER, ASM_CMPF_REVISION_NUMBER, ASM_CMPF_CULTURE, ASM_CMPF_PUBLIC_KEY_TOKEN }; DWORD dwNumProps = sizeof(adwProperties) / sizeof(adwProperties[0]); if (FAILED(CreateAssemblyNameObject(&pNameFull, pwzFullName, CANOF_PARSE_DISPLAY_NAME, 0))) { goto Exit; } if (FAILED(CreateAssemblyNameObject(&pNamePartial, pwzPartialName, CANOF_PARSE_DISPLAY_NAME, 0))) { goto Exit; } // Check validity of qualification if (CAssemblyName::IsPartial(pNameFull) || !CAssemblyName::IsPartial(pNamePartial)) { goto Exit; } if (FAILED(pNamePartial->Clone(&pNameQualified))) { goto Exit; } for (DWORD i = 0; i < dwNumProps; i++) { dwSize = 0; if (pNamePartial->GetProperty(adwProperties[i], NULL, &dwSize) != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) { // Partial on this field. Set pNameQualified's corresponding // property to whatever is in pNameFull. dwSize = 0; pNameFull->GetProperty(adwProperties[i], NULL, &dwSize); if (!dwSize) { goto Exit; } else { BYTE *pBuf; pBuf = NEW(BYTE[dwSize]); if (!pBuf) { hr = E_OUTOFMEMORY; goto Exit; } if (FAILED(pNameFull->GetProperty(adwProperties[i], pBuf, &dwSize))) { SAFEDELETEARRAY(pBuf); goto Exit; } if (FAILED(pNameQualified->SetProperty(adwProperties[i], pBuf, dwSize))) { SAFEDELETEARRAY(pBuf); goto Exit; } SAFEDELETEARRAY(pBuf); } } else { // Full-specified on this field. Make sure it matches the full ref specified. if (pNamePartial->IsEqual(pNameFull, adwCmpFlags[i]) != S_OK) { goto Exit; } } } if (CAssemblyName::IsPartial(pNameQualified)) { goto Exit; } // Get canonical display name format wzCanonicalDisplayName = NEW(WCHAR[MAX_URL_LENGTH+1]); if (!wzCanonicalDisplayName) { hr = E_OUTOFMEMORY; goto Exit; } dwSize = MAX_URL_LENGTH; if (FAILED(pNamePartial->GetDisplayName(wzCanonicalDisplayName, &dwSize, 0))) { goto Exit; } // Add qualified assembly entry to list pqa = new CQualifyAssembly; if (!pqa) { hr = E_OUTOFMEMORY; goto Exit; } pqa->_pwzPartialName = WSTRDupDynamic(wzCanonicalDisplayName); if (!pqa->_pwzPartialName) { hr = E_OUTOFMEMORY; goto Exit; } pqa->_pNameFull = pNameQualified; pNameQualified->AddRef(); _listQualifyAssembly.AddTail(pqa); } Exit: SAFEDELETEARRAY(pwzPartialName); SAFEDELETEARRAY(pwzFullName); SAFERELEASE(pNameFull); SAFERELEASE(pNamePartial); SAFERELEASE(pNameQualified); SAFEDELETEARRAY(wzCanonicalDisplayName); return hr; }
HRESULT CNodeFactory::CreateNode(IXMLNodeSource __RPC_FAR *pSource, PVOID pNodeParent, USHORT cNumRecs, XML_NODE_INFO __RPC_FAR **aNodeInfo) { HRESULT hr = S_OK; LPWSTR pwzElementNameNS = NULL; CCodebaseHint *pCodebaseInfo = NULL; CBindingRedir *pRedirInfo = NULL; hr = _nsmgr.OnCreateNode(pSource, pNodeParent, cNumRecs, aNodeInfo); if (FAILED(hr)) { goto Exit; } if (aNodeInfo[0]->dwType == XML_ELEMENT) { _dwCurDepth++; hr = ApplyNamespace(aNodeInfo[0], &pwzElementNameNS, XMLNS_FLAGS_APPLY_DEFAULT_NAMESPACE); if (FAILED(hr)) { goto Exit; } switch (_dwState) { case PSTATE_LOOKUP_CONFIGURATION: // Still looking for <configuration> tag if ((_dwCurDepth == XML_CONFIGURATION_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_CONFIGURATION))) { _dwState = PSTATE_CONFIGURATION; } break; case PSTATE_CONFIGURATION: // In <configuration> tag, and looking for <runtime> tag if ((_dwCurDepth == XML_RUNTIME_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_RUNTIME))) { _dwState = PSTATE_RUNTIME; } break; case PSTATE_RUNTIME: // In <runtime> tag, and looking for <assemblyBinding> tag if ((_dwCurDepth == XML_ASSEMBLYBINDING_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_ASSEMBLYBINDING))) { _dwState = PSTATE_ASSEMBLYBINDING; } break; case PSTATE_ASSEMBLYBINDING: // In <assemblyBinding> tag. if ((_dwCurDepth == XML_PROBING_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_PROBING))) { hr = ProcessProbingTag(aNodeInfo, cNumRecs); if (FAILED(hr)) { goto Exit; } } else if ((_dwCurDepth == XML_QUALIFYASSEMBLY_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_QUALIFYASSEMBLY))) { hr = ProcessQualifyAssemblyTag(aNodeInfo, cNumRecs); if (FAILED(hr)) { goto Exit; } } else if ((_dwCurDepth == XML_GLOBAL_PUBLISHERPOLICY_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_PUBLISHERPOLICY))) { hr = ProcessPublisherPolicyTag(aNodeInfo, cNumRecs, TRUE); if (FAILED(hr)) { goto Exit; } } else if ((_dwCurDepth == XML_DEPENDENTASSEMBLY_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_DEPENDENTASSEMBLY))) { // Create new assembly info struct ASSERT(!_pAsmInfo); _pAsmInfo = NEW(CAsmBindingInfo); if (!_pAsmInfo) { hr = E_OUTOFMEMORY; goto Exit; } // Transition state _dwState = PSTATE_DEPENDENTASSEMBLY; } break; case PSTATE_DEPENDENTASSEMBLY: // In <dependentAssembly> tag. if ((_dwCurDepth == XML_ASSEMBLYIDENTITY_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_ASSEMBLYIDENTITY))) { hr = ProcessAssemblyIdentityTag(aNodeInfo, cNumRecs); if (hr == HRESULT_FROM_WIN32(ERROR_TAG_NOT_PRESENT)) { DEBUGOUT(_pdbglog, 1, ID_FUSLOG_XML_ASSEMBLYIDENTITY_MISSING_NAME); hr = S_OK; } else if (FAILED(hr)) { goto Exit; } } else if ((_dwCurDepth == XML_BINDINGREDIRECT_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_BINDINGREDIRECT))) { pRedirInfo = NEW(CBindingRedir); if (!pRedirInfo) { hr = E_OUTOFMEMORY; goto Exit; } hr = ProcessBindingRedirectTag(aNodeInfo, cNumRecs, pRedirInfo); if (hr == S_OK) { (_pAsmInfo->_listBindingRedir).AddTail(pRedirInfo); pRedirInfo = NULL; } else if (hr == HRESULT_FROM_WIN32(ERROR_TAG_NOT_PRESENT)) { SAFEDELETE(pRedirInfo); DEBUGOUT(_pdbglog, 1, ID_FUSLOG_XML_BINDINGREDIRECT_INSUFFICIENT_DATA); hr = S_OK; } else if (FAILED(hr)) { SAFEDELETE(pRedirInfo); goto Exit; } } else if ((_dwCurDepth == XML_CODEBASE_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_CODEBASE))) { pCodebaseInfo = NEW(CCodebaseHint); if (!pCodebaseInfo) { hr = E_OUTOFMEMORY; goto Exit; } hr = ProcessCodebaseTag(aNodeInfo, cNumRecs, pCodebaseInfo); if (hr == S_OK) { (_pAsmInfo->_listCodebase).AddTail(pCodebaseInfo); pCodebaseInfo = NULL; } else if (hr == HRESULT_FROM_WIN32(ERROR_TAG_NOT_PRESENT)) { DEBUGOUT(_pdbglog, 1, ID_FUSLOG_XML_CODEBASE_HREF_MISSING); SAFEDELETE(pCodebaseInfo); hr = S_OK; } else if (FAILED(hr)) { SAFEDELETE(pCodebaseInfo); goto Exit; } } else if ((_dwCurDepth == XML_PUBLISHERPOLICY_DEPTH) && (!lstrcmpW(pwzElementNameNS, POLICY_TAG_PUBLISHERPOLICY))) { hr = ProcessPublisherPolicyTag(aNodeInfo, cNumRecs, FALSE); if (FAILED(hr)) { goto Exit; } } break; default: // Unknown state! ASSERT(0); break; } } Exit: SAFEDELETEARRAY(pwzElementNameNS); return hr; }
//////////////////////////////////////////////////////////// /// /// @brief 为应用程序创建一个会话对象、获取用户IE代理设置 /// /// @note 在应用程序开始时调用 /// /// @param void /// /// @return HRESULT /// /// @retval S_OK 正常返回 /// @retval 通过GetLastError()返回 /// //////////////////////////////////////////////////////////// HRESULT WinHTTPLW::Initialize() { if (m_hSession == NULL) { m_hSession = ::WinHttpOpen( L"LeWei WinHTTP/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); } if (m_hSession == NULL) { return HRESULT_FROM_WIN32(::GetLastError()); } // 获取当前用户IE的代理设置 if (!::WinHttpGetIEProxyConfigForCurrentUser(&m_ieProxyConfig)) { Uninitialize(); return HRESULT_FROM_WIN32(::GetLastError()); } WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions = { 0 }; // lpszAutoConfigUrl不为空表示钩选"使用自动配置脚本",Internet Explorer将下载代理自动配置(PAC)文件来确定特定连接的代理服务器 if (m_ieProxyConfig.lpszAutoConfigUrl != NULL) { // fAutoDetect为true表示钩选"自动检测设置",意味着Internet Explorer使用Web代理自动发现(WPAD)协议来查找代理设置。 if (m_ieProxyConfig.fAutoDetect) { autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; } else { autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; autoProxyOptions.lpszAutoConfigUrl = m_ieProxyConfig.lpszAutoConfigUrl; } // 获取当前的IE代理服务器信息 if (!::WinHttpGetProxyForUrl( m_hSession, NULL, &autoProxyOptions, &m_proxyInfo)) { Uninitialize(); return HRESULT_FROM_WIN32(::GetLastError()); } // 设置代理方式默认为IE代理 if (!::WinHttpSetOption( m_hSession, WINHTTP_OPTION_PROXY, &m_proxyInfo, sizeof(m_proxyInfo) )) { Uninitialize(); return HRESULT_FROM_WIN32(::GetLastError()); } } else if (m_ieProxyConfig.lpszProxy != NULL) { // 获取当前的IE代理服务器信息 m_proxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; m_proxyInfo.lpszProxy = m_ieProxyConfig.lpszProxy; m_proxyInfo.lpszProxyBypass = m_ieProxyConfig.lpszProxyBypass; // 设置代理方式默认为IE代理 if (!::WinHttpSetOption( m_hSession, WINHTTP_OPTION_PROXY, &m_proxyInfo, sizeof(m_proxyInfo) )) { Uninitialize(); return HRESULT_FROM_WIN32(::GetLastError()); } } return S_OK; }
DAPI_(HRESULT) PathExpand( __out LPWSTR *psczFullPath, __in_z LPCWSTR wzRelativePath, __in DWORD dwResolveFlags ) { Assert(wzRelativePath && *wzRelativePath); HRESULT hr = S_OK; DWORD cch = 0; LPWSTR sczExpandedPath = NULL; DWORD cchExpandedPath = 0; LPWSTR sczFullPath = NULL; // // First, expand any environment variables. // if (dwResolveFlags & PATH_EXPAND_ENVIRONMENT) { cchExpandedPath = PATH_GOOD_ENOUGH; hr = StrAlloc(&sczExpandedPath, cchExpandedPath); ExitOnFailure(hr, "Failed to allocate space for expanded path."); cch = ::ExpandEnvironmentStringsW(wzRelativePath, sczExpandedPath, cchExpandedPath); if (0 == cch) { ExitWithLastError1(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); } else if (cchExpandedPath < cch) { cchExpandedPath = cch; hr = StrAlloc(&sczExpandedPath, cchExpandedPath); ExitOnFailure(hr, "Failed to re-allocate more space for expanded path."); cch = ::ExpandEnvironmentStringsW(wzRelativePath, sczExpandedPath, cchExpandedPath); if (0 == cch) { ExitWithLastError1(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); } else if (cchExpandedPath < cch) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); ExitOnRootFailure(hr, "Failed to allocate buffer for expanded path."); } } if (MAX_PATH < cch) { hr = PathPrefix(&sczExpandedPath); // ignore invald arg from path prefix because this may not be a complete path yet if (E_INVALIDARG == hr) { hr = S_OK; } ExitOnFailure(hr, "Failed to prefix long path after expanding environment variables."); hr = StrMaxLength(sczExpandedPath, reinterpret_cast<DWORD_PTR *>(&cchExpandedPath)); ExitOnFailure(hr, "Failed to get max length of expanded path."); } } // // Second, get the full path. // if (dwResolveFlags & PATH_EXPAND_FULLPATH) { LPWSTR wzFileName = NULL; LPCWSTR wzPath = sczExpandedPath ? sczExpandedPath : wzRelativePath; DWORD cchFullPath = PATH_GOOD_ENOUGH < cchExpandedPath ? cchExpandedPath : PATH_GOOD_ENOUGH; hr = StrAlloc(&sczFullPath, cchFullPath); ExitOnFailure(hr, "Failed to allocate space for full path."); cch = ::GetFullPathNameW(wzPath, cchFullPath, sczFullPath, &wzFileName); if (0 == cch) { ExitWithLastError1(hr, "Failed to get full path for string: %ls", wzPath); } else if (cchFullPath < cch) { cchFullPath = cch < MAX_PATH ? cch : cch + 7; // ensure space for "\\?\UNC" prefix if needed hr = StrAlloc(&sczFullPath, cchFullPath); ExitOnFailure(hr, "Failed to re-allocate more space for full path."); cch = ::GetFullPathNameW(wzPath, cchFullPath, sczFullPath, &wzFileName); if (0 == cch) { ExitWithLastError1(hr, "Failed to get full path for string: %ls", wzPath); } else if (cchFullPath < cch) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); ExitOnRootFailure(hr, "Failed to allocate buffer for full path."); } } if (MAX_PATH < cch) { hr = PathPrefix(&sczFullPath); ExitOnFailure(hr, "Failed to prefix long path after expanding."); } } else { sczFullPath = sczExpandedPath; sczExpandedPath = NULL; } hr = StrAllocString(psczFullPath, sczFullPath? sczFullPath : wzRelativePath, 0); ExitOnFailure(hr, "Failed to copy relative path into full path."); LExit: ReleaseStr(sczFullPath); ReleaseStr(sczExpandedPath); return hr; }
static void test_audioclient(void) { IAudioClient *ac; IUnknown *unk; HRESULT hr; ULONG ref; WAVEFORMATEX *pwfx, *pwfx2; REFERENCE_TIME t1, t2; HANDLE handle; hr = IMMDevice_Activate(dev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, (void**)&ac); ok(hr == S_OK, "Activation failed with %08x\n", hr); if(hr != S_OK) return; handle = CreateEventW(NULL, FALSE, FALSE, NULL); hr = IAudioClient_QueryInterface(ac, &IID_IUnknown, NULL); ok(hr == E_POINTER, "QueryInterface(NULL) returned %08x\n", hr); unk = (void*)(LONG_PTR)0x12345678; hr = IAudioClient_QueryInterface(ac, &IID_NULL, (void**)&unk); ok(hr == E_NOINTERFACE, "QueryInterface(IID_NULL) returned %08x\n", hr); ok(!unk, "QueryInterface(IID_NULL) returned non-null pointer %p\n", unk); hr = IAudioClient_QueryInterface(ac, &IID_IUnknown, (void**)&unk); ok(hr == S_OK, "QueryInterface(IID_IUnknown) returned %08x\n", hr); if (unk) { ref = IUnknown_Release(unk); ok(ref == 1, "Released count is %u\n", ref); } hr = IAudioClient_QueryInterface(ac, &IID_IAudioClient, (void**)&unk); ok(hr == S_OK, "QueryInterface(IID_IAudioClient) returned %08x\n", hr); if (unk) { ref = IUnknown_Release(unk); ok(ref == 1, "Released count is %u\n", ref); } hr = IAudioClient_GetDevicePeriod(ac, NULL, NULL); ok(hr == E_POINTER, "Invalid GetDevicePeriod call returns %08x\n", hr); hr = IAudioClient_GetDevicePeriod(ac, &t1, NULL); ok(hr == S_OK, "Valid GetDevicePeriod call returns %08x\n", hr); hr = IAudioClient_GetDevicePeriod(ac, NULL, &t2); ok(hr == S_OK, "Valid GetDevicePeriod call returns %08x\n", hr); hr = IAudioClient_GetDevicePeriod(ac, &t1, &t2); ok(hr == S_OK, "Valid GetDevicePeriod call returns %08x\n", hr); trace("Returned periods: %u.%05u ms %u.%05u ms\n", (UINT)(t1/10000), (UINT)(t1 % 10000), (UINT)(t2/10000), (UINT)(t2 % 10000)); hr = IAudioClient_GetMixFormat(ac, NULL); ok(hr == E_POINTER, "GetMixFormat returns %08x\n", hr); hr = IAudioClient_GetMixFormat(ac, &pwfx); ok(hr == S_OK, "Valid GetMixFormat returns %08x\n", hr); if (hr == S_OK) { trace("pwfx: %p\n", pwfx); trace("Tag: %04x\n", pwfx->wFormatTag); trace("bits: %u\n", pwfx->wBitsPerSample); trace("chan: %u\n", pwfx->nChannels); trace("rate: %u\n", pwfx->nSamplesPerSec); trace("align: %u\n", pwfx->nBlockAlign); trace("extra: %u\n", pwfx->cbSize); ok(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE, "wFormatTag is %x\n", pwfx->wFormatTag); if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE *pwfxe = (void*)pwfx; trace("Res: %u\n", pwfxe->Samples.wReserved); trace("Mask: %x\n", pwfxe->dwChannelMask); trace("Alg: %s\n", IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)?"PCM": (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)?"FLOAT":"Other")); } hr = IAudioClient_IsFormatSupported(ac, AUDCLNT_SHAREMODE_SHARED, pwfx, &pwfx2); ok(hr == S_OK, "Valid IsFormatSupported(Shared) call returns %08x\n", hr); ok(pwfx2 == NULL, "pwfx2 is non-null\n"); CoTaskMemFree(pwfx2); hr = IAudioClient_IsFormatSupported(ac, AUDCLNT_SHAREMODE_SHARED, NULL, NULL); ok(hr == E_POINTER, "IsFormatSupported(NULL) call returns %08x\n", hr); hr = IAudioClient_IsFormatSupported(ac, AUDCLNT_SHAREMODE_SHARED, pwfx, NULL); ok(hr == E_POINTER, "IsFormatSupported(Shared,NULL) call returns %08x\n", hr); hr = IAudioClient_IsFormatSupported(ac, AUDCLNT_SHAREMODE_EXCLUSIVE, pwfx, NULL); ok(hr == S_OK || hr == AUDCLNT_E_UNSUPPORTED_FORMAT, "IsFormatSupported(Exclusive) call returns %08x\n", hr); hr = IAudioClient_IsFormatSupported(ac, AUDCLNT_SHAREMODE_EXCLUSIVE, pwfx, &pwfx2); ok(hr == S_OK || hr == AUDCLNT_E_UNSUPPORTED_FORMAT, "IsFormatSupported(Exclusive) call returns %08x\n", hr); ok(pwfx2 == NULL, "pwfx2 non-null on exclusive IsFormatSupported\n"); hr = IAudioClient_IsFormatSupported(ac, 0xffffffff, pwfx, NULL); ok(hr == E_INVALIDARG || hr == AUDCLNT_E_UNSUPPORTED_FORMAT, "IsFormatSupported(0xffffffff) call returns %08x\n", hr); } test_uninitialized(ac); hr = IAudioClient_Initialize(ac, 3, 0, 5000000, 0, pwfx, NULL); ok(hr == AUDCLNT_E_NOT_INITIALIZED, "Initialize with invalid sharemode returns %08x\n", hr); hr = IAudioClient_Initialize(ac, AUDCLNT_SHAREMODE_SHARED, 0xffffffff, 5000000, 0, pwfx, NULL); ok(hr == E_INVALIDARG, "Initialize with invalid flags returns %08x\n", hr); /* It seems that if length > 2s or periodicity != 0 the length is ignored and call succeeds * Since we can only initialize successfully once, skip those tests. */ hr = IAudioClient_Initialize(ac, AUDCLNT_SHAREMODE_SHARED, 0, 5000000, 0, NULL, NULL); ok(hr == E_POINTER, "Initialize with null format returns %08x\n", hr); hr = IAudioClient_Initialize(ac, AUDCLNT_SHAREMODE_SHARED, 0, 5000000, 0, pwfx, NULL); ok(hr == S_OK, "Valid Initialize returns %08x\n", hr); if (hr != S_OK) { skip("Cannot initialize %08x, remainder of tests is useless\n", hr); CoTaskMemFree(pwfx); return; } hr = IAudioClient_GetStreamLatency(ac, NULL); ok(hr == E_POINTER, "GetStreamLatency(NULL) call returns %08x\n", hr); hr = IAudioClient_GetStreamLatency(ac, &t1); ok(hr == S_OK, "Valid GetStreamLatency call returns %08x\n", hr); trace("Returned latency: %u.%05u ms\n", (UINT)(t1/10000), (UINT)(t1 % 10000)); hr = IAudioClient_Initialize(ac, AUDCLNT_SHAREMODE_SHARED, 0, 5000000, 0, pwfx, NULL); ok(hr == AUDCLNT_E_ALREADY_INITIALIZED, "Calling Initialize twice returns %08x\n", hr); hr = IAudioClient_SetEventHandle(ac, NULL); ok(hr == E_INVALIDARG, "SetEventHandle(NULL) returns %08x\n", hr); hr = IAudioClient_SetEventHandle(ac, handle); ok(hr == AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED || broken(hr == HRESULT_FROM_WIN32(ERROR_INVALID_NAME)) || broken(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) /* Some 2k8 */ || broken(hr == HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME)) /* Some Vista */ , "SetEventHandle returns %08x\n", hr); hr = IAudioClient_Reset(ac); ok(hr == S_OK, "Reset on a resetted stream returns %08x\n", hr); hr = IAudioClient_Stop(ac); ok(hr == S_FALSE, "Stop on a stopped stream returns %08x\n", hr); hr = IAudioClient_Start(ac); ok(hr == S_OK, "Start on a stopped stream returns %08x\n", hr); IAudioClient_Release(ac); CloseHandle(handle); CoTaskMemFree(pwfx); }
// Returns true only if an env variable can be read successfully to be non-empty. bool pal::getenv(const char_t* name, string_t* recv) { recv->clear(); auto length = ::GetEnvironmentVariableW(name, nullptr, 0); if (length == 0) { auto err = GetLastError(); if (err != ERROR_ENVVAR_NOT_FOUND) { trace::error(_X("Failed to read environment variable [%s], HRESULT: 0x%X"), name, HRESULT_FROM_WIN32(GetLastError())); } return false; } auto buf = new char_t[length]; if (::GetEnvironmentVariableW(name, buf, length) == 0) { trace::error(_X("Failed to read environment variable [%s], HRESULT: 0x%X"), name, HRESULT_FROM_WIN32(GetLastError())); return false; } recv->assign(buf); delete[] buf; return true; }
virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD grfStatFlag) { if (GetFileSizeEx(_hFile, (PLARGE_INTEGER) &pStatstg->cbSize) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; }
HRESULT WINAPI PSStringFromPropertyKey(REFPROPERTYKEY pkey, LPWSTR psz, UINT cch) { static const WCHAR guid_fmtW[] = {'{','%','0','8','X','-','%','0','4','X','-', '%','0','4','X','-','%','0','2','X','%','0','2','X','-', '%','0','2','X','%','0','2','X','%','0','2','X', '%','0','2','X','%','0','2','X','%','0','2','X','}',0}; static const WCHAR pid_fmtW[] = {'%','u',0}; WCHAR pidW[PKEY_PIDSTR_MAX + 1]; LPWSTR p = psz; int len; TRACE("(%p, %p, %u)\n", pkey, psz, cch); if (!psz) return E_POINTER; /* GUIDSTRING_MAX accounts for null terminator, +1 for space character. */ if (cch <= GUIDSTRING_MAX + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); if (!pkey) { psz[0] = '\0'; return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } sprintfW(psz, guid_fmtW, pkey->fmtid.Data1, pkey->fmtid.Data2, pkey->fmtid.Data3, pkey->fmtid.Data4[0], pkey->fmtid.Data4[1], pkey->fmtid.Data4[2], pkey->fmtid.Data4[3], pkey->fmtid.Data4[4], pkey->fmtid.Data4[5], pkey->fmtid.Data4[6], pkey->fmtid.Data4[7]); /* Overwrite the null terminator with the space character. */ p += GUIDSTRING_MAX - 1; *p++ = ' '; cch -= GUIDSTRING_MAX - 1 + 1; len = sprintfW(pidW, pid_fmtW, pkey->pid); if (cch >= len + 1) { strcpyW(p, pidW); return S_OK; } else { WCHAR *ptr = pidW + len - 1; psz[0] = '\0'; *p++ = '\0'; cch--; /* Replicate a quirk of the native implementation where the contents * of the property ID string are written backwards to the output * buffer, skipping the rightmost digit. */ if (cch) { ptr--; while (cch--) *p++ = *ptr--; } return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } }
virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) { BOOL rc = ReadFile(_hFile, pv, cb, pcbRead, NULL); return (rc) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); }
/*********************************************************************** * register_interfaces */ static HRESULT register_interfaces(struct regsvr_interface const *list) { LONG res = ERROR_SUCCESS; HKEY interface_key; res = RegCreateKeyExW(HKEY_CLASSES_ROOT, interface_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &interface_key, NULL); if (res != ERROR_SUCCESS) goto error_return; for (; res == ERROR_SUCCESS && list->iid; ++list) { WCHAR buf[39]; HKEY iid_key; StringFromGUID2(list->iid, buf, 39); res = RegCreateKeyExW(interface_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &iid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_interface_key; if (list->name) { res = RegSetValueExA(iid_key, NULL, 0, REG_SZ, (CONST BYTE*)(list->name), strlen(list->name) + 1); if (res != ERROR_SUCCESS) goto error_close_iid_key; } if (list->base_iid) { res = register_key_guid(iid_key, base_ifa_keyname, list->base_iid); if (res != ERROR_SUCCESS) goto error_close_iid_key; } if (0 <= list->num_methods) { static WCHAR const fmt[3] = { '%', 'd', 0 }; HKEY key; res = RegCreateKeyExW(iid_key, num_methods_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &key, NULL); if (res != ERROR_SUCCESS) goto error_close_iid_key; wsprintfW(buf, fmt, list->num_methods); res = RegSetValueExW(key, NULL, 0, REG_SZ, (CONST BYTE*)buf, (lstrlenW(buf) + 1) * sizeof(WCHAR)); RegCloseKey(key); if (res != ERROR_SUCCESS) goto error_close_iid_key; } if (list->ps_clsid) { res = register_key_guid(iid_key, ps_clsid_keyname, list->ps_clsid); if (res != ERROR_SUCCESS) goto error_close_iid_key; } if (list->ps_clsid32) { res = register_key_guid(iid_key, ps_clsid32_keyname, list->ps_clsid32); if (res != ERROR_SUCCESS) goto error_close_iid_key; } error_close_iid_key: RegCloseKey(iid_key); } error_close_interface_key: RegCloseKey(interface_key); error_return: return res != ERROR_SUCCESS ? HRESULT_FROM_WIN32(res) : S_OK; }
virtual HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) { BOOL rc = WriteFile(_hFile, pv, cb, pcbWritten, NULL); return rc ? S_OK : HRESULT_FROM_WIN32(GetLastError()); }
HRESULT DSoundRender_create(IUnknown * pUnkOuter, LPVOID * ppv) { HRESULT hr; DSoundRenderImpl * pDSoundRender; TRACE("(%p, %p)\n", pUnkOuter, ppv); *ppv = NULL; if (pUnkOuter) return CLASS_E_NOAGGREGATION; pDSoundRender = CoTaskMemAlloc(sizeof(DSoundRenderImpl)); if (!pDSoundRender) return E_OUTOFMEMORY; ZeroMemory(pDSoundRender, sizeof(DSoundRenderImpl)); hr = BaseRenderer_Init(&pDSoundRender->renderer, &DSoundRender_Vtbl, (IUnknown*)pDSoundRender, &CLSID_DSoundRender, (DWORD_PTR)(__FILE__ ": DSoundRenderImpl.csFilter"), &BaseFuncTable); BasicAudio_Init(&pDSoundRender->basicAudio,&IBasicAudio_Vtbl); pDSoundRender->IReferenceClock_iface.lpVtbl = &IReferenceClock_Vtbl; pDSoundRender->IAMDirectSound_iface.lpVtbl = &IAMDirectSound_Vtbl; pDSoundRender->IAMFilterMiscFlags_iface.lpVtbl = &IAMFilterMiscFlags_Vtbl; if (SUCCEEDED(hr)) { hr = DirectSoundCreate8(NULL, &pDSoundRender->dsound, NULL); if (FAILED(hr)) ERR("Cannot create Direct Sound object (%x)\n", hr); else hr = IDirectSound_SetCooperativeLevel(pDSoundRender->dsound, GetDesktopWindow(), DSSCL_PRIORITY); if (SUCCEEDED(hr)) { IDirectSoundBuffer *buf; DSBUFFERDESC buf_desc; memset(&buf_desc,0,sizeof(DSBUFFERDESC)); buf_desc.dwSize = sizeof(DSBUFFERDESC); buf_desc.dwFlags = DSBCAPS_PRIMARYBUFFER; hr = IDirectSound_CreateSoundBuffer(pDSoundRender->dsound, &buf_desc, &buf, NULL); if (SUCCEEDED(hr)) { IDirectSoundBuffer_Play(buf, 0, 0, DSBPLAY_LOOPING); IDirectSoundBuffer_Release(buf); } hr = S_OK; } } if (SUCCEEDED(hr)) { pDSoundRender->blocked = CreateEventW(NULL, TRUE, TRUE, NULL); if (!pDSoundRender->blocked || FAILED(hr)) { IUnknown_Release((IUnknown *)pDSoundRender); return HRESULT_FROM_WIN32(GetLastError()); } *ppv = pDSoundRender; } else { BaseRendererImpl_Release(&pDSoundRender->renderer.filter.IBaseFilter_iface); CoTaskMemFree(pDSoundRender); } return hr; }
////////////////////////////////////////////////////////////////////////////// // ReceiveBinary - Creates a local file in the files-directory // from the inbound attachment ////////////////////////////////////////////////////////////////////////////// HRESULT CGetFileAsyncCallback::ReceiveBinary( IWSDAttachment* pAttachment, LPCWSTR pszLocalFileName) { HRESULT hr = S_OK; IWSDInboundAttachment* pStream = NULL; BYTE buffer[8192]; ULONG cbBytesRead = 0; ULONG cbBytesLeft = 0; DWORD cbBytesWritten = 0; ULONG cbBytesTotal = 0; HANDLE hFile = NULL; DWORD dwErr = 0; // Validate parameters if( NULL == pAttachment ) { return E_INVALIDARG; } if( NULL == pszLocalFileName ) { return E_INVALIDARG; } if( 0 == wcscmp( pszLocalFileName, L"" ) ) { return E_INVALIDARG; } // Make sure this attachment is an inbound attachment, and get that // interface hr = pAttachment->QueryInterface( __uuidof(IWSDInboundAttachment), (void**)&pStream); // Create a file to write attachment data into if( S_OK == hr ) { _cwprintf(L" Creating local file %s... ", pszLocalFileName); hFile = ::CreateFileW( pszLocalFileName, FILE_WRITE_DATA, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if ( INVALID_HANDLE_VALUE == hFile ) { hFile = NULL; dwErr = ::GetLastError(); hr = HRESULT_FROM_WIN32( dwErr ); } print_result( hr ); } // Read from the inbound attachment and write to file until finished while( S_OK == hr ) { _cwprintf(L" Reading attachment data... "); hr = pStream->Read( buffer, sizeof(buffer), &cbBytesRead ); cbBytesLeft = cbBytesRead; // pStream->Read will return S_FALSE on the last read if the buffer // was not completely filled. Hang onto the S_FALSE until the // end of this loop while( (S_OK == hr || S_FALSE == hr) && 0 < cbBytesLeft ) { if( 0 == WriteFile( hFile, buffer + (cbBytesRead - cbBytesLeft), cbBytesLeft, &cbBytesWritten, NULL ) ) { dwErr = ::GetLastError(); hr = HRESULT_FROM_WIN32( dwErr ); } if( S_OK == hr || S_FALSE == hr ) { cbBytesLeft -= cbBytesWritten; } } print_result( hr ); cbBytesTotal += (cbBytesRead - cbBytesLeft); // If that was the last read, reset hr and bail out if( S_FALSE == hr ) { hr = S_OK; break; } } // Print success message if we got the file without any problems if( S_OK == hr ) { _cwprintf( L"%s recieved (%d bytes).\r\n", pszLocalFileName, cbBytesTotal ); } else { _cwprintf( L"Error receiving %s. Only recieved (%d bytes).\r\n", pszLocalFileName, cbBytesTotal ); } // cleanup if( NULL != hFile ) { ::CloseHandle( hFile ); hFile = NULL; } if( NULL != pStream ) { pStream->Release(); pStream = NULL; } return hr; }
void OnStartRecord(HWND hwnd) { IFileSaveDialog *pFileSave = NULL; IShellItem *pItem = NULL; PWSTR pszFileName = NULL; HRESULT hr = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFileSave)); if (FAILED(hr)) { goto done; } hr = pFileSave->SetTitle(L"Select File Name"); if (FAILED(hr)) { goto done; } hr = pFileSave->SetFileName(L"MyVideo.mp4"); if (FAILED(hr)) { goto done; } hr = pFileSave->SetDefaultExtension(L"mp4"); if (FAILED(hr)) { goto done; } const COMDLG_FILTERSPEC rgSpec[] = { { L"MP4 (H.264/AAC)", L"*.mp4" }, { L"Windows Media Video", L"*.wmv" }, { L"All Files", L"*.*" }, }; hr = pFileSave->SetFileTypes(ARRAYSIZE(rgSpec), rgSpec); if (FAILED(hr)) { goto done; } hr = pFileSave->Show(hwnd); if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { hr = S_OK; // The user canceled the dialog. goto done; } if (FAILED(hr)) { goto done; } hr = pFileSave->GetResult(&pItem); if (FAILED(hr)) { goto done; } hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFileName); if (FAILED(hr)) { goto done; } hr = g_pEngine->StartRecord(pszFileName); if (FAILED(hr)) { goto done; } done: CoTaskMemFree(pszFileName); SafeRelease(&pItem); SafeRelease(&pFileSave); if (FAILED(hr)) { ShowError(hwnd, IDS_ERR_RECORD, hr); } UpdateUI(hwnd); }
static HRESULT WINAPI ComponentFactory_CreateBitmapFromHICON(IWICComponentFactory *iface, HICON hicon, IWICBitmap **bitmap) { IWICBitmapLock *lock; ICONINFO info; BITMAP bm; int width, height, x, y; UINT stride, size; BYTE *buffer; DWORD *bits; BITMAPINFO bi; HDC hdc; BOOL has_alpha; HRESULT hr; TRACE("(%p,%p,%p)\n", iface, hicon, bitmap); if (!bitmap) return E_INVALIDARG; if (!GetIconInfo(hicon, &info)) return HRESULT_FROM_WIN32(GetLastError()); GetObjectW(info.hbmColor ? info.hbmColor : info.hbmMask, sizeof(bm), &bm); width = bm.bmWidth; height = info.hbmColor ? abs(bm.bmHeight) : abs(bm.bmHeight) / 2; stride = width * 4; size = stride * height; hr = BitmapImpl_Create(width, height, stride, size, NULL, &GUID_WICPixelFormat32bppBGRA, WICBitmapCacheOnLoad, bitmap); if (hr != S_OK) goto failed; hr = IWICBitmap_Lock(*bitmap, NULL, WICBitmapLockWrite, &lock); if (hr != S_OK) { IWICBitmap_Release(*bitmap); goto failed; } IWICBitmapLock_GetDataPointer(lock, &size, &buffer); hdc = CreateCompatibleDC(0); memset(&bi, 0, sizeof(bi)); bi.bmiHeader.biSize = sizeof(bi.bmiHeader); bi.bmiHeader.biWidth = width; bi.bmiHeader.biHeight = info.hbmColor ? -height: -height * 2; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; has_alpha = FALSE; if (info.hbmColor) { GetDIBits(hdc, info.hbmColor, 0, height, buffer, &bi, DIB_RGB_COLORS); if (bm.bmBitsPixel == 32) { /* If any pixel has a non-zero alpha, ignore hbmMask */ bits = (DWORD *)buffer; for (x = 0; x < width && !has_alpha; x++, bits++) { for (y = 0; y < height; y++) { if (*bits & 0xff000000) { has_alpha = TRUE; break; } } } } } else GetDIBits(hdc, info.hbmMask, 0, height, buffer, &bi, DIB_RGB_COLORS); if (!has_alpha) { DWORD *rgba; if (info.hbmMask) { BYTE *mask; mask = HeapAlloc(GetProcessHeap(), 0, size); if (!mask) { IWICBitmapLock_Release(lock); IWICBitmap_Release(*bitmap); DeleteDC(hdc); hr = E_OUTOFMEMORY; goto failed; } /* read alpha data from the mask */ GetDIBits(hdc, info.hbmMask, info.hbmColor ? 0 : height, height, mask, &bi, DIB_RGB_COLORS); for (y = 0; y < height; y++) { rgba = (DWORD *)(buffer + y * stride); bits = (DWORD *)(mask + y * stride); for (x = 0; x < width; x++, rgba++, bits++) { if (*bits) *rgba = 0; else *rgba |= 0xff000000; } } HeapFree(GetProcessHeap(), 0, mask); } else { /* set constant alpha of 255 */ for (y = 0; y < height; y++) { rgba = (DWORD *)(buffer + y * stride); for (x = 0; x < width; x++, rgba++) *rgba |= 0xff000000; } } } IWICBitmapLock_Release(lock); DeleteDC(hdc); failed: DeleteObject(info.hbmColor); DeleteObject(info.hbmMask); return hr; }
/***************************************************************************** wmain *****************************************************************************/ DWORD __cdecl wmain( int argc, LPWSTR argv[] ) { HRESULT hr = S_OK; int i = 0; BOOL fPeerTrust = FALSE; DWORD dwChainFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; LPCWSTR wsCertFile = NULL; LPCWSTR wsStoreFile = NULL; PCCERT_CONTEXT pCert = NULL; HCERTSTORE hStore = NULL; HCERTCHAINENGINE hChainEngine = NULL; PCCERT_CHAIN_CONTEXT pChainContext = NULL; CERT_ENHKEY_USAGE EnhkeyUsage = {0}; CERT_USAGE_MATCH CertUsage = {0}; CERT_CHAIN_PARA ChainPara = {0}; CERT_CHAIN_POLICY_PARA ChainPolicy = {0}; CERT_CHAIN_POLICY_STATUS PolicyStatus = {0}; CERT_CHAIN_ENGINE_CONFIG EngineConfig = {0}; //--------------------------------------------------------- // Initialize data structures for chain building. EnhkeyUsage.cUsageIdentifier = 0; EnhkeyUsage.rgpszUsageIdentifier=NULL; CertUsage.dwType = USAGE_MATCH_TYPE_AND; CertUsage.Usage = EnhkeyUsage; ChainPara.cbSize = sizeof(ChainPara); ChainPara.RequestedUsage=CertUsage; ChainPolicy.cbSize = sizeof(ChainPolicy); PolicyStatus.cbSize = sizeof(PolicyStatus); EngineConfig.cbSize = sizeof(EngineConfig); EngineConfig.dwUrlRetrievalTimeout = 0; // // options // for( i=1; i<argc; i++ ) { if ( lstrcmpW (argv[i], L"/?") == 0 || lstrcmpW (argv[i], L"-?") == 0 ) { Usage(argv[0]); goto CleanUp; } if( *argv[i] != L'-' ) break; if ( lstrcmpW (argv[i], L"-fc") == 0 ) { if( i+1 >= argc ) { goto InvalidCommandLine; } dwChainFlags = (DWORD)wcstoul( argv[++i], NULL, 0 ); } else if ( lstrcmpW (argv[i], L"-fe") == 0 ) { if( i+1 >= argc ) { goto InvalidCommandLine; } EngineConfig.dwFlags = (DWORD)wcstoul( argv[++i], NULL, 0 ); } else if ( lstrcmpW (argv[i], L"-p") == 0 ) { fPeerTrust = TRUE; } else { goto InvalidCommandLine; } } if( i >= argc ) { goto InvalidCommandLine; } wsStoreFile = argv[i++]; if( i < argc ) { wsCertFile = argv[i]; } hStore = CertOpenStore( CERT_STORE_PROV_FILENAME_W, X509_ASN_ENCODING, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, wsStoreFile ); if( NULL == hStore ) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } if( NULL != wsCertFile && 0 != *wsCertFile ) { if( !CryptQueryObject( CERT_QUERY_OBJECT_FILE, wsCertFile, CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_SERIALIZED_CERT , CERT_QUERY_FORMAT_FLAG_ALL, 0, // dwFlags, 0, // pdwMsgAndCertEncodingType, 0, // pdwContentType, 0, // pdwFormatType, 0, // phCertStore, 0, // phMsg, (const void**)&pCert )) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } } else { pCert = CertFindCertificateInStore( hStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, NULL ); if( NULL == pCert ) { hr = CRYPT_E_NOT_FOUND; goto CleanUp; } } if( fPeerTrust ) { EngineConfig.hExclusiveTrustedPeople = hStore; // Exclusive peer trust dwChainFlags |= CERT_CHAIN_ENABLE_PEER_TRUST; } else { EngineConfig.hExclusiveRoot = hStore; // Exclusive root } //--------------------------------------------------------- // Create chain engine. if( !CertCreateCertificateChainEngine( &EngineConfig, &hChainEngine )) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } //------------------------------------------------------------------- // Build a chain using CertGetCertificateChain if( !CertGetCertificateChain( hChainEngine, pCert, // pointer to the end certificate NULL, // use the default time NULL, // search no additional stores &ChainPara, // use AND logic and enhanced key usage // as indicated in the ChainPara // data structure dwChainFlags, NULL, // currently reserved &pChainContext )) // return a pointer to the chain created { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } //--------------------------------------------------------------- // Verify that the chain complies with policy if( !CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_BASE, // use the base policy pChainContext, // pointer to the chain &ChainPolicy, &PolicyStatus )) // return a pointer to the policy status { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } if( PolicyStatus.dwError != S_OK ) { hr = PolicyStatus.dwError; // Instruction: If the PolicyStatus.dwError is CRYPT_E_NO_REVOCATION_CHECK or CRYPT_E_REVOCATION_OFFLINE, it indicates errors in obtaining // revocation information. These can be ignored since the retrieval of revocation information depends on network availability goto CleanUp; } wprintf( L"CertVerifyCertificateChainPolicy succeeded.\n" ); hr = S_OK; // // END // goto CleanUp; // // Invalid Command Line // InvalidCommandLine: if( i < argc ) { wprintf( L"Invalid command line '%s'\n", argv[i] ); } else Usage(argv[0]); hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); CleanUp: if( FAILED(hr) ) { ReportError( NULL, hr ); } if( NULL != pChainContext ) { CertFreeCertificateChain( pChainContext ); } if( NULL != hChainEngine ) { CertFreeCertificateChainEngine( hChainEngine ); } if( NULL != pCert ) { CertFreeCertificateContext( pCert ); } if( NULL != hStore ) { CertCloseStore( hStore, 0 ); } return (DWORD)hr; } // end main
int wxDirDialog::ShowIFileDialog(WXHWND owner) { HRESULT hr; wxCOMPtr<IFileDialog> fileDialog; hr = ::CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, wxIID_PPV_ARGS(IFileDialog, &fileDialog)); if ( FAILED(hr) ) { wxLogApiError(wxS("CoCreateInstance(CLSID_FileOpenDialog)"), hr); return wxID_NONE; } // allow user to select only a file system folder hr = fileDialog->SetOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM); if ( FAILED(hr) ) { wxLogApiError(wxS("IFileDialog::SetOptions"), hr); return wxID_NONE; } hr = fileDialog->SetTitle(m_message.wc_str()); if ( FAILED(hr) ) { // This error is not serious, let's just log it and continue even // without the title set. wxLogApiError(wxS("IFileDialog::SetTitle"), hr); } // set the initial path if ( !m_path.empty() ) { // We need to link SHCreateItemFromParsingName() dynamically as it's // not available on pre-Vista systems. typedef HRESULT (WINAPI *SHCreateItemFromParsingName_t)(PCWSTR, IBindCtx*, REFIID, void**); SHCreateItemFromParsingName_t pfnSHCreateItemFromParsingName = NULL; wxDynamicLibrary dllShell32; if ( dllShell32.Load(wxS("shell32.dll"), wxDL_VERBATIM | wxDL_QUIET) ) { wxDL_INIT_FUNC(pfn, SHCreateItemFromParsingName, dllShell32); } if ( !pfnSHCreateItemFromParsingName ) { wxLogLastError(wxS("SHCreateItemFromParsingName() not found")); return wxID_NONE; } wxCOMPtr<IShellItem> folder; hr = pfnSHCreateItemFromParsingName(m_path.wc_str(), NULL, wxIID_PPV_ARGS(IShellItem, &folder)); // Failing to parse the folder name is not really an error, we'll just // ignore the initial directory in this case, but we should still show // the dialog. if ( FAILED(hr) ) { if ( hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ) { wxLogApiError(wxS("SHCreateItemFromParsingName"), hr); return wxID_NONE; } } else // The folder was parsed correctly. { hr = fileDialog->SetFolder(folder); if ( FAILED(hr) ) { wxLogApiError(wxS("IFileDialog::SetFolder"), hr); return wxID_NONE; } } } wxString path; hr = fileDialog->Show(owner); if ( SUCCEEDED(hr) ) { wxCOMPtr<IShellItem> folder; hr = fileDialog->GetResult(&folder); if ( SUCCEEDED(hr) ) { LPOLESTR pathOLE = NULL; hr = folder->GetDisplayName(SIGDN_FILESYSPATH, &pathOLE); if ( SUCCEEDED(hr) ) { path = pathOLE; CoTaskMemFree(pathOLE); } else { wxLogApiError(wxS("IShellItem::GetDisplayName"), hr); } } else { wxLogApiError(wxS("IFileDialog::GetResult"), hr); } } else if ( hr == HRESULT_FROM_WIN32(ERROR_CANCELLED) ) { return wxID_CANCEL; // the user cancelled the dialog } else { wxLogApiError(wxS("IFileDialog::Show"), hr); } if ( path.empty() ) { // the user didn't cancel the dialog and yet the path is empty // it means there was an error, already logged by wxLogApiError() // now report the error to the user and return wxLogSysError(_("Couldn't obtain folder name"), hr); return wxID_CANCEL; } m_path = path; return wxID_OK; }
HRESULT InitShellServices(HDPA * phdpa) { IOleCommandTarget * pOct; HKEY hkey; CLSID clsid; WCHAR name[MAX_PATH]; WCHAR value[MAX_PATH]; DWORD type; LONG ret; HDPA hdpa; HRESULT hr = S_OK; int count = 0; *phdpa = NULL; TRACE("Enumerating Shell Service Ojbect GUIDs...\n"); if (RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ShellServiceObjectDelayLoad", &hkey)) { ERR("RegOpenKey failed.\n"); return HRESULT_FROM_WIN32(GetLastError()); } hdpa = DPA_Create(5); /* Enumerate */ do { DWORD name_len = MAX_PATH; DWORD value_len = sizeof(value); /* byte count! */ ret = RegEnumValueW(hkey, count, name, &name_len, 0, &type, (LPBYTE) &value, &value_len); if (ret) break; if (type != REG_SZ) { WARN("Value type was not REG_SZ.\n"); continue; } hr = CLSIDFromString(value, &clsid); if (FAILED_UNEXPECTEDLY(hr)) { ERR("CLSIDFromString failed %08x.\n", hr); goto cleanup; } hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARG(IOleCommandTarget, &pOct)); if (FAILED_UNEXPECTEDLY(hr)) { ERR("CoCreateInstance failed %08x.\n", hr); goto cleanup; } DPA_AppendPtr(hdpa, pOct); count++; } while (1); if (ret != ERROR_NO_MORE_ITEMS) { ERR("RegEnumValueW failed %08x.\n", ret); hr = HRESULT_FROM_WIN32(GetLastError()); goto cleanup; } RegCloseKey(hkey); /* Initialize */ DPA_EnumCallback(hdpa, InitializeAllCallback, &hr); if (FAILED_UNEXPECTEDLY(hr)) goto cleanup; *phdpa = hdpa; return count > 0 ? S_OK : S_FALSE; cleanup: *phdpa = NULL; ShutdownShellServices(hdpa); return hr; }
HRESULT HealthBloodPressureServiceContent::InitializeContent( _In_ IWDFDevice* pDevice, _Inout_ DWORD *pdwLastObjectID, _In_ HANDLE hDeviceHandle, _In_ BthLEDevice * pBthLEDevice) { HRESULT hr = S_OK; // // Service // PBTH_LE_GATT_SERVICE services = NULL; USHORT numServices = 0; USHORT numServicesActual = 0; USHORT serviceIndex = 0; BOOLEAN isFoundService = FALSE; // // Characteristic // PBTH_LE_GATT_CHARACTERISTIC characteristics = NULL; USHORT numChar = 0; USHORT numCharsActual = 0; BOOLEAN isCharacteristicFound = FALSE; USHORT foundCharacteristicIndex = 0; if (pDevice == NULL || pdwLastObjectID == NULL || hDeviceHandle == NULL) { hr = E_POINTER; CHECK_HR(hr, "Cannot have NULL parameter"); } // // Save the WDF device and client context map for async events // if (SUCCEEDED(hr)) { m_pDevice = pDevice; m_pBthLEDevice = pBthLEDevice; } // // Get the WpdSerializer to use to Object Change events // if (SUCCEEDED(hr)) { hr = CoCreateInstance(CLSID_WpdSerializer, NULL, CLSCTX_INPROC_SERVER, IID_IWpdSerializer, (VOID**)&m_pWpdSerializer); CHECK_HR(hr, "Failed to CoCreate CLSID_WpdSerializer"); } // // Get the number of services // if (SUCCEEDED(hr)) { hr = BluetoothGATTGetServices( hDeviceHandle, 0, NULL, &numServices, BLUETOOTH_GATT_FLAG_NONE); if (HRESULT_FROM_WIN32(ERROR_MORE_DATA) == hr) { hr = S_OK; } else { CHECK_HR(hr, "Failed to get the service count - changing to E_FAIL"); hr = E_FAIL; } } if (SUCCEEDED(hr)) { services = new BTH_LE_GATT_SERVICE[numServices]; if (NULL == services) { hr = E_OUTOFMEMORY; } CHECK_HR(hr, "Failed to allocate the service buffer"); } if (SUCCEEDED(hr)) { // // Get the services // hr = BluetoothGATTGetServices( hDeviceHandle, numServices, services, &numServicesActual, BLUETOOTH_GATT_FLAG_NONE); CHECK_HR(hr, "Failed to get the services"); } if (SUCCEEDED(hr)) { // // Double check to confirm that the number of services that are returned // are what we have expected, just in case if the cache has changed due // to things like service change events. // if (numServices != numServicesActual) { // The returned number of services do not match what we have // originally. hr = E_FAIL; } CHECK_HR(hr, "The service count doesn't match the returned services"); } if (SUCCEEDED(hr)) { // // Find the service in the list // for(USHORT i = 0; i < numServices; i++) { if (IsHealthBloodPressureServiceUuid(services[i].ServiceUuid)) { isFoundService = TRUE; serviceIndex = i; break; } } if (FALSE == isFoundService) { hr = E_FAIL; } CHECK_HR(hr, "The HealthBloodPressure Service was not found"); } if (SUCCEEDED(hr)) { // // Find the blood pressure measurement characteristic // hr = BluetoothGATTGetCharacteristics( hDeviceHandle, &services[serviceIndex], 0, NULL, &numChar, BLUETOOTH_GATT_FLAG_NONE); if (HRESULT_FROM_WIN32(ERROR_MORE_DATA) == hr) { hr = S_OK; } else { CHECK_HR(hr, "Failed to get the Characteristic count - changing to E_FAIL"); hr = E_FAIL; } } if (SUCCEEDED(hr)) { characteristics= new BTH_LE_GATT_CHARACTERISTIC[numChar]; if (NULL == characteristics) { hr = E_OUTOFMEMORY; } CHECK_HR(hr, "Failed to allocate the Characteristic buffer"); } if (SUCCEEDED(hr)) { hr = BluetoothGATTGetCharacteristics( hDeviceHandle, &services[serviceIndex], numChar, characteristics, &numCharsActual, BLUETOOTH_GATT_FLAG_NONE); CHECK_HR(hr, "Failed to get the Characteristics"); } if (SUCCEEDED(hr)) { // // Double check to confirm that the number of characteristics that are // returned are what we have expected,. // if (numChar != numCharsActual) { // The returned number of characteristics do not match what we have // originally. hr = E_FAIL; } CHECK_HR(hr, "Number of Characteristics do not match"); } if (SUCCEEDED(hr)) { for (USHORT i = 0; i < numChar; i++) { if (IsBloodPressureMeasurementCharacteristic(characteristics[i].CharacteristicUuid)) { isCharacteristicFound = TRUE; foundCharacteristicIndex = i; break; } } if (FALSE == isCharacteristicFound) { hr = E_FAIL; } CHECK_HR(hr, "BloodPressureMeasurement characteristic not found"); } if (SUCCEEDED(hr)) { // // Cache the characteristic to differ reading the value when the client requests it (client polling) // CopyMemory(&m_BloodPressureMeasurementCharacteristic, &characteristics[foundCharacteristicIndex], sizeof(m_BloodPressureMeasurementCharacteristic)); // // Setting the member DeviceHandle for use by SetCCCD // m_hDeviceHandle = hDeviceHandle; hr = SetCCCD(); CHECK_HR(hr, "Setting the CCCD on Device Content initialization failed"); if (SUCCEEDED(hr)) { // // Setting a member flag to ensure we don't try to set the CCCD more than once // This is a performance optimization that avoids a cache query to get the current CCCD value // and also avoids resetting the CCCD (over the air - with the biggest performance hit) // CComCritSecLock<CComAutoCriticalSection> Lock(m_CCCDSetCS); m_bCCCDSet = TRUE; } // // This only needs to be set once, so ignoring errors in the event the device is not connectable (ie: reboot) // hr = S_OK; } // // Cleanup // if (NULL != services) { delete [] services; } if (NULL != characteristics) { delete [] characteristics; } return hr; }