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.
29 
30 #include <assert.h>
31 
32 // Disable exception handler warnings.
33 #pragma warning(disable:4530)
34 
35 #include <fstream>
36 
37 #include "common/windows/string_utils-inl.h"
38 
39 #include "common/windows/http_upload.h"
40 
41 namespace google_breakpad {
42 
43 using std::ifstream;
44 using std::ios;
45 
46 static const wchar_t kUserAgent[] = L"Breakpad/1.0 (Windows)";
47 
48 // Helper class which closes an internet handle when it goes away
49 class HTTPUpload::AutoInternetHandle {
50  public:
AutoInternetHandle(HINTERNET handle)51   explicit AutoInternetHandle(HINTERNET handle) : handle_(handle) {}
~AutoInternetHandle()52   ~AutoInternetHandle() {
53     if (handle_) {
54       InternetCloseHandle(handle_);
55     }
56   }
57 
get()58   HINTERNET get() { return handle_; }
59 
60  private:
61   HINTERNET handle_;
62 };
63 
64 // static
SendRequest(const wstring & url,const map<wstring,wstring> & parameters,const wstring & upload_file,const wstring & file_part_name,int * timeout,wstring * response_body,int * response_code)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   }
75 
76   // TODO(bryner): support non-ASCII parameter names
77   if (!CheckParameters(parameters)) {
78     return false;
79   }
80 
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   }
102 
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   }
111 
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   }
123 
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   }
137 
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);
144 
145   string request_body;
146   if (!GenerateRequestBody(parameters, upload_file,
147                            file_part_name, boundary, &request_body)) {
148     return false;
149   }
150 
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     }
158 
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   }
166 
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   }
172 
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   }
181 
182   int http_response = wcstol(http_status, NULL, 10);
183   if (response_code) {
184     *response_code = http_response;
185   }
186 
187   bool result = (http_response == 200);
188 
189   if (result) {
190     result = ReadResponse(request.get(), response_body);
191   }
192 
193   return result;
194 }
195 
196 // static
ReadResponse(HINTERNET request,wstring * response)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;
203 
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   }
211 
212 
213   DWORD bytes_available;
214   DWORD total_read = 0;
215   BOOL return_code;
216 
217   while (((return_code = InternetQueryDataAvailable(request, &bytes_available,
218       0, 0)) != 0) && bytes_available > 0) {
219     vector<char> response_buffer(bytes_available);
220     DWORD size_read;
221 
222     return_code = InternetReadFile(request,
223                                    &response_buffer[0],
224                                    bytes_available, &size_read);
225 
226     if (return_code && size_read > 0) {
227       total_read += size_read;
228       response_body.append(&response_buffer[0], size_read);
229     } else {
230       break;
231     }
232   }
233 
234   bool succeeded = return_code && (!has_content_length_header ||
235                                    (total_read == claimed_size));
236   if (succeeded && response) {
237     *response = UTF8ToWide(response_body);
238   }
239 
240   return succeeded;
241 }
242 
243 // static
GenerateMultipartBoundary()244 wstring HTTPUpload::GenerateMultipartBoundary() {
245   // The boundary has 27 '-' characters followed by 16 hex digits
246   static const wchar_t kBoundaryPrefix[] = L"---------------------------";
247   static const int kBoundaryLength = 27 + 16 + 1;
248 
249   // Generate some random numbers to fill out the boundary
250   int r0 = rand();
251   int r1 = rand();
252 
253   wchar_t temp[kBoundaryLength];
254   swprintf(temp, kBoundaryLength, L"%s%08X%08X", kBoundaryPrefix, r0, r1);
255 
256   // remove when VC++7.1 is no longer supported
257   temp[kBoundaryLength - 1] = L'\0';
258 
259   return wstring(temp);
260 }
261 
262 // static
GenerateRequestHeader(const wstring & boundary)263 wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) {
264   wstring header = L"Content-Type: multipart/form-data; boundary=";
265   header += boundary;
266   return header;
267 }
268 
269 // static
GenerateRequestBody(const map<wstring,wstring> & parameters,const wstring & upload_file,const wstring & file_part_name,const wstring & boundary,string * request_body)270 bool HTTPUpload::GenerateRequestBody(const map<wstring, wstring> &parameters,
271                                      const wstring &upload_file,
272                                      const wstring &file_part_name,
273                                      const wstring &boundary,
274                                      string *request_body) {
275   vector<char> contents;
276   if (!GetFileContents(upload_file, &contents)) {
277     return false;
278   }
279 
280   string boundary_str = WideToUTF8(boundary);
281   if (boundary_str.empty()) {
282     return false;
283   }
284 
285   request_body->clear();
286 
287   // Append each of the parameter pairs as a form-data part
288   for (map<wstring, wstring>::const_iterator pos = parameters.begin();
289        pos != parameters.end(); ++pos) {
290     request_body->append("--" + boundary_str + "\r\n");
291     request_body->append("Content-Disposition: form-data; name=\"" +
292                          WideToUTF8(pos->first) + "\"\r\n\r\n" +
293                          WideToUTF8(pos->second) + "\r\n");
294   }
295 
296   // Now append the upload file as a binary (octet-stream) part
297   string filename_utf8 = WideToUTF8(upload_file);
298   if (filename_utf8.empty()) {
299     return false;
300   }
301 
302   string file_part_name_utf8 = WideToUTF8(file_part_name);
303   if (file_part_name_utf8.empty()) {
304     return false;
305   }
306 
307   request_body->append("--" + boundary_str + "\r\n");
308   request_body->append("Content-Disposition: form-data; "
309                        "name=\"" + file_part_name_utf8 + "\"; "
310                        "filename=\"" + filename_utf8 + "\"\r\n");
311   request_body->append("Content-Type: application/octet-stream\r\n");
312   request_body->append("\r\n");
313 
314   if (!contents.empty()) {
315       request_body->append(&(contents[0]), contents.size());
316   }
317   request_body->append("\r\n");
318   request_body->append("--" + boundary_str + "--\r\n");
319   return true;
320 }
321 
322 // static
GetFileContents(const wstring & filename,vector<char> * contents)323 bool HTTPUpload::GetFileContents(const wstring &filename,
324                                  vector<char> *contents) {
325   bool rv = false;
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   // GCC doesn't support wide file name and opening on FILE* requires ugly
331   // hacks, so fallback to multi byte file.
332 #ifdef _MSC_VER
333   ifstream file;
334   file.open(filename.c_str(), ios::binary);
335 #else // GCC
336   ifstream file(WideToMBCP(filename, CP_ACP).c_str(), ios::binary);
337 #endif  // _MSC_VER >= 1400
338   if (file.is_open()) {
339     file.seekg(0, ios::end);
340     std::streamoff length = file.tellg();
341     // Check for loss of data when converting lenght from std::streamoff into
342     // std::vector<char>::size_type
343     std::vector<char>::size_type vector_size =
344         static_cast<std::vector<char>::size_type>(length);
345     if (static_cast<std::streamoff>(vector_size) == length) {
346       contents->resize(vector_size);
347       if (length != 0) {
348         file.seekg(0, ios::beg);
349         file.read(&((*contents)[0]), length);
350       }
351       rv = true;
352     }
353     file.close();
354   }
355   return rv;
356 }
357 
358 // static
UTF8ToWide(const string & utf8)359 wstring HTTPUpload::UTF8ToWide(const string &utf8) {
360   if (utf8.length() == 0) {
361     return wstring();
362   }
363 
364   // compute the length of the buffer we'll need
365   int charcount = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
366 
367   if (charcount == 0) {
368     return wstring();
369   }
370 
371   // convert
372   wchar_t* buf = new wchar_t[charcount];
373   MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, buf, charcount);
374   wstring result(buf);
375   delete[] buf;
376   return result;
377 }
378 
379 // static
WideToMBCP(const wstring & wide,unsigned int cp)380 string HTTPUpload::WideToMBCP(const wstring &wide, unsigned int cp) {
381   if (wide.length() == 0) {
382     return string();
383   }
384 
385   // compute the length of the buffer we'll need
386   int charcount = WideCharToMultiByte(cp, 0, wide.c_str(), -1,
387                                       NULL, 0, NULL, NULL);
388   if (charcount == 0) {
389     return string();
390   }
391 
392   // convert
393   char *buf = new char[charcount];
394   WideCharToMultiByte(cp, 0, wide.c_str(), -1, buf, charcount,
395                       NULL, NULL);
396 
397   string result(buf);
398   delete[] buf;
399   return result;
400 }
401 
402 // static
CheckParameters(const map<wstring,wstring> & parameters)403 bool HTTPUpload::CheckParameters(const map<wstring, wstring> &parameters) {
404   for (map<wstring, wstring>::const_iterator pos = parameters.begin();
405        pos != parameters.end(); ++pos) {
406     const wstring &str = pos->first;
407     if (str.size() == 0) {
408       return false;  // disallow empty parameter names
409     }
410     for (unsigned int i = 0; i < str.size(); ++i) {
411       wchar_t c = str[i];
412       if (c < 32 || c == '"' || c > 127) {
413         return false;
414       }
415     }
416   }
417   return true;
418 }
419 
420 }  // namespace google_breakpad
421