1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef NET_HTTP_HTTP_RESPONSE_HEADERS_H_
6 #define NET_HTTP_HTTP_RESPONSE_HEADERS_H_
11 #include "base/basictypes.h"
12 #include "base/containers/hash_tables.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/strings/string_piece.h"
15 #include "net/base/net_export.h"
16 #include "net/base/net_log.h"
17 #include "net/http/http_version.h"
19 #if defined(SPDY_PROXY_AUTH_ORIGIN)
20 #include "net/proxy/proxy_service.h"
35 // HttpResponseHeaders: parses and holds HTTP response headers.
36 class NET_EXPORT HttpResponseHeaders
37 : public base::RefCountedThreadSafe
<HttpResponseHeaders
> {
40 typedef int PersistOptions
;
41 static const PersistOptions PERSIST_RAW
= -1; // Raw, unparsed headers.
42 static const PersistOptions PERSIST_ALL
= 0; // Parsed headers.
43 static const PersistOptions PERSIST_SANS_COOKIES
= 1 << 0;
44 static const PersistOptions PERSIST_SANS_CHALLENGES
= 1 << 1;
45 static const PersistOptions PERSIST_SANS_HOP_BY_HOP
= 1 << 2;
46 static const PersistOptions PERSIST_SANS_NON_CACHEABLE
= 1 << 3;
47 static const PersistOptions PERSIST_SANS_RANGES
= 1 << 4;
48 static const PersistOptions PERSIST_SANS_SECURITY_STATE
= 1 << 5;
50 static const char kContentRange
[];
52 // Parses the given raw_headers. raw_headers should be formatted thus:
53 // includes the http status response line, each line is \0-terminated, and
54 // it's terminated by an empty line (ie, 2 \0s in a row).
55 // (Note that line continuations should have already been joined;
56 // see HttpUtil::AssembleRawHeaders)
58 // HttpResponseHeaders does not perform any encoding changes on the input.
60 explicit HttpResponseHeaders(const std::string
& raw_headers
);
62 // Initializes from the representation stored in the given pickle. The data
63 // for this object is found relative to the given pickle_iter, which should
64 // be passed to the pickle's various Read* methods.
65 HttpResponseHeaders(const Pickle
& pickle
, PickleIterator
* pickle_iter
);
67 // Appends a representation of this object to the given pickle.
68 // The options argument can be a combination of PersistOptions.
69 void Persist(Pickle
* pickle
, PersistOptions options
);
71 // Performs header merging as described in 13.5.3 of RFC 2616.
72 void Update(const HttpResponseHeaders
& new_headers
);
74 // Removes all instances of a particular header.
75 void RemoveHeader(const std::string
& name
);
77 // Removes a particular header line. The header name is compared
78 // case-insensitively.
79 void RemoveHeaderLine(const std::string
& name
, const std::string
& value
);
81 // Adds a particular header. |header| has to be a single header without any
82 // EOL termination, just [<header-name>: <header-values>]
83 // If a header with the same name is already stored, the two headers are not
84 // merged together by this method; the one provided is simply put at the
86 void AddHeader(const std::string
& header
);
88 // Replaces the current status line with the provided one (|new_status| should
90 void ReplaceStatusLine(const std::string
& new_status
);
92 // Updates headers (Content-Length and Content-Range) in the |headers| to
93 // include the right content length and range for |byte_range|. This also
94 // updates HTTP status line if |replace_status_line| is true.
95 // |byte_range| must have a valid, bounded range (i.e. coming from a valid
96 // response or should be usable for a response).
97 void UpdateWithNewRange(const HttpByteRange
& byte_range
,
99 bool replace_status_line
);
101 // Creates a normalized header string. The output will be formatted exactly
103 // HTTP/<version> <status_code> <status_text>\n
104 // [<header-name>: <header-values>\n]*
105 // meaning, each line is \n-terminated, and there is no extra whitespace
106 // beyond the single space separators shown (of course, values can contain
107 // whitespace within them). If a given header-name appears more than once
108 // in the set of headers, they are combined into a single line like so:
109 // <header-name>: <header-value1>, <header-value2>, ...<header-valueN>\n
111 // DANGER: For some headers (e.g., "Set-Cookie"), the normalized form can be
112 // a lossy format. This is due to the fact that some servers generate
113 // Set-Cookie headers that contain unquoted commas (usually as part of the
114 // value of an "expires" attribute). So, use this function with caution. Do
115 // not expect to be able to re-parse Set-Cookie headers from this output.
117 // NOTE: Do not make any assumptions about the encoding of this output
118 // string. It may be non-ASCII, and the encoding used by the server is not
119 // necessarily known to us. Do not assume that this output is UTF-8!
121 // TODO(darin): remove this method
123 void GetNormalizedHeaders(std::string
* output
) const;
125 // Fetch the "normalized" value of a single header, where all values for the
126 // header name are separated by commas. See the GetNormalizedHeaders for
127 // format details. Returns false if this header wasn't found.
129 // NOTE: Do not make any assumptions about the encoding of this output
130 // string. It may be non-ASCII, and the encoding used by the server is not
131 // necessarily known to us. Do not assume that this output is UTF-8!
133 // TODO(darin): remove this method
135 bool GetNormalizedHeader(const std::string
& name
, std::string
* value
) const;
137 // Returns the normalized status line. For HTTP/0.9 responses (i.e.,
138 // responses that lack a status line), this is the manufactured string
139 // "HTTP/0.9 200 OK".
140 std::string
GetStatusLine() const;
142 // Get the HTTP version of the normalized status line.
143 HttpVersion
GetHttpVersion() const {
144 return http_version_
;
147 // Get the HTTP version determined while parsing; or (0,0) if parsing failed
148 HttpVersion
GetParsedHttpVersion() const {
149 return parsed_http_version_
;
152 // Get the HTTP status text of the normalized status line.
153 std::string
GetStatusText() const;
155 // Enumerate the "lines" of the response headers. This skips over the status
156 // line. Use GetStatusLine if you are interested in that. Note that this
157 // method returns the un-coalesced response header lines, so if a response
158 // header appears on multiple lines, then it will appear multiple times in
159 // this enumeration (in the order the header lines were received from the
160 // server). Also, a given header might have an empty value. Initialize a
161 // 'void*' variable to NULL and pass it by address to EnumerateHeaderLines.
162 // Call EnumerateHeaderLines repeatedly until it returns false. The
163 // out-params 'name' and 'value' are set upon success.
164 bool EnumerateHeaderLines(void** iter
,
166 std::string
* value
) const;
168 // Enumerate the values of the specified header. If you are only interested
169 // in the first header, then you can pass NULL for the 'iter' parameter.
170 // Otherwise, to iterate across all values for the specified header,
171 // initialize a 'void*' variable to NULL and pass it by address to
172 // EnumerateHeader. Note that a header might have an empty value. Call
173 // EnumerateHeader repeatedly until it returns false.
174 bool EnumerateHeader(void** iter
,
175 const base::StringPiece
& name
,
176 std::string
* value
) const;
178 // Returns true if the response contains the specified header-value pair.
179 // Both name and value are compared case insensitively.
180 bool HasHeaderValue(const base::StringPiece
& name
,
181 const base::StringPiece
& value
) const;
183 // Returns true if the response contains the specified header.
184 // The name is compared case insensitively.
185 bool HasHeader(const base::StringPiece
& name
) const;
187 // Get the mime type and charset values in lower case form from the headers.
188 // Empty strings are returned if the values are not present.
189 void GetMimeTypeAndCharset(std::string
* mime_type
,
190 std::string
* charset
) const;
192 // Get the mime type in lower case from the headers. If there's no mime
193 // type, returns false.
194 bool GetMimeType(std::string
* mime_type
) const;
196 // Get the charset in lower case from the headers. If there's no charset,
198 bool GetCharset(std::string
* charset
) const;
200 // Returns true if this response corresponds to a redirect. The target
201 // location of the redirect is optionally returned if location is non-null.
202 bool IsRedirect(std::string
* location
) const;
204 // Returns true if the HTTP response code passed in corresponds to a
206 static bool IsRedirectResponseCode(int response_code
);
208 // Returns true if the response cannot be reused without validation. The
209 // result is relative to the current_time parameter, which is a parameter to
210 // support unit testing. The request_time parameter indicates the time at
211 // which the request was made that resulted in this response, which was
212 // received at response_time.
213 bool RequiresValidation(const base::Time
& request_time
,
214 const base::Time
& response_time
,
215 const base::Time
& current_time
) const;
217 // Returns the amount of time the server claims the response is fresh from
218 // the time the response was generated. See section 13.2.4 of RFC 2616. See
219 // RequiresValidation for a description of the response_time parameter.
220 base::TimeDelta
GetFreshnessLifetime(const base::Time
& response_time
) const;
222 // Returns the age of the response. See section 13.2.3 of RFC 2616.
223 // See RequiresValidation for a description of this method's parameters.
224 base::TimeDelta
GetCurrentAge(const base::Time
& request_time
,
225 const base::Time
& response_time
,
226 const base::Time
& current_time
) const;
228 // The following methods extract values from the response headers. If a
229 // value is not present, then false is returned. Otherwise, true is returned
230 // and the out param is assigned to the corresponding value.
231 bool GetMaxAgeValue(base::TimeDelta
* value
) const;
232 bool GetAgeValue(base::TimeDelta
* value
) const;
233 bool GetDateValue(base::Time
* value
) const;
234 bool GetLastModifiedValue(base::Time
* value
) const;
235 bool GetExpiresValue(base::Time
* value
) const;
237 // Extracts the time value of a particular header. This method looks for the
238 // first matching header value and parses its value as a HTTP-date.
239 bool GetTimeValuedHeader(const std::string
& name
, base::Time
* result
) const;
241 // Determines if this response indicates a keep-alive connection.
242 bool IsKeepAlive() const;
244 // Returns true if this response has a strong etag or last-modified header.
245 // See section 13.3.3 of RFC 2616.
246 bool HasStrongValidators() const;
248 // Extracts the value of the Content-Length header or returns -1 if there is
249 // no such header in the response.
250 int64
GetContentLength() const;
252 // Extracts the value of the specified header or returns -1 if there is no
253 // such header in the response.
254 int64
GetInt64HeaderValue(const std::string
& header
) const;
256 // Extracts the values in a Content-Range header and returns true if they are
257 // valid for a 206 response; otherwise returns false.
258 // The following values will be outputted:
259 // |*first_byte_position| = inclusive position of the first byte of the range
260 // |*last_byte_position| = inclusive position of the last byte of the range
261 // |*instance_length| = size in bytes of the object requested
262 // If any of the above values is unknown, its value will be -1.
263 bool GetContentRange(int64
* first_byte_position
,
264 int64
* last_byte_position
,
265 int64
* instance_length
) const;
267 // Returns true if the response is chunk-encoded.
268 bool IsChunkEncoded() const;
270 #if defined (SPDY_PROXY_AUTH_ORIGIN)
271 // Contains instructions contained in the Chrome-Proxy header.
272 struct ChromeProxyInfo
{
273 ChromeProxyInfo() : bypass_all(false) {}
275 // True if Chrome should bypass all available Chrome proxies. False if only
276 // the currently connected Chrome proxy should be bypassed.
279 // Amount of time to bypass the Chrome proxy or proxies.
280 base::TimeDelta bypass_duration
;
283 // Returns true if the Chrome-Proxy header is present and contains a bypass
284 // delay. Sets |proxy_info->bypass_duration| to the specified delay if greater
285 // than 0, and to 0 otherwise to indicate that the default proxy delay
286 // (as specified in |ProxyList::UpdateRetryInfoOnFallback|) should be used.
287 // If all available Chrome proxies should by bypassed, |bypass_all| is set to
288 // true. |proxy_info| must be non-NULL.
289 bool GetChromeProxyInfo(ChromeProxyInfo
* proxy_info
) const;
291 // Returns true if response headers contain the Chrome proxy Via header value.
292 bool IsChromeProxyResponse() const;
294 // Returns the reason why the Chrome proxy should be bypassed or not, and
295 // populates |proxy_info| with information on how long to bypass if
297 ProxyService::DataReductionProxyBypassEventType
298 GetChromeProxyBypassEventType(ChromeProxyInfo
* proxy_info
) const;
301 // Creates a Value for use with the NetLog containing the response headers.
302 base::Value
* NetLogCallback(NetLog::LogLevel log_level
) const;
304 // Takes in a Value created by the above function, and attempts to create a
305 // copy of the original headers. Returns true on success. On failure,
306 // clears |http_response_headers|.
307 // TODO(mmenke): Long term, we want to remove this, and migrate external
308 // consumers to be NetworkDelegates.
309 static bool FromNetLogParam(
310 const base::Value
* event_param
,
311 scoped_refptr
<HttpResponseHeaders
>* http_response_headers
);
313 // Returns the HTTP response code. This is 0 if the response code text seems
314 // to exist but could not be parsed. Otherwise, it defaults to 200 if the
315 // response code is not found in the raw headers.
316 int response_code() const { return response_code_
; }
318 // Returns the raw header string.
319 const std::string
& raw_headers() const { return raw_headers_
; }
322 friend class base::RefCountedThreadSafe
<HttpResponseHeaders
>;
324 typedef base::hash_set
<std::string
> HeaderSet
;
326 // The members of this structure point into raw_headers_.
328 typedef std::vector
<ParsedHeader
> HeaderList
;
330 HttpResponseHeaders();
331 ~HttpResponseHeaders();
333 // Initializes from the given raw headers.
334 void Parse(const std::string
& raw_input
);
336 // Helper function for ParseStatusLine.
337 // Tries to extract the "HTTP/X.Y" from a status line formatted like:
339 // with line_begin and end pointing at the begin and end of this line. If the
340 // status line is malformed, returns HttpVersion(0,0).
341 static HttpVersion
ParseVersion(std::string::const_iterator line_begin
,
342 std::string::const_iterator line_end
);
344 // Tries to extract the status line from a header block, given the first
345 // line of said header block. If the status line is malformed, we'll
346 // construct a valid one. Example input:
348 // with line_begin and end pointing at the begin and end of this line.
349 // Output will be a normalized version of this.
350 void ParseStatusLine(std::string::const_iterator line_begin
,
351 std::string::const_iterator line_end
,
354 // Find the header in our list (case-insensitive) starting with parsed_ at
355 // index |from|. Returns string::npos if not found.
356 size_t FindHeader(size_t from
, const base::StringPiece
& name
) const;
358 // Add a header->value pair to our list. If we already have header in our
359 // list, append the value to it.
360 void AddHeader(std::string::const_iterator name_begin
,
361 std::string::const_iterator name_end
,
362 std::string::const_iterator value_begin
,
363 std::string::const_iterator value_end
);
365 // Add to parsed_ given the fields of a ParsedHeader object.
366 void AddToParsed(std::string::const_iterator name_begin
,
367 std::string::const_iterator name_end
,
368 std::string::const_iterator value_begin
,
369 std::string::const_iterator value_end
);
371 // Replaces the current headers with the merged version of |raw_headers| and
372 // the current headers without the headers in |headers_to_remove|. Note that
373 // |headers_to_remove| are removed from the current headers (before the
374 // merge), not after the merge.
375 void MergeWithHeaders(const std::string
& raw_headers
,
376 const HeaderSet
& headers_to_remove
);
378 // Adds the values from any 'cache-control: no-cache="foo,bar"' headers.
379 void AddNonCacheableHeaders(HeaderSet
* header_names
) const;
381 // Adds the set of header names that contain cookie values.
382 static void AddSensitiveHeaders(HeaderSet
* header_names
);
384 // Adds the set of rfc2616 hop-by-hop response headers.
385 static void AddHopByHopHeaders(HeaderSet
* header_names
);
387 // Adds the set of challenge response headers.
388 static void AddChallengeHeaders(HeaderSet
* header_names
);
390 // Adds the set of cookie response headers.
391 static void AddCookieHeaders(HeaderSet
* header_names
);
393 // Adds the set of content range response headers.
394 static void AddHopContentRangeHeaders(HeaderSet
* header_names
);
396 // Adds the set of transport security state headers.
397 static void AddSecurityStateHeaders(HeaderSet
* header_names
);
399 #if defined(SPDY_PROXY_AUTH_ORIGIN)
400 // Searches for the specified Chrome-Proxy action, and if present interprets
401 // its value as a duration in seconds.
402 bool GetChromeProxyBypassDuration(const std::string
& action_prefix
,
403 base::TimeDelta
* duration
) const;
406 // We keep a list of ParsedHeader objects. These tell us where to locate the
407 // header-value pairs within raw_headers_.
410 // The raw_headers_ consists of the normalized status line (terminated with a
411 // null byte) and then followed by the raw null-terminated headers from the
412 // input that was passed to our constructor. We preserve the input [*] to
413 // maintain as much ancillary fidelity as possible (since it is sometimes
414 // hard to tell what may matter down-stream to a consumer of XMLHttpRequest).
415 // [*] The status line may be modified.
416 std::string raw_headers_
;
418 // This is the parsed HTTP response code.
421 // The normalized http version (consistent with what GetStatusLine() returns).
422 HttpVersion http_version_
;
424 // The parsed http version number (not normalized).
425 HttpVersion parsed_http_version_
;
427 DISALLOW_COPY_AND_ASSIGN(HttpResponseHeaders
);
432 #endif // NET_HTTP_HTTP_RESPONSE_HEADERS_H_