Upstream version 7.36.149.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 #if defined(SPDY_PROXY_AUTH_ORIGIN)
20 #include "net/proxy/proxy_service.h"
21 #endif
22
23 class Pickle;
24 class PickleIterator;
25
26 namespace base {
27 class Time;
28 class TimeDelta;
29 }
30
31 namespace net {
32
33 class HttpByteRange;
34
35 // HttpResponseHeaders: parses and holds HTTP response headers.
36 class NET_EXPORT HttpResponseHeaders
37     : public base::RefCountedThreadSafe<HttpResponseHeaders> {
38  public:
39   // Persist options.
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;
49
50   static const char kContentRange[];
51
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)
57   //
58   // HttpResponseHeaders does not perform any encoding changes on the input.
59   //
60   explicit HttpResponseHeaders(const std::string& raw_headers);
61
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);
66
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);
70
71   // Performs header merging as described in 13.5.3 of RFC 2616.
72   void Update(const HttpResponseHeaders& new_headers);
73
74   // Removes all instances of a particular header.
75   void RemoveHeader(const std::string& name);
76
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);
80
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
85   // end of the list.
86   void AddHeader(const std::string& header);
87
88   // Replaces the current status line with the provided one (|new_status| should
89   // not have any EOL).
90   void ReplaceStatusLine(const std::string& new_status);
91
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,
98                           int64 resource_size,
99                           bool replace_status_line);
100
101   // Creates a normalized header string.  The output will be formatted exactly
102   // like so:
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
110   //
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.
116   //
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!
120   //
121   // TODO(darin): remove this method
122   //
123   void GetNormalizedHeaders(std::string* output) const;
124
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.
128   //
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!
132   //
133   // TODO(darin): remove this method
134   //
135   bool GetNormalizedHeader(const std::string& name, std::string* value) const;
136
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;
141
142   // Get the HTTP version of the normalized status line.
143   HttpVersion GetHttpVersion() const {
144     return http_version_;
145   }
146
147   // Get the HTTP version determined while parsing; or (0,0) if parsing failed
148   HttpVersion GetParsedHttpVersion() const {
149     return parsed_http_version_;
150   }
151
152   // Get the HTTP status text of the normalized status line.
153   std::string GetStatusText() const;
154
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,
165                             std::string* name,
166                             std::string* value) const;
167
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;
177
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;
182
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;
186
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;
191
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;
195
196   // Get the charset in lower case from the headers.  If there's no charset,
197   // returns false.
198   bool GetCharset(std::string* charset) const;
199
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;
203
204   // Returns true if the HTTP response code passed in corresponds to a
205   // redirect.
206   static bool IsRedirectResponseCode(int response_code);
207
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;
216
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;
221
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;
227
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;
236
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;
240
241   // Determines if this response indicates a keep-alive connection.
242   bool IsKeepAlive() const;
243
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;
247
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;
251
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;
255
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;
266
267   // Returns true if the response is chunk-encoded.
268   bool IsChunkEncoded() const;
269
270 #if defined (SPDY_PROXY_AUTH_ORIGIN)
271   // Contains instructions contained in the Chrome-Proxy header.
272   struct DataReductionProxyInfo {
273     DataReductionProxyInfo() : bypass_all(false) {}
274
275     // True if Chrome should bypass all available data reduction proxies. False
276     // if only the currently connected data reduction proxy should be bypassed.
277     bool bypass_all;
278
279     // Amount of time to bypass the data reduction proxy or proxies.
280     base::TimeDelta bypass_duration;
281   };
282
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 data reduction proxies should by bypassed, |bypass_all| is
288   // set to true. |proxy_info| must be non-NULL.
289   bool GetDataReductionProxyInfo(DataReductionProxyInfo* proxy_info) const;
290
291   // Returns the reason why the Chrome proxy should be bypassed or not, and
292   // populates |proxy_info| with information on how long to bypass if
293   // applicable.
294   ProxyService::DataReductionProxyBypassEventType
295   GetDataReductionProxyBypassEventType(
296       DataReductionProxyInfo* proxy_info) const;
297 #endif
298
299   // Returns true if response headers contain the data reduction proxy Via
300   // header value.
301   bool IsDataReductionProxyResponse() const;
302
303   // Creates a Value for use with the NetLog containing the response headers.
304   base::Value* NetLogCallback(NetLog::LogLevel log_level) const;
305
306   // Takes in a Value created by the above function, and attempts to create a
307   // copy of the original headers.  Returns true on success.  On failure,
308   // clears |http_response_headers|.
309   // TODO(mmenke):  Long term, we want to remove this, and migrate external
310   //                consumers to be NetworkDelegates.
311   static bool FromNetLogParam(
312       const base::Value* event_param,
313       scoped_refptr<HttpResponseHeaders>* http_response_headers);
314
315   // Returns the HTTP response code.  This is 0 if the response code text seems
316   // to exist but could not be parsed.  Otherwise, it defaults to 200 if the
317   // response code is not found in the raw headers.
318   int response_code() const { return response_code_; }
319
320   // Returns the raw header string.
321   const std::string& raw_headers() const { return raw_headers_; }
322
323  private:
324   friend class base::RefCountedThreadSafe<HttpResponseHeaders>;
325
326   typedef base::hash_set<std::string> HeaderSet;
327
328   // The members of this structure point into raw_headers_.
329   struct ParsedHeader;
330   typedef std::vector<ParsedHeader> HeaderList;
331
332   HttpResponseHeaders();
333   ~HttpResponseHeaders();
334
335   // Initializes from the given raw headers.
336   void Parse(const std::string& raw_input);
337
338   // Helper function for ParseStatusLine.
339   // Tries to extract the "HTTP/X.Y" from a status line formatted like:
340   //    HTTP/1.1 200 OK
341   // with line_begin and end pointing at the begin and end of this line.  If the
342   // status line is malformed, returns HttpVersion(0,0).
343   static HttpVersion ParseVersion(std::string::const_iterator line_begin,
344                                   std::string::const_iterator line_end);
345
346   // Tries to extract the status line from a header block, given the first
347   // line of said header block.  If the status line is malformed, we'll
348   // construct a valid one.  Example input:
349   //    HTTP/1.1 200 OK
350   // with line_begin and end pointing at the begin and end of this line.
351   // Output will be a normalized version of this.
352   void ParseStatusLine(std::string::const_iterator line_begin,
353                        std::string::const_iterator line_end,
354                        bool has_headers);
355
356   // Find the header in our list (case-insensitive) starting with parsed_ at
357   // index |from|.  Returns string::npos if not found.
358   size_t FindHeader(size_t from, const base::StringPiece& name) const;
359
360   // Add a header->value pair to our list.  If we already have header in our
361   // list, append the value to it.
362   void AddHeader(std::string::const_iterator name_begin,
363                  std::string::const_iterator name_end,
364                  std::string::const_iterator value_begin,
365                  std::string::const_iterator value_end);
366
367   // Add to parsed_ given the fields of a ParsedHeader object.
368   void AddToParsed(std::string::const_iterator name_begin,
369                    std::string::const_iterator name_end,
370                    std::string::const_iterator value_begin,
371                    std::string::const_iterator value_end);
372
373   // Replaces the current headers with the merged version of |raw_headers| and
374   // the current headers without the headers in |headers_to_remove|. Note that
375   // |headers_to_remove| are removed from the current headers (before the
376   // merge), not after the merge.
377   void MergeWithHeaders(const std::string& raw_headers,
378                         const HeaderSet& headers_to_remove);
379
380   // Adds the values from any 'cache-control: no-cache="foo,bar"' headers.
381   void AddNonCacheableHeaders(HeaderSet* header_names) const;
382
383   // Adds the set of header names that contain cookie values.
384   static void AddSensitiveHeaders(HeaderSet* header_names);
385
386   // Adds the set of rfc2616 hop-by-hop response headers.
387   static void AddHopByHopHeaders(HeaderSet* header_names);
388
389   // Adds the set of challenge response headers.
390   static void AddChallengeHeaders(HeaderSet* header_names);
391
392   // Adds the set of cookie response headers.
393   static void AddCookieHeaders(HeaderSet* header_names);
394
395   // Adds the set of content range response headers.
396   static void AddHopContentRangeHeaders(HeaderSet* header_names);
397
398   // Adds the set of transport security state headers.
399   static void AddSecurityStateHeaders(HeaderSet* header_names);
400
401 #if defined(SPDY_PROXY_AUTH_ORIGIN)
402   // Searches for the specified Chrome-Proxy action, and if present interprets
403   // its value as a duration in seconds.
404   bool GetDataReductionProxyBypassDuration(const std::string& action_prefix,
405                                            base::TimeDelta* duration) const;
406 #endif
407
408   // We keep a list of ParsedHeader objects.  These tell us where to locate the
409   // header-value pairs within raw_headers_.
410   HeaderList parsed_;
411
412   // The raw_headers_ consists of the normalized status line (terminated with a
413   // null byte) and then followed by the raw null-terminated headers from the
414   // input that was passed to our constructor.  We preserve the input [*] to
415   // maintain as much ancillary fidelity as possible (since it is sometimes
416   // hard to tell what may matter down-stream to a consumer of XMLHttpRequest).
417   // [*] The status line may be modified.
418   std::string raw_headers_;
419
420   // This is the parsed HTTP response code.
421   int response_code_;
422
423   // The normalized http version (consistent with what GetStatusLine() returns).
424   HttpVersion http_version_;
425
426   // The parsed http version number (not normalized).
427   HttpVersion parsed_http_version_;
428
429   DISALLOW_COPY_AND_ASSIGN(HttpResponseHeaders);
430 };
431
432 }  // namespace net
433
434 #endif  // NET_HTTP_HTTP_RESPONSE_HEADERS_H_