Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / net / http / http_response_headers.h
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.
4
5 #ifndef NET_HTTP_HTTP_RESPONSE_HEADERS_H_
6 #define NET_HTTP_HTTP_RESPONSE_HEADERS_H_
7
8 #include <string>
9 #include <vector>
10
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"
18
19 class Pickle;
20 class PickleIterator;
21
22 namespace base {
23 class Time;
24 class TimeDelta;
25 }
26
27 namespace net {
28
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;
43
44   static const char kContentRange[];
45
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)
51   //
52   // HttpResponseHeaders does not perform any encoding changes on the input.
53   //
54   explicit HttpResponseHeaders(const std::string& raw_headers);
55
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);
60
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);
64
65   // Performs header merging as described in 13.5.3 of RFC 2616.
66   void Update(const HttpResponseHeaders& new_headers);
67
68   // Removes all instances of a particular header.
69   void RemoveHeader(const std::string& name);
70
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);
74
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);
81
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);
85
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
95   //
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.
101   //
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!
105   //
106   // TODO(darin): remove this method
107   //
108   void GetNormalizedHeaders(std::string* output) const;
109
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.
113   //
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!
117   //
118   // TODO(darin): remove this method
119   //
120   bool GetNormalizedHeader(const std::string& name, std::string* value) const;
121
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;
126
127   // Get the HTTP version of the normalized status line.
128   HttpVersion GetHttpVersion() const {
129     return http_version_;
130   }
131
132   // Get the HTTP version determined while parsing; or (0,0) if parsing failed
133   HttpVersion GetParsedHttpVersion() const {
134     return parsed_http_version_;
135   }
136
137   // Get the HTTP status text of the normalized status line.
138   std::string GetStatusText() const;
139
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;
152
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;
162
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;
167
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;
171
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;
176
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;
180
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;
184
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;
188
189   // Returns true if the HTTP response code passed in corresponds to a
190   // redirect.
191   static bool IsRedirectResponseCode(int response_code);
192
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;
201
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;
206
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;
212
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;
221
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;
225
226   // Determines if this response indicates a keep-alive connection.
227   bool IsKeepAlive() const;
228
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;
232
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;
236
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;
240
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;
251
252   // Returns true if the response is chunk-encoded.
253   bool IsChunkEncoded() const;
254
255 #if defined (SPDY_PROXY_AUTH_ORIGIN)
256   // Contains instructions contained in the Chrome-Proxy header.
257   struct ChromeProxyInfo {
258     ChromeProxyInfo() : bypass_all(false) {}
259
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;
263
264     // Amount of time to bypass the Chrome proxy or proxies.
265     base::TimeDelta bypass_duration;
266   };
267
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
276   // Returns true if response headers contain the Chrome proxy Via header value.
277   bool IsChromeProxyResponse() const;
278 #endif
279
280   // Creates a Value for use with the NetLog containing the response headers.
281   base::Value* NetLogCallback(NetLog::LogLevel log_level) const;
282
283   // Takes in a Value created by the above function, and attempts to create a
284   // copy of the original headers.  Returns true on success.  On failure,
285   // clears |http_response_headers|.
286   // TODO(mmenke):  Long term, we want to remove this, and migrate external
287   //                consumers to be NetworkDelegates.
288   static bool FromNetLogParam(
289       const base::Value* event_param,
290       scoped_refptr<HttpResponseHeaders>* http_response_headers);
291
292   // Returns the HTTP response code.  This is 0 if the response code text seems
293   // to exist but could not be parsed.  Otherwise, it defaults to 200 if the
294   // response code is not found in the raw headers.
295   int response_code() const { return response_code_; }
296
297   // Returns the raw header string.
298   const std::string& raw_headers() const { return raw_headers_; }
299
300  private:
301   friend class base::RefCountedThreadSafe<HttpResponseHeaders>;
302
303   typedef base::hash_set<std::string> HeaderSet;
304
305   // The members of this structure point into raw_headers_.
306   struct ParsedHeader;
307   typedef std::vector<ParsedHeader> HeaderList;
308
309   HttpResponseHeaders();
310   ~HttpResponseHeaders();
311
312   // Initializes from the given raw headers.
313   void Parse(const std::string& raw_input);
314
315   // Helper function for ParseStatusLine.
316   // Tries to extract the "HTTP/X.Y" from a status line formatted like:
317   //    HTTP/1.1 200 OK
318   // with line_begin and end pointing at the begin and end of this line.  If the
319   // status line is malformed, returns HttpVersion(0,0).
320   static HttpVersion ParseVersion(std::string::const_iterator line_begin,
321                                   std::string::const_iterator line_end);
322
323   // Tries to extract the status line from a header block, given the first
324   // line of said header block.  If the status line is malformed, we'll
325   // construct a valid one.  Example input:
326   //    HTTP/1.1 200 OK
327   // with line_begin and end pointing at the begin and end of this line.
328   // Output will be a normalized version of this.
329   void ParseStatusLine(std::string::const_iterator line_begin,
330                        std::string::const_iterator line_end,
331                        bool has_headers);
332
333   // Find the header in our list (case-insensitive) starting with parsed_ at
334   // index |from|.  Returns string::npos if not found.
335   size_t FindHeader(size_t from, const base::StringPiece& name) const;
336
337   // Add a header->value pair to our list.  If we already have header in our
338   // list, append the value to it.
339   void AddHeader(std::string::const_iterator name_begin,
340                  std::string::const_iterator name_end,
341                  std::string::const_iterator value_begin,
342                  std::string::const_iterator value_end);
343
344   // Add to parsed_ given the fields of a ParsedHeader object.
345   void AddToParsed(std::string::const_iterator name_begin,
346                    std::string::const_iterator name_end,
347                    std::string::const_iterator value_begin,
348                    std::string::const_iterator value_end);
349
350   // Replaces the current headers with the merged version of |raw_headers| and
351   // the current headers without the headers in |headers_to_remove|. Note that
352   // |headers_to_remove| are removed from the current headers (before the
353   // merge), not after the merge.
354   void MergeWithHeaders(const std::string& raw_headers,
355                         const HeaderSet& headers_to_remove);
356
357   // Adds the values from any 'cache-control: no-cache="foo,bar"' headers.
358   void AddNonCacheableHeaders(HeaderSet* header_names) const;
359
360   // Adds the set of header names that contain cookie values.
361   static void AddSensitiveHeaders(HeaderSet* header_names);
362
363   // Adds the set of rfc2616 hop-by-hop response headers.
364   static void AddHopByHopHeaders(HeaderSet* header_names);
365
366   // Adds the set of challenge response headers.
367   static void AddChallengeHeaders(HeaderSet* header_names);
368
369   // Adds the set of cookie response headers.
370   static void AddCookieHeaders(HeaderSet* header_names);
371
372   // Adds the set of content range response headers.
373   static void AddHopContentRangeHeaders(HeaderSet* header_names);
374
375   // Adds the set of transport security state headers.
376   static void AddSecurityStateHeaders(HeaderSet* header_names);
377
378 #if defined(SPDY_PROXY_AUTH_ORIGIN)
379   // Searches for the specified Chrome-Proxy action, and if present interprets
380   // its value as a duration in seconds.
381   bool GetChromeProxyBypassDuration(const std::string& action_prefix,
382                                     base::TimeDelta* duration) const;
383 #endif
384
385   // We keep a list of ParsedHeader objects.  These tell us where to locate the
386   // header-value pairs within raw_headers_.
387   HeaderList parsed_;
388
389   // The raw_headers_ consists of the normalized status line (terminated with a
390   // null byte) and then followed by the raw null-terminated headers from the
391   // input that was passed to our constructor.  We preserve the input [*] to
392   // maintain as much ancillary fidelity as possible (since it is sometimes
393   // hard to tell what may matter down-stream to a consumer of XMLHttpRequest).
394   // [*] The status line may be modified.
395   std::string raw_headers_;
396
397   // This is the parsed HTTP response code.
398   int response_code_;
399
400   // The normalized http version (consistent with what GetStatusLine() returns).
401   HttpVersion http_version_;
402
403   // The parsed http version number (not normalized).
404   HttpVersion parsed_http_version_;
405
406   DISALLOW_COPY_AND_ASSIGN(HttpResponseHeaders);
407 };
408
409 }  // namespace net
410
411 #endif  // NET_HTTP_HTTP_RESPONSE_HEADERS_H_