1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // The rules for parsing content-types were borrowed from Firefox:
6 // http://lxr.mozilla.org/mozilla/source/netwerk/base/src/nsURLHelper.cpp#834
7
8 #include "net/http/http_util.h"
9
10 #include <algorithm>
11 #include <string>
12
13 #include "base/check_op.h"
14 #include "base/strings/strcat.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_piece.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_tokenizer.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/time/time.h"
22 #include "net/base/features.h"
23 #include "net/base/mime_util.h"
24 #include "net/base/parse_number.h"
25 #include "net/base/url_util.h"
26 #include "net/http/http_response_headers.h"
27
28 namespace net {
29
30 namespace {
31
32 template <typename ConstIterator>
TrimLWSImplementation(ConstIterator * begin,ConstIterator * end)33 void TrimLWSImplementation(ConstIterator* begin, ConstIterator* end) {
34 // leading whitespace
35 while (*begin < *end && HttpUtil::IsLWS((*begin)[0]))
36 ++(*begin);
37
38 // trailing whitespace
39 while (*begin < *end && HttpUtil::IsLWS((*end)[-1]))
40 --(*end);
41 }
42
43 // Helper class that builds the list of languages for the Accept-Language
44 // headers.
45 // The output is a comma-separated list of languages as string.
46 // Duplicates are removed.
47 class AcceptLanguageBuilder {
48 public:
49 // Adds a language to the string.
50 // Duplicates are ignored.
AddLanguageCode(const std::string & language)51 void AddLanguageCode(const std::string& language) {
52 // No Q score supported, only supports ASCII.
53 DCHECK_EQ(std::string::npos, language.find_first_of("; "));
54 DCHECK(base::IsStringASCII(language));
55 if (seen_.find(language) == seen_.end()) {
56 if (str_.empty()) {
57 base::StringAppendF(&str_, "%s", language.c_str());
58 } else {
59 base::StringAppendF(&str_, ",%s", language.c_str());
60 }
61 seen_.insert(language);
62 }
63 }
64
65 // Returns the string constructed up to this point.
GetString() const66 std::string GetString() const { return str_; }
67
68 private:
69 // The string that contains the list of languages, comma-separated.
70 std::string str_;
71 // Set the remove duplicates.
72 std::unordered_set<std::string> seen_;
73 };
74
75 // Extract the base language code from a language code.
76 // If there is no '-' in the code, the original code is returned.
GetBaseLanguageCode(const std::string & language_code)77 std::string GetBaseLanguageCode(const std::string& language_code) {
78 const std::vector<std::string> tokens = base::SplitString(
79 language_code, "-", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
80 return tokens.empty() ? "" : tokens[0];
81 }
82
83 } // namespace
84
85 // HttpUtil -------------------------------------------------------------------
86
87 // static
SpecForRequest(const GURL & url)88 std::string HttpUtil::SpecForRequest(const GURL& url) {
89 DCHECK(url.is_valid() &&
90 (url.SchemeIsHTTPOrHTTPS() || url.SchemeIsWSOrWSS()));
91 return SimplifyUrlForRequest(url).spec();
92 }
93
94 // static
ParseContentType(const std::string & content_type_str,std::string * mime_type,std::string * charset,bool * had_charset,std::string * boundary)95 void HttpUtil::ParseContentType(const std::string& content_type_str,
96 std::string* mime_type,
97 std::string* charset,
98 bool* had_charset,
99 std::string* boundary) {
100 std::string mime_type_value;
101 base::StringPairs params;
102 bool result = ParseMimeType(content_type_str, &mime_type_value, ¶ms);
103 // If the server sent "*/*", it is meaningless, so do not store it.
104 // Also, reject a mime-type if it does not include a slash.
105 // Some servers give junk after the charset parameter, which may
106 // include a comma, so this check makes us a bit more tolerant.
107 if (!result || content_type_str == "*/*")
108 return;
109
110 std::string charset_value;
111 bool type_has_charset = false;
112 bool type_has_boundary = false;
113 for (const auto& param : params) {
114 // Trim LWS from param value, ParseMimeType() leaves WS for quoted-string.
115 // TODO(mmenke): Check that name has only valid characters.
116 if (!type_has_charset &&
117 base::EqualsCaseInsensitiveASCII(param.first, "charset")) {
118 type_has_charset = true;
119 charset_value = std::string(HttpUtil::TrimLWS(param.second));
120 continue;
121 }
122
123 if (boundary && !type_has_boundary &&
124 base::EqualsCaseInsensitiveASCII(param.first, "boundary")) {
125 type_has_boundary = true;
126 *boundary = std::string(HttpUtil::TrimLWS(param.second));
127 continue;
128 }
129 }
130
131 // If `mime_type_value` is the same as `mime_type`, then just update
132 // `charset`. However, if `charset` is empty and `mime_type` hasn't changed,
133 // then don't wipe-out an existing `charset`.
134 bool eq = base::EqualsCaseInsensitiveASCII(mime_type_value, *mime_type);
135 if (!eq) {
136 *mime_type = base::ToLowerASCII(mime_type_value);
137 }
138 if ((!eq && *had_charset) || type_has_charset) {
139 *had_charset = true;
140 *charset = base::ToLowerASCII(charset_value);
141 }
142 }
143
144 // static
ParseRangeHeader(const std::string & ranges_specifier,std::vector<HttpByteRange> * ranges)145 bool HttpUtil::ParseRangeHeader(const std::string& ranges_specifier,
146 std::vector<HttpByteRange>* ranges) {
147 size_t equal_char_offset = ranges_specifier.find('=');
148 if (equal_char_offset == std::string::npos)
149 return false;
150
151 // Try to extract bytes-unit part.
152 base::StringPiece bytes_unit =
153 base::StringPiece(ranges_specifier).substr(0, equal_char_offset);
154
155 // "bytes" unit identifier is not found.
156 bytes_unit = TrimLWS(bytes_unit);
157 if (!base::EqualsCaseInsensitiveASCII(bytes_unit, "bytes")) {
158 return false;
159 }
160
161 std::string::const_iterator byte_range_set_begin =
162 ranges_specifier.begin() + equal_char_offset + 1;
163 std::string::const_iterator byte_range_set_end = ranges_specifier.end();
164
165 ValuesIterator byte_range_set_iterator(byte_range_set_begin,
166 byte_range_set_end, ',');
167 while (byte_range_set_iterator.GetNext()) {
168 base::StringPiece value = byte_range_set_iterator.value_piece();
169 size_t minus_char_offset = value.find('-');
170 // If '-' character is not found, reports failure.
171 if (minus_char_offset == std::string::npos)
172 return false;
173
174 base::StringPiece first_byte_pos = value.substr(0, minus_char_offset);
175 first_byte_pos = TrimLWS(first_byte_pos);
176
177 HttpByteRange range;
178 // Try to obtain first-byte-pos.
179 if (!first_byte_pos.empty()) {
180 int64_t first_byte_position = -1;
181 if (!base::StringToInt64(first_byte_pos, &first_byte_position))
182 return false;
183 range.set_first_byte_position(first_byte_position);
184 }
185
186 base::StringPiece last_byte_pos = value.substr(minus_char_offset + 1);
187 last_byte_pos = TrimLWS(last_byte_pos);
188
189 // We have last-byte-pos or suffix-byte-range-spec in this case.
190 if (!last_byte_pos.empty()) {
191 int64_t last_byte_position;
192 if (!base::StringToInt64(last_byte_pos, &last_byte_position))
193 return false;
194 if (range.HasFirstBytePosition())
195 range.set_last_byte_position(last_byte_position);
196 else
197 range.set_suffix_length(last_byte_position);
198 } else if (!range.HasFirstBytePosition()) {
199 return false;
200 }
201
202 // Do a final check on the HttpByteRange object.
203 if (!range.IsValid())
204 return false;
205 ranges->push_back(range);
206 }
207 return !ranges->empty();
208 }
209
210 // static
211 // From RFC 2616 14.16:
212 // content-range-spec =
213 // bytes-unit SP byte-range-resp-spec "/" ( instance-length | "*" )
214 // byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*"
215 // instance-length = 1*DIGIT
216 // bytes-unit = "bytes"
ParseContentRangeHeaderFor206(base::StringPiece content_range_spec,int64_t * first_byte_position,int64_t * last_byte_position,int64_t * instance_length)217 bool HttpUtil::ParseContentRangeHeaderFor206(
218 base::StringPiece content_range_spec,
219 int64_t* first_byte_position,
220 int64_t* last_byte_position,
221 int64_t* instance_length) {
222 *first_byte_position = *last_byte_position = *instance_length = -1;
223 content_range_spec = TrimLWS(content_range_spec);
224
225 size_t space_position = content_range_spec.find(' ');
226 if (space_position == base::StringPiece::npos)
227 return false;
228
229 // Invalid header if it doesn't contain "bytes-unit".
230 if (!base::EqualsCaseInsensitiveASCII(
231 TrimLWS(content_range_spec.substr(0, space_position)), "bytes")) {
232 return false;
233 }
234
235 size_t minus_position = content_range_spec.find('-', space_position + 1);
236 if (minus_position == base::StringPiece::npos)
237 return false;
238 size_t slash_position = content_range_spec.find('/', minus_position + 1);
239 if (slash_position == base::StringPiece::npos)
240 return false;
241
242 if (base::StringToInt64(
243 TrimLWS(content_range_spec.substr(
244 space_position + 1, minus_position - (space_position + 1))),
245 first_byte_position) &&
246 *first_byte_position >= 0 &&
247 base::StringToInt64(
248 TrimLWS(content_range_spec.substr(
249 minus_position + 1, slash_position - (minus_position + 1))),
250 last_byte_position) &&
251 *last_byte_position >= *first_byte_position &&
252 base::StringToInt64(
253 TrimLWS(content_range_spec.substr(slash_position + 1)),
254 instance_length) &&
255 *instance_length > *last_byte_position) {
256 return true;
257 }
258 *first_byte_position = *last_byte_position = *instance_length = -1;
259 return false;
260 }
261
262 // static
ParseRetryAfterHeader(const std::string & retry_after_string,base::Time now,base::TimeDelta * retry_after)263 bool HttpUtil::ParseRetryAfterHeader(const std::string& retry_after_string,
264 base::Time now,
265 base::TimeDelta* retry_after) {
266 uint32_t seconds;
267 base::Time time;
268 base::TimeDelta interval;
269
270 if (net::ParseUint32(retry_after_string, ParseIntFormat::NON_NEGATIVE,
271 &seconds)) {
272 interval = base::Seconds(seconds);
273 } else if (base::Time::FromUTCString(retry_after_string.c_str(), &time)) {
274 interval = time - now;
275 } else {
276 return false;
277 }
278
279 if (interval < base::Seconds(0))
280 return false;
281
282 *retry_after = interval;
283 return true;
284 }
285
286 // static
TimeFormatHTTP(base::Time time)287 std::string HttpUtil::TimeFormatHTTP(base::Time time) {
288 static constexpr char kWeekdayName[7][4] = {"Sun", "Mon", "Tue", "Wed",
289 "Thu", "Fri", "Sat"};
290 static constexpr char kMonthName[12][4] = {"Jan", "Feb", "Mar", "Apr",
291 "May", "Jun", "Jul", "Aug",
292 "Sep", "Oct", "Nov", "Dec"};
293 base::Time::Exploded exploded;
294 time.UTCExplode(&exploded);
295 return base::StringPrintf(
296 "%s, %02d %s %04d %02d:%02d:%02d GMT", kWeekdayName[exploded.day_of_week],
297 exploded.day_of_month, kMonthName[exploded.month - 1], exploded.year,
298 exploded.hour, exploded.minute, exploded.second);
299 }
300
301 namespace {
302
303 // A header string containing any of the following fields will cause
304 // an error. The list comes from the fetch standard.
305 const char* const kForbiddenHeaderFields[] = {
306 "accept-charset",
307 "accept-encoding",
308 "access-control-request-headers",
309 "access-control-request-method",
310 "access-control-request-private-network",
311 "connection",
312 "content-length",
313 "cookie",
314 "cookie2",
315 "date",
316 "dnt",
317 "expect",
318 "host",
319 "keep-alive",
320 "origin",
321 "referer",
322 "set-cookie",
323 "te",
324 "trailer",
325 "transfer-encoding",
326 "upgrade",
327 // TODO(mmenke): This is no longer banned, but still here due to issues
328 // mentioned in https://crbug.com/571722.
329 "user-agent",
330 "via",
331 };
332
333 // A header string containing any of the following fields with a forbidden
334 // method name in the value will cause an error. The list comes from the fetch
335 // standard.
336 const char* const kForbiddenHeaderFieldsWithForbiddenMethod[] = {
337 "x-http-method",
338 "x-http-method-override",
339 "x-method-override",
340 };
341
342 // The forbidden method names that is defined in the fetch standard, and used
343 // to check the kForbiddenHeaderFileWithForbiddenMethod above.
344 const char* const kForbiddenMethods[] = {
345 "connect",
346 "trace",
347 "track",
348 };
349
350 } // namespace
351
352 // static
IsMethodSafe(base::StringPiece method)353 bool HttpUtil::IsMethodSafe(base::StringPiece method) {
354 return method == "GET" || method == "HEAD" || method == "OPTIONS" ||
355 method == "TRACE";
356 }
357
358 // static
IsMethodIdempotent(base::StringPiece method)359 bool HttpUtil::IsMethodIdempotent(base::StringPiece method) {
360 return IsMethodSafe(method) || method == "PUT" || method == "DELETE";
361 }
362
363 // static
IsSafeHeader(base::StringPiece name,base::StringPiece value)364 bool HttpUtil::IsSafeHeader(base::StringPiece name, base::StringPiece value) {
365 if (base::StartsWith(name, "proxy-", base::CompareCase::INSENSITIVE_ASCII) ||
366 base::StartsWith(name, "sec-", base::CompareCase::INSENSITIVE_ASCII))
367 return false;
368
369 for (const char* field : kForbiddenHeaderFields) {
370 if (base::EqualsCaseInsensitiveASCII(name, field))
371 return false;
372 }
373
374 if (base::FeatureList::IsEnabled(features::kBlockNewForbiddenHeaders)) {
375 bool is_forbidden_header_fields_with_forbidden_method = false;
376 for (const char* field : kForbiddenHeaderFieldsWithForbiddenMethod) {
377 if (base::EqualsCaseInsensitiveASCII(name, field)) {
378 is_forbidden_header_fields_with_forbidden_method = true;
379 break;
380 }
381 }
382 if (is_forbidden_header_fields_with_forbidden_method) {
383 std::string value_string(value);
384 ValuesIterator method_iterator(value_string.begin(), value_string.end(),
385 ',');
386 while (method_iterator.GetNext()) {
387 base::StringPiece method = method_iterator.value_piece();
388 for (const char* forbidden_method : kForbiddenMethods) {
389 if (base::EqualsCaseInsensitiveASCII(method, forbidden_method))
390 return false;
391 }
392 }
393 }
394 }
395 return true;
396 }
397
398 // static
IsValidHeaderName(base::StringPiece name)399 bool HttpUtil::IsValidHeaderName(base::StringPiece name) {
400 // Check whether the header name is RFC 2616-compliant.
401 return HttpUtil::IsToken(name);
402 }
403
404 // static
IsValidHeaderValue(base::StringPiece value)405 bool HttpUtil::IsValidHeaderValue(base::StringPiece value) {
406 // Just a sanity check: disallow NUL, CR and LF.
407 for (char c : value) {
408 if (c == '\0' || c == '\r' || c == '\n')
409 return false;
410 }
411 return true;
412 }
413
414 // static
IsNonCoalescingHeader(base::StringPiece name)415 bool HttpUtil::IsNonCoalescingHeader(base::StringPiece name) {
416 // NOTE: "set-cookie2" headers do not support expires attributes, so we don't
417 // have to list them here.
418 // As of 2023, using FlatSet here actually makes the lookup slower, and
419 // unordered_set is even slower than that.
420 static constexpr base::StringPiece kNonCoalescingHeaders[] = {
421 "date", "expires", "last-modified",
422 "location", // See bug 1050541 for details
423 "retry-after", "set-cookie",
424 // The format of auth-challenges mixes both space separated tokens and
425 // comma separated properties, so coalescing on comma won't work.
426 "www-authenticate", "proxy-authenticate",
427 // STS specifies that UAs must not process any STS headers after the first
428 // one.
429 "strict-transport-security"};
430
431 for (const base::StringPiece& header : kNonCoalescingHeaders) {
432 if (base::EqualsCaseInsensitiveASCII(name, header)) {
433 return true;
434 }
435 }
436 return false;
437 }
438
439 // static
TrimLWS(std::string::const_iterator * begin,std::string::const_iterator * end)440 void HttpUtil::TrimLWS(std::string::const_iterator* begin,
441 std::string::const_iterator* end) {
442 TrimLWSImplementation(begin, end);
443 }
444
445 // static
TrimLWS(base::StringPiece string)446 base::StringPiece HttpUtil::TrimLWS(base::StringPiece string) {
447 const char* begin = string.data();
448 const char* end = string.data() + string.size();
449 TrimLWSImplementation(&begin, &end);
450 return base::StringPiece(begin, end - begin);
451 }
452
IsTokenChar(char c)453 bool HttpUtil::IsTokenChar(char c) {
454 return !(c >= 0x7F || c <= 0x20 || c == '(' || c == ')' || c == '<' ||
455 c == '>' || c == '@' || c == ',' || c == ';' || c == ':' ||
456 c == '\\' || c == '"' || c == '/' || c == '[' || c == ']' ||
457 c == '?' || c == '=' || c == '{' || c == '}');
458 }
459
460 // See RFC 7230 Sec 3.2.6 for the definition of |token|.
IsToken(base::StringPiece string)461 bool HttpUtil::IsToken(base::StringPiece string) {
462 if (string.empty())
463 return false;
464 for (char c : string) {
465 if (!IsTokenChar(c))
466 return false;
467 }
468 return true;
469 }
470
471 // See RFC 5987 Sec 3.2.1 for the definition of |parmname|.
IsParmName(base::StringPiece str)472 bool HttpUtil::IsParmName(base::StringPiece str) {
473 if (str.empty())
474 return false;
475 for (char c : str) {
476 if (!IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
477 return false;
478 }
479 return true;
480 }
481
482 namespace {
483
IsQuote(char c)484 bool IsQuote(char c) {
485 return c == '"';
486 }
487
UnquoteImpl(base::StringPiece str,bool strict_quotes,std::string * out)488 bool UnquoteImpl(base::StringPiece str, bool strict_quotes, std::string* out) {
489 if (str.empty())
490 return false;
491
492 // Nothing to unquote.
493 if (!IsQuote(str[0]))
494 return false;
495
496 // No terminal quote mark.
497 if (str.size() < 2 || str.front() != str.back())
498 return false;
499
500 // Strip quotemarks
501 str.remove_prefix(1);
502 str.remove_suffix(1);
503
504 // Unescape quoted-pair (defined in RFC 2616 section 2.2)
505 bool prev_escape = false;
506 std::string unescaped;
507 for (char c : str) {
508 if (c == '\\' && !prev_escape) {
509 prev_escape = true;
510 continue;
511 }
512 if (strict_quotes && !prev_escape && IsQuote(c))
513 return false;
514 prev_escape = false;
515 unescaped.push_back(c);
516 }
517
518 // Terminal quote is escaped.
519 if (strict_quotes && prev_escape)
520 return false;
521
522 *out = std::move(unescaped);
523 return true;
524 }
525
526 } // anonymous namespace
527
528 // static
Unquote(base::StringPiece str)529 std::string HttpUtil::Unquote(base::StringPiece str) {
530 std::string result;
531 if (!UnquoteImpl(str, false, &result))
532 return std::string(str);
533
534 return result;
535 }
536
537 // static
StrictUnquote(base::StringPiece str,std::string * out)538 bool HttpUtil::StrictUnquote(base::StringPiece str, std::string* out) {
539 return UnquoteImpl(str, true, out);
540 }
541
542 // static
Quote(base::StringPiece str)543 std::string HttpUtil::Quote(base::StringPiece str) {
544 std::string escaped;
545 escaped.reserve(2 + str.size());
546
547 // Esape any backslashes or quotemarks within the string, and
548 // then surround with quotes.
549 escaped.push_back('"');
550 for (char c : str) {
551 if (c == '"' || c == '\\')
552 escaped.push_back('\\');
553 escaped.push_back(c);
554 }
555 escaped.push_back('"');
556 return escaped;
557 }
558
559 // Find the "http" substring in a status line. This allows for
560 // some slop at the start. If the "http" string could not be found
561 // then returns std::string::npos.
562 // static
LocateStartOfStatusLine(const char * buf,size_t buf_len)563 size_t HttpUtil::LocateStartOfStatusLine(const char* buf, size_t buf_len) {
564 const size_t slop = 4;
565 const size_t http_len = 4;
566
567 if (buf_len >= http_len) {
568 size_t i_max = std::min(buf_len - http_len, slop);
569 for (size_t i = 0; i <= i_max; ++i) {
570 if (base::EqualsCaseInsensitiveASCII(base::StringPiece(buf + i, http_len),
571 "http"))
572 return i;
573 }
574 }
575 return std::string::npos; // Not found
576 }
577
LocateEndOfHeadersHelper(const char * buf,size_t buf_len,size_t i,bool accept_empty_header_list)578 static size_t LocateEndOfHeadersHelper(const char* buf,
579 size_t buf_len,
580 size_t i,
581 bool accept_empty_header_list) {
582 char last_c = '\0';
583 bool was_lf = false;
584 if (accept_empty_header_list) {
585 // Normally two line breaks signal the end of a header list. An empty header
586 // list ends with a single line break at the start of the buffer.
587 last_c = '\n';
588 was_lf = true;
589 }
590
591 for (; i < buf_len; ++i) {
592 char c = buf[i];
593 if (c == '\n') {
594 if (was_lf)
595 return i + 1;
596 was_lf = true;
597 } else if (c != '\r' || last_c != '\n') {
598 was_lf = false;
599 }
600 last_c = c;
601 }
602 return std::string::npos;
603 }
604
LocateEndOfAdditionalHeaders(const char * buf,size_t buf_len,size_t i)605 size_t HttpUtil::LocateEndOfAdditionalHeaders(const char* buf,
606 size_t buf_len,
607 size_t i) {
608 return LocateEndOfHeadersHelper(buf, buf_len, i, true);
609 }
610
LocateEndOfHeaders(const char * buf,size_t buf_len,size_t i)611 size_t HttpUtil::LocateEndOfHeaders(const char* buf, size_t buf_len, size_t i) {
612 return LocateEndOfHeadersHelper(buf, buf_len, i, false);
613 }
614
615 // In order for a line to be continuable, it must specify a
616 // non-blank header-name. Line continuations are specifically for
617 // header values -- do not allow headers names to span lines.
IsLineSegmentContinuable(base::StringPiece line)618 static bool IsLineSegmentContinuable(base::StringPiece line) {
619 if (line.empty())
620 return false;
621
622 size_t colon = line.find(':');
623 if (colon == base::StringPiece::npos)
624 return false;
625
626 base::StringPiece name = line.substr(0, colon);
627
628 // Name can't be empty.
629 if (name.empty())
630 return false;
631
632 // Can't start with LWS (this would imply the segment is a continuation)
633 if (HttpUtil::IsLWS(name[0]))
634 return false;
635
636 return true;
637 }
638
639 // Helper used by AssembleRawHeaders, to find the end of the status line.
FindStatusLineEnd(base::StringPiece str)640 static size_t FindStatusLineEnd(base::StringPiece str) {
641 size_t i = str.find_first_of("\r\n");
642 if (i == base::StringPiece::npos)
643 return str.size();
644 return i;
645 }
646
647 // Helper used by AssembleRawHeaders, to skip past leading LWS.
RemoveLeadingNonLWS(base::StringPiece str)648 static base::StringPiece RemoveLeadingNonLWS(base::StringPiece str) {
649 for (size_t i = 0; i < str.size(); i++) {
650 if (!HttpUtil::IsLWS(str[i]))
651 return str.substr(i);
652 }
653 return base::StringPiece(); // Remove everything.
654 }
655
AssembleRawHeaders(base::StringPiece input)656 std::string HttpUtil::AssembleRawHeaders(base::StringPiece input) {
657 std::string raw_headers;
658 raw_headers.reserve(input.size());
659
660 // Skip any leading slop, since the consumers of this output
661 // (HttpResponseHeaders) don't deal with it.
662 size_t status_begin_offset =
663 LocateStartOfStatusLine(input.data(), input.size());
664 if (status_begin_offset != std::string::npos)
665 input.remove_prefix(status_begin_offset);
666
667 // Copy the status line.
668 size_t status_line_end = FindStatusLineEnd(input);
669 raw_headers.append(input.data(), status_line_end);
670 input.remove_prefix(status_line_end);
671
672 // After the status line, every subsequent line is a header line segment.
673 // Should a segment start with LWS, it is a continuation of the previous
674 // line's field-value.
675
676 // TODO(ericroman): is this too permissive? (delimits on [\r\n]+)
677 base::CStringTokenizer lines(input.data(), input.data() + input.size(),
678 "\r\n");
679
680 // This variable is true when the previous line was continuable.
681 bool prev_line_continuable = false;
682
683 while (lines.GetNext()) {
684 base::StringPiece line = lines.token_piece();
685
686 if (prev_line_continuable && IsLWS(line[0])) {
687 // Join continuation; reduce the leading LWS to a single SP.
688 base::StrAppend(&raw_headers, {" ", RemoveLeadingNonLWS(line)});
689 } else {
690 // Terminate the previous line and copy the raw data to output.
691 base::StrAppend(&raw_headers, {"\n", line});
692
693 // Check if the current line can be continued.
694 prev_line_continuable = IsLineSegmentContinuable(line);
695 }
696 }
697
698 raw_headers.append("\n\n", 2);
699
700 // Use '\0' as the canonical line terminator. If the input already contained
701 // any embeded '\0' characters we will strip them first to avoid interpreting
702 // them as line breaks.
703 std::erase(raw_headers, '\0');
704
705 std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
706
707 return raw_headers;
708 }
709
ConvertHeadersBackToHTTPResponse(const std::string & str)710 std::string HttpUtil::ConvertHeadersBackToHTTPResponse(const std::string& str) {
711 std::string disassembled_headers;
712 base::StringTokenizer tokenizer(str, std::string(1, '\0'));
713 while (tokenizer.GetNext()) {
714 base::StrAppend(&disassembled_headers, {tokenizer.token_piece(), "\r\n"});
715 }
716 disassembled_headers.append("\r\n");
717
718 return disassembled_headers;
719 }
720
ExpandLanguageList(const std::string & language_prefs)721 std::string HttpUtil::ExpandLanguageList(const std::string& language_prefs) {
722 const std::vector<std::string> languages = base::SplitString(
723 language_prefs, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
724
725 if (languages.empty())
726 return "";
727
728 AcceptLanguageBuilder builder;
729
730 const size_t size = languages.size();
731 for (size_t i = 0; i < size; ++i) {
732 const std::string& language = languages[i];
733 builder.AddLanguageCode(language);
734
735 // Extract the primary language subtag.
736 const std::string& base_language = GetBaseLanguageCode(language);
737
738 // Skip 'x' and 'i' as a primary language subtag per RFC 5646 section 2.1.1.
739 if (base_language == "x" || base_language == "i")
740 continue;
741
742 // Look ahead and add the primary language subtag as a language if the next
743 // language is not part of the same family. This may not be perfect because
744 // an input of "en-US,fr,en" will yield "en-US,en,fr,en" and later make "en"
745 // a higher priority than "fr" despite the original preference.
746 const size_t j = i + 1;
747 if (j >= size || GetBaseLanguageCode(languages[j]) != base_language) {
748 builder.AddLanguageCode(base_language);
749 }
750 }
751
752 return builder.GetString();
753 }
754
755 // TODO(jungshik): This function assumes that the input is a comma separated
756 // list without any whitespace. As long as it comes from the preference and
757 // a user does not manually edit the preference file, it's the case. Still,
758 // we may have to make it more robust.
GenerateAcceptLanguageHeader(const std::string & raw_language_list)759 std::string HttpUtil::GenerateAcceptLanguageHeader(
760 const std::string& raw_language_list) {
761 // We use integers for qvalue and qvalue decrement that are 10 times
762 // larger than actual values to avoid a problem with comparing
763 // two floating point numbers.
764 const unsigned int kQvalueDecrement10 = 1;
765 unsigned int qvalue10 = 10;
766 base::StringTokenizer t(raw_language_list, ",");
767 std::string lang_list_with_q;
768 while (t.GetNext()) {
769 std::string language = t.token();
770 if (qvalue10 == 10) {
771 // q=1.0 is implicit.
772 lang_list_with_q = language;
773 } else {
774 DCHECK_LT(qvalue10, 10U);
775 base::StringAppendF(&lang_list_with_q, ",%s;q=0.%d", language.c_str(),
776 qvalue10);
777 }
778 // It does not make sense to have 'q=0'.
779 if (qvalue10 > kQvalueDecrement10)
780 qvalue10 -= kQvalueDecrement10;
781 }
782 return lang_list_with_q;
783 }
784
HasStrongValidators(HttpVersion version,const std::string & etag_header,const std::string & last_modified_header,const std::string & date_header)785 bool HttpUtil::HasStrongValidators(HttpVersion version,
786 const std::string& etag_header,
787 const std::string& last_modified_header,
788 const std::string& date_header) {
789 if (!HasValidators(version, etag_header, last_modified_header))
790 return false;
791
792 if (version < HttpVersion(1, 1))
793 return false;
794
795 if (!etag_header.empty()) {
796 size_t slash = etag_header.find('/');
797 if (slash == std::string::npos || slash == 0)
798 return true;
799
800 std::string::const_iterator i = etag_header.begin();
801 std::string::const_iterator j = etag_header.begin() + slash;
802 TrimLWS(&i, &j);
803 if (!base::EqualsCaseInsensitiveASCII(base::MakeStringPiece(i, j), "w"))
804 return true;
805 }
806
807 base::Time last_modified;
808 if (!base::Time::FromString(last_modified_header.c_str(), &last_modified))
809 return false;
810
811 base::Time date;
812 if (!base::Time::FromString(date_header.c_str(), &date))
813 return false;
814
815 // Last-Modified is implicitly weak unless it is at least 60 seconds before
816 // the Date value.
817 return ((date - last_modified).InSeconds() >= 60);
818 }
819
HasValidators(HttpVersion version,const std::string & etag_header,const std::string & last_modified_header)820 bool HttpUtil::HasValidators(HttpVersion version,
821 const std::string& etag_header,
822 const std::string& last_modified_header) {
823 if (version < HttpVersion(1, 0))
824 return false;
825
826 base::Time last_modified;
827 if (base::Time::FromString(last_modified_header.c_str(), &last_modified))
828 return true;
829
830 // It is OK to consider an empty string in etag_header to be a missing header
831 // since valid ETags are always quoted-strings (see RFC 2616 3.11) and thus
832 // empty ETags aren't empty strings (i.e., an empty ETag might be "\"\"").
833 return version >= HttpVersion(1, 1) && !etag_header.empty();
834 }
835
836 // Functions for histogram initialization. The code 0 is put in the map to
837 // track status codes that are invalid.
838 // TODO(gavinp): Greatly prune the collected codes once we learn which
839 // ones are not sent in practice, to reduce upload size & memory use.
840
841 enum {
842 HISTOGRAM_MIN_HTTP_STATUS_CODE = 100,
843 HISTOGRAM_MAX_HTTP_STATUS_CODE = 599,
844 };
845
846 // static
GetStatusCodesForHistogram()847 std::vector<int> HttpUtil::GetStatusCodesForHistogram() {
848 std::vector<int> codes;
849 codes.reserve(
850 HISTOGRAM_MAX_HTTP_STATUS_CODE - HISTOGRAM_MIN_HTTP_STATUS_CODE + 2);
851 codes.push_back(0);
852 for (int i = HISTOGRAM_MIN_HTTP_STATUS_CODE;
853 i <= HISTOGRAM_MAX_HTTP_STATUS_CODE; ++i)
854 codes.push_back(i);
855 return codes;
856 }
857
858 // static
MapStatusCodeForHistogram(int code)859 int HttpUtil::MapStatusCodeForHistogram(int code) {
860 if (HISTOGRAM_MIN_HTTP_STATUS_CODE <= code &&
861 code <= HISTOGRAM_MAX_HTTP_STATUS_CODE)
862 return code;
863 return 0;
864 }
865
866 // BNF from section 4.2 of RFC 2616:
867 //
868 // message-header = field-name ":" [ field-value ]
869 // field-name = token
870 // field-value = *( field-content | LWS )
871 // field-content = <the OCTETs making up the field-value
872 // and consisting of either *TEXT or combinations
873 // of token, separators, and quoted-string>
874 //
875
HeadersIterator(std::string::const_iterator headers_begin,std::string::const_iterator headers_end,const std::string & line_delimiter)876 HttpUtil::HeadersIterator::HeadersIterator(
877 std::string::const_iterator headers_begin,
878 std::string::const_iterator headers_end,
879 const std::string& line_delimiter)
880 : lines_(headers_begin, headers_end, line_delimiter) {
881 }
882
883 HttpUtil::HeadersIterator::~HeadersIterator() = default;
884
GetNext()885 bool HttpUtil::HeadersIterator::GetNext() {
886 while (lines_.GetNext()) {
887 name_begin_ = lines_.token_begin();
888 values_end_ = lines_.token_end();
889
890 std::string::const_iterator colon(std::find(name_begin_, values_end_, ':'));
891 if (colon == values_end_)
892 continue; // skip malformed header
893
894 name_end_ = colon;
895
896 // If the name starts with LWS, it is an invalid line.
897 // Leading LWS implies a line continuation, and these should have
898 // already been joined by AssembleRawHeaders().
899 if (name_begin_ == name_end_ || IsLWS(*name_begin_))
900 continue;
901
902 TrimLWS(&name_begin_, &name_end_);
903 DCHECK(name_begin_ < name_end_);
904 if (!IsToken(base::MakeStringPiece(name_begin_, name_end_)))
905 continue; // skip malformed header
906
907 values_begin_ = colon + 1;
908 TrimLWS(&values_begin_, &values_end_);
909
910 // if we got a header name, then we are done.
911 return true;
912 }
913 return false;
914 }
915
AdvanceTo(const char * name)916 bool HttpUtil::HeadersIterator::AdvanceTo(const char* name) {
917 DCHECK(name != nullptr);
918 DCHECK_EQ(0, base::ToLowerASCII(name).compare(name))
919 << "the header name must be in all lower case";
920
921 while (GetNext()) {
922 if (base::EqualsCaseInsensitiveASCII(
923 base::MakeStringPiece(name_begin_, name_end_), name)) {
924 return true;
925 }
926 }
927
928 return false;
929 }
930
ValuesIterator(std::string::const_iterator values_begin,std::string::const_iterator values_end,char delimiter,bool ignore_empty_values)931 HttpUtil::ValuesIterator::ValuesIterator(
932 std::string::const_iterator values_begin,
933 std::string::const_iterator values_end,
934 char delimiter,
935 bool ignore_empty_values)
936 : values_(values_begin, values_end, std::string(1, delimiter)),
937 ignore_empty_values_(ignore_empty_values) {
938 values_.set_quote_chars("\"");
939 // Could set this unconditionally, since code below has to check for empty
940 // values after trimming, anyways, but may provide a minor performance
941 // improvement.
942 if (!ignore_empty_values_)
943 values_.set_options(base::StringTokenizer::RETURN_EMPTY_TOKENS);
944 }
945
946 HttpUtil::ValuesIterator::ValuesIterator(const ValuesIterator& other) = default;
947
948 HttpUtil::ValuesIterator::~ValuesIterator() = default;
949
GetNext()950 bool HttpUtil::ValuesIterator::GetNext() {
951 while (values_.GetNext()) {
952 value_begin_ = values_.token_begin();
953 value_end_ = values_.token_end();
954 TrimLWS(&value_begin_, &value_end_);
955
956 if (!ignore_empty_values_ || value_begin_ != value_end_)
957 return true;
958 }
959 return false;
960 }
961
NameValuePairsIterator(std::string::const_iterator begin,std::string::const_iterator end,char delimiter,Values optional_values,Quotes strict_quotes)962 HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
963 std::string::const_iterator begin,
964 std::string::const_iterator end,
965 char delimiter,
966 Values optional_values,
967 Quotes strict_quotes)
968 : props_(begin, end, delimiter),
969 name_begin_(end),
970 name_end_(end),
971 value_begin_(end),
972 value_end_(end),
973 values_optional_(optional_values == Values::NOT_REQUIRED),
974 strict_quotes_(strict_quotes == Quotes::STRICT_QUOTES) {}
975
NameValuePairsIterator(std::string::const_iterator begin,std::string::const_iterator end,char delimiter)976 HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
977 std::string::const_iterator begin,
978 std::string::const_iterator end,
979 char delimiter)
980 : NameValuePairsIterator(begin,
981 end,
982 delimiter,
983 Values::REQUIRED,
984 Quotes::NOT_STRICT) {}
985
986 HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
987 const NameValuePairsIterator& other) = default;
988
989 HttpUtil::NameValuePairsIterator::~NameValuePairsIterator() = default;
990
991 // We expect properties to be formatted as one of:
992 // name="value"
993 // name='value'
994 // name='\'value\''
995 // name=value
996 // name = value
997 // name (if values_optional_ is true)
998 // Due to buggy implementations found in some embedded devices, we also
999 // accept values with missing close quotemark (http://crbug.com/39836):
1000 // name="value
GetNext()1001 bool HttpUtil::NameValuePairsIterator::GetNext() {
1002 if (!props_.GetNext())
1003 return false;
1004
1005 // Set the value as everything. Next we will split out the name.
1006 value_begin_ = props_.value_begin();
1007 value_end_ = props_.value_end();
1008 name_begin_ = name_end_ = value_end_;
1009
1010 // Scan for the equals sign.
1011 std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
1012 if (equals == value_begin_)
1013 return valid_ = false; // Malformed, no name
1014 if (equals == value_end_ && !values_optional_)
1015 return valid_ = false; // Malformed, no equals sign and values are required
1016
1017 // If an equals sign was found, verify that it wasn't inside of quote marks.
1018 if (equals != value_end_) {
1019 for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
1020 if (IsQuote(*it))
1021 return valid_ = false; // Malformed, quote appears before equals sign
1022 }
1023 }
1024
1025 name_begin_ = value_begin_;
1026 name_end_ = equals;
1027 value_begin_ = (equals == value_end_) ? value_end_ : equals + 1;
1028
1029 TrimLWS(&name_begin_, &name_end_);
1030 TrimLWS(&value_begin_, &value_end_);
1031 value_is_quoted_ = false;
1032 unquoted_value_.clear();
1033
1034 if (equals != value_end_ && value_begin_ == value_end_) {
1035 // Malformed; value is empty
1036 return valid_ = false;
1037 }
1038
1039 if (value_begin_ != value_end_ && IsQuote(*value_begin_)) {
1040 value_is_quoted_ = true;
1041
1042 if (strict_quotes_) {
1043 if (!HttpUtil::StrictUnquote(
1044 base::MakeStringPiece(value_begin_, value_end_),
1045 &unquoted_value_))
1046 return valid_ = false;
1047 return true;
1048 }
1049
1050 // Trim surrounding quotemarks off the value
1051 if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_) {
1052 // NOTE: This is not as graceful as it sounds:
1053 // * quoted-pairs will no longer be unquoted
1054 // (["\"hello] should give ["hello]).
1055 // * Does not detect when the final quote is escaped
1056 // (["value\"] should give [value"])
1057 value_is_quoted_ = false;
1058 ++value_begin_; // Gracefully recover from mismatching quotes.
1059 } else {
1060 // Do not store iterators into this. See declaration of unquoted_value_.
1061 unquoted_value_ =
1062 HttpUtil::Unquote(base::MakeStringPiece(value_begin_, value_end_));
1063 }
1064 }
1065
1066 return true;
1067 }
1068
ParseAcceptEncoding(const std::string & accept_encoding,std::set<std::string> * allowed_encodings)1069 bool HttpUtil::ParseAcceptEncoding(const std::string& accept_encoding,
1070 std::set<std::string>* allowed_encodings) {
1071 DCHECK(allowed_encodings);
1072 if (accept_encoding.find_first_of("\"") != std::string::npos)
1073 return false;
1074 allowed_encodings->clear();
1075
1076 base::StringTokenizer tokenizer(accept_encoding.begin(),
1077 accept_encoding.end(), ",");
1078 while (tokenizer.GetNext()) {
1079 base::StringPiece entry = tokenizer.token_piece();
1080 entry = TrimLWS(entry);
1081 size_t semicolon_pos = entry.find(';');
1082 if (semicolon_pos == base::StringPiece::npos) {
1083 if (entry.find_first_of(HTTP_LWS) != base::StringPiece::npos)
1084 return false;
1085 allowed_encodings->insert(base::ToLowerASCII(entry));
1086 continue;
1087 }
1088 base::StringPiece encoding = entry.substr(0, semicolon_pos);
1089 encoding = TrimLWS(encoding);
1090 if (encoding.find_first_of(HTTP_LWS) != base::StringPiece::npos)
1091 return false;
1092 base::StringPiece params = entry.substr(semicolon_pos + 1);
1093 params = TrimLWS(params);
1094 size_t equals_pos = params.find('=');
1095 if (equals_pos == base::StringPiece::npos)
1096 return false;
1097 base::StringPiece param_name = params.substr(0, equals_pos);
1098 param_name = TrimLWS(param_name);
1099 if (!base::EqualsCaseInsensitiveASCII(param_name, "q"))
1100 return false;
1101 base::StringPiece qvalue = params.substr(equals_pos + 1);
1102 qvalue = TrimLWS(qvalue);
1103 if (qvalue.empty())
1104 return false;
1105 if (qvalue[0] == '1') {
1106 if (std::string_view("1.000").starts_with(qvalue)) {
1107 allowed_encodings->insert(base::ToLowerASCII(encoding));
1108 continue;
1109 }
1110 return false;
1111 }
1112 if (qvalue[0] != '0')
1113 return false;
1114 if (qvalue.length() == 1)
1115 continue;
1116 if (qvalue.length() <= 2 || qvalue.length() > 5)
1117 return false;
1118 if (qvalue[1] != '.')
1119 return false;
1120 bool nonzero_number = false;
1121 for (size_t i = 2; i < qvalue.length(); ++i) {
1122 if (!base::IsAsciiDigit(qvalue[i]))
1123 return false;
1124 if (qvalue[i] != '0')
1125 nonzero_number = true;
1126 }
1127 if (nonzero_number)
1128 allowed_encodings->insert(base::ToLowerASCII(encoding));
1129 }
1130
1131 // RFC 7231 5.3.4 "A request without an Accept-Encoding header field implies
1132 // that the user agent has no preferences regarding content-codings."
1133 if (allowed_encodings->empty()) {
1134 allowed_encodings->insert("*");
1135 return true;
1136 }
1137
1138 // Any browser must support "identity".
1139 allowed_encodings->insert("identity");
1140
1141 // RFC says gzip == x-gzip; mirror it here for easier matching.
1142 if (allowed_encodings->find("gzip") != allowed_encodings->end())
1143 allowed_encodings->insert("x-gzip");
1144 if (allowed_encodings->find("x-gzip") != allowed_encodings->end())
1145 allowed_encodings->insert("gzip");
1146
1147 // RFC says compress == x-compress; mirror it here for easier matching.
1148 if (allowed_encodings->find("compress") != allowed_encodings->end())
1149 allowed_encodings->insert("x-compress");
1150 if (allowed_encodings->find("x-compress") != allowed_encodings->end())
1151 allowed_encodings->insert("compress");
1152 return true;
1153 }
1154
ParseContentEncoding(const std::string & content_encoding,std::set<std::string> * used_encodings)1155 bool HttpUtil::ParseContentEncoding(const std::string& content_encoding,
1156 std::set<std::string>* used_encodings) {
1157 DCHECK(used_encodings);
1158 if (content_encoding.find_first_of("\"=;*") != std::string::npos)
1159 return false;
1160 used_encodings->clear();
1161
1162 base::StringTokenizer encoding_tokenizer(content_encoding.begin(),
1163 content_encoding.end(), ",");
1164 while (encoding_tokenizer.GetNext()) {
1165 base::StringPiece encoding = TrimLWS(encoding_tokenizer.token_piece());
1166 if (encoding.find_first_of(HTTP_LWS) != base::StringPiece::npos)
1167 return false;
1168 used_encodings->insert(base::ToLowerASCII(encoding));
1169 }
1170 return true;
1171 }
1172
HeadersContainMultipleCopiesOfField(const HttpResponseHeaders & headers,const std::string & field_name)1173 bool HttpUtil::HeadersContainMultipleCopiesOfField(
1174 const HttpResponseHeaders& headers,
1175 const std::string& field_name) {
1176 size_t it = 0;
1177 std::string field_value;
1178 if (!headers.EnumerateHeader(&it, field_name, &field_value))
1179 return false;
1180 // There's at least one `field_name` header. Check if there are any more
1181 // such headers, and if so, return true if they have different values.
1182 std::string field_value2;
1183 while (headers.EnumerateHeader(&it, field_name, &field_value2)) {
1184 if (field_value != field_value2)
1185 return true;
1186 }
1187 return false;
1188 }
1189
1190 } // namespace net
1191