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 E : if (LowerCaseEqualsASCII(param_name_begin, param_name_end, "charset")) {
115 E : charset_val = param_value_begin - begin;
116 E : charset_end = param_value_end - begin;
117 E : type_has_charset = true;
118 E : } else if (LowerCaseEqualsASCII(param_name_begin, param_name_end,
119 E : "boundary")) {
120 E : if (boundary)
121 E : boundary->assign(param_value_begin, param_value_end);
122 : }
123 E : }
124 E : }
125 :
126 E : if (type_has_charset) {
127 : // Trim leading and trailing whitespace from charset_val. We include '(' in
128 : // the trailing trim set to catch media-type comments, which are not at all
129 : // standard, but may occur in rare cases.
130 E : charset_val = content_type_str.find_first_not_of(kHttpLws, charset_val);
131 E : charset_val = std::min(charset_val, charset_end);
132 E : base::char16 first_char = content_type_str[charset_val];
133 E : if (first_char == L'"' || first_char == L'\'') {
134 E : charset_end = FindStringEnd(content_type_str, charset_val, first_char);
135 E : ++charset_val;
136 E : DCHECK(charset_end >= charset_val);
137 E : } else {
138 : charset_end = std::min(content_type_str.find_first_of(
139 : base::string16(kHttpLws) + L";(", charset_val),
140 E : charset_end);
141 : }
142 : }
143 :
144 : // If the server sent "*/*", it is meaningless, so do not store it.
145 : // Also, if type_val is the same as mime_type, then just update the charset
146 : // However, if charset is empty and mime_type hasn't changed, then don't
147 : // wipe-out an existing charset. We also want to reject a mime-type if it does
148 : // not include a slash. Some servers give junk after the charset parameter,
149 : // which may include a comma, so this check makes us a bit more tolerant.
150 : if (content_type_str.length() != 0 &&
151 : content_type_str != L"*/*" &&
152 E : content_type_str.find_first_of(L'/') != base::string16::npos) {
153 : // The common case here is that mime_type is empty.
154 : bool eq = !mime_type->empty() &&
155 : LowerCaseEqualsASCII(begin + type_val, begin + type_end,
156 E : base::WideToUTF8(*mime_type).data());
157 E : if (!eq) {
158 E : mime_type->assign(begin + type_val, begin + type_end);
159 E : StringToLowerASCII(mime_type);
160 : }
161 E : if ((!eq && *had_charset) || type_has_charset) {
162 E : *had_charset = true;
163 E : charset->assign(begin + charset_val, begin + charset_end);
164 E : StringToLowerASCII(charset);
165 : }
166 : }
167 E : }
168 :
169 : bool DecomposeUrl(const base::string16& url,
170 : base::string16* scheme,
171 : base::string16* host,
172 : uint16_t* port,
173 E : base::string16* path) {
174 E : DCHECK(scheme);
175 E : DCHECK(host);
176 E : DCHECK(path);
177 :
178 : wchar_t scheme_buffer[16], host_buffer[256], path_buffer[256];
179 : URL_COMPONENTS components;
180 E : memset(&components, 0, sizeof(components));
181 E : components.dwStructSize = sizeof(components);
182 E : components.lpszScheme = scheme_buffer;
183 E : components.dwSchemeLength = sizeof(scheme_buffer) / sizeof(scheme_buffer[0]);
184 E : components.lpszHostName = host_buffer;
185 E : components.dwHostNameLength = sizeof(host_buffer) / sizeof(host_buffer[0]);
186 E : components.lpszUrlPath = path_buffer;
187 E : components.dwUrlPathLength = sizeof(path_buffer) / sizeof(path_buffer[0]);
188 E : if (!::WinHttpCrackUrl(url.c_str(), 0, 0, &components))
189 E : return false;
190 E : *scheme = scheme_buffer;
191 E : *host = host_buffer;
192 E : *path = path_buffer;
193 E : *port = components.nPort;
194 E : return true;
195 E : }
196 :
197 : base::string16 ComposeUrl(const base::string16& host,
198 : uint16_t port,
199 : const base::string16& path,
200 E : bool secure) {
201 E : if (secure) {
202 E : if (port == 443)
203 E : return L"https://" + host + path;
204 E : return L"https://" + host + L':' + base::UintToString16(port) + path;
205 : }
206 E : if (port == 80)
207 E : return L"http://" + host + path;
208 E : return L"http://" + host + L':' + base::UintToString16(port) + path;
209 E : }
210 :
211 E : base::string16 GenerateMultipartHttpRequestBoundary() {
212 : // The boundary has 27 '-' characters followed by 16 hex digits.
213 : static const base::char16 kBoundaryPrefix[] = L"---------------------------";
214 : static const size_t kBoundaryLength = 27 + 16;
215 :
216 : // Generate some random numbers to fill out the boundary.
217 E : int r0 = rand();
218 E : int r1 = rand();
219 :
220 : // Add one character for the NULL termination.
221 : base::char16 temp[kBoundaryLength + 1];
222 : ::swprintf(temp, sizeof(temp) / sizeof(*temp), L"%s%08X%08X", kBoundaryPrefix,
223 E : r0, r1);
224 :
225 E : return base::string16(temp, kBoundaryLength);
226 E : }
227 :
228 : base::string16 GenerateMultipartHttpRequestContentTypeHeader(
229 E : const base::string16 boundary) {
230 E : return L"Content-Type: multipart/form-data; boundary=" + boundary;
231 E : }
232 :
233 : std::string GenerateMultipartHttpRequestBody(
234 : const std::map<base::string16, base::string16>& parameters,
235 : const std::string& upload_file,
236 : const base::string16& file_part_name,
237 E : const base::string16& boundary) {
238 E : DCHECK(!boundary.empty());
239 E : DCHECK(!file_part_name.empty());
240 E : std::string boundary_utf8 = base::WideToUTF8(boundary);
241 :
242 E : std::string request_body;
243 :
244 : // Append each of the parameter pairs as a form-data part.
245 E : for (const auto& entry : parameters) {
246 E : request_body.append("--" + boundary_utf8 + "\r\n");
247 : request_body.append("Content-Disposition: form-data; name=\"" +
248 : base::WideToUTF8(entry.first) + "\"\r\n\r\n" +
249 E : base::WideToUTF8(entry.second) + "\r\n");
250 E : }
251 :
252 E : std::string file_part_name_utf8 = base::WideToUTF8(file_part_name);
253 :
254 E : request_body.append("--" + boundary_utf8 + "\r\n");
255 : request_body.append("Content-Disposition: form-data; "
256 : "name=\"" + file_part_name_utf8 + "\"; "
257 E : "filename=\"" + file_part_name_utf8 + "\"\r\n");
258 E : request_body.append("Content-Type: application/octet-stream\r\n");
259 E : request_body.append("\r\n");
260 :
261 E : request_body.append(upload_file);
262 E : request_body.append("\r\n");
263 E : request_body.append("--" + boundary_utf8 + "--\r\n");
264 :
265 E : return request_body;
266 E : }
267 :
268 : } // namespace kasko
|