michael@0: // Copyright (c) 2006, Google Inc. michael@0: // All rights reserved. michael@0: // michael@0: // Redistribution and use in source and binary forms, with or without michael@0: // modification, are permitted provided that the following conditions are michael@0: // met: michael@0: // michael@0: // * Redistributions of source code must retain the above copyright michael@0: // notice, this list of conditions and the following disclaimer. michael@0: // * Redistributions in binary form must reproduce the above michael@0: // copyright notice, this list of conditions and the following disclaimer michael@0: // in the documentation and/or other materials provided with the michael@0: // distribution. michael@0: // * Neither the name of Google Inc. nor the names of its michael@0: // contributors may be used to endorse or promote products derived from michael@0: // this software without specific prior written permission. michael@0: // michael@0: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS michael@0: // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT michael@0: // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR michael@0: // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT michael@0: // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, michael@0: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT michael@0: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: michael@0: #include michael@0: michael@0: // Disable exception handler warnings. michael@0: #pragma warning( disable : 4530 ) michael@0: michael@0: #include michael@0: michael@0: #include "common/windows/string_utils-inl.h" michael@0: michael@0: #include "common/windows/http_upload.h" michael@0: michael@0: namespace google_breakpad { michael@0: michael@0: using std::ifstream; michael@0: using std::ios; michael@0: michael@0: static const wchar_t kUserAgent[] = L"Breakpad/1.0 (Windows)"; michael@0: michael@0: // Helper class which closes an internet handle when it goes away michael@0: class HTTPUpload::AutoInternetHandle { michael@0: public: michael@0: explicit AutoInternetHandle(HINTERNET handle) : handle_(handle) {} michael@0: ~AutoInternetHandle() { michael@0: if (handle_) { michael@0: InternetCloseHandle(handle_); michael@0: } michael@0: } michael@0: michael@0: HINTERNET get() { return handle_; } michael@0: michael@0: private: michael@0: HINTERNET handle_; michael@0: }; michael@0: michael@0: // static michael@0: bool HTTPUpload::SendRequest(const wstring &url, michael@0: const map ¶meters, michael@0: const wstring &upload_file, michael@0: const wstring &file_part_name, michael@0: int *timeout, michael@0: wstring *response_body, michael@0: int *response_code) { michael@0: if (response_code) { michael@0: *response_code = 0; michael@0: } michael@0: michael@0: // TODO(bryner): support non-ASCII parameter names michael@0: if (!CheckParameters(parameters)) { michael@0: return false; michael@0: } michael@0: michael@0: // Break up the URL and make sure we can handle it michael@0: wchar_t scheme[16], host[256], path[256]; michael@0: URL_COMPONENTS components; michael@0: memset(&components, 0, sizeof(components)); michael@0: components.dwStructSize = sizeof(components); michael@0: components.lpszScheme = scheme; michael@0: components.dwSchemeLength = sizeof(scheme) / sizeof(scheme[0]); michael@0: components.lpszHostName = host; michael@0: components.dwHostNameLength = sizeof(host) / sizeof(host[0]); michael@0: components.lpszUrlPath = path; michael@0: components.dwUrlPathLength = sizeof(path) / sizeof(path[0]); michael@0: if (!InternetCrackUrl(url.c_str(), static_cast(url.size()), michael@0: 0, &components)) { michael@0: return false; michael@0: } michael@0: bool secure = false; michael@0: if (wcscmp(scheme, L"https") == 0) { michael@0: secure = true; michael@0: } else if (wcscmp(scheme, L"http") != 0) { michael@0: return false; michael@0: } michael@0: michael@0: AutoInternetHandle internet(InternetOpen(kUserAgent, michael@0: INTERNET_OPEN_TYPE_PRECONFIG, michael@0: NULL, // proxy name michael@0: NULL, // proxy bypass michael@0: 0)); // flags michael@0: if (!internet.get()) { michael@0: return false; michael@0: } michael@0: michael@0: AutoInternetHandle connection(InternetConnect(internet.get(), michael@0: host, michael@0: components.nPort, michael@0: NULL, // user name michael@0: NULL, // password michael@0: INTERNET_SERVICE_HTTP, michael@0: 0, // flags michael@0: NULL)); // context michael@0: if (!connection.get()) { michael@0: return false; michael@0: } michael@0: michael@0: DWORD http_open_flags = secure ? INTERNET_FLAG_SECURE : 0; michael@0: http_open_flags |= INTERNET_FLAG_NO_COOKIES; michael@0: AutoInternetHandle request(HttpOpenRequest(connection.get(), michael@0: L"POST", michael@0: path, michael@0: NULL, // version michael@0: NULL, // referer michael@0: NULL, // agent type michael@0: http_open_flags, michael@0: NULL)); // context michael@0: if (!request.get()) { michael@0: return false; michael@0: } michael@0: michael@0: wstring boundary = GenerateMultipartBoundary(); michael@0: wstring content_type_header = GenerateRequestHeader(boundary); michael@0: HttpAddRequestHeaders(request.get(), michael@0: content_type_header.c_str(), michael@0: static_cast(-1), michael@0: HTTP_ADDREQ_FLAG_ADD); michael@0: michael@0: string request_body; michael@0: if (!GenerateRequestBody(parameters, upload_file, michael@0: file_part_name, boundary, &request_body)) { michael@0: return false; michael@0: } michael@0: michael@0: if (timeout) { michael@0: if (!InternetSetOption(request.get(), michael@0: INTERNET_OPTION_SEND_TIMEOUT, michael@0: timeout, michael@0: sizeof(*timeout))) { michael@0: fwprintf(stderr, L"Could not unset send timeout, continuing...\n"); michael@0: } michael@0: michael@0: if (!InternetSetOption(request.get(), michael@0: INTERNET_OPTION_RECEIVE_TIMEOUT, michael@0: timeout, michael@0: sizeof(*timeout))) { michael@0: fwprintf(stderr, L"Could not unset receive timeout, continuing...\n"); michael@0: } michael@0: } michael@0: michael@0: if (!HttpSendRequest(request.get(), NULL, 0, michael@0: const_cast(request_body.data()), michael@0: static_cast(request_body.size()))) { michael@0: return false; michael@0: } michael@0: michael@0: // The server indicates a successful upload with HTTP status 200. michael@0: wchar_t http_status[4]; michael@0: DWORD http_status_size = sizeof(http_status); michael@0: if (!HttpQueryInfo(request.get(), HTTP_QUERY_STATUS_CODE, michael@0: static_cast(&http_status), &http_status_size, michael@0: 0)) { michael@0: return false; michael@0: } michael@0: michael@0: int http_response = wcstol(http_status, NULL, 10); michael@0: if (response_code) { michael@0: *response_code = http_response; michael@0: } michael@0: michael@0: bool result = (http_response == 200); michael@0: michael@0: if (result) { michael@0: result = ReadResponse(request.get(), response_body); michael@0: } michael@0: michael@0: return result; michael@0: } michael@0: michael@0: // static michael@0: bool HTTPUpload::ReadResponse(HINTERNET request, wstring *response) { michael@0: bool has_content_length_header = false; michael@0: wchar_t content_length[32]; michael@0: DWORD content_length_size = sizeof(content_length); michael@0: DWORD claimed_size = 0; michael@0: string response_body; michael@0: michael@0: if (HttpQueryInfo(request, HTTP_QUERY_CONTENT_LENGTH, michael@0: static_cast(&content_length), michael@0: &content_length_size, 0)) { michael@0: has_content_length_header = true; michael@0: claimed_size = wcstol(content_length, NULL, 10); michael@0: response_body.reserve(claimed_size); michael@0: } michael@0: michael@0: michael@0: DWORD bytes_available; michael@0: DWORD total_read = 0; michael@0: BOOL return_code; michael@0: michael@0: while (((return_code = InternetQueryDataAvailable(request, &bytes_available, michael@0: 0, 0)) != 0) && bytes_available > 0) { michael@0: michael@0: vector response_buffer(bytes_available); michael@0: DWORD size_read; michael@0: michael@0: return_code = InternetReadFile(request, michael@0: &response_buffer[0], michael@0: bytes_available, &size_read); michael@0: michael@0: if (return_code && size_read > 0) { michael@0: total_read += size_read; michael@0: response_body.append(&response_buffer[0], size_read); michael@0: } else { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: bool succeeded = return_code && (!has_content_length_header || michael@0: (total_read == claimed_size)); michael@0: if (succeeded && response) { michael@0: *response = UTF8ToWide(response_body); michael@0: } michael@0: michael@0: return succeeded; michael@0: } michael@0: michael@0: // static michael@0: wstring HTTPUpload::GenerateMultipartBoundary() { michael@0: // The boundary has 27 '-' characters followed by 16 hex digits michael@0: static const wchar_t kBoundaryPrefix[] = L"---------------------------"; michael@0: static const int kBoundaryLength = 27 + 16 + 1; michael@0: michael@0: // Generate some random numbers to fill out the boundary michael@0: int r0 = rand(); michael@0: int r1 = rand(); michael@0: michael@0: wchar_t temp[kBoundaryLength]; michael@0: swprintf(temp, kBoundaryLength, L"%s%08X%08X", kBoundaryPrefix, r0, r1); michael@0: michael@0: // remove when VC++7.1 is no longer supported michael@0: temp[kBoundaryLength - 1] = L'\0'; michael@0: michael@0: return wstring(temp); michael@0: } michael@0: michael@0: // static michael@0: wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) { michael@0: wstring header = L"Content-Type: multipart/form-data; boundary="; michael@0: header += boundary; michael@0: return header; michael@0: } michael@0: michael@0: // static michael@0: bool HTTPUpload::GenerateRequestBody(const map ¶meters, michael@0: const wstring &upload_file, michael@0: const wstring &file_part_name, michael@0: const wstring &boundary, michael@0: string *request_body) { michael@0: vector contents; michael@0: if (!GetFileContents(upload_file, &contents)) { michael@0: return false; michael@0: } michael@0: michael@0: string boundary_str = WideToUTF8(boundary); michael@0: if (boundary_str.empty()) { michael@0: return false; michael@0: } michael@0: michael@0: request_body->clear(); michael@0: michael@0: // Append each of the parameter pairs as a form-data part michael@0: for (map::const_iterator pos = parameters.begin(); michael@0: pos != parameters.end(); ++pos) { michael@0: request_body->append("--" + boundary_str + "\r\n"); michael@0: request_body->append("Content-Disposition: form-data; name=\"" + michael@0: WideToUTF8(pos->first) + "\"\r\n\r\n" + michael@0: WideToUTF8(pos->second) + "\r\n"); michael@0: } michael@0: michael@0: // Now append the upload file as a binary (octet-stream) part michael@0: string filename_utf8 = WideToUTF8(upload_file); michael@0: if (filename_utf8.empty()) { michael@0: return false; michael@0: } michael@0: michael@0: string file_part_name_utf8 = WideToUTF8(file_part_name); michael@0: if (file_part_name_utf8.empty()) { michael@0: return false; michael@0: } michael@0: michael@0: request_body->append("--" + boundary_str + "\r\n"); michael@0: request_body->append("Content-Disposition: form-data; " michael@0: "name=\"" + file_part_name_utf8 + "\"; " michael@0: "filename=\"" + filename_utf8 + "\"\r\n"); michael@0: request_body->append("Content-Type: application/octet-stream\r\n"); michael@0: request_body->append("\r\n"); michael@0: michael@0: if (!contents.empty()) { michael@0: request_body->append(&(contents[0]), contents.size()); michael@0: } michael@0: request_body->append("\r\n"); michael@0: request_body->append("--" + boundary_str + "--\r\n"); michael@0: return true; michael@0: } michael@0: michael@0: // static michael@0: bool HTTPUpload::GetFileContents(const wstring &filename, michael@0: vector *contents) { michael@0: // The "open" method on pre-MSVC8 ifstream implementations doesn't accept a michael@0: // wchar_t* filename, so use _wfopen directly in that case. For VC8 and michael@0: // later, _wfopen has been deprecated in favor of _wfopen_s, which does michael@0: // not exist in earlier versions, so let the ifstream open the file itself. michael@0: #if _MSC_VER >= 1400 // MSVC 2005/8 michael@0: ifstream file; michael@0: file.open(filename.c_str(), ios::binary); michael@0: #else // _MSC_VER >= 1400 michael@0: ifstream file(_wfopen(filename.c_str(), L"rb")); michael@0: #endif // _MSC_VER >= 1400 michael@0: if (file.is_open()) { michael@0: file.seekg(0, ios::end); michael@0: std::streamoff length = file.tellg(); michael@0: contents->resize(length); michael@0: if (length != 0) { michael@0: file.seekg(0, ios::beg); michael@0: file.read(&((*contents)[0]), length); michael@0: } michael@0: file.close(); michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: // static michael@0: wstring HTTPUpload::UTF8ToWide(const string &utf8) { michael@0: if (utf8.length() == 0) { michael@0: return wstring(); michael@0: } michael@0: michael@0: // compute the length of the buffer we'll need michael@0: int charcount = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0); michael@0: michael@0: if (charcount == 0) { michael@0: return wstring(); michael@0: } michael@0: michael@0: // convert michael@0: wchar_t* buf = new wchar_t[charcount]; michael@0: MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, buf, charcount); michael@0: wstring result(buf); michael@0: delete[] buf; michael@0: return result; michael@0: } michael@0: michael@0: // static michael@0: string HTTPUpload::WideToUTF8(const wstring &wide) { michael@0: if (wide.length() == 0) { michael@0: return string(); michael@0: } michael@0: michael@0: // compute the length of the buffer we'll need michael@0: int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, michael@0: NULL, 0, NULL, NULL); michael@0: if (charcount == 0) { michael@0: return string(); michael@0: } michael@0: michael@0: // convert michael@0: char *buf = new char[charcount]; michael@0: WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, buf, charcount, michael@0: NULL, NULL); michael@0: michael@0: string result(buf); michael@0: delete[] buf; michael@0: return result; michael@0: } michael@0: michael@0: // static michael@0: bool HTTPUpload::CheckParameters(const map ¶meters) { michael@0: for (map::const_iterator pos = parameters.begin(); michael@0: pos != parameters.end(); ++pos) { michael@0: const wstring &str = pos->first; michael@0: if (str.size() == 0) { michael@0: return false; // disallow empty parameter names michael@0: } michael@0: for (unsigned int i = 0; i < str.size(); ++i) { michael@0: wchar_t c = str[i]; michael@0: if (c < 32 || c == '"' || c > 127) { michael@0: return false; michael@0: } michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: } // namespace google_breakpad