1 : // Copyright 2014 Google Inc. All Rights Reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // http://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 : //
15 : // Much of this file has been adapted from Chromium (net/http/http_util.cc) and
16 : // Breakpad (common/linux/http_upload.cc).
17 : // See http://www.ietf.org/rfc/rfc2388.txt for a description of the
18 : // multipart/form-data HTTP message type implemented in this file.
19 : #include "syzygy/kasko/internet_helpers.h"
20 :
21 : #include <winhttp.h> // NOLINT
22 :
23 : #include <wchar.h>
24 :
25 : #include "base/logging.h"
26 : #include "base/strings/string_number_conversions.h"
27 : #include "base/strings/string_tokenizer.h"
28 : #include "base/strings/string_util.h"
29 : #include "base/strings/utf_string_conversions.h"
30 :
31 : namespace kasko {
32 :
33 : namespace {
34 :
35 : // Returns the index of the closing quote of the string, if any. |start| points
36 : // at the opening quote.
37 : size_t FindStringEnd(const base::string16& line,
38 : size_t start,
39 E : base::char16 delim) {
40 E : DCHECK_LT(start, line.length());
41 E : DCHECK_EQ(line[start], delim);
42 E : DCHECK((delim == L'"') || (delim == L'\''));
43 :
44 E : const base::char16 set[] = { delim, L'\\', L'\0' };
45 E : for (size_t end = line.find_first_of(set, start + 1);
46 E : end != base::string16::npos; end = line.find_first_of(set, end + 2)) {
47 E : if (line[end] != L'\\')
48 E : return end;
49 i : }
50 E : return line.length();
51 E : }
52 :
53 : const base::char16 kHttpLws[] = L" \t";
54 :
55 E : bool IsLWS(base::char16 c) {
56 E : return ::wcschr(kHttpLws, c) != NULL;
57 E : }
58 :
59 : void TrimLWS(base::string16::const_iterator* begin,
60 E : base::string16::const_iterator* end) {
61 : // Skip leading whitespace.
62 E : while (*begin < *end && IsLWS((*begin)[0]))
63 E : ++(*begin);
64 :
65 : // Skip trailing whitespace.
66 E : while (*begin < *end && IsLWS((*end)[-1]))
67 E : --(*end);
68 E : }
69 :
70 : } // namespace
71 :
72 : void ParseContentType(const base::string16& content_type_str,
73 : base::string16* mime_type,
74 : base::string16* charset,
75 : bool* had_charset,
76 E : base::string16* boundary) {
77 E : const base::string16::const_iterator begin = content_type_str.begin();
78 :
79 : // Trim leading and trailing whitespace from type. We include '(' in the
80 : // trailing trim set to catch media-type comments, which are not at all
81 : // standard, but may occur in rare cases.
82 E : size_t type_val = content_type_str.find_first_not_of(kHttpLws);
83 E : type_val = std::min(type_val, content_type_str.length());
84 : size_t type_end = content_type_str.find_first_of(
85 E : base::string16(kHttpLws) + L";(", type_val);
86 E : if (type_end == base::string16::npos)
87 E : type_end = content_type_str.length();
88 :
89 E : size_t charset_val = 0;
90 E : size_t charset_end = 0;
91 E : bool type_has_charset = false;
92 :
93 : // Iterate over parameters.
94 E : size_t param_start = content_type_str.find_first_of(';', type_end);
95 E : if (param_start != std::string::npos) {
96 : base::StringTokenizerT<base::string16, base::string16::const_iterator>
97 E : tokenizer(begin + param_start, content_type_str.end(), L";");
98 E : tokenizer.set_quote_chars(L"\"");
99 E : while (tokenizer.GetNext()) {
100 : base::string16::const_iterator equals_sign =
101 E : std::find(tokenizer.token_begin(), tokenizer.token_end(), L'=');
102 E : if (equals_sign == tokenizer.token_end())
103 E : continue;
104 :
105 E : base::string16::const_iterator param_name_begin = tokenizer.token_begin();
106 E : base::string16::const_iterator param_name_end = equals_sign;
107 E : TrimLWS(¶m_name_begin, ¶m_name_end);
108 :
109 E : base::string16::const_iterator param_value_begin = equals_sign + 1;
110 E : base::string16::const_iterator param_value_end = tokenizer.token_end();
111 E : DCHECK(param_value_begin <= tokenizer.token_end());
112 E : TrimLWS(¶m_value_begin, ¶m_value_end);
113 :
114 : if (base::LowerCaseEqualsASCII(
115 : base::StringPiece16(param_name_begin, param_name_end),
116 E : "charset")) {
117 E : charset_val = param_value_begin - begin;
118 E : charset_end = param_value_end - begin;
119 E : type_has_charset = true;
120 E : } else if (base::LowerCaseEqualsASCII(
121 : base::StringPiece16(param_name_begin, param_name_end),
122 E : "boundary")) {
123 E : if (boundary)
124 E : boundary->assign(param_value_begin, param_value_end);
125 : }
126 E : }
127 E : }
128 :
129 E : if (type_has_charset) {
130 : // Trim leading and trailing whitespace from charset_val. We include '(' in
131 : // the trailing trim set to catch media-type comments, which are not at all
132 : // standard, but may occur in rare cases.
133 E : charset_val = content_type_str.find_first_not_of(kHttpLws, charset_val);
134 E : charset_val = std::min(charset_val, charset_end);
135 E : base::char16 first_char = content_type_str[charset_val];
136 E : if (first_char == L'"' || first_char == L'\'') {
137 E : charset_end = FindStringEnd(content_type_str, charset_val, first_char);
138 E : ++charset_val;
139 E : DCHECK(charset_end >= charset_val);
140 E : } else {
141 : charset_end = std::min(content_type_str.find_first_of(
142 : base::string16(kHttpLws) + L";(", charset_val),
143 E : charset_end);
144 : }
145 : }
146 :
147 : // If the server sent "*/*", it is meaningless, so do not store it.
148 : // Also, if type_val is the same as mime_type, then just update the charset
149 : // However, if charset is empty and mime_type hasn't changed, then don't
150 : // wipe-out an existing charset. We also want to reject a mime-type if it does
151 : // not include a slash. Some servers give junk after the charset parameter,
152 : // which may include a comma, so this check makes us a bit more tolerant.
153 : if (content_type_str.length() != 0 &&
154 : content_type_str != L"*/*" &&
155 E : content_type_str.find_first_of(L'/') != base::string16::npos) {
156 : // The common case here is that mime_type is empty.
157 : bool eq = !mime_type->empty() &&
158 : base::LowerCaseEqualsASCII(
159 : base::StringPiece16(begin + type_val, begin + type_end),
160 E : base::WideToUTF8(*mime_type).data());
161 E : if (!eq) {
162 E : mime_type->assign(begin + type_val, begin + type_end);
163 E : *mime_type = base::ToLowerASCII(*mime_type);
164 : }
165 E : if ((!eq && *had_charset) || type_has_charset) {
166 E : *had_charset = true;
167 E : charset->assign(begin + charset_val, begin + charset_end);
168 E : *charset = base::ToLowerASCII(*charset);
169 : }
170 : }
171 E : }
172 :
173 : bool DecomposeUrl(const base::string16& url,
174 : base::string16* scheme,
175 : base::string16* host,
176 : uint16_t* port,
177 E : base::string16* path) {
178 E : DCHECK(scheme);
179 E : DCHECK(host);
180 E : DCHECK(path);
181 :
182 : wchar_t scheme_buffer[16], host_buffer[256], path_buffer[256];
183 : URL_COMPONENTS components;
184 E : memset(&components, 0, sizeof(components));
185 E : components.dwStructSize = sizeof(components);
186 E : components.lpszScheme = scheme_buffer;
187 E : components.dwSchemeLength = sizeof(scheme_buffer) / sizeof(scheme_buffer[0]);
188 E : components.lpszHostName = host_buffer;
189 E : components.dwHostNameLength = sizeof(host_buffer) / sizeof(host_buffer[0]);
190 E : components.lpszUrlPath = path_buffer;
191 E : components.dwUrlPathLength = sizeof(path_buffer) / sizeof(path_buffer[0]);
192 E : if (!::WinHttpCrackUrl(url.c_str(), 0, 0, &components))
193 E : return false;
194 E : *scheme = scheme_buffer;
195 E : *host = host_buffer;
196 E : *path = path_buffer;
197 E : *port = components.nPort;
198 E : return true;
199 E : }
200 :
201 : base::string16 ComposeUrl(const base::string16& host,
202 : uint16_t port,
203 : const base::string16& path,
204 E : bool secure) {
205 E : if (secure) {
206 E : if (port == 443)
207 E : return L"https://" + host + path;
208 E : return L"https://" + host + L':' + base::UintToString16(port) + path;
209 : }
210 E : if (port == 80)
211 E : return L"http://" + host + path;
212 E : return L"http://" + host + L':' + base::UintToString16(port) + path;
213 E : }
214 :
215 E : base::string16 GenerateMultipartHttpRequestBoundary() {
216 : // The boundary has 27 '-' characters followed by 16 hex digits.
217 : static const base::char16 kBoundaryPrefix[] = L"---------------------------";
218 : static const size_t kBoundaryLength = 27 + 16;
219 :
220 : // Generate some random numbers to fill out the boundary.
221 E : int r0 = rand();
222 E : int r1 = rand();
223 :
224 : // Add one character for the NULL termination.
225 : base::char16 temp[kBoundaryLength + 1];
226 : ::swprintf(temp, sizeof(temp) / sizeof(*temp), L"%s%08X%08X", kBoundaryPrefix,
227 E : r0, r1);
228 :
229 E : return base::string16(temp, kBoundaryLength);
230 E : }
231 :
232 : base::string16 GenerateMultipartHttpRequestContentTypeHeader(
233 E : const base::string16 boundary) {
234 E : return L"Content-Type: multipart/form-data; boundary=" + boundary;
235 E : }
236 :
237 : std::string GenerateMultipartHttpRequestBody(
238 : const std::map<base::string16, base::string16>& parameters,
239 : const std::string& upload_file,
240 : const base::string16& file_part_name,
241 E : const base::string16& boundary) {
242 E : DCHECK(!boundary.empty());
243 E : DCHECK(!file_part_name.empty());
244 E : std::string boundary_utf8 = base::WideToUTF8(boundary);
245 :
246 E : std::string request_body;
247 :
248 : // Append each of the parameter pairs as a form-data part.
249 E : for (const auto& entry : parameters) {
250 E : request_body.append("--" + boundary_utf8 + "\r\n");
251 : request_body.append("Content-Disposition: form-data; name=\"" +
252 : base::WideToUTF8(entry.first) + "\"\r\n\r\n" +
253 E : base::WideToUTF8(entry.second) + "\r\n");
254 E : }
255 :
256 E : std::string file_part_name_utf8 = base::WideToUTF8(file_part_name);
257 :
258 E : request_body.append("--" + boundary_utf8 + "\r\n");
259 : request_body.append("Content-Disposition: form-data; "
260 : "name=\"" + file_part_name_utf8 + "\"; "
261 E : "filename=\"" + file_part_name_utf8 + "\"\r\n");
262 E : request_body.append("Content-Type: application/octet-stream\r\n");
263 E : request_body.append("\r\n");
264 :
265 E : request_body.append(upload_file);
266 E : request_body.append("\r\n");
267 E : request_body.append("--" + boundary_utf8 + "--\r\n");
268 :
269 E : return request_body;
270 E : }
271 :
272 : } // namespace kasko
|