1
// Copyright (c) 2006, Google Inc.
2
// All rights reserved.
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are
8
// * Redistributions of source code must retain the above copyright
9
// notice, this list of conditions and the following disclaimer.
10
// * Redistributions in binary form must reproduce the above
11
// copyright notice, this list of conditions and the following disclaimer
12
// in the documentation and/or other materials provided with the
14
// * Neither the name of Google Inc. nor the names of its
15
// contributors may be used to endorse or promote products derived from
16
// this software without specific prior written permission.
18
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
// Disable exception handler warnings.
33
#pragma warning( disable : 4530 )
37
#include "common/windows/string_utils-inl.h"
39
#include "common/windows/http_upload.h"
41
namespace google_breakpad {
46
static const wchar_t kUserAgent[] = L"Breakpad/1.0 (Windows)";
48
// Helper class which closes an internet handle when it goes away
49
class HTTPUpload::AutoInternetHandle {
51
explicit AutoInternetHandle(HINTERNET handle) : handle_(handle) {}
52
~AutoInternetHandle() {
54
InternetCloseHandle(handle_);
58
HINTERNET get() { return handle_; }
65
bool HTTPUpload::SendRequest(const wstring &url,
66
const map<wstring, wstring> ¶meters,
67
const wstring &upload_file,
68
const wstring &file_part_name,
70
wstring *response_body,
76
// TODO(bryner): support non-ASCII parameter names
77
if (!CheckParameters(parameters)) {
81
// Break up the URL and make sure we can handle it
82
wchar_t scheme[16], host[256], path[256];
83
URL_COMPONENTS components;
84
memset(&components, 0, sizeof(components));
85
components.dwStructSize = sizeof(components);
86
components.lpszScheme = scheme;
87
components.dwSchemeLength = sizeof(scheme) / sizeof(scheme[0]);
88
components.lpszHostName = host;
89
components.dwHostNameLength = sizeof(host) / sizeof(host[0]);
90
components.lpszUrlPath = path;
91
components.dwUrlPathLength = sizeof(path) / sizeof(path[0]);
92
if (!InternetCrackUrl(url.c_str(), static_cast<DWORD>(url.size()),
97
if (wcscmp(scheme, L"https") == 0) {
99
} else if (wcscmp(scheme, L"http") != 0) {
103
AutoInternetHandle internet(InternetOpen(kUserAgent,
104
INTERNET_OPEN_TYPE_PRECONFIG,
106
NULL, // proxy bypass
108
if (!internet.get()) {
112
AutoInternetHandle connection(InternetConnect(internet.get(),
117
INTERNET_SERVICE_HTTP,
120
if (!connection.get()) {
124
DWORD http_open_flags = secure ? INTERNET_FLAG_SECURE : 0;
125
http_open_flags |= INTERNET_FLAG_NO_COOKIES;
126
AutoInternetHandle request(HttpOpenRequest(connection.get(),
134
if (!request.get()) {
138
wstring boundary = GenerateMultipartBoundary();
139
wstring content_type_header = GenerateRequestHeader(boundary);
140
HttpAddRequestHeaders(request.get(),
141
content_type_header.c_str(),
142
static_cast<DWORD>(-1),
143
HTTP_ADDREQ_FLAG_ADD);
146
if (!GenerateRequestBody(parameters, upload_file,
147
file_part_name, boundary, &request_body)) {
152
if (!InternetSetOption(request.get(),
153
INTERNET_OPTION_SEND_TIMEOUT,
156
fwprintf(stderr, L"Could not unset send timeout, continuing...\n");
159
if (!InternetSetOption(request.get(),
160
INTERNET_OPTION_RECEIVE_TIMEOUT,
163
fwprintf(stderr, L"Could not unset receive timeout, continuing...\n");
167
if (!HttpSendRequest(request.get(), NULL, 0,
168
const_cast<char *>(request_body.data()),
169
static_cast<DWORD>(request_body.size()))) {
173
// The server indicates a successful upload with HTTP status 200.
174
wchar_t http_status[4];
175
DWORD http_status_size = sizeof(http_status);
176
if (!HttpQueryInfo(request.get(), HTTP_QUERY_STATUS_CODE,
177
static_cast<LPVOID>(&http_status), &http_status_size,
182
int http_response = wcstol(http_status, NULL, 10);
184
*response_code = http_response;
187
bool result = (http_response == 200);
190
result = ReadResponse(request.get(), response_body);
197
bool HTTPUpload::ReadResponse(HINTERNET request, wstring *response) {
198
bool has_content_length_header = false;
199
wchar_t content_length[32];
200
DWORD content_length_size = sizeof(content_length);
201
DWORD claimed_size = 0;
202
string response_body;
204
if (HttpQueryInfo(request, HTTP_QUERY_CONTENT_LENGTH,
205
static_cast<LPVOID>(&content_length),
206
&content_length_size, 0)) {
207
has_content_length_header = true;
208
claimed_size = wcstol(content_length, NULL, 10);
209
response_body.reserve(claimed_size);
213
DWORD bytes_available;
214
DWORD total_read = 0;
217
while (((return_code = InternetQueryDataAvailable(request, &bytes_available,
218
0, 0)) != 0) && bytes_available > 0) {
220
vector<char> response_buffer(bytes_available);
223
return_code = InternetReadFile(request,
225
bytes_available, &size_read);
227
if (return_code && size_read > 0) {
228
total_read += size_read;
229
response_body.append(&response_buffer[0], size_read);
235
bool succeeded = return_code && (!has_content_length_header ||
236
(total_read == claimed_size));
237
if (succeeded && response) {
238
*response = UTF8ToWide(response_body);
245
wstring HTTPUpload::GenerateMultipartBoundary() {
246
// The boundary has 27 '-' characters followed by 16 hex digits
247
static const wchar_t kBoundaryPrefix[] = L"---------------------------";
248
static const int kBoundaryLength = 27 + 16 + 1;
250
// Generate some random numbers to fill out the boundary
254
wchar_t temp[kBoundaryLength];
255
swprintf(temp, kBoundaryLength, L"%s%08X%08X", kBoundaryPrefix, r0, r1);
257
// remove when VC++7.1 is no longer supported
258
temp[kBoundaryLength - 1] = L'\0';
260
return wstring(temp);
264
wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) {
265
wstring header = L"Content-Type: multipart/form-data; boundary=";
271
bool HTTPUpload::GenerateRequestBody(const map<wstring, wstring> ¶meters,
272
const wstring &upload_file,
273
const wstring &file_part_name,
274
const wstring &boundary,
275
string *request_body) {
276
vector<char> contents;
277
if (!GetFileContents(upload_file, &contents)) {
281
string boundary_str = WideToUTF8(boundary);
282
if (boundary_str.empty()) {
286
request_body->clear();
288
// Append each of the parameter pairs as a form-data part
289
for (map<wstring, wstring>::const_iterator pos = parameters.begin();
290
pos != parameters.end(); ++pos) {
291
request_body->append("--" + boundary_str + "\r\n");
292
request_body->append("Content-Disposition: form-data; name=\"" +
293
WideToUTF8(pos->first) + "\"\r\n\r\n" +
294
WideToUTF8(pos->second) + "\r\n");
297
// Now append the upload file as a binary (octet-stream) part
298
string filename_utf8 = WideToUTF8(upload_file);
299
if (filename_utf8.empty()) {
303
string file_part_name_utf8 = WideToUTF8(file_part_name);
304
if (file_part_name_utf8.empty()) {
308
request_body->append("--" + boundary_str + "\r\n");
309
request_body->append("Content-Disposition: form-data; "
310
"name=\"" + file_part_name_utf8 + "\"; "
311
"filename=\"" + filename_utf8 + "\"\r\n");
312
request_body->append("Content-Type: application/octet-stream\r\n");
313
request_body->append("\r\n");
315
if (!contents.empty()) {
316
request_body->append(&(contents[0]), contents.size());
318
request_body->append("\r\n");
319
request_body->append("--" + boundary_str + "--\r\n");
324
bool HTTPUpload::GetFileContents(const wstring &filename,
325
vector<char> *contents) {
326
// The "open" method on pre-MSVC8 ifstream implementations doesn't accept a
327
// wchar_t* filename, so use _wfopen directly in that case. For VC8 and
328
// later, _wfopen has been deprecated in favor of _wfopen_s, which does
329
// not exist in earlier versions, so let the ifstream open the file itself.
330
#if _MSC_VER >= 1400 // MSVC 2005/8
332
file.open(filename.c_str(), ios::binary);
333
#else // _MSC_VER >= 1400
334
ifstream file(_wfopen(filename.c_str(), L"rb"));
335
#endif // _MSC_VER >= 1400
336
if (file.is_open()) {
337
file.seekg(0, ios::end);
338
std::streamoff length = file.tellg();
339
contents->resize(length);
341
file.seekg(0, ios::beg);
342
file.read(&((*contents)[0]), length);
351
wstring HTTPUpload::UTF8ToWide(const string &utf8) {
352
if (utf8.length() == 0) {
356
// compute the length of the buffer we'll need
357
int charcount = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
359
if (charcount == 0) {
364
wchar_t* buf = new wchar_t[charcount];
365
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, buf, charcount);
372
string HTTPUpload::WideToUTF8(const wstring &wide) {
373
if (wide.length() == 0) {
377
// compute the length of the buffer we'll need
378
int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,
379
NULL, 0, NULL, NULL);
380
if (charcount == 0) {
385
char *buf = new char[charcount];
386
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, buf, charcount,
395
bool HTTPUpload::CheckParameters(const map<wstring, wstring> ¶meters) {
396
for (map<wstring, wstring>::const_iterator pos = parameters.begin();
397
pos != parameters.end(); ++pos) {
398
const wstring &str = pos->first;
399
if (str.size() == 0) {
400
return false; // disallow empty parameter names
402
for (unsigned int i = 0; i < str.size(); ++i) {
404
if (c < 32 || c == '"' || c > 127) {
412
} // namespace google_breakpad