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