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