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