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_RESPONSE_HEADERS_H_ 6 #define NET_HTTP_HTTP_RESPONSE_HEADERS_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <string> 12 #include <unordered_set> 13 #include <vector> 14 15 #include "base/check.h" 16 #include "base/functional/callback.h" 17 #include "base/memory/ref_counted.h" 18 #include "base/strings/string_piece.h" 19 #include "base/time/time.h" 20 #include "base/trace_event/base_tracing_forward.h" 21 #include "base/types/pass_key.h" 22 #include "base/values.h" 23 #include "net/base/net_export.h" 24 #include "net/http/http_util.h" 25 #include "net/http/http_version.h" 26 #include "net/log/net_log_capture_mode.h" 27 #include "third_party/abseil-cpp/absl/container/inlined_vector.h" 28 29 namespace base { 30 class Pickle; 31 class PickleIterator; 32 class Time; 33 class TimeDelta; 34 } 35 36 namespace net { 37 38 class HttpByteRange; 39 40 enum ValidationType { 41 VALIDATION_NONE, // The resource is fresh. 42 VALIDATION_ASYNCHRONOUS, // The resource requires async revalidation. 43 VALIDATION_SYNCHRONOUS // The resource requires sync revalidation. 44 }; 45 46 // HttpResponseHeaders: parses and holds HTTP response headers. 47 class NET_EXPORT HttpResponseHeaders 48 : public base::RefCountedThreadSafe<HttpResponseHeaders> { 49 public: 50 // This class provides the most efficient way to build an HttpResponseHeaders 51 // object if the headers are all available in memory at once. 52 // Example usage: 53 // scoped_refptr<HttpResponseHeaders> headers = 54 // HttpResponseHeaders::Builder(HttpVersion(1, 1), 307) 55 // .AddHeader("Location", url.spec()) 56 // .Build(); 57 class NET_EXPORT Builder { 58 public: 59 // Constructs a builder with a particular `version` and `status`. `version` 60 // must be (1,0), (1,1) or (2,0). `status` is the response code optionally 61 // followed by a space and the status text, eg. "200 OK". The caller is 62 // required to guarantee that `status` does not contain embedded nul 63 // characters, and that it will remain valid until Build() is called. 64 Builder(HttpVersion version, base::StringPiece status); 65 66 Builder(const Builder&) = delete; 67 Builder& operator=(const Builder&) = delete; 68 69 ~Builder(); 70 71 // Adds a header. Returns a reference to the object so that calls can be 72 // chained. Duplicates will be preserved. Order will be preserved. For 73 // performance reasons, strings are not copied until Build() is called. It 74 // is the caller's responsibility to ensure the values remain valid until 75 // then. The caller is required to guarantee that `name` and `value` are 76 // valid HTTP headers and in particular that they do not contain embedded 77 // nul characters. AddHeader(base::StringPiece name,base::StringPiece value)78 Builder& AddHeader(base::StringPiece name, base::StringPiece value) { 79 DCHECK(HttpUtil::IsValidHeaderName(name)); 80 DCHECK(HttpUtil::IsValidHeaderValue(value)); 81 headers_.push_back({name, value}); 82 return *this; 83 } 84 85 scoped_refptr<HttpResponseHeaders> Build(); 86 87 private: 88 using KeyValuePair = std::pair<base::StringPiece, base::StringPiece>; 89 90 const HttpVersion version_; 91 const base::StringPiece status_; 92 // 40 is enough for 94% of responses on Windows and 98% on Android. 93 absl::InlinedVector<KeyValuePair, 40> headers_; 94 }; 95 96 using BuilderPassKey = base::PassKey<Builder>; 97 98 // Persist options. 99 typedef int PersistOptions; 100 static const PersistOptions PERSIST_RAW = -1; // Raw, unparsed headers. 101 static const PersistOptions PERSIST_ALL = 0; // Parsed headers. 102 static const PersistOptions PERSIST_SANS_COOKIES = 1 << 0; 103 static const PersistOptions PERSIST_SANS_CHALLENGES = 1 << 1; 104 static const PersistOptions PERSIST_SANS_HOP_BY_HOP = 1 << 2; 105 static const PersistOptions PERSIST_SANS_NON_CACHEABLE = 1 << 3; 106 static const PersistOptions PERSIST_SANS_RANGES = 1 << 4; 107 static const PersistOptions PERSIST_SANS_SECURITY_STATE = 1 << 5; 108 109 struct FreshnessLifetimes { 110 // How long the resource will be fresh for. 111 base::TimeDelta freshness; 112 // How long after becoming not fresh that the resource will be stale but 113 // usable (if async revalidation is enabled). 114 base::TimeDelta staleness; 115 }; 116 117 static const char kContentRange[]; 118 static const char kLastModified[]; 119 static const char kVary[]; 120 121 HttpResponseHeaders() = delete; 122 123 // Parses the given raw_headers. raw_headers should be formatted thus: 124 // includes the http status response line, each line is \0-terminated, and 125 // it's terminated by an empty line (ie, 2 \0s in a row). 126 // (Note that line continuations should have already been joined; 127 // see HttpUtil::AssembleRawHeaders) 128 // 129 // HttpResponseHeaders does not perform any encoding changes on the input. 130 // 131 explicit HttpResponseHeaders(const std::string& raw_headers); 132 133 // Initializes from the representation stored in the given pickle. The data 134 // for this object is found relative to the given pickle_iter, which should 135 // be passed to the pickle's various Read* methods. 136 explicit HttpResponseHeaders(base::PickleIterator* pickle_iter); 137 138 // Use Builder::Build() rather than calling this directly. The BuilderPassKey 139 // prevents accidental use from other code. 140 HttpResponseHeaders( 141 BuilderPassKey, 142 HttpVersion version, 143 base::StringPiece status, 144 base::span<const std::pair<base::StringPiece, base::StringPiece>> 145 headers); 146 147 // Takes headers as an ASCII string and tries to parse them as HTTP response 148 // headers. returns nullptr on failure. Unlike the HttpResponseHeaders 149 // constructor that takes a std::string, HttpUtil::AssembleRawHeaders should 150 // not be called on |headers| before calling this method. 151 static scoped_refptr<HttpResponseHeaders> TryToCreate( 152 base::StringPiece headers); 153 154 HttpResponseHeaders(const HttpResponseHeaders&) = delete; 155 HttpResponseHeaders& operator=(const HttpResponseHeaders&) = delete; 156 157 // Appends a representation of this object to the given pickle. 158 // The options argument can be a combination of PersistOptions. 159 void Persist(base::Pickle* pickle, PersistOptions options); 160 161 // Performs header merging as described in 13.5.3 of RFC 2616. 162 void Update(const HttpResponseHeaders& new_headers); 163 164 // Removes all instances of a particular header. 165 void RemoveHeader(base::StringPiece name); 166 167 // Removes all instances of particular headers. 168 void RemoveHeaders(const std::unordered_set<std::string>& header_names); 169 170 // Removes a particular header line. The header name is compared 171 // case-insensitively. 172 void RemoveHeaderLine(const std::string& name, const std::string& value); 173 174 // Adds the specified response header. If a header with the same name is 175 // already stored, the two headers are not merged together by this method; the 176 // one provided is simply put at the end of the list. 177 void AddHeader(base::StringPiece name, base::StringPiece value); 178 179 // Sets the specified response header, removing any matching old one if 180 // present. The new header is added to the end of the header list, rather than 181 // replacing the old one. This is the same as calling RemoveHeader() followed 182 // be SetHeader(). 183 void SetHeader(base::StringPiece name, base::StringPiece value); 184 185 // Adds a cookie header. |cookie_string| should be the header value without 186 // the header name (Set-Cookie). 187 void AddCookie(const std::string& cookie_string); 188 189 // Replaces the current status line with the provided one (|new_status| should 190 // not have any EOL). 191 void ReplaceStatusLine(const std::string& new_status); 192 193 // Updates headers (Content-Length and Content-Range) in the |headers| to 194 // include the right content length and range for |byte_range|. This also 195 // updates HTTP status line if |replace_status_line| is true. 196 // |byte_range| must have a valid, bounded range (i.e. coming from a valid 197 // response or should be usable for a response). 198 void UpdateWithNewRange(const HttpByteRange& byte_range, 199 int64_t resource_size, 200 bool replace_status_line); 201 202 // Fetches the "normalized" value of a single header, where all values for the 203 // header name are separated by commas. This will be the sequence of strings 204 // that would be returned from repeated calls to EnumerateHeader, joined by 205 // the string ", ". 206 // 207 // Returns false if this header wasn't found. 208 // 209 // Example: 210 // Foo: a, b,c 211 // Foo: d 212 // 213 // string value; 214 // GetNormalizedHeader("Foo", &value); // Now, |value| is "a, b, c, d". 215 // 216 // NOTE: Do not make any assumptions about the encoding of this output 217 // string. It may be non-ASCII, and the encoding used by the server is not 218 // necessarily known to us. Do not assume that this output is UTF-8! 219 bool GetNormalizedHeader(base::StringPiece name, std::string* value) const; 220 221 // Returns the normalized status line. 222 std::string GetStatusLine() const; 223 224 // Get the HTTP version of the normalized status line. GetHttpVersion()225 HttpVersion GetHttpVersion() const { 226 return http_version_; 227 } 228 229 // Get the HTTP status text of the normalized status line. 230 std::string GetStatusText() const; 231 232 // Enumerate the "lines" of the response headers. This skips over the status 233 // line. Use GetStatusLine if you are interested in that. Note that this 234 // method returns the un-coalesced response header lines, so if a response 235 // header appears on multiple lines, then it will appear multiple times in 236 // this enumeration (in the order the header lines were received from the 237 // server). Also, a given header might have an empty value. Initialize a 238 // 'size_t' variable to 0 and pass it by address to EnumerateHeaderLines. 239 // Call EnumerateHeaderLines repeatedly until it returns false. The 240 // out-params 'name' and 'value' are set upon success. 241 // 242 // WARNING: In effect, repeatedly calling EnumerateHeaderLines should return 243 // the same collection of (name, value) pairs that you'd obtain from passing 244 // each header name into EnumerateHeader and repeatedly calling 245 // EnumerateHeader. This means the output will *not* necessarily correspond to 246 // the verbatim lines of the headers. For instance, given 247 // Foo: a, b 248 // Foo: c 249 // EnumerateHeaderLines will output ("Foo", "a"), ("Foo", "b"), and 250 // ("Foo", "c"). 251 bool EnumerateHeaderLines(size_t* iter, 252 std::string* name, 253 std::string* value) const; 254 255 // Enumerate the values of the specified header. If you are only interested 256 // in the first header, then you can pass nullptr for the 'iter' parameter. 257 // Otherwise, to iterate across all values for the specified header, 258 // initialize a 'size_t' variable to 0 and pass it by address to 259 // EnumerateHeader. Note that a header might have an empty value. Call 260 // EnumerateHeader repeatedly until it returns false. 261 // 262 // Unless a header is explicitly marked as non-coalescing (see 263 // HttpUtil::IsNonCoalescingHeader), headers that contain 264 // comma-separated lists are treated "as if" they had been sent as 265 // distinct headers. That is, a header of "Foo: a, b, c" would 266 // enumerate into distinct values of "a", "b", and "c". This is also 267 // true for headers that occur multiple times in a response; unless 268 // they are marked non-coalescing, "Foo: a, b" followed by "Foo: c" 269 // will enumerate to "a", "b", "c". Commas inside quoted strings are ignored, 270 // for example a header of 'Foo: "a, b", "c"' would enumerate as '"a, b"', 271 // '"c"'. 272 // 273 // This can cause issues for headers that might have commas in fields that 274 // aren't quoted strings, for example a header of "Foo: <a, b>, <c>" would 275 // enumerate as '<a', 'b>', '<c>', rather than as '<a, b>', '<c>'. 276 // 277 // To handle cases such as this, use GetNormalizedHeader to return the full 278 // concatenated header, and then parse manually. 279 bool EnumerateHeader(size_t* iter, 280 base::StringPiece name, 281 std::string* value) const; 282 283 // Returns true if the response contains the specified header-value pair. 284 // Both name and value are compared case insensitively. 285 bool HasHeaderValue(base::StringPiece name, base::StringPiece value) const; 286 287 // Returns true if the response contains the specified header. 288 // The name is compared case insensitively. 289 bool HasHeader(base::StringPiece name) const; 290 291 // Get the mime type and charset values in lower case form from the headers. 292 // Empty strings are returned if the values are not present. 293 void GetMimeTypeAndCharset(std::string* mime_type, 294 std::string* charset) const; 295 296 // Get the mime type in lower case from the headers. If there's no mime 297 // type, returns false. 298 bool GetMimeType(std::string* mime_type) const; 299 300 // Get the charset in lower case from the headers. If there's no charset, 301 // returns false. 302 bool GetCharset(std::string* charset) const; 303 304 // Returns true if this response corresponds to a redirect. The target 305 // location of the redirect is optionally returned if location is non-null. 306 bool IsRedirect(std::string* location) const; 307 308 // Returns true if the HTTP response code passed in corresponds to a 309 // redirect. 310 static bool IsRedirectResponseCode(int response_code); 311 312 // Returns VALIDATION_NONE if the response can be reused without 313 // validation. VALIDATION_ASYNCHRONOUS means the response can be re-used, but 314 // asynchronous revalidation must be performed. VALIDATION_SYNCHRONOUS means 315 // that the result cannot be reused without revalidation. 316 // The result is relative to the current_time parameter, which is 317 // a parameter to support unit testing. The request_time parameter indicates 318 // the time at which the request was made that resulted in this response, 319 // which was received at response_time. 320 ValidationType RequiresValidation(const base::Time& request_time, 321 const base::Time& response_time, 322 const base::Time& current_time) const; 323 324 // Calculates the amount of time the server claims the response is fresh from 325 // the time the response was generated. See section 13.2.4 of RFC 2616. See 326 // RequiresValidation for a description of the response_time parameter. See 327 // the definition of FreshnessLifetimes above for the meaning of the return 328 // value. See RFC 5861 section 3 for the definition of 329 // stale-while-revalidate. 330 FreshnessLifetimes GetFreshnessLifetimes( 331 const base::Time& response_time) const; 332 333 // Returns the age of the response. See section 13.2.3 of RFC 2616. 334 // See RequiresValidation for a description of this method's parameters. 335 base::TimeDelta GetCurrentAge(const base::Time& request_time, 336 const base::Time& response_time, 337 const base::Time& current_time) const; 338 339 // The following methods extract values from the response headers. If a 340 // value is not present, or is invalid, then false is returned. Otherwise, 341 // true is returned and the out param is assigned to the corresponding value. 342 bool GetMaxAgeValue(base::TimeDelta* value) const; 343 bool GetAgeValue(base::TimeDelta* value) const; 344 bool GetDateValue(base::Time* value) const; 345 bool GetLastModifiedValue(base::Time* value) const; 346 bool GetExpiresValue(base::Time* value) const; 347 bool GetStaleWhileRevalidateValue(base::TimeDelta* value) const; 348 349 // Extracts the time value of a particular header. This method looks for the 350 // first matching header value and parses its value as a HTTP-date. 351 bool GetTimeValuedHeader(const std::string& name, base::Time* result) const; 352 353 // Determines if this response indicates a keep-alive connection. 354 bool IsKeepAlive() const; 355 356 // Returns true if this response has a strong etag or last-modified header. 357 // See section 13.3.3 of RFC 2616. 358 bool HasStrongValidators() const; 359 360 // Returns true if this response has any validator (either a Last-Modified or 361 // an ETag) regardless of whether it is strong or weak. See section 13.3.3 of 362 // RFC 2616. 363 bool HasValidators() const; 364 365 // Extracts the value of the Content-Length header or returns -1 if there is 366 // no such header in the response. 367 int64_t GetContentLength() const; 368 369 // Extracts the value of the specified header or returns -1 if there is no 370 // such header in the response. 371 int64_t GetInt64HeaderValue(const std::string& header) const; 372 373 // Extracts the values in a Content-Range header and returns true if all three 374 // values are present and valid for a 206 response; otherwise returns false. 375 // The following values will be outputted: 376 // |*first_byte_position| = inclusive position of the first byte of the range 377 // |*last_byte_position| = inclusive position of the last byte of the range 378 // |*instance_length| = size in bytes of the object requested 379 // If this method returns false, then all of the outputs will be -1. 380 bool GetContentRangeFor206(int64_t* first_byte_position, 381 int64_t* last_byte_position, 382 int64_t* instance_length) const; 383 384 // Returns true if the response is chunk-encoded. 385 bool IsChunkEncoded() const; 386 387 // Creates a Value for use with the NetLog containing the response headers. 388 base::Value::Dict NetLogParams(NetLogCaptureMode capture_mode) const; 389 390 // Returns the HTTP response code. This is 0 if the response code text seems 391 // to exist but could not be parsed. Otherwise, it defaults to 200 if the 392 // response code is not found in the raw headers. response_code()393 int response_code() const { return response_code_; } 394 395 // Returns the raw header string. raw_headers()396 const std::string& raw_headers() const { return raw_headers_; } 397 398 // Returns true if |name| is a cookie related header name. This is consistent 399 // with |PERSIST_SANS_COOKIES|. 400 static bool IsCookieResponseHeader(base::StringPiece name); 401 402 // Write a representation of this object into tracing proto. 403 void WriteIntoTrace(perfetto::TracedValue context) const; 404 405 // Returns true if this instance precises matches another. This is stronger 406 // than semantic equality as it is intended for verification that the new 407 // Builder implementation works correctly. 408 bool StrictlyEquals(const HttpResponseHeaders& other) const; 409 410 private: 411 friend class base::RefCountedThreadSafe<HttpResponseHeaders>; 412 413 using HeaderSet = std::unordered_set<std::string>; 414 415 // The members of this structure point into raw_headers_. 416 struct ParsedHeader; 417 typedef std::vector<ParsedHeader> HeaderList; 418 419 // Whether or not a header value passed to the private AddHeader() method 420 // contains commas. 421 enum class ContainsCommas { 422 kNo, // Definitely no commas. No need to parse it. 423 kYes, // Contains commas. Needs to be parsed. 424 kMaybe, // Unknown whether commas are present. Needs to be parsed. 425 }; 426 427 ~HttpResponseHeaders(); 428 429 // Initializes from the given raw headers. 430 void Parse(const std::string& raw_input); 431 432 // Helper function for ParseStatusLine. 433 // Tries to extract the "HTTP/X.Y" from a status line formatted like: 434 // HTTP/1.1 200 OK 435 // with line_begin and end pointing at the begin and end of this line. If the 436 // status line is malformed, returns HttpVersion(0,0). 437 static HttpVersion ParseVersion(std::string::const_iterator line_begin, 438 std::string::const_iterator line_end); 439 440 // Tries to extract the status line from a header block, given the first 441 // line of said header block. If the status line is malformed, we'll 442 // construct a valid one. Example input: 443 // HTTP/1.1 200 OK 444 // with line_begin and end pointing at the begin and end of this line. 445 // Output will be a normalized version of this. 446 void ParseStatusLine(std::string::const_iterator line_begin, 447 std::string::const_iterator line_end, 448 bool has_headers); 449 450 // Find the header in our list (case-insensitive) starting with |parsed_| at 451 // index |from|. Returns string::npos if not found. 452 size_t FindHeader(size_t from, base::StringPiece name) const; 453 454 // Search the Cache-Control header for a directive matching |directive|. If 455 // present, treat its value as a time offset in seconds, write it to |result|, 456 // and return true. 457 bool GetCacheControlDirective(base::StringPiece directive, 458 base::TimeDelta* result) const; 459 460 // Add header->value pair(s) to our list. The value will be split into 461 // multiple values if it contains unquoted commas. If `contains_commas` is 462 // ContainsCommas::kNo then the value will not be parsed as a performance 463 // optimization. 464 void AddHeader(std::string::const_iterator name_begin, 465 std::string::const_iterator name_end, 466 std::string::const_iterator value_begin, 467 std::string::const_iterator value_end, 468 ContainsCommas contains_commas); 469 470 // Add to parsed_ given the fields of a ParsedHeader object. 471 void AddToParsed(std::string::const_iterator name_begin, 472 std::string::const_iterator name_end, 473 std::string::const_iterator value_begin, 474 std::string::const_iterator value_end); 475 476 // Replaces the current headers with the merged version of `raw_headers` and 477 // the current headers without the headers in `headers_to_remove`. Note that 478 // `headers_to_remove` are removed from the current headers (before the 479 // merge), not after the merge. 480 // `raw_headers` is a std::string, not a const reference to a std::string, 481 // to avoid a potentially excessive copy. 482 void MergeWithHeaders(std::string raw_headers, 483 const HeaderSet& headers_to_remove); 484 485 // Adds the values from any 'cache-control: no-cache="foo,bar"' headers. 486 void AddNonCacheableHeaders(HeaderSet* header_names) const; 487 488 // Adds the set of header names that contain cookie values. 489 static void AddSensitiveHeaders(HeaderSet* header_names); 490 491 // Adds the set of rfc2616 hop-by-hop response headers. 492 static void AddHopByHopHeaders(HeaderSet* header_names); 493 494 // Adds the set of challenge response headers. 495 static void AddChallengeHeaders(HeaderSet* header_names); 496 497 // Adds the set of cookie response headers. 498 static void AddCookieHeaders(HeaderSet* header_names); 499 500 // Adds the set of content range response headers. 501 static void AddHopContentRangeHeaders(HeaderSet* header_names); 502 503 // Adds the set of transport security state headers. 504 static void AddSecurityStateHeaders(HeaderSet* header_names); 505 506 // We keep a list of ParsedHeader objects. These tell us where to locate the 507 // header-value pairs within raw_headers_. 508 HeaderList parsed_; 509 510 // The raw_headers_ consists of the normalized status line (terminated with a 511 // null byte) and then followed by the raw null-terminated headers from the 512 // input that was passed to our constructor. We preserve the input [*] to 513 // maintain as much ancillary fidelity as possible (since it is sometimes 514 // hard to tell what may matter down-stream to a consumer of XMLHttpRequest). 515 // [*] The status line may be modified. 516 std::string raw_headers_; 517 518 // This is the parsed HTTP response code. 519 int response_code_; 520 521 // The normalized http version (consistent with what GetStatusLine() returns). 522 HttpVersion http_version_; 523 }; 524 525 using ResponseHeadersCallback = 526 base::RepeatingCallback<void(scoped_refptr<const HttpResponseHeaders>)>; 527 528 } // namespace net 529 530 #endif // NET_HTTP_HTTP_RESPONSE_HEADERS_H_ 531