win: Add implementation of HTTPTransport based on WinHTTP

(There's also https://codereview.chromium.org/854363006/ based on
WinInet, I'm still a little uncertain which is preferable here.)

R=cpu@chromium.org, mark@chromium.org, rsesek@chromium.org, ananta@chromium.org
BUG=crashpad:1

Review URL: https://codereview.chromium.org/852213004
This commit is contained in:
Scott Graham 2015-01-26 13:31:35 -08:00
parent ee98449755
commit 7c9bd944ae
4 changed files with 241 additions and 1 deletions

View File

@ -15,10 +15,12 @@
#include "util/net/http_transport.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/stringprintf.h"
@ -50,7 +52,17 @@ class HTTPTransportTestFixture : public MultiprocessExec {
request_validator_(request_validator) {
// TODO(rsesek): Use a more robust mechanism to locate testdata
// <https://code.google.com/p/crashpad/issues/detail?id=4>.
#if defined(OS_POSIX)
SetChildCommand("util/net/http_transport_test_server.py", nullptr);
#elif defined(OS_WIN)
// Explicitly invoke a shell and python so that python can be found in the
// path, and run the test script.
std::vector<std::string> args;
args.push_back("/c");
args.push_back("python");
args.push_back("util/net/http_transport_test_server.py");
SetChildCommand(getenv("COMSPEC"), &args);
#endif // OS_POSIX
}
const HTTPHeaders& headers() { return headers_; }
@ -234,7 +246,7 @@ TEST(HTTPTransport, UnchunkedPlainText) {
HTTPHeaders headers;
headers[kContentType] = kTextPlain;
headers[kContentLength] = base::StringPrintf("%zu", strlen(kTextBody));
headers[kContentLength] = base::StringPrintf("%" PRIuS, strlen(kTextBody));
HTTPTransportTestFixture test(headers, body_stream.Pass(), 200,
&UnchunkedPlainText);

View File

@ -77,6 +77,8 @@ class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
body = self.rfile.read(length)
self.send_response(self.response_code)
self.end_headers()
writer.write(body)
writer.flush()
@ -118,6 +120,10 @@ class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def Main():
if sys.platform == 'win32':
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
# Start the server.
server = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), RequestHandler)

View File

@ -0,0 +1,214 @@
// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/net/http_transport.h"
#include <windows.h>
#include <winhttp.h>
#include "base/logging.h"
#include "base/scoped_generic.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "util/net/http_body.h"
#include "package.h"
namespace crashpad {
namespace {
// PLOG doesn't work for messages from WinHTTP, so we need to use
// FORMAT_MESSAGE_FROM_HMODULE + the dll name manually here.
void LogErrorWinHttpMessage(const char* extra) {
DWORD error_code = GetLastError();
char msgbuf[256];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_HMODULE;
DWORD len = FormatMessageA(flags,
GetModuleHandle(L"winhttp.dll"),
error_code,
0,
msgbuf,
arraysize(msgbuf),
NULL);
if (len) {
LOG(ERROR) << extra << ": " << msgbuf
<< base::StringPrintf(" (0x%X)", error_code);
} else {
LOG(ERROR) << base::StringPrintf(
"Error (0x%X) while retrieving error. (0x%X)",
GetLastError(),
error_code);
}
}
struct ScopedHINTERNETTraits {
static HINTERNET InvalidValue() {
return nullptr;
}
static void Free(HINTERNET handle) {
if (handle) {
if (!WinHttpCloseHandle(handle)) {
LogErrorWinHttpMessage("WinHttpCloseHandle");
}
}
}
};
using ScopedHINTERNET = base::ScopedGeneric<HINTERNET, ScopedHINTERNETTraits>;
class HTTPTransportWin final : public HTTPTransport {
public:
HTTPTransportWin();
~HTTPTransportWin() override;
bool ExecuteSynchronously() override;
private:
DISALLOW_COPY_AND_ASSIGN(HTTPTransportWin);
};
HTTPTransportWin::HTTPTransportWin() : HTTPTransport() {
}
HTTPTransportWin::~HTTPTransportWin() {
}
bool HTTPTransportWin::ExecuteSynchronously() {
ScopedHINTERNET session(
WinHttpOpen(base::UTF8ToUTF16(PACKAGE_NAME "/" PACKAGE_VERSION).c_str(),
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
0));
if (!session.get()) {
LogErrorWinHttpMessage("WinHttpOpen");
return false;
}
URL_COMPONENTS url_components = {0};
url_components.dwStructSize = sizeof(URL_COMPONENTS);
url_components.dwHostNameLength = 1;
url_components.dwUrlPathLength = 1;
url_components.dwExtraInfoLength = 1;
std::wstring url_wide(base::UTF8ToUTF16(url()));
if (!WinHttpCrackUrl(
url_wide.c_str(), 0, ICU_REJECT_USERPWD, &url_components)) {
LogErrorWinHttpMessage("WinHttpCrackUrl");
return false;
}
std::wstring host_name(url_components.lpszHostName,
url_components.dwHostNameLength);
std::wstring url_path(url_components.lpszUrlPath,
url_components.dwUrlPathLength);
std::wstring extra_info(url_components.lpszExtraInfo,
url_components.dwExtraInfoLength);
ScopedHINTERNET connect(WinHttpConnect(
session.get(), host_name.c_str(), url_components.nPort, 0));
if (!connect.get()) {
LogErrorWinHttpMessage("WinHttpConnect");
return false;
}
ScopedHINTERNET request(
WinHttpOpenRequest(connect.get(),
base::UTF8ToUTF16(method()).c_str(),
url_path.c_str(),
nullptr,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
0));
if (!request.get()) {
LogErrorWinHttpMessage("WinHttpOpenRequest");
return false;
}
// Add headers to the request.
for (const auto& pair : headers()) {
std::wstring header_string =
base::UTF8ToUTF16(pair.first) + L": " + base::UTF8ToUTF16(pair.second);
if (!WinHttpAddRequestHeaders(request.get(),
header_string.c_str(),
header_string.size(),
WINHTTP_ADDREQ_FLAG_ADD)) {
LogErrorWinHttpMessage("WinHttpAddRequestHeaders");
return false;
}
}
// We need the Content-Length up front, so buffer in memory. We should modify
// the interface to not require this, and then use WinHttpWriteData after
// WinHttpSendRequest.
std::vector<uint8_t> post_data;
// Write the body of a POST if any.
for (;;) {
uint8_t buffer[4096];
ssize_t bytes_to_write =
body_stream()->GetBytesBuffer(buffer, sizeof(buffer));
if (bytes_to_write == 0)
break;
post_data.insert(post_data.end(), buffer, buffer + bytes_to_write);
}
if (!WinHttpSendRequest(request.get(),
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
&post_data[0],
post_data.size(),
post_data.size(),
0)) {
LogErrorWinHttpMessage("WinHttpSendRequest");
return false;
}
if (!WinHttpReceiveResponse(request.get(), nullptr)) {
LogErrorWinHttpMessage("WinHttpReceiveResponse");
return false;
}
DWORD status_code = 0;
DWORD sizeof_status_code = sizeof(status_code);
if (!WinHttpQueryHeaders(
request.get(),
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&status_code,
&sizeof_status_code,
WINHTTP_NO_HEADER_INDEX)) {
LogErrorWinHttpMessage("WinHttpQueryHeaders");
return false;
}
if (status_code != 200) {
LOG(ERROR) << base::StringPrintf("HTTP status %d", status_code);
return false;
}
// TODO(scottmg): Retrieve body of response if necessary with
// WinHttpQueryDataAvailable and WinHttpReadData.
return true;
}
} // namespace
// static
scoped_ptr<HTTPTransport> HTTPTransport::Create() {
return scoped_ptr<HTTPTransportWin>(new HTTPTransportWin);
}
} // namespace crashpad

View File

@ -97,6 +97,7 @@
'net/http_transport.cc',
'net/http_transport.h',
'net/http_transport_mac.mm',
'net/http_transport_win.cc',
'numeric/checked_range.h',
'numeric/in_range_cast.h',
'numeric/int128.h',
@ -186,6 +187,13 @@
],
},
}],
['OS=="win"', {
'link_settings': {
'libraries': [
'-lwinhttp.lib',
],
},
}],
],
},
{