toolkit/crashreporter/google-breakpad/src/common/windows/http_upload.cc

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     1 // Copyright (c) 2006, Google Inc.
     2 // All rights reserved.
     3 //
     4 // Redistribution and use in source and binary forms, with or without
     5 // modification, are permitted provided that the following conditions are
     6 // met:
     7 //
     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
    13 // distribution.
    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.
    17 //
    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.
    30 #include <assert.h>
    32 // Disable exception handler warnings.
    33 #pragma warning( disable : 4530 )
    35 #include <fstream>
    37 #include "common/windows/string_utils-inl.h"
    39 #include "common/windows/http_upload.h"
    41 namespace google_breakpad {
    43 using std::ifstream;
    44 using std::ios;
    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 {
    50  public:
    51   explicit AutoInternetHandle(HINTERNET handle) : handle_(handle) {}
    52   ~AutoInternetHandle() {
    53     if (handle_) {
    54       InternetCloseHandle(handle_);
    55     }
    56   }
    58   HINTERNET get() { return handle_; }
    60  private:
    61   HINTERNET handle_;
    62 };
    64 // static
    65 bool HTTPUpload::SendRequest(const wstring &url,
    66                              const map<wstring, wstring> &parameters,
    67                              const wstring &upload_file,
    68                              const wstring &file_part_name,
    69                              int *timeout,
    70                              wstring *response_body,
    71                              int *response_code) {
    72   if (response_code) {
    73     *response_code = 0;
    74   }
    76   // TODO(bryner): support non-ASCII parameter names
    77   if (!CheckParameters(parameters)) {
    78     return false;
    79   }
    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()),
    93                         0, &components)) {
    94     return false;
    95   }
    96   bool secure = false;
    97   if (wcscmp(scheme, L"https") == 0) {
    98     secure = true;
    99   } else if (wcscmp(scheme, L"http") != 0) {
   100     return false;
   101   }
   103   AutoInternetHandle internet(InternetOpen(kUserAgent,
   104                                            INTERNET_OPEN_TYPE_PRECONFIG,
   105                                            NULL,  // proxy name
   106                                            NULL,  // proxy bypass
   107                                            0));   // flags
   108   if (!internet.get()) {
   109     return false;
   110   }
   112   AutoInternetHandle connection(InternetConnect(internet.get(),
   113                                                 host,
   114                                                 components.nPort,
   115                                                 NULL,    // user name
   116                                                 NULL,    // password
   117                                                 INTERNET_SERVICE_HTTP,
   118                                                 0,       // flags
   119                                                 NULL));  // context
   120   if (!connection.get()) {
   121     return false;
   122   }
   124   DWORD http_open_flags = secure ? INTERNET_FLAG_SECURE : 0;
   125   http_open_flags |= INTERNET_FLAG_NO_COOKIES;
   126   AutoInternetHandle request(HttpOpenRequest(connection.get(),
   127                                              L"POST",
   128                                              path,
   129                                              NULL,    // version
   130                                              NULL,    // referer
   131                                              NULL,    // agent type
   132                                              http_open_flags,
   133                                              NULL));  // context
   134   if (!request.get()) {
   135     return false;
   136   }
   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);
   145   string request_body;
   146   if (!GenerateRequestBody(parameters, upload_file,
   147                            file_part_name, boundary, &request_body)) {
   148     return false;
   149   }
   151   if (timeout) {
   152     if (!InternetSetOption(request.get(),
   153                            INTERNET_OPTION_SEND_TIMEOUT,
   154                            timeout,
   155                            sizeof(*timeout))) {
   156       fwprintf(stderr, L"Could not unset send timeout, continuing...\n");
   157     }
   159     if (!InternetSetOption(request.get(),
   160                            INTERNET_OPTION_RECEIVE_TIMEOUT,
   161                            timeout,
   162                            sizeof(*timeout))) {
   163       fwprintf(stderr, L"Could not unset receive timeout, continuing...\n");
   164     }
   165   }
   167   if (!HttpSendRequest(request.get(), NULL, 0,
   168                        const_cast<char *>(request_body.data()),
   169                        static_cast<DWORD>(request_body.size()))) {
   170     return false;
   171   }
   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,
   178                      0)) {
   179     return false;
   180   }
   182   int http_response = wcstol(http_status, NULL, 10);
   183   if (response_code) {
   184     *response_code = http_response;
   185   }
   187   bool result = (http_response == 200);
   189   if (result) {
   190     result = ReadResponse(request.get(), response_body);
   191   }
   193   return result;
   194 }
   196 // static
   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);
   210   }
   213   DWORD bytes_available;
   214   DWORD total_read = 0;
   215   BOOL return_code;
   217   while (((return_code = InternetQueryDataAvailable(request, &bytes_available,
   218 	  0, 0)) != 0) && bytes_available > 0) {
   220     vector<char> response_buffer(bytes_available);
   221     DWORD size_read;
   223     return_code = InternetReadFile(request,
   224                                    &response_buffer[0],
   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);
   230     } else {
   231       break;
   232     }
   233   }
   235   bool succeeded = return_code && (!has_content_length_header ||
   236                                    (total_read == claimed_size));
   237   if (succeeded && response) {
   238     *response = UTF8ToWide(response_body);
   239   }
   241   return succeeded;
   242 }
   244 // static
   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
   251   int r0 = rand();
   252   int r1 = rand();
   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);
   261 }
   263 // static
   264 wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) {
   265   wstring header = L"Content-Type: multipart/form-data; boundary=";
   266   header += boundary;
   267   return header;
   268 }
   270 // static
   271 bool HTTPUpload::GenerateRequestBody(const map<wstring, wstring> &parameters,
   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)) {
   278     return false;
   279   }
   281   string boundary_str = WideToUTF8(boundary);
   282   if (boundary_str.empty()) {
   283     return false;
   284   }
   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");
   295   }
   297   // Now append the upload file as a binary (octet-stream) part
   298   string filename_utf8 = WideToUTF8(upload_file);
   299   if (filename_utf8.empty()) {
   300     return false;
   301   }
   303   string file_part_name_utf8 = WideToUTF8(file_part_name);
   304   if (file_part_name_utf8.empty()) {
   305     return false;
   306   }
   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());
   317   }
   318   request_body->append("\r\n");
   319   request_body->append("--" + boundary_str + "--\r\n");
   320   return true;
   321 }
   323 // static
   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
   331   ifstream file;
   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);
   340     if (length != 0) {
   341       file.seekg(0, ios::beg);
   342       file.read(&((*contents)[0]), length);
   343     }
   344     file.close();
   345     return true;
   346   }
   347   return false;
   348 }
   350 // static
   351 wstring HTTPUpload::UTF8ToWide(const string &utf8) {
   352   if (utf8.length() == 0) {
   353     return wstring();
   354   }
   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) {
   360     return wstring();
   361   }
   363   // convert
   364   wchar_t* buf = new wchar_t[charcount];
   365   MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, buf, charcount);
   366   wstring result(buf);
   367   delete[] buf;
   368   return result;
   369 }
   371 // static
   372 string HTTPUpload::WideToUTF8(const wstring &wide) {
   373   if (wide.length() == 0) {
   374     return string();
   375   }
   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) {
   381     return string();
   382   }
   384   // convert
   385   char *buf = new char[charcount];
   386   WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, buf, charcount,
   387                       NULL, NULL);
   389   string result(buf);
   390   delete[] buf;
   391   return result;
   392 }
   394 // static
   395 bool HTTPUpload::CheckParameters(const map<wstring, wstring> &parameters) {
   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
   401     }
   402     for (unsigned int i = 0; i < str.size(); ++i) {
   403       wchar_t c = str[i];
   404       if (c < 32 || c == '"' || c > 127) {
   405         return false;
   406       }
   407     }
   408   }
   409   return true;
   410 }
   412 }  // namespace google_breakpad

mercurial