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