net_util.cc 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/winhttp/net_util.h"
  5. #include <vector>
  6. namespace winhttp {
  7. HRESULT HRESULTFromLastError() {
  8. const auto error_code = ::GetLastError();
  9. return (error_code != NO_ERROR) ? HRESULT_FROM_WIN32(error_code) : E_FAIL;
  10. }
  11. HRESULT QueryHeadersString(HINTERNET request_handle,
  12. uint32_t info_level,
  13. const wchar_t* name,
  14. std::wstring* value) {
  15. DWORD num_bytes = 0;
  16. ::WinHttpQueryHeaders(request_handle, info_level, name,
  17. WINHTTP_NO_OUTPUT_BUFFER, &num_bytes,
  18. WINHTTP_NO_HEADER_INDEX);
  19. auto hr = HRESULTFromLastError();
  20. if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
  21. return hr;
  22. std::vector<wchar_t> buffer(num_bytes / sizeof(wchar_t));
  23. if (!::WinHttpQueryHeaders(request_handle, info_level, name, &buffer.front(),
  24. &num_bytes, WINHTTP_NO_HEADER_INDEX)) {
  25. return HRESULTFromLastError();
  26. }
  27. DCHECK_EQ(0u, num_bytes % sizeof(wchar_t));
  28. buffer.resize(num_bytes / sizeof(wchar_t));
  29. value->assign(buffer.begin(), buffer.end());
  30. return S_OK;
  31. }
  32. HRESULT QueryHeadersInt(HINTERNET request_handle,
  33. uint32_t info_level,
  34. const wchar_t* name,
  35. int* value) {
  36. info_level |= WINHTTP_QUERY_FLAG_NUMBER;
  37. DWORD num_bytes = sizeof(*value);
  38. if (!::WinHttpQueryHeaders(request_handle, info_level, name, value,
  39. &num_bytes, WINHTTP_NO_HEADER_INDEX)) {
  40. return HRESULTFromLastError();
  41. }
  42. return S_OK;
  43. }
  44. } // namespace winhttp