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