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 #ifndef NET_HTTP_HTTP_UTIL_H_ 6 #define NET_HTTP_HTTP_UTIL_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <set> 12 #include <string> 13 #include <string_view> 14 #include <vector> 15 16 #include "base/compiler_specific.h" 17 #include "base/strings/string_tokenizer.h" 18 #include "base/strings/string_util.h" 19 #include "base/time/time.h" 20 #include "net/base/net_export.h" 21 #include "net/http/http_byte_range.h" 22 #include "net/http/http_version.h" 23 #include "url/gurl.h" 24 #include "url/origin.h" 25 26 // This is a macro to support extending this string literal at compile time. 27 // Please excuse me polluting your global namespace! 28 #define HTTP_LWS " \t" 29 30 namespace net { 31 32 class HttpResponseHeaders; 33 34 class NET_EXPORT HttpUtil { 35 public: 36 // Returns the absolute URL, to be used for the http request. This url is 37 // made up of the protocol, host, [port], path, [query]. Everything else 38 // is stripped (username, password, reference). 39 static std::string SpecForRequest(const GURL& url); 40 41 // Parses the value of a Content-Type header. |mime_type|, |charset|, and 42 // |had_charset| output parameters must be valid pointers. |boundary| may be 43 // nullptr. |*mime_type| and |*charset| should be empty and |*had_charset| 44 // false when called with the first Content-Type header value in a given 45 // header list. 46 // 47 // ParseContentType() supports parsing multiple Content-Type headers in the 48 // same header list. For this operation, subsequent calls should pass in the 49 // same |mime_type|, |charset|, and |had_charset| arguments without clearing 50 // them. 51 // 52 // The resulting mime_type and charset values are normalized to lowercase. 53 // The mime_type and charset output values are only modified if the 54 // content_type_str contains a mime type and charset value, respectively. If 55 // |boundary| is not null, then |*boundary| will be assigned the (unquoted) 56 // value of the boundary parameter, if any. 57 static void ParseContentType(const std::string& content_type_str, 58 std::string* mime_type, 59 std::string* charset, 60 bool* had_charset, 61 std::string* boundary); 62 63 // Parses the value of a "Range" header as defined in RFC 7233 Section 2.1. 64 // https://tools.ietf.org/html/rfc7233#section-2.1 65 // Returns false on failure. 66 static bool ParseRangeHeader(const std::string& range_specifier, 67 std::vector<HttpByteRange>* ranges); 68 69 // Extracts the values in a Content-Range header and returns true if all three 70 // values are present and valid for a 206 response; otherwise returns false. 71 // The following values will be outputted: 72 // |*first_byte_position| = inclusive position of the first byte of the range 73 // |*last_byte_position| = inclusive position of the last byte of the range 74 // |*instance_length| = size in bytes of the object requested 75 // If this method returns false, then all of the outputs will be -1. 76 static bool ParseContentRangeHeaderFor206(std::string_view content_range_spec, 77 int64_t* first_byte_position, 78 int64_t* last_byte_position, 79 int64_t* instance_length); 80 81 // Parses a Retry-After header that is either an absolute date/time or a 82 // number of seconds in the future. Interprets absolute times as relative to 83 // |now|. If |retry_after_string| is successfully parsed and indicates a time 84 // that is not in the past, fills in |*retry_after| and returns true; 85 // otherwise, returns false. 86 static bool ParseRetryAfterHeader(const std::string& retry_after_string, 87 base::Time now, 88 base::TimeDelta* retry_after); 89 90 // Formats a time in the IMF-fixdate format defined by RFC 7231 (satisfying 91 // its HTTP-date format). 92 // 93 // This behaves identically to the function in base/i18n/time_formatting.h. It 94 // is reimplemented here since net/ cannot depend on base/i18n/. 95 static std::string TimeFormatHTTP(base::Time time); 96 97 // Returns true if the request method is "safe" (per section 4.2.1 of 98 // RFC 7231). 99 static bool IsMethodSafe(std::string_view method); 100 101 // Returns true if the request method is idempotent (per section 4.2.2 of 102 // RFC 7231). 103 static bool IsMethodIdempotent(std::string_view method); 104 105 // Returns true if it is safe to allow users and scripts to specify a header 106 // with a given |name| and |value|. 107 // See https://fetch.spec.whatwg.org/#forbidden-request-header. 108 // Does not check header validity. 109 static bool IsSafeHeader(std::string_view name, std::string_view value); 110 111 // Returns true if |name| is a valid HTTP header name. 112 static bool IsValidHeaderName(std::string_view name); 113 114 // Returns false if |value| contains NUL or CRLF. This method does not perform 115 // a fully RFC-2616-compliant header value validation. 116 static bool IsValidHeaderValue(std::string_view value); 117 118 // Multiple occurances of some headers cannot be coalesced into a comma- 119 // separated list since their values are (or contain) unquoted HTTP-date 120 // values, which may contain a comma (see RFC 2616 section 3.3.1). 121 static bool IsNonCoalescingHeader(std::string_view name); 122 123 // Return true if the character is HTTP "linear white space" (SP | HT). 124 // This definition corresponds with the HTTP_LWS macro, and does not match 125 // newlines. 126 // 127 // ALWAYS_INLINE to force inlining even when compiled with -Oz in Clang. IsLWS(char c)128 ALWAYS_INLINE static bool IsLWS(char c) { 129 constexpr std::string_view kWhiteSpaceCharacters(HTTP_LWS); 130 // Clang performs this optimization automatically at -O3, but Android is 131 // compiled at -Oz, so we need to do it by hand. 132 static_assert(kWhiteSpaceCharacters == " \t"); 133 return c == ' ' || c == '\t'; 134 } 135 136 // Trim HTTP_LWS chars from the beginning and end of the string. 137 static void TrimLWS(std::string::const_iterator* begin, 138 std::string::const_iterator* end); 139 static std::string_view TrimLWS(std::string_view string); 140 141 // Whether the character is a valid |tchar| as defined in RFC 7230 Sec 3.2.6. 142 static bool IsTokenChar(char c); 143 // Whether the string is a valid |token| as defined in RFC 7230 Sec 3.2.6. 144 static bool IsToken(std::string_view str); 145 146 // Whether the character is a control character (CTL) as defined in RFC 5234 147 // Appendix B.1. IsControlChar(char c)148 static inline bool IsControlChar(char c) { 149 return (c >= 0x00 && c <= 0x1F) || c == 0x7F; 150 } 151 152 // Whether the string is a valid |parmname| as defined in RFC 5987 Sec 3.2.1. 153 static bool IsParmName(std::string_view str); 154 155 // RFC 2616 Sec 2.2: 156 // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) 157 // Unquote() strips the surrounding quotemarks off a string, and unescapes 158 // any quoted-pair to obtain the value contained by the quoted-string. 159 // If the input is not quoted, then it works like the identity function. 160 static std::string Unquote(std::string_view str); 161 162 // Similar to Unquote(), but additionally validates that the string being 163 // unescaped actually is a valid quoted string. Returns false for an empty 164 // string, a string without quotes, a string with mismatched quotes, and 165 // a string with unescaped embeded quotes. 166 [[nodiscard]] static bool StrictUnquote(std::string_view str, 167 std::string* out); 168 169 // The reverse of Unquote() -- escapes and surrounds with " 170 static std::string Quote(std::string_view str); 171 172 // Returns the start of the status line, or std::string::npos if no status 173 // line was found. This allows for 4 bytes of junk to precede the status line 174 // (which is what Mozilla does too). 175 static size_t LocateStartOfStatusLine(const char* buf, size_t buf_len); 176 177 // Returns index beyond the end-of-headers marker or std::string::npos if not 178 // found. RFC 2616 defines the end-of-headers marker as a double CRLF; 179 // however, some servers only send back LFs (e.g., Unix-based CGI scripts 180 // written using the ASIS Apache module). This function therefore accepts the 181 // pattern LF[CR]LF as end-of-headers (just like Mozilla). The first line of 182 // |buf| is considered the status line, even if empty. The parameter |i| is 183 // the offset within |buf| to begin searching from. 184 static size_t LocateEndOfHeaders(const char* buf, 185 size_t buf_len, 186 size_t i = 0); 187 188 // Same as |LocateEndOfHeaders|, but does not expect a status line, so can be 189 // used on multi-part responses or HTTP/1.x trailers. As a result, if |buf| 190 // starts with a single [CR]LF, it is considered an empty header list, as 191 // opposed to an empty status line above a header list. 192 static size_t LocateEndOfAdditionalHeaders(const char* buf, 193 size_t buf_len, 194 size_t i = 0); 195 196 // Assemble "raw headers" in the format required by HttpResponseHeaders. 197 // This involves normalizing line terminators, converting [CR]LF to \0 and 198 // handling HTTP line continuations (i.e., lines starting with LWS are 199 // continuations of the previous line). |buf| should end at the 200 // end-of-headers marker as defined by LocateEndOfHeaders. If a \0 appears 201 // within the headers themselves, it will be stripped. This is a workaround to 202 // avoid later code from incorrectly interpreting it as a line terminator. 203 // 204 // TODO(crbug.com/671799): Should remove or internalize this to 205 // HttpResponseHeaders. 206 static std::string AssembleRawHeaders(std::string_view buf); 207 208 // Converts assembled "raw headers" back to the HTTP response format. That is 209 // convert each \0 occurence to CRLF. This is used by DevTools. 210 // Since all line continuations info is already lost at this point, the result 211 // consists of status line and then one line for each header. 212 static std::string ConvertHeadersBackToHTTPResponse(const std::string& str); 213 214 // Given a comma separated ordered list of language codes, return an expanded 215 // list by adding the base language from language-region pair if it doesn't 216 // already exist. This increases the chances of language matching in many 217 // cases as explained at this w3c doc: 218 // https://www.w3.org/International/questions/qa-lang-priorities#langtagdetail 219 // Note that we do not support Q values (e.g. ;q=0.9) in |language_prefs|. 220 static std::string ExpandLanguageList(const std::string& language_prefs); 221 222 // Given a comma separated ordered list of language codes, return 223 // the list with a qvalue appended to each language. 224 // The way qvalues are assigned is rather simple. The qvalue 225 // starts with 1.0 and is decremented by 0.1 for each successive entry 226 // in the list until it reaches 0.1. All the entries after that are 227 // assigned the same qvalue of 0.1. Also, note that the 1st language 228 // will not have a qvalue added because the absence of a qvalue implicitly 229 // means q=1.0. 230 // 231 // When making a http request, this should be used to determine what 232 // to put in Accept-Language header. If a comma separated list of language 233 // codes *without* qvalue is sent, web servers regard all 234 // of them as having q=1.0 and pick one of them even though it may not 235 // be at the beginning of the list (see http://crbug.com/5899). 236 static std::string GenerateAcceptLanguageHeader( 237 const std::string& raw_language_list); 238 239 // Returns true if the parameters describe a response with a strong etag or 240 // last-modified header. See section 13.3.3 of RFC 2616. 241 // An empty string should be passed for missing headers. 242 static bool HasStrongValidators(HttpVersion version, 243 const std::string& etag_header, 244 const std::string& last_modified_header, 245 const std::string& date_header); 246 247 // Returns true if this response has any validator (either a Last-Modified or 248 // an ETag) regardless of whether it is strong or weak. See section 13.3.3 of 249 // RFC 2616. 250 // An empty string should be passed for missing headers. 251 static bool HasValidators(HttpVersion version, 252 const std::string& etag_header, 253 const std::string& last_modified_header); 254 255 // Gets a vector of common HTTP status codes for histograms of status 256 // codes. Currently returns everything in the range [100, 600), plus 0 257 // (for invalid responses/status codes). 258 static std::vector<int> GetStatusCodesForHistogram(); 259 260 // Maps an HTTP status code to one of the status codes in the vector 261 // returned by GetStatusCodesForHistogram. 262 static int MapStatusCodeForHistogram(int code); 263 264 // Returns true if |accept_encoding| is well-formed. Parsed encodings turned 265 // to lower case, are placed to provided string-set. Resulting set is 266 // augmented to fulfill the RFC 2616 and RFC 7231 recommendations, e.g. if 267 // there is no encodings specified, then {"*"} is returned to denote that 268 // client has to encoding preferences (but it does not imply that the 269 // user agent will be able to correctly process all encodings). 270 static bool ParseAcceptEncoding(const std::string& accept_encoding, 271 std::set<std::string>* allowed_encodings); 272 273 // Returns true if |content_encoding| is well-formed. Parsed encodings turned 274 // to lower case, are placed to provided string-set. See sections 14.11 and 275 // 3.5 of RFC 2616. 276 static bool ParseContentEncoding(const std::string& content_encoding, 277 std::set<std::string>* used_encodings); 278 279 // Return true if `headers` contain multiple `field_name` fields with 280 // different values. 281 static bool HeadersContainMultipleCopiesOfField( 282 const HttpResponseHeaders& headers, 283 const std::string& field_name); 284 285 // Used to iterate over the name/value pairs of HTTP headers. To iterate 286 // over the values in a multi-value header, use ValuesIterator. 287 // See AssembleRawHeaders for joining line continuations (this iterator 288 // does not expect any). 289 class NET_EXPORT HeadersIterator { 290 public: 291 HeadersIterator(std::string::const_iterator headers_begin, 292 std::string::const_iterator headers_end, 293 const std::string& line_delimiter); 294 ~HeadersIterator(); 295 296 // Advances the iterator to the next header, if any. Returns true if there 297 // is a next header. Use name* and values* methods to access the resultant 298 // header name and values. 299 bool GetNext(); 300 301 // Iterates through the list of headers, starting with the current position 302 // and looks for the specified header. Note that the name _must_ be 303 // lower cased. 304 // If the header was found, the return value will be true and the current 305 // position points to the header. If the return value is false, the 306 // current position will be at the end of the headers. 307 bool AdvanceTo(const char* lowercase_name); 308 Reset()309 void Reset() { 310 lines_.Reset(); 311 } 312 name_begin()313 std::string::const_iterator name_begin() const { 314 return name_begin_; 315 } name_end()316 std::string::const_iterator name_end() const { 317 return name_end_; 318 } name()319 std::string name() const { 320 return std::string(name_begin_, name_end_); 321 } name_piece()322 std::string_view name_piece() const { 323 return base::MakeStringPiece(name_begin_, name_end_); 324 } 325 values_begin()326 std::string::const_iterator values_begin() const { 327 return values_begin_; 328 } values_end()329 std::string::const_iterator values_end() const { 330 return values_end_; 331 } values()332 std::string values() const { 333 return std::string(values_begin_, values_end_); 334 } values_piece()335 std::string_view values_piece() const { 336 return base::MakeStringPiece(values_begin_, values_end_); 337 } 338 339 private: 340 base::StringTokenizer lines_; 341 std::string::const_iterator name_begin_; 342 std::string::const_iterator name_end_; 343 std::string::const_iterator values_begin_; 344 std::string::const_iterator values_end_; 345 }; 346 347 // Iterates over delimited values in an HTTP header. HTTP LWS is 348 // automatically trimmed from the resulting values. 349 // 350 // When using this class to iterate over response header values, be aware that 351 // for some headers (e.g., Last-Modified), commas are not used as delimiters. 352 // This iterator should be avoided for headers like that which are considered 353 // non-coalescing (see IsNonCoalescingHeader). 354 // 355 // This iterator is careful to skip over delimiters found inside an HTTP 356 // quoted string. 357 class NET_EXPORT ValuesIterator { 358 public: 359 ValuesIterator(std::string::const_iterator values_begin, 360 std::string::const_iterator values_end, 361 char delimiter, 362 bool ignore_empty_values = true); 363 ValuesIterator(const ValuesIterator& other); 364 ~ValuesIterator(); 365 366 // Advances the iterator to the next value, if any. Returns true if there 367 // is a next value. Use value* methods to access the resultant value. 368 bool GetNext(); 369 value_begin()370 std::string::const_iterator value_begin() const { 371 return value_begin_; 372 } value_end()373 std::string::const_iterator value_end() const { 374 return value_end_; 375 } value()376 std::string value() const { 377 return std::string(value_begin_, value_end_); 378 } value_piece()379 std::string_view value_piece() const { 380 return base::MakeStringPiece(value_begin_, value_end_); 381 } 382 383 private: 384 base::StringTokenizer values_; 385 std::string::const_iterator value_begin_; 386 std::string::const_iterator value_end_; 387 bool ignore_empty_values_; 388 }; 389 390 // Iterates over a delimited sequence of name-value pairs in an HTTP header. 391 // Each pair consists of a token (the name), an equals sign, and either a 392 // token or quoted-string (the value). Arbitrary HTTP LWS is permitted outside 393 // of and between names, values, and delimiters. 394 // 395 // String iterators returned from this class' methods may be invalidated upon 396 // calls to GetNext() or after the NameValuePairsIterator is destroyed. 397 class NET_EXPORT NameValuePairsIterator { 398 public: 399 // Whether or not values are optional. Values::NOT_REQUIRED allows 400 // e.g. name1=value1;name2;name3=value3, whereas Vaues::REQUIRED 401 // will treat it as a parse error because name2 does not have a 402 // corresponding equals sign. 403 enum class Values { NOT_REQUIRED, REQUIRED }; 404 405 // Whether or not unmatched quotes should be considered a failure. By 406 // default this class is pretty lenient and does a best effort to parse 407 // values with mismatched quotes. When set to STRICT_QUOTES a value with 408 // mismatched or otherwise invalid quotes is considered a parse error. 409 enum class Quotes { STRICT_QUOTES, NOT_STRICT }; 410 411 NameValuePairsIterator(std::string::const_iterator begin, 412 std::string::const_iterator end, 413 char delimiter, 414 Values optional_values, 415 Quotes strict_quotes); 416 417 // Treats values as not optional by default (Values::REQUIRED) and 418 // treats quotes as not strict. 419 NameValuePairsIterator(std::string::const_iterator begin, 420 std::string::const_iterator end, 421 char delimiter); 422 423 NameValuePairsIterator(const NameValuePairsIterator& other); 424 425 ~NameValuePairsIterator(); 426 427 // Advances the iterator to the next pair, if any. Returns true if there 428 // is a next pair. Use name* and value* methods to access the resultant 429 // value. 430 bool GetNext(); 431 432 // Returns false if there was a parse error. valid()433 bool valid() const { return valid_; } 434 435 // The name of the current name-value pair. name_begin()436 std::string::const_iterator name_begin() const { return name_begin_; } name_end()437 std::string::const_iterator name_end() const { return name_end_; } name()438 std::string name() const { return std::string(name_begin_, name_end_); } name_piece()439 std::string_view name_piece() const { 440 return base::MakeStringPiece(name_begin_, name_end_); 441 } 442 443 // The value of the current name-value pair. value_begin()444 std::string::const_iterator value_begin() const { 445 return value_is_quoted_ ? unquoted_value_.begin() : value_begin_; 446 } value_end()447 std::string::const_iterator value_end() const { 448 return value_is_quoted_ ? unquoted_value_.end() : value_end_; 449 } value()450 std::string value() const { 451 return value_is_quoted_ ? unquoted_value_ : std::string(value_begin_, 452 value_end_); 453 } value_piece()454 std::string_view value_piece() const { 455 return value_is_quoted_ ? unquoted_value_ 456 : base::MakeStringPiece(value_begin_, value_end_); 457 } 458 value_is_quoted()459 bool value_is_quoted() const { return value_is_quoted_; } 460 461 // The value before unquoting (if any). raw_value()462 std::string raw_value() const { return std::string(value_begin_, 463 value_end_); } 464 465 private: 466 HttpUtil::ValuesIterator props_; 467 bool valid_ = true; 468 469 std::string::const_iterator name_begin_; 470 std::string::const_iterator name_end_; 471 472 std::string::const_iterator value_begin_; 473 std::string::const_iterator value_end_; 474 475 // Do not store iterators into this string. The NameValuePairsIterator 476 // is copyable/assignable, and if copied the copy's iterators would point 477 // into the original's unquoted_value_ member. 478 std::string unquoted_value_; 479 480 bool value_is_quoted_ = false; 481 482 // True if values are required for each name/value pair; false if a 483 // name is permitted to appear without a corresponding value. 484 bool values_optional_; 485 486 // True if quotes values are required to be properly quoted; false if 487 // mismatched quotes and other problems with quoted values should be more 488 // or less gracefully treated as valid. 489 bool strict_quotes_; 490 }; 491 }; 492 493 } // namespace net 494 495 #endif // NET_HTTP_HTTP_UTIL_H_ 496