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 map<wstring,wstring> & files,int * timeout,wstring * response_body,int * response_code)65 bool HTTPUpload::SendRequest(const wstring &url,
66                              const map<wstring, wstring> &parameters,
67                              const map<wstring, wstring> &files,
68                              int *timeout,
69                              wstring *response_body,
70                              int *response_code) {
71   if (response_code) {
72     *response_code = 0;
73   }
74 
75   // TODO(bryner): support non-ASCII parameter names
76   if (!CheckParameters(parameters)) {
77     return false;
78   }
79 
80   // Break up the URL and make sure we can handle it
81   wchar_t scheme[16], host[256], path[256];
82   URL_COMPONENTS components;
83   memset(&components, 0, sizeof(components));
84   components.dwStructSize = sizeof(components);
85   components.lpszScheme = scheme;
86   components.dwSchemeLength = sizeof(scheme) / sizeof(scheme[0]);
87   components.lpszHostName = host;
88   components.dwHostNameLength = sizeof(host) / sizeof(host[0]);
89   components.lpszUrlPath = path;
90   components.dwUrlPathLength = sizeof(path) / sizeof(path[0]);
91   if (!InternetCrackUrl(url.c_str(), static_cast<DWORD>(url.size()),
92                         0, &components)) {
93     return false;
94   }
95   bool secure = false;
96   if (wcscmp(scheme, L"https") == 0) {
97     secure = true;
98   } else if (wcscmp(scheme, L"http") != 0) {
99     return false;
100   }
101 
102   AutoInternetHandle internet(InternetOpen(kUserAgent,
103                                            INTERNET_OPEN_TYPE_PRECONFIG,
104                                            NULL,  // proxy name
105                                            NULL,  // proxy bypass
106                                            0));   // flags
107   if (!internet.get()) {
108     return false;
109   }
110 
111   AutoInternetHandle connection(InternetConnect(internet.get(),
112                                                 host,
113                                                 components.nPort,
114                                                 NULL,    // user name
115                                                 NULL,    // password
116                                                 INTERNET_SERVICE_HTTP,
117                                                 0,       // flags
118                                                 NULL));  // context
119   if (!connection.get()) {
120     return false;
121   }
122 
123   DWORD http_open_flags = secure ? INTERNET_FLAG_SECURE : 0;
124   http_open_flags |= INTERNET_FLAG_NO_COOKIES;
125   AutoInternetHandle request(HttpOpenRequest(connection.get(),
126                                              L"POST",
127                                              path,
128                                              NULL,    // version
129                                              NULL,    // referer
130                                              NULL,    // agent type
131                                              http_open_flags,
132                                              NULL));  // context
133   if (!request.get()) {
134     return false;
135   }
136 
137   wstring boundary = GenerateMultipartBoundary();
138   wstring content_type_header = GenerateRequestHeader(boundary);
139   HttpAddRequestHeaders(request.get(),
140                         content_type_header.c_str(),
141                         static_cast<DWORD>(-1),
142                         HTTP_ADDREQ_FLAG_ADD);
143 
144   string request_body;
145   if (!GenerateRequestBody(parameters, files, boundary, &request_body)) {
146     return false;
147   }
148 
149   if (timeout) {
150     if (!InternetSetOption(request.get(),
151                            INTERNET_OPTION_SEND_TIMEOUT,
152                            timeout,
153                            sizeof(*timeout))) {
154       fwprintf(stderr, L"Could not unset send timeout, continuing...\n");
155     }
156 
157     if (!InternetSetOption(request.get(),
158                            INTERNET_OPTION_RECEIVE_TIMEOUT,
159                            timeout,
160                            sizeof(*timeout))) {
161       fwprintf(stderr, L"Could not unset receive timeout, continuing...\n");
162     }
163   }
164 
165   if (!HttpSendRequest(request.get(), NULL, 0,
166                        const_cast<char *>(request_body.data()),
167                        static_cast<DWORD>(request_body.size()))) {
168     return false;
169   }
170 
171   // The server indicates a successful upload with HTTP status 200.
172   wchar_t http_status[4];
173   DWORD http_status_size = sizeof(http_status);
174   if (!HttpQueryInfo(request.get(), HTTP_QUERY_STATUS_CODE,
175                      static_cast<LPVOID>(&http_status), &http_status_size,
176                      0)) {
177     return false;
178   }
179 
180   int http_response = wcstol(http_status, NULL, 10);
181   if (response_code) {
182     *response_code = http_response;
183   }
184 
185   bool result = (http_response == 200);
186 
187   if (result) {
188     result = ReadResponse(request.get(), response_body);
189   }
190 
191   return result;
192 }
193 
194 // static
ReadResponse(HINTERNET request,wstring * response)195 bool HTTPUpload::ReadResponse(HINTERNET request, wstring *response) {
196   bool has_content_length_header = false;
197   wchar_t content_length[32];
198   DWORD content_length_size = sizeof(content_length);
199   DWORD claimed_size = 0;
200   string response_body;
201 
202   if (HttpQueryInfo(request, HTTP_QUERY_CONTENT_LENGTH,
203                     static_cast<LPVOID>(&content_length),
204                     &content_length_size, 0)) {
205     has_content_length_header = true;
206     claimed_size = wcstol(content_length, NULL, 10);
207     response_body.reserve(claimed_size);
208   }
209 
210 
211   DWORD bytes_available;
212   DWORD total_read = 0;
213   BOOL return_code;
214 
215   while (((return_code = InternetQueryDataAvailable(request, &bytes_available,
216       0, 0)) != 0) && bytes_available > 0) {
217     vector<char> response_buffer(bytes_available);
218     DWORD size_read;
219 
220     return_code = InternetReadFile(request,
221                                    &response_buffer[0],
222                                    bytes_available, &size_read);
223 
224     if (return_code && size_read > 0) {
225       total_read += size_read;
226       response_body.append(&response_buffer[0], size_read);
227     } else {
228       break;
229     }
230   }
231 
232   bool succeeded = return_code && (!has_content_length_header ||
233                                    (total_read == claimed_size));
234   if (succeeded && response) {
235     *response = UTF8ToWide(response_body);
236   }
237 
238   return succeeded;
239 }
240 
241 // static
GenerateMultipartBoundary()242 wstring HTTPUpload::GenerateMultipartBoundary() {
243   // The boundary has 27 '-' characters followed by 16 hex digits
244   static const wchar_t kBoundaryPrefix[] = L"---------------------------";
245   static const int kBoundaryLength = 27 + 16 + 1;
246 
247   // Generate some random numbers to fill out the boundary
248   int r0 = rand();
249   int r1 = rand();
250 
251   wchar_t temp[kBoundaryLength];
252   swprintf(temp, kBoundaryLength, L"%s%08X%08X", kBoundaryPrefix, r0, r1);
253 
254   // remove when VC++7.1 is no longer supported
255   temp[kBoundaryLength - 1] = L'\0';
256 
257   return wstring(temp);
258 }
259 
260 // static
GenerateRequestHeader(const wstring & boundary)261 wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) {
262   wstring header = L"Content-Type: multipart/form-data; boundary=";
263   header += boundary;
264   return header;
265 }
266 
267 // static
GenerateRequestBody(const map<wstring,wstring> & parameters,const map<wstring,wstring> & files,const wstring & boundary,string * request_body)268 bool HTTPUpload::GenerateRequestBody(const map<wstring, wstring> &parameters,
269                                      const map<wstring, wstring> &files,
270                                      const wstring &boundary,
271                                      string *request_body) {
272   string boundary_str = WideToUTF8(boundary);
273   if (boundary_str.empty()) {
274     return false;
275   }
276 
277   request_body->clear();
278 
279   // Append each of the parameter pairs as a form-data part
280   for (map<wstring, wstring>::const_iterator pos = parameters.begin();
281        pos != parameters.end(); ++pos) {
282     request_body->append("--" + boundary_str + "\r\n");
283     request_body->append("Content-Disposition: form-data; name=\"" +
284                          WideToUTF8(pos->first) + "\"\r\n\r\n" +
285                          WideToUTF8(pos->second) + "\r\n");
286   }
287 
288   for (map<wstring, wstring>::const_iterator pos = files.begin();
289        pos != files.end(); ++pos) {
290     vector<char> contents;
291     if (!GetFileContents(pos->second, &contents)) {
292       return false;
293     }
294 
295     // Now append the upload files as a binary (octet-stream) part
296     string filename_utf8 = WideToUTF8(pos->second);
297     if (filename_utf8.empty()) {
298       return false;
299     }
300 
301     string file_part_name_utf8 = WideToUTF8(pos->first);
302     if (file_part_name_utf8.empty()) {
303       return false;
304     }
305 
306     request_body->append("--" + boundary_str + "\r\n");
307     request_body->append("Content-Disposition: form-data; "
308       "name=\"" + file_part_name_utf8 + "\"; "
309       "filename=\"" + filename_utf8 + "\"\r\n");
310     request_body->append("Content-Type: application/octet-stream\r\n");
311     request_body->append("\r\n");
312 
313     if (!contents.empty()) {
314       request_body->append(&(contents[0]), contents.size());
315     }
316     request_body->append("\r\n");
317   }
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