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