• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
12 #include "base/check_op.h"
13 #include "base/containers/cxx20_erase.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, &params);
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 namespace {
287 
288 // A header string containing any of the following fields will cause
289 // an error. The list comes from the fetch standard.
290 const char* const kForbiddenHeaderFields[] = {
291     "accept-charset",
292     "accept-encoding",
293     "access-control-request-headers",
294     "access-control-request-method",
295     "access-control-request-private-network",
296     "connection",
297     "content-length",
298     "cookie",
299     "cookie2",
300     "date",
301     "dnt",
302     "expect",
303     "host",
304     "keep-alive",
305     "origin",
306     "referer",
307     "te",
308     "trailer",
309     "transfer-encoding",
310     "upgrade",
311     // TODO(mmenke): This is no longer banned, but still here due to issues
312     // mentioned in https://crbug.com/571722.
313     "user-agent",
314     "via",
315 };
316 
317 // A header string containing any of the following fields with a forbidden
318 // method name in the value will cause an error. The list comes from the fetch
319 // standard.
320 const char* const kForbiddenHeaderFieldsWithForbiddenMethod[] = {
321     "x-http-method",
322     "x-http-method-override",
323     "x-method-override",
324 };
325 
326 // The forbidden method names that is defined in the fetch standard, and used
327 // to check the kForbiddenHeaderFileWithForbiddenMethod above.
328 const char* const kForbiddenMethods[] = {
329     "connect",
330     "trace",
331     "track",
332 };
333 
334 }  // namespace
335 
336 // static
IsMethodSafe(base::StringPiece method)337 bool HttpUtil::IsMethodSafe(base::StringPiece method) {
338   return method == "GET" || method == "HEAD" || method == "OPTIONS" ||
339          method == "TRACE";
340 }
341 
342 // static
IsMethodIdempotent(base::StringPiece method)343 bool HttpUtil::IsMethodIdempotent(base::StringPiece method) {
344   return IsMethodSafe(method) || method == "PUT" || method == "DELETE";
345 }
346 
347 // static
IsSafeHeader(base::StringPiece name,base::StringPiece value)348 bool HttpUtil::IsSafeHeader(base::StringPiece name, base::StringPiece value) {
349   if (base::StartsWith(name, "proxy-", base::CompareCase::INSENSITIVE_ASCII) ||
350       base::StartsWith(name, "sec-", base::CompareCase::INSENSITIVE_ASCII))
351     return false;
352 
353   for (const char* field : kForbiddenHeaderFields) {
354     if (base::EqualsCaseInsensitiveASCII(name, field))
355       return false;
356   }
357 
358   if (base::FeatureList::IsEnabled(features::kBlockSetCookieHeader) &&
359       base::EqualsCaseInsensitiveASCII(name, "set-cookie")) {
360     return false;
361   }
362 
363   if (base::FeatureList::IsEnabled(features::kBlockNewForbiddenHeaders)) {
364     bool is_forbidden_header_fields_with_forbidden_method = false;
365     for (const char* field : kForbiddenHeaderFieldsWithForbiddenMethod) {
366       if (base::EqualsCaseInsensitiveASCII(name, field)) {
367         is_forbidden_header_fields_with_forbidden_method = true;
368         break;
369       }
370     }
371     if (is_forbidden_header_fields_with_forbidden_method) {
372       std::string value_string(value);
373       ValuesIterator method_iterator(value_string.begin(), value_string.end(),
374                                      ',');
375       while (method_iterator.GetNext()) {
376         base::StringPiece method = method_iterator.value_piece();
377         for (const char* forbidden_method : kForbiddenMethods) {
378           if (base::EqualsCaseInsensitiveASCII(method, forbidden_method))
379             return false;
380         }
381       }
382     }
383   }
384   return true;
385 }
386 
387 // static
IsValidHeaderName(base::StringPiece name)388 bool HttpUtil::IsValidHeaderName(base::StringPiece name) {
389   // Check whether the header name is RFC 2616-compliant.
390   return HttpUtil::IsToken(name);
391 }
392 
393 // static
IsValidHeaderValue(base::StringPiece value)394 bool HttpUtil::IsValidHeaderValue(base::StringPiece value) {
395   // Just a sanity check: disallow NUL, CR and LF.
396   for (char c : value) {
397     if (c == '\0' || c == '\r' || c == '\n')
398       return false;
399   }
400   return true;
401 }
402 
403 // static
IsNonCoalescingHeader(base::StringPiece name)404 bool HttpUtil::IsNonCoalescingHeader(base::StringPiece name) {
405   // NOTE: "set-cookie2" headers do not support expires attributes, so we don't
406   // have to list them here.
407   const char* const kNonCoalescingHeaders[] = {
408     "date",
409     "expires",
410     "last-modified",
411     "location",  // See bug 1050541 for details
412     "retry-after",
413     "set-cookie",
414     // The format of auth-challenges mixes both space separated tokens and
415     // comma separated properties, so coalescing on comma won't work.
416     "www-authenticate",
417     "proxy-authenticate",
418     // STS specifies that UAs must not process any STS headers after the first
419     // one.
420     "strict-transport-security"
421   };
422 
423   for (const char* header : kNonCoalescingHeaders) {
424     if (base::EqualsCaseInsensitiveASCII(name, header)) {
425       return true;
426     }
427   }
428   return false;
429 }
430 
IsLWS(char c)431 bool HttpUtil::IsLWS(char c) {
432   const base::StringPiece kWhiteSpaceCharacters(HTTP_LWS);
433   return kWhiteSpaceCharacters.find(c) != base::StringPiece::npos;
434 }
435 
436 // static
TrimLWS(std::string::const_iterator * begin,std::string::const_iterator * end)437 void HttpUtil::TrimLWS(std::string::const_iterator* begin,
438                        std::string::const_iterator* end) {
439   TrimLWSImplementation(begin, end);
440 }
441 
442 // static
TrimLWS(base::StringPiece string)443 base::StringPiece HttpUtil::TrimLWS(base::StringPiece string) {
444   const char* begin = string.data();
445   const char* end = string.data() + string.size();
446   TrimLWSImplementation(&begin, &end);
447   return base::StringPiece(begin, end - begin);
448 }
449 
IsTokenChar(char c)450 bool HttpUtil::IsTokenChar(char c) {
451   return !(c >= 0x7F || c <= 0x20 || c == '(' || c == ')' || c == '<' ||
452            c == '>' || c == '@' || c == ',' || c == ';' || c == ':' ||
453            c == '\\' || c == '"' || c == '/' || c == '[' || c == ']' ||
454            c == '?' || c == '=' || c == '{' || c == '}');
455 }
456 
457 // See RFC 7230 Sec 3.2.6 for the definition of |token|.
IsToken(base::StringPiece string)458 bool HttpUtil::IsToken(base::StringPiece string) {
459   if (string.empty())
460     return false;
461   for (char c : string) {
462     if (!IsTokenChar(c))
463       return false;
464   }
465   return true;
466 }
467 
468 // See RFC 5987 Sec 3.2.1 for the definition of |parmname|.
IsParmName(base::StringPiece str)469 bool HttpUtil::IsParmName(base::StringPiece str) {
470   if (str.empty())
471     return false;
472   for (char c : str) {
473     if (!IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
474       return false;
475   }
476   return true;
477 }
478 
479 namespace {
480 
IsQuote(char c)481 bool IsQuote(char c) {
482   return c == '"';
483 }
484 
UnquoteImpl(base::StringPiece str,bool strict_quotes,std::string * out)485 bool UnquoteImpl(base::StringPiece str, bool strict_quotes, std::string* out) {
486   if (str.empty())
487     return false;
488 
489   // Nothing to unquote.
490   if (!IsQuote(str[0]))
491     return false;
492 
493   // No terminal quote mark.
494   if (str.size() < 2 || str.front() != str.back())
495     return false;
496 
497   // Strip quotemarks
498   str.remove_prefix(1);
499   str.remove_suffix(1);
500 
501   // Unescape quoted-pair (defined in RFC 2616 section 2.2)
502   bool prev_escape = false;
503   std::string unescaped;
504   for (char c : str) {
505     if (c == '\\' && !prev_escape) {
506       prev_escape = true;
507       continue;
508     }
509     if (strict_quotes && !prev_escape && IsQuote(c))
510       return false;
511     prev_escape = false;
512     unescaped.push_back(c);
513   }
514 
515   // Terminal quote is escaped.
516   if (strict_quotes && prev_escape)
517     return false;
518 
519   *out = std::move(unescaped);
520   return true;
521 }
522 
523 }  // anonymous namespace
524 
525 // static
Unquote(base::StringPiece str)526 std::string HttpUtil::Unquote(base::StringPiece str) {
527   std::string result;
528   if (!UnquoteImpl(str, false, &result))
529     return std::string(str);
530 
531   return result;
532 }
533 
534 // static
StrictUnquote(base::StringPiece str,std::string * out)535 bool HttpUtil::StrictUnquote(base::StringPiece str, std::string* out) {
536   return UnquoteImpl(str, true, out);
537 }
538 
539 // static
Quote(base::StringPiece str)540 std::string HttpUtil::Quote(base::StringPiece str) {
541   std::string escaped;
542   escaped.reserve(2 + str.size());
543 
544   // Esape any backslashes or quotemarks within the string, and
545   // then surround with quotes.
546   escaped.push_back('"');
547   for (char c : str) {
548     if (c == '"' || c == '\\')
549       escaped.push_back('\\');
550     escaped.push_back(c);
551   }
552   escaped.push_back('"');
553   return escaped;
554 }
555 
556 // Find the "http" substring in a status line. This allows for
557 // some slop at the start. If the "http" string could not be found
558 // then returns std::string::npos.
559 // static
LocateStartOfStatusLine(const char * buf,size_t buf_len)560 size_t HttpUtil::LocateStartOfStatusLine(const char* buf, size_t buf_len) {
561   const size_t slop = 4;
562   const size_t http_len = 4;
563 
564   if (buf_len >= http_len) {
565     size_t i_max = std::min(buf_len - http_len, slop);
566     for (size_t i = 0; i <= i_max; ++i) {
567       if (base::EqualsCaseInsensitiveASCII(base::StringPiece(buf + i, http_len),
568                                            "http"))
569         return i;
570     }
571   }
572   return std::string::npos;  // Not found
573 }
574 
LocateEndOfHeadersHelper(const char * buf,size_t buf_len,size_t i,bool accept_empty_header_list)575 static size_t LocateEndOfHeadersHelper(const char* buf,
576                                        size_t buf_len,
577                                        size_t i,
578                                        bool accept_empty_header_list) {
579   char last_c = '\0';
580   bool was_lf = false;
581   if (accept_empty_header_list) {
582     // Normally two line breaks signal the end of a header list. An empty header
583     // list ends with a single line break at the start of the buffer.
584     last_c = '\n';
585     was_lf = true;
586   }
587 
588   for (; i < buf_len; ++i) {
589     char c = buf[i];
590     if (c == '\n') {
591       if (was_lf)
592         return i + 1;
593       was_lf = true;
594     } else if (c != '\r' || last_c != '\n') {
595       was_lf = false;
596     }
597     last_c = c;
598   }
599   return std::string::npos;
600 }
601 
LocateEndOfAdditionalHeaders(const char * buf,size_t buf_len,size_t i)602 size_t HttpUtil::LocateEndOfAdditionalHeaders(const char* buf,
603                                               size_t buf_len,
604                                               size_t i) {
605   return LocateEndOfHeadersHelper(buf, buf_len, i, true);
606 }
607 
LocateEndOfHeaders(const char * buf,size_t buf_len,size_t i)608 size_t HttpUtil::LocateEndOfHeaders(const char* buf, size_t buf_len, size_t i) {
609   return LocateEndOfHeadersHelper(buf, buf_len, i, false);
610 }
611 
612 // In order for a line to be continuable, it must specify a
613 // non-blank header-name. Line continuations are specifically for
614 // header values -- do not allow headers names to span lines.
IsLineSegmentContinuable(base::StringPiece line)615 static bool IsLineSegmentContinuable(base::StringPiece line) {
616   if (line.empty())
617     return false;
618 
619   size_t colon = line.find(':');
620   if (colon == base::StringPiece::npos)
621     return false;
622 
623   base::StringPiece name = line.substr(0, colon);
624 
625   // Name can't be empty.
626   if (name.empty())
627     return false;
628 
629   // Can't start with LWS (this would imply the segment is a continuation)
630   if (HttpUtil::IsLWS(name[0]))
631     return false;
632 
633   return true;
634 }
635 
636 // Helper used by AssembleRawHeaders, to find the end of the status line.
FindStatusLineEnd(base::StringPiece str)637 static size_t FindStatusLineEnd(base::StringPiece str) {
638   size_t i = str.find_first_of("\r\n");
639   if (i == base::StringPiece::npos)
640     return str.size();
641   return i;
642 }
643 
644 // Helper used by AssembleRawHeaders, to skip past leading LWS.
RemoveLeadingNonLWS(base::StringPiece str)645 static base::StringPiece RemoveLeadingNonLWS(base::StringPiece str) {
646   for (size_t i = 0; i < str.size(); i++) {
647     if (!HttpUtil::IsLWS(str[i]))
648       return str.substr(i);
649   }
650   return base::StringPiece();  // Remove everything.
651 }
652 
AssembleRawHeaders(base::StringPiece input)653 std::string HttpUtil::AssembleRawHeaders(base::StringPiece input) {
654   std::string raw_headers;
655   raw_headers.reserve(input.size());
656 
657   // Skip any leading slop, since the consumers of this output
658   // (HttpResponseHeaders) don't deal with it.
659   size_t status_begin_offset =
660       LocateStartOfStatusLine(input.data(), input.size());
661   if (status_begin_offset != std::string::npos)
662     input.remove_prefix(status_begin_offset);
663 
664   // Copy the status line.
665   size_t status_line_end = FindStatusLineEnd(input);
666   raw_headers.append(input.data(), status_line_end);
667   input.remove_prefix(status_line_end);
668 
669   // After the status line, every subsequent line is a header line segment.
670   // Should a segment start with LWS, it is a continuation of the previous
671   // line's field-value.
672 
673   // TODO(ericroman): is this too permissive? (delimits on [\r\n]+)
674   base::CStringTokenizer lines(input.data(), input.data() + input.size(),
675                                "\r\n");
676 
677   // This variable is true when the previous line was continuable.
678   bool prev_line_continuable = false;
679 
680   while (lines.GetNext()) {
681     base::StringPiece line = lines.token_piece();
682 
683     if (prev_line_continuable && IsLWS(line[0])) {
684       // Join continuation; reduce the leading LWS to a single SP.
685       base::StrAppend(&raw_headers, {" ", RemoveLeadingNonLWS(line)});
686     } else {
687       // Terminate the previous line and copy the raw data to output.
688       base::StrAppend(&raw_headers, {"\n", line});
689 
690       // Check if the current line can be continued.
691       prev_line_continuable = IsLineSegmentContinuable(line);
692     }
693   }
694 
695   raw_headers.append("\n\n", 2);
696 
697   // Use '\0' as the canonical line terminator. If the input already contained
698   // any embeded '\0' characters we will strip them first to avoid interpreting
699   // them as line breaks.
700   base::Erase(raw_headers, '\0');
701 
702   std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
703 
704   return raw_headers;
705 }
706 
ConvertHeadersBackToHTTPResponse(const std::string & str)707 std::string HttpUtil::ConvertHeadersBackToHTTPResponse(const std::string& str) {
708   std::string disassembled_headers;
709   base::StringTokenizer tokenizer(str, std::string(1, '\0'));
710   while (tokenizer.GetNext()) {
711     base::StrAppend(&disassembled_headers, {tokenizer.token_piece(), "\r\n"});
712   }
713   disassembled_headers.append("\r\n");
714 
715   return disassembled_headers;
716 }
717 
ExpandLanguageList(const std::string & language_prefs)718 std::string HttpUtil::ExpandLanguageList(const std::string& language_prefs) {
719   const std::vector<std::string> languages = base::SplitString(
720       language_prefs, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
721 
722   if (languages.empty())
723     return "";
724 
725   AcceptLanguageBuilder builder;
726 
727   const size_t size = languages.size();
728   for (size_t i = 0; i < size; ++i) {
729     const std::string& language = languages[i];
730     builder.AddLanguageCode(language);
731 
732     // Extract the primary language subtag.
733     const std::string& base_language = GetBaseLanguageCode(language);
734 
735     // Skip 'x' and 'i' as a primary language subtag per RFC 5646 section 2.1.1.
736     if (base_language == "x" || base_language == "i")
737       continue;
738 
739     // Look ahead and add the primary language subtag as a language if the next
740     // language is not part of the same family. This may not be perfect because
741     // an input of "en-US,fr,en" will yield "en-US,en,fr,en" and later make "en"
742     // a higher priority than "fr" despite the original preference.
743     const size_t j = i + 1;
744     if (j >= size || GetBaseLanguageCode(languages[j]) != base_language) {
745       builder.AddLanguageCode(base_language);
746     }
747   }
748 
749   return builder.GetString();
750 }
751 
752 // TODO(jungshik): This function assumes that the input is a comma separated
753 // list without any whitespace. As long as it comes from the preference and
754 // a user does not manually edit the preference file, it's the case. Still,
755 // we may have to make it more robust.
GenerateAcceptLanguageHeader(const std::string & raw_language_list)756 std::string HttpUtil::GenerateAcceptLanguageHeader(
757     const std::string& raw_language_list) {
758   // We use integers for qvalue and qvalue decrement that are 10 times
759   // larger than actual values to avoid a problem with comparing
760   // two floating point numbers.
761   const unsigned int kQvalueDecrement10 = 1;
762   unsigned int qvalue10 = 10;
763   base::StringTokenizer t(raw_language_list, ",");
764   std::string lang_list_with_q;
765   while (t.GetNext()) {
766     std::string language = t.token();
767     if (qvalue10 == 10) {
768       // q=1.0 is implicit.
769       lang_list_with_q = language;
770     } else {
771       DCHECK_LT(qvalue10, 10U);
772       base::StringAppendF(&lang_list_with_q, ",%s;q=0.%d", language.c_str(),
773                           qvalue10);
774     }
775     // It does not make sense to have 'q=0'.
776     if (qvalue10 > kQvalueDecrement10)
777       qvalue10 -= kQvalueDecrement10;
778   }
779   return lang_list_with_q;
780 }
781 
HasStrongValidators(HttpVersion version,const std::string & etag_header,const std::string & last_modified_header,const std::string & date_header)782 bool HttpUtil::HasStrongValidators(HttpVersion version,
783                                    const std::string& etag_header,
784                                    const std::string& last_modified_header,
785                                    const std::string& date_header) {
786   if (!HasValidators(version, etag_header, last_modified_header))
787     return false;
788 
789   if (version < HttpVersion(1, 1))
790     return false;
791 
792   if (!etag_header.empty()) {
793     size_t slash = etag_header.find('/');
794     if (slash == std::string::npos || slash == 0)
795       return true;
796 
797     std::string::const_iterator i = etag_header.begin();
798     std::string::const_iterator j = etag_header.begin() + slash;
799     TrimLWS(&i, &j);
800     if (!base::EqualsCaseInsensitiveASCII(base::MakeStringPiece(i, j), "w"))
801       return true;
802   }
803 
804   base::Time last_modified;
805   if (!base::Time::FromString(last_modified_header.c_str(), &last_modified))
806     return false;
807 
808   base::Time date;
809   if (!base::Time::FromString(date_header.c_str(), &date))
810     return false;
811 
812   // Last-Modified is implicitly weak unless it is at least 60 seconds before
813   // the Date value.
814   return ((date - last_modified).InSeconds() >= 60);
815 }
816 
HasValidators(HttpVersion version,const std::string & etag_header,const std::string & last_modified_header)817 bool HttpUtil::HasValidators(HttpVersion version,
818                              const std::string& etag_header,
819                              const std::string& last_modified_header) {
820   if (version < HttpVersion(1, 0))
821     return false;
822 
823   base::Time last_modified;
824   if (base::Time::FromString(last_modified_header.c_str(), &last_modified))
825     return true;
826 
827   // It is OK to consider an empty string in etag_header to be a missing header
828   // since valid ETags are always quoted-strings (see RFC 2616 3.11) and thus
829   // empty ETags aren't empty strings (i.e., an empty ETag might be "\"\"").
830   return version >= HttpVersion(1, 1) && !etag_header.empty();
831 }
832 
833 // Functions for histogram initialization.  The code 0 is put in the map to
834 // track status codes that are invalid.
835 // TODO(gavinp): Greatly prune the collected codes once we learn which
836 // ones are not sent in practice, to reduce upload size & memory use.
837 
838 enum {
839   HISTOGRAM_MIN_HTTP_STATUS_CODE = 100,
840   HISTOGRAM_MAX_HTTP_STATUS_CODE = 599,
841 };
842 
843 // static
GetStatusCodesForHistogram()844 std::vector<int> HttpUtil::GetStatusCodesForHistogram() {
845   std::vector<int> codes;
846   codes.reserve(
847       HISTOGRAM_MAX_HTTP_STATUS_CODE - HISTOGRAM_MIN_HTTP_STATUS_CODE + 2);
848   codes.push_back(0);
849   for (int i = HISTOGRAM_MIN_HTTP_STATUS_CODE;
850        i <= HISTOGRAM_MAX_HTTP_STATUS_CODE; ++i)
851     codes.push_back(i);
852   return codes;
853 }
854 
855 // static
MapStatusCodeForHistogram(int code)856 int HttpUtil::MapStatusCodeForHistogram(int code) {
857   if (HISTOGRAM_MIN_HTTP_STATUS_CODE <= code &&
858       code <= HISTOGRAM_MAX_HTTP_STATUS_CODE)
859     return code;
860   return 0;
861 }
862 
863 // BNF from section 4.2 of RFC 2616:
864 //
865 //   message-header = field-name ":" [ field-value ]
866 //   field-name     = token
867 //   field-value    = *( field-content | LWS )
868 //   field-content  = <the OCTETs making up the field-value
869 //                     and consisting of either *TEXT or combinations
870 //                     of token, separators, and quoted-string>
871 //
872 
HeadersIterator(std::string::const_iterator headers_begin,std::string::const_iterator headers_end,const std::string & line_delimiter)873 HttpUtil::HeadersIterator::HeadersIterator(
874     std::string::const_iterator headers_begin,
875     std::string::const_iterator headers_end,
876     const std::string& line_delimiter)
877     : lines_(headers_begin, headers_end, line_delimiter) {
878 }
879 
880 HttpUtil::HeadersIterator::~HeadersIterator() = default;
881 
GetNext()882 bool HttpUtil::HeadersIterator::GetNext() {
883   while (lines_.GetNext()) {
884     name_begin_ = lines_.token_begin();
885     values_end_ = lines_.token_end();
886 
887     std::string::const_iterator colon(std::find(name_begin_, values_end_, ':'));
888     if (colon == values_end_)
889       continue;  // skip malformed header
890 
891     name_end_ = colon;
892 
893     // If the name starts with LWS, it is an invalid line.
894     // Leading LWS implies a line continuation, and these should have
895     // already been joined by AssembleRawHeaders().
896     if (name_begin_ == name_end_ || IsLWS(*name_begin_))
897       continue;
898 
899     TrimLWS(&name_begin_, &name_end_);
900     DCHECK(name_begin_ < name_end_);
901     if (!IsToken(base::MakeStringPiece(name_begin_, name_end_)))
902       continue;  // skip malformed header
903 
904     values_begin_ = colon + 1;
905     TrimLWS(&values_begin_, &values_end_);
906 
907     // if we got a header name, then we are done.
908     return true;
909   }
910   return false;
911 }
912 
AdvanceTo(const char * name)913 bool HttpUtil::HeadersIterator::AdvanceTo(const char* name) {
914   DCHECK(name != nullptr);
915   DCHECK_EQ(0, base::ToLowerASCII(name).compare(name))
916       << "the header name must be in all lower case";
917 
918   while (GetNext()) {
919     if (base::EqualsCaseInsensitiveASCII(
920             base::MakeStringPiece(name_begin_, name_end_), name)) {
921       return true;
922     }
923   }
924 
925   return false;
926 }
927 
ValuesIterator(std::string::const_iterator values_begin,std::string::const_iterator values_end,char delimiter,bool ignore_empty_values)928 HttpUtil::ValuesIterator::ValuesIterator(
929     std::string::const_iterator values_begin,
930     std::string::const_iterator values_end,
931     char delimiter,
932     bool ignore_empty_values)
933     : values_(values_begin, values_end, std::string(1, delimiter)),
934       ignore_empty_values_(ignore_empty_values) {
935   values_.set_quote_chars("\"");
936   // Could set this unconditionally, since code below has to check for empty
937   // values after trimming, anyways, but may provide a minor performance
938   // improvement.
939   if (!ignore_empty_values_)
940     values_.set_options(base::StringTokenizer::RETURN_EMPTY_TOKENS);
941 }
942 
943 HttpUtil::ValuesIterator::ValuesIterator(const ValuesIterator& other) = default;
944 
945 HttpUtil::ValuesIterator::~ValuesIterator() = default;
946 
GetNext()947 bool HttpUtil::ValuesIterator::GetNext() {
948   while (values_.GetNext()) {
949     value_begin_ = values_.token_begin();
950     value_end_ = values_.token_end();
951     TrimLWS(&value_begin_, &value_end_);
952 
953     if (!ignore_empty_values_ || value_begin_ != value_end_)
954       return true;
955   }
956   return false;
957 }
958 
NameValuePairsIterator(std::string::const_iterator begin,std::string::const_iterator end,char delimiter,Values optional_values,Quotes strict_quotes)959 HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
960     std::string::const_iterator begin,
961     std::string::const_iterator end,
962     char delimiter,
963     Values optional_values,
964     Quotes strict_quotes)
965     : props_(begin, end, delimiter),
966       name_begin_(end),
967       name_end_(end),
968       value_begin_(end),
969       value_end_(end),
970       values_optional_(optional_values == Values::NOT_REQUIRED),
971       strict_quotes_(strict_quotes == Quotes::STRICT_QUOTES) {}
972 
NameValuePairsIterator(std::string::const_iterator begin,std::string::const_iterator end,char delimiter)973 HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
974     std::string::const_iterator begin,
975     std::string::const_iterator end,
976     char delimiter)
977     : NameValuePairsIterator(begin,
978                              end,
979                              delimiter,
980                              Values::REQUIRED,
981                              Quotes::NOT_STRICT) {}
982 
983 HttpUtil::NameValuePairsIterator::NameValuePairsIterator(
984     const NameValuePairsIterator& other) = default;
985 
986 HttpUtil::NameValuePairsIterator::~NameValuePairsIterator() = default;
987 
988 // We expect properties to be formatted as one of:
989 //   name="value"
990 //   name='value'
991 //   name='\'value\''
992 //   name=value
993 //   name = value
994 //   name (if values_optional_ is true)
995 // Due to buggy implementations found in some embedded devices, we also
996 // accept values with missing close quotemark (http://crbug.com/39836):
997 //   name="value
GetNext()998 bool HttpUtil::NameValuePairsIterator::GetNext() {
999   if (!props_.GetNext())
1000     return false;
1001 
1002   // Set the value as everything. Next we will split out the name.
1003   value_begin_ = props_.value_begin();
1004   value_end_ = props_.value_end();
1005   name_begin_ = name_end_ = value_end_;
1006 
1007   // Scan for the equals sign.
1008   std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
1009   if (equals == value_begin_)
1010     return valid_ = false;  // Malformed, no name
1011   if (equals == value_end_ && !values_optional_)
1012     return valid_ = false;  // Malformed, no equals sign and values are required
1013 
1014   // If an equals sign was found, verify that it wasn't inside of quote marks.
1015   if (equals != value_end_) {
1016     for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
1017       if (IsQuote(*it))
1018         return valid_ = false;  // Malformed, quote appears before equals sign
1019     }
1020   }
1021 
1022   name_begin_ = value_begin_;
1023   name_end_ = equals;
1024   value_begin_ = (equals == value_end_) ? value_end_ : equals + 1;
1025 
1026   TrimLWS(&name_begin_, &name_end_);
1027   TrimLWS(&value_begin_, &value_end_);
1028   value_is_quoted_ = false;
1029   unquoted_value_.clear();
1030 
1031   if (equals != value_end_ && value_begin_ == value_end_) {
1032     // Malformed; value is empty
1033     return valid_ = false;
1034   }
1035 
1036   if (value_begin_ != value_end_ && IsQuote(*value_begin_)) {
1037     value_is_quoted_ = true;
1038 
1039     if (strict_quotes_) {
1040       if (!HttpUtil::StrictUnquote(
1041               base::MakeStringPiece(value_begin_, value_end_),
1042               &unquoted_value_))
1043         return valid_ = false;
1044       return true;
1045     }
1046 
1047     // Trim surrounding quotemarks off the value
1048     if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_) {
1049       // NOTE: This is not as graceful as it sounds:
1050       // * quoted-pairs will no longer be unquoted
1051       //   (["\"hello] should give ["hello]).
1052       // * Does not detect when the final quote is escaped
1053       //   (["value\"] should give [value"])
1054       value_is_quoted_ = false;
1055       ++value_begin_;  // Gracefully recover from mismatching quotes.
1056     } else {
1057       // Do not store iterators into this. See declaration of unquoted_value_.
1058       unquoted_value_ =
1059           HttpUtil::Unquote(base::MakeStringPiece(value_begin_, value_end_));
1060     }
1061   }
1062 
1063   return true;
1064 }
1065 
ParseAcceptEncoding(const std::string & accept_encoding,std::set<std::string> * allowed_encodings)1066 bool HttpUtil::ParseAcceptEncoding(const std::string& accept_encoding,
1067                                    std::set<std::string>* allowed_encodings) {
1068   DCHECK(allowed_encodings);
1069   if (accept_encoding.find_first_of("\"") != std::string::npos)
1070     return false;
1071   allowed_encodings->clear();
1072 
1073   base::StringTokenizer tokenizer(accept_encoding.begin(),
1074                                   accept_encoding.end(), ",");
1075   while (tokenizer.GetNext()) {
1076     base::StringPiece entry = tokenizer.token_piece();
1077     entry = TrimLWS(entry);
1078     size_t semicolon_pos = entry.find(';');
1079     if (semicolon_pos == base::StringPiece::npos) {
1080       if (entry.find_first_of(HTTP_LWS) != base::StringPiece::npos)
1081         return false;
1082       allowed_encodings->insert(base::ToLowerASCII(entry));
1083       continue;
1084     }
1085     base::StringPiece encoding = entry.substr(0, semicolon_pos);
1086     encoding = TrimLWS(encoding);
1087     if (encoding.find_first_of(HTTP_LWS) != base::StringPiece::npos)
1088       return false;
1089     base::StringPiece params = entry.substr(semicolon_pos + 1);
1090     params = TrimLWS(params);
1091     size_t equals_pos = params.find('=');
1092     if (equals_pos == base::StringPiece::npos)
1093       return false;
1094     base::StringPiece param_name = params.substr(0, equals_pos);
1095     param_name = TrimLWS(param_name);
1096     if (!base::EqualsCaseInsensitiveASCII(param_name, "q"))
1097       return false;
1098     base::StringPiece qvalue = params.substr(equals_pos + 1);
1099     qvalue = TrimLWS(qvalue);
1100     if (qvalue.empty())
1101       return false;
1102     if (qvalue[0] == '1') {
1103       if (base::StartsWith("1.000", qvalue)) {
1104         allowed_encodings->insert(base::ToLowerASCII(encoding));
1105         continue;
1106       }
1107       return false;
1108     }
1109     if (qvalue[0] != '0')
1110       return false;
1111     if (qvalue.length() == 1)
1112       continue;
1113     if (qvalue.length() <= 2 || qvalue.length() > 5)
1114       return false;
1115     if (qvalue[1] != '.')
1116       return false;
1117     bool nonzero_number = false;
1118     for (size_t i = 2; i < qvalue.length(); ++i) {
1119       if (!base::IsAsciiDigit(qvalue[i]))
1120         return false;
1121       if (qvalue[i] != '0')
1122         nonzero_number = true;
1123     }
1124     if (nonzero_number)
1125       allowed_encodings->insert(base::ToLowerASCII(encoding));
1126   }
1127 
1128   // RFC 7231 5.3.4 "A request without an Accept-Encoding header field implies
1129   // that the user agent has no preferences regarding content-codings."
1130   if (allowed_encodings->empty()) {
1131     allowed_encodings->insert("*");
1132     return true;
1133   }
1134 
1135   // Any browser must support "identity".
1136   allowed_encodings->insert("identity");
1137 
1138   // RFC says gzip == x-gzip; mirror it here for easier matching.
1139   if (allowed_encodings->find("gzip") != allowed_encodings->end())
1140     allowed_encodings->insert("x-gzip");
1141   if (allowed_encodings->find("x-gzip") != allowed_encodings->end())
1142     allowed_encodings->insert("gzip");
1143 
1144   // RFC says compress == x-compress; mirror it here for easier matching.
1145   if (allowed_encodings->find("compress") != allowed_encodings->end())
1146     allowed_encodings->insert("x-compress");
1147   if (allowed_encodings->find("x-compress") != allowed_encodings->end())
1148     allowed_encodings->insert("compress");
1149   return true;
1150 }
1151 
ParseContentEncoding(const std::string & content_encoding,std::set<std::string> * used_encodings)1152 bool HttpUtil::ParseContentEncoding(const std::string& content_encoding,
1153                                     std::set<std::string>* used_encodings) {
1154   DCHECK(used_encodings);
1155   if (content_encoding.find_first_of("\"=;*") != std::string::npos)
1156     return false;
1157   used_encodings->clear();
1158 
1159   base::StringTokenizer encoding_tokenizer(content_encoding.begin(),
1160                                            content_encoding.end(), ",");
1161   while (encoding_tokenizer.GetNext()) {
1162     base::StringPiece encoding = TrimLWS(encoding_tokenizer.token_piece());
1163     if (encoding.find_first_of(HTTP_LWS) != base::StringPiece::npos)
1164       return false;
1165     used_encodings->insert(base::ToLowerASCII(encoding));
1166   }
1167   return true;
1168 }
1169 
HeadersContainMultipleCopiesOfField(const HttpResponseHeaders & headers,const std::string & field_name)1170 bool HttpUtil::HeadersContainMultipleCopiesOfField(
1171     const HttpResponseHeaders& headers,
1172     const std::string& field_name) {
1173   size_t it = 0;
1174   std::string field_value;
1175   if (!headers.EnumerateHeader(&it, field_name, &field_value))
1176     return false;
1177   // There's at least one `field_name` header.  Check if there are any more
1178   // such headers, and if so, return true if they have different values.
1179   std::string field_value2;
1180   while (headers.EnumerateHeader(&it, field_name, &field_value2)) {
1181     if (field_value != field_value2)
1182       return true;
1183   }
1184   return false;
1185 }
1186 
1187 }  // namespace net
1188