Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / net / http / http_response_headers.h
blob3d8e656cfbfd9a6da75760061ade85f5eb57a295
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/http/http_version.h"
17 #include "net/log/net_log.h"
19 namespace base {
20 class Pickle;
21 class PickleIterator;
22 class Time;
23 class TimeDelta;
26 namespace net {
28 class HttpByteRange;
30 enum ValidationType {
31 VALIDATION_NONE, // The resource is fresh.
32 VALIDATION_ASYNCHRONOUS, // The resource requires async revalidation.
33 VALIDATION_SYNCHRONOUS // The resource requires sync revalidation.
36 // HttpResponseHeaders: parses and holds HTTP response headers.
37 class NET_EXPORT HttpResponseHeaders
38 : public base::RefCountedThreadSafe<HttpResponseHeaders> {
39 public:
40 // Persist options.
41 typedef int PersistOptions;
42 static const PersistOptions PERSIST_RAW = -1; // Raw, unparsed headers.
43 static const PersistOptions PERSIST_ALL = 0; // Parsed headers.
44 static const PersistOptions PERSIST_SANS_COOKIES = 1 << 0;
45 static const PersistOptions PERSIST_SANS_CHALLENGES = 1 << 1;
46 static const PersistOptions PERSIST_SANS_HOP_BY_HOP = 1 << 2;
47 static const PersistOptions PERSIST_SANS_NON_CACHEABLE = 1 << 3;
48 static const PersistOptions PERSIST_SANS_RANGES = 1 << 4;
49 static const PersistOptions PERSIST_SANS_SECURITY_STATE = 1 << 5;
51 struct FreshnessLifetimes {
52 // How long the resource will be fresh for.
53 base::TimeDelta freshness;
54 // How long after becoming not fresh that the resource will be stale but
55 // usable (if async revalidation is enabled).
56 base::TimeDelta staleness;
59 static const char kContentRange[];
61 // Parses the given raw_headers. raw_headers should be formatted thus:
62 // includes the http status response line, each line is \0-terminated, and
63 // it's terminated by an empty line (ie, 2 \0s in a row).
64 // (Note that line continuations should have already been joined;
65 // see HttpUtil::AssembleRawHeaders)
67 // HttpResponseHeaders does not perform any encoding changes on the input.
69 explicit HttpResponseHeaders(const std::string& raw_headers);
71 // Initializes from the representation stored in the given pickle. The data
72 // for this object is found relative to the given pickle_iter, which should
73 // be passed to the pickle's various Read* methods.
74 explicit HttpResponseHeaders(base::PickleIterator* pickle_iter);
76 // Appends a representation of this object to the given pickle.
77 // The options argument can be a combination of PersistOptions.
78 void Persist(base::Pickle* pickle, PersistOptions options);
80 // Performs header merging as described in 13.5.3 of RFC 2616.
81 void Update(const HttpResponseHeaders& new_headers);
83 // Removes all instances of a particular header.
84 void RemoveHeader(const std::string& name);
86 // Removes a particular header line. The header name is compared
87 // case-insensitively.
88 void RemoveHeaderLine(const std::string& name, const std::string& value);
90 // Adds a particular header. |header| has to be a single header without any
91 // EOL termination, just [<header-name>: <header-values>]
92 // If a header with the same name is already stored, the two headers are not
93 // merged together by this method; the one provided is simply put at the
94 // end of the list.
95 void AddHeader(const std::string& header);
97 // Replaces the current status line with the provided one (|new_status| should
98 // not have any EOL).
99 void ReplaceStatusLine(const std::string& new_status);
101 // Updates headers (Content-Length and Content-Range) in the |headers| to
102 // include the right content length and range for |byte_range|. This also
103 // updates HTTP status line if |replace_status_line| is true.
104 // |byte_range| must have a valid, bounded range (i.e. coming from a valid
105 // response or should be usable for a response).
106 void UpdateWithNewRange(const HttpByteRange& byte_range,
107 int64 resource_size,
108 bool replace_status_line);
110 // Creates a normalized header string. The output will be formatted exactly
111 // like so:
112 // HTTP/<version> <status_code> <status_text>\n
113 // [<header-name>: <header-values>\n]*
114 // meaning, each line is \n-terminated, and there is no extra whitespace
115 // beyond the single space separators shown (of course, values can contain
116 // whitespace within them). If a given header-name appears more than once
117 // in the set of headers, they are combined into a single line like so:
118 // <header-name>: <header-value1>, <header-value2>, ...<header-valueN>\n
120 // DANGER: For some headers (e.g., "Set-Cookie"), the normalized form can be
121 // a lossy format. This is due to the fact that some servers generate
122 // Set-Cookie headers that contain unquoted commas (usually as part of the
123 // value of an "expires" attribute). So, use this function with caution. Do
124 // not expect to be able to re-parse Set-Cookie headers from this output.
126 // NOTE: Do not make any assumptions about the encoding of this output
127 // string. It may be non-ASCII, and the encoding used by the server is not
128 // necessarily known to us. Do not assume that this output is UTF-8!
130 // TODO(darin): remove this method
132 void GetNormalizedHeaders(std::string* output) const;
134 // Fetch the "normalized" value of a single header, where all values for the
135 // header name are separated by commas. See the GetNormalizedHeaders for
136 // format details. Returns false if this header wasn't found.
138 // NOTE: Do not make any assumptions about the encoding of this output
139 // string. It may be non-ASCII, and the encoding used by the server is not
140 // necessarily known to us. Do not assume that this output is UTF-8!
142 // TODO(darin): remove this method
144 bool GetNormalizedHeader(const std::string& name, std::string* value) const;
146 // Returns the normalized status line. For HTTP/0.9 responses (i.e.,
147 // responses that lack a status line), this is the manufactured string
148 // "HTTP/0.9 200 OK".
149 std::string GetStatusLine() const;
151 // Get the HTTP version of the normalized status line.
152 HttpVersion GetHttpVersion() const {
153 return http_version_;
156 // Get the HTTP version determined while parsing; or (0,0) if parsing failed
157 HttpVersion GetParsedHttpVersion() const {
158 return parsed_http_version_;
161 // Get the HTTP status text of the normalized status line.
162 std::string GetStatusText() const;
164 // Enumerate the "lines" of the response headers. This skips over the status
165 // line. Use GetStatusLine if you are interested in that. Note that this
166 // method returns the un-coalesced response header lines, so if a response
167 // header appears on multiple lines, then it will appear multiple times in
168 // this enumeration (in the order the header lines were received from the
169 // server). Also, a given header might have an empty value. Initialize a
170 // 'void*' variable to NULL and pass it by address to EnumerateHeaderLines.
171 // Call EnumerateHeaderLines repeatedly until it returns false. The
172 // out-params 'name' and 'value' are set upon success.
173 bool EnumerateHeaderLines(void** iter,
174 std::string* name,
175 std::string* value) const;
177 // Enumerate the values of the specified header. If you are only interested
178 // in the first header, then you can pass NULL for the 'iter' parameter.
179 // Otherwise, to iterate across all values for the specified header,
180 // initialize a 'void*' variable to NULL and pass it by address to
181 // EnumerateHeader. Note that a header might have an empty value. Call
182 // EnumerateHeader repeatedly until it returns false.
183 bool EnumerateHeader(void** iter,
184 const base::StringPiece& name,
185 std::string* value) const;
187 // Returns true if the response contains the specified header-value pair.
188 // Both name and value are compared case insensitively.
189 bool HasHeaderValue(const base::StringPiece& name,
190 const base::StringPiece& value) const;
192 // Returns true if the response contains the specified header.
193 // The name is compared case insensitively.
194 bool HasHeader(const base::StringPiece& name) const;
196 // Get the mime type and charset values in lower case form from the headers.
197 // Empty strings are returned if the values are not present.
198 void GetMimeTypeAndCharset(std::string* mime_type,
199 std::string* charset) const;
201 // Get the mime type in lower case from the headers. If there's no mime
202 // type, returns false.
203 bool GetMimeType(std::string* mime_type) const;
205 // Get the charset in lower case from the headers. If there's no charset,
206 // returns false.
207 bool GetCharset(std::string* charset) const;
209 // Returns true if this response corresponds to a redirect. The target
210 // location of the redirect is optionally returned if location is non-null.
211 bool IsRedirect(std::string* location) const;
213 // Returns true if the HTTP response code passed in corresponds to a
214 // redirect.
215 static bool IsRedirectResponseCode(int response_code);
217 // Returns VALIDATION_NONE if the response can be reused without
218 // validation. VALIDATION_ASYNCHRONOUS means the response can be re-used, but
219 // asynchronous revalidation must be performed. VALIDATION_SYNCHRONOUS means
220 // that the result cannot be reused without revalidation.
221 // The result is relative to the current_time parameter, which is
222 // a parameter to support unit testing. The request_time parameter indicates
223 // the time at which the request was made that resulted in this response,
224 // which was received at response_time.
225 ValidationType RequiresValidation(const base::Time& request_time,
226 const base::Time& response_time,
227 const base::Time& current_time) const;
229 // Calculates the amount of time the server claims the response is fresh from
230 // the time the response was generated. See section 13.2.4 of RFC 2616. See
231 // RequiresValidation for a description of the response_time parameter. See
232 // the definition of FreshnessLifetimes above for the meaning of the return
233 // value. See RFC 5861 section 3 for the definition of
234 // stale-while-revalidate.
235 FreshnessLifetimes GetFreshnessLifetimes(
236 const base::Time& response_time) const;
238 // Returns the age of the response. See section 13.2.3 of RFC 2616.
239 // See RequiresValidation for a description of this method's parameters.
240 base::TimeDelta GetCurrentAge(const base::Time& request_time,
241 const base::Time& response_time,
242 const base::Time& current_time) const;
244 // The following methods extract values from the response headers. If a
245 // value is not present, then false is returned. Otherwise, true is returned
246 // and the out param is assigned to the corresponding value.
247 bool GetMaxAgeValue(base::TimeDelta* value) const;
248 bool GetAgeValue(base::TimeDelta* value) const;
249 bool GetDateValue(base::Time* value) const;
250 bool GetLastModifiedValue(base::Time* value) const;
251 bool GetExpiresValue(base::Time* value) const;
252 bool GetStaleWhileRevalidateValue(base::TimeDelta* value) const;
254 // Extracts the time value of a particular header. This method looks for the
255 // first matching header value and parses its value as a HTTP-date.
256 bool GetTimeValuedHeader(const std::string& name, base::Time* result) const;
258 // Determines if this response indicates a keep-alive connection.
259 bool IsKeepAlive() const;
261 // Returns true if this response has a strong etag or last-modified header.
262 // See section 13.3.3 of RFC 2616.
263 bool HasStrongValidators() const;
265 // Extracts the value of the Content-Length header or returns -1 if there is
266 // no such header in the response.
267 int64 GetContentLength() const;
269 // Extracts the value of the specified header or returns -1 if there is no
270 // such header in the response.
271 int64 GetInt64HeaderValue(const std::string& header) const;
273 // Extracts the values in a Content-Range header and returns true if they are
274 // valid for a 206 response; otherwise returns false.
275 // The following values will be outputted:
276 // |*first_byte_position| = inclusive position of the first byte of the range
277 // |*last_byte_position| = inclusive position of the last byte of the range
278 // |*instance_length| = size in bytes of the object requested
279 // If any of the above values is unknown, its value will be -1.
280 bool GetContentRange(int64* first_byte_position,
281 int64* last_byte_position,
282 int64* instance_length) const;
284 // Returns true if the response is chunk-encoded.
285 bool IsChunkEncoded() const;
287 // Creates a Value for use with the NetLog containing the response headers.
288 scoped_ptr<base::Value> NetLogCallback(NetLogCaptureMode capture_mode) const;
290 // Takes in a Value created by the above function, and attempts to create a
291 // copy of the original headers. Returns true on success. On failure,
292 // clears |http_response_headers|.
293 // TODO(mmenke): Long term, we want to remove this, and migrate external
294 // consumers to be NetworkDelegates.
295 static bool FromNetLogParam(
296 const base::Value* event_param,
297 scoped_refptr<HttpResponseHeaders>* http_response_headers);
299 // Returns the HTTP response code. This is 0 if the response code text seems
300 // to exist but could not be parsed. Otherwise, it defaults to 200 if the
301 // response code is not found in the raw headers.
302 int response_code() const { return response_code_; }
304 // Returns the raw header string.
305 const std::string& raw_headers() const { return raw_headers_; }
307 private:
308 friend class base::RefCountedThreadSafe<HttpResponseHeaders>;
310 typedef base::hash_set<std::string> HeaderSet;
312 // The members of this structure point into raw_headers_.
313 struct ParsedHeader;
314 typedef std::vector<ParsedHeader> HeaderList;
316 HttpResponseHeaders();
317 ~HttpResponseHeaders();
319 // Initializes from the given raw headers.
320 void Parse(const std::string& raw_input);
322 // Helper function for ParseStatusLine.
323 // Tries to extract the "HTTP/X.Y" from a status line formatted like:
324 // HTTP/1.1 200 OK
325 // with line_begin and end pointing at the begin and end of this line. If the
326 // status line is malformed, returns HttpVersion(0,0).
327 static HttpVersion ParseVersion(std::string::const_iterator line_begin,
328 std::string::const_iterator line_end);
330 // Tries to extract the status line from a header block, given the first
331 // line of said header block. If the status line is malformed, we'll
332 // construct a valid one. Example input:
333 // HTTP/1.1 200 OK
334 // with line_begin and end pointing at the begin and end of this line.
335 // Output will be a normalized version of this.
336 void ParseStatusLine(std::string::const_iterator line_begin,
337 std::string::const_iterator line_end,
338 bool has_headers);
340 // Find the header in our list (case-insensitive) starting with parsed_ at
341 // index |from|. Returns string::npos if not found.
342 size_t FindHeader(size_t from, const base::StringPiece& name) const;
344 // Search the Cache-Control header for a directive matching |directive|. If
345 // present, treat its value as a time offset in seconds, write it to |result|,
346 // and return true.
347 bool GetCacheControlDirective(const base::StringPiece& directive,
348 base::TimeDelta* result) const;
350 // Add a header->value pair to our list. If we already have header in our
351 // list, append the value to it.
352 void AddHeader(std::string::const_iterator name_begin,
353 std::string::const_iterator name_end,
354 std::string::const_iterator value_begin,
355 std::string::const_iterator value_end);
357 // Add to parsed_ given the fields of a ParsedHeader object.
358 void AddToParsed(std::string::const_iterator name_begin,
359 std::string::const_iterator name_end,
360 std::string::const_iterator value_begin,
361 std::string::const_iterator value_end);
363 // Replaces the current headers with the merged version of |raw_headers| and
364 // the current headers without the headers in |headers_to_remove|. Note that
365 // |headers_to_remove| are removed from the current headers (before the
366 // merge), not after the merge.
367 void MergeWithHeaders(const std::string& raw_headers,
368 const HeaderSet& headers_to_remove);
370 // Adds the values from any 'cache-control: no-cache="foo,bar"' headers.
371 void AddNonCacheableHeaders(HeaderSet* header_names) const;
373 // Adds the set of header names that contain cookie values.
374 static void AddSensitiveHeaders(HeaderSet* header_names);
376 // Adds the set of rfc2616 hop-by-hop response headers.
377 static void AddHopByHopHeaders(HeaderSet* header_names);
379 // Adds the set of challenge response headers.
380 static void AddChallengeHeaders(HeaderSet* header_names);
382 // Adds the set of cookie response headers.
383 static void AddCookieHeaders(HeaderSet* header_names);
385 // Adds the set of content range response headers.
386 static void AddHopContentRangeHeaders(HeaderSet* header_names);
388 // Adds the set of transport security state headers.
389 static void AddSecurityStateHeaders(HeaderSet* header_names);
391 // We keep a list of ParsedHeader objects. These tell us where to locate the
392 // header-value pairs within raw_headers_.
393 HeaderList parsed_;
395 // The raw_headers_ consists of the normalized status line (terminated with a
396 // null byte) and then followed by the raw null-terminated headers from the
397 // input that was passed to our constructor. We preserve the input [*] to
398 // maintain as much ancillary fidelity as possible (since it is sometimes
399 // hard to tell what may matter down-stream to a consumer of XMLHttpRequest).
400 // [*] The status line may be modified.
401 std::string raw_headers_;
403 // This is the parsed HTTP response code.
404 int response_code_;
406 // The normalized http version (consistent with what GetStatusLine() returns).
407 HttpVersion http_version_;
409 // The parsed http version number (not normalized).
410 HttpVersion parsed_http_version_;
412 DISALLOW_COPY_AND_ASSIGN(HttpResponseHeaders);
415 } // namespace net
417 #endif // NET_HTTP_HTTP_RESPONSE_HEADERS_H_