Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / net / http / http_util.h
blob1bb3c93f8ab168152dc75205e00aabcc0d9c30cf
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_UTIL_H_
6 #define NET_HTTP_HTTP_UTIL_H_
8 #include <string>
9 #include <vector>
11 #include "base/memory/ref_counted.h"
12 #include "base/strings/string_tokenizer.h"
13 #include "base/time/time.h"
14 #include "net/base/net_export.h"
15 #include "net/http/http_byte_range.h"
16 #include "net/http/http_version.h"
17 #include "url/gurl.h"
19 // This is a macro to support extending this string literal at compile time.
20 // Please excuse me polluting your global namespace!
21 #define HTTP_LWS " \t"
23 namespace net {
25 class NET_EXPORT HttpUtil {
26 public:
27 // Returns the absolute URL, to be used for the http request. This url is
28 // made up of the protocol, host, [port], path, [query]. Everything else
29 // is stripped (username, password, reference).
30 static std::string SpecForRequest(const GURL& url);
32 // Parses the value of a Content-Type header. The resulting mime_type and
33 // charset values are normalized to lowercase. The mime_type and charset
34 // output values are only modified if the content_type_str contains a mime
35 // type and charset value, respectively. The boundary output value is
36 // optional and will be assigned the (quoted) value of the boundary
37 // paramter, if any.
38 static void ParseContentType(const std::string& content_type_str,
39 std::string* mime_type,
40 std::string* charset,
41 bool* had_charset,
42 std::string* boundary);
44 // Scans the headers and look for the first "Range" header in |headers|,
45 // if "Range" exists and the first one of it is well formatted then returns
46 // true, |ranges| will contain a list of valid ranges. If return
47 // value is false then values in |ranges| should not be used. The format of
48 // "Range" header is defined in RFC 7233 Section 2.1.
49 // https://tools.ietf.org/html/rfc7233#section-2.1
50 static bool ParseRanges(const std::string& headers,
51 std::vector<HttpByteRange>* ranges);
53 // Same thing as ParseRanges except the Range header is known and its value
54 // is directly passed in, rather than requiring searching through a string.
55 static bool ParseRangeHeader(const std::string& range_specifier,
56 std::vector<HttpByteRange>* ranges);
58 // Parses a Retry-After header that is either an absolute date/time or a
59 // number of seconds in the future. Interprets absolute times as relative to
60 // |now|. If |retry_after_string| is successfully parsed and indicates a time
61 // that is not in the past, fills in |*retry_after| and returns true;
62 // otherwise, returns false.
63 static bool ParseRetryAfterHeader(const std::string& retry_after_string,
64 base::Time now,
65 base::TimeDelta* retry_after);
67 // Scans the '\r\n'-delimited headers for the given header name. Returns
68 // true if a match is found. Input is assumed to be well-formed.
69 // TODO(darin): kill this
70 static bool HasHeader(const std::string& headers, const char* name);
72 // Returns true if it is safe to allow users and scripts to specify the header
73 // named |name|.
74 static bool IsSafeHeader(const std::string& name);
76 // Returns true if |name| is a valid HTTP header name.
77 static bool IsValidHeaderName(const std::string& name);
79 // Returns false if |value| contains NUL or CRLF. This method does not perform
80 // a fully RFC-2616-compliant header value validation.
81 static bool IsValidHeaderValue(const std::string& value);
83 // Strips all header lines from |headers| whose name matches
84 // |headers_to_remove|. |headers_to_remove| is a list of null-terminated
85 // lower-case header names, with array length |headers_to_remove_len|.
86 // Returns the stripped header lines list, separated by "\r\n".
87 static std::string StripHeaders(const std::string& headers,
88 const char* const headers_to_remove[],
89 size_t headers_to_remove_len);
91 // Multiple occurances of some headers cannot be coalesced into a comma-
92 // separated list since their values are (or contain) unquoted HTTP-date
93 // values, which may contain a comma (see RFC 2616 section 3.3.1).
94 static bool IsNonCoalescingHeader(std::string::const_iterator name_begin,
95 std::string::const_iterator name_end);
96 static bool IsNonCoalescingHeader(const std::string& name) {
97 return IsNonCoalescingHeader(name.begin(), name.end());
100 // Return true if the character is HTTP "linear white space" (SP | HT).
101 // This definition corresponds with the HTTP_LWS macro, and does not match
102 // newlines.
103 static bool IsLWS(char c);
105 // Trim HTTP_LWS chars from the beginning and end of the string.
106 static void TrimLWS(std::string::const_iterator* begin,
107 std::string::const_iterator* end);
109 // Whether the character is the start of a quotation mark.
110 static bool IsQuote(char c);
112 // Whether the string is a valid |token| as defined in RFC 2616 Sec 2.2.
113 static bool IsToken(std::string::const_iterator begin,
114 std::string::const_iterator end);
115 static bool IsToken(const std::string& str) {
116 return IsToken(str.begin(), str.end());
119 // RFC 2616 Sec 2.2:
120 // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
121 // Unquote() strips the surrounding quotemarks off a string, and unescapes
122 // any quoted-pair to obtain the value contained by the quoted-string.
123 // If the input is not quoted, then it works like the identity function.
124 static std::string Unquote(std::string::const_iterator begin,
125 std::string::const_iterator end);
127 // Same as above.
128 static std::string Unquote(const std::string& str);
130 // The reverse of Unquote() -- escapes and surrounds with "
131 static std::string Quote(const std::string& str);
133 // Returns the start of the status line, or -1 if no status line was found.
134 // This allows for 4 bytes of junk to precede the status line (which is what
135 // mozilla does too).
136 static int LocateStartOfStatusLine(const char* buf, int buf_len);
138 // Returns index beyond the end-of-headers marker or -1 if not found. RFC
139 // 2616 defines the end-of-headers marker as a double CRLF; however, some
140 // servers only send back LFs (e.g., Unix-based CGI scripts written using the
141 // ASIS Apache module). This function therefore accepts the pattern LF[CR]LF
142 // as end-of-headers (just like Mozilla). The first line of |buf| is
143 // considered the status line, even if empty.
144 // The parameter |i| is the offset within |buf| to begin searching from.
145 static int LocateEndOfHeaders(const char* buf, int buf_len, int i = 0);
147 // Same as |LocateEndOfHeaders|, but does not expect a status line, so can be
148 // used on multi-part responses or HTTP/1.x trailers. As a result, if |buf|
149 // starts with a single [CR]LF, it is considered an empty header list, as
150 // opposed to an empty status line above a header list.
151 static int LocateEndOfAdditionalHeaders(const char* buf,
152 int buf_len,
153 int i = 0);
155 // Assemble "raw headers" in the format required by HttpResponseHeaders.
156 // This involves normalizing line terminators, converting [CR]LF to \0 and
157 // handling HTTP line continuations (i.e., lines starting with LWS are
158 // continuations of the previous line). |buf_len| indicates the position of
159 // the end-of-headers marker as defined by LocateEndOfHeaders.
160 // If a \0 appears within the headers themselves, it will be stripped. This
161 // is a workaround to avoid later code from incorrectly interpreting it as
162 // a line terminator.
164 // TODO(eroman): we should use \n as the canonical line separator rather than
165 // \0 to avoid this problem. Unfortunately the persistence layer
166 // is already dependent on newlines being replaced by NULL so
167 // this is hard to change without breaking things.
168 static std::string AssembleRawHeaders(const char* buf, int buf_len);
170 // Converts assembled "raw headers" back to the HTTP response format. That is
171 // convert each \0 occurence to CRLF. This is used by DevTools.
172 // Since all line continuations info is already lost at this point, the result
173 // consists of status line and then one line for each header.
174 static std::string ConvertHeadersBackToHTTPResponse(const std::string& str);
176 // Given a comma separated ordered list of language codes, return
177 // the list with a qvalue appended to each language.
178 // The way qvalues are assigned is rather simple. The qvalue
179 // starts with 1.0 and is decremented by 0.2 for each successive entry
180 // in the list until it reaches 0.2. All the entries after that are
181 // assigned the same qvalue of 0.2. Also, note that the 1st language
182 // will not have a qvalue added because the absence of a qvalue implicitly
183 // means q=1.0.
185 // When making a http request, this should be used to determine what
186 // to put in Accept-Language header. If a comma separated list of language
187 // codes *without* qvalue is sent, web servers regard all
188 // of them as having q=1.0 and pick one of them even though it may not
189 // be at the beginning of the list (see http://crbug.com/5899).
190 static std::string GenerateAcceptLanguageHeader(
191 const std::string& raw_language_list);
193 // Helper. If |*headers| already contains |header_name| do nothing,
194 // otherwise add <header_name> ": " <header_value> to the end of the list.
195 static void AppendHeaderIfMissing(const char* header_name,
196 const std::string& header_value,
197 std::string* headers);
199 // Returns true if the parameters describe a response with a strong etag or
200 // last-modified header. See section 13.3.3 of RFC 2616.
201 static bool HasStrongValidators(HttpVersion version,
202 const std::string& etag_header,
203 const std::string& last_modified_header,
204 const std::string& date_header);
206 // Gets a vector of common HTTP status codes for histograms of status
207 // codes. Currently returns everything in the range [100, 600), plus 0
208 // (for invalid responses/status codes).
209 static std::vector<int> GetStatusCodesForHistogram();
211 // Maps an HTTP status code to one of the status codes in the vector
212 // returned by GetStatusCodesForHistogram.
213 static int MapStatusCodeForHistogram(int code);
215 // Used to iterate over the name/value pairs of HTTP headers. To iterate
216 // over the values in a multi-value header, use ValuesIterator.
217 // See AssembleRawHeaders for joining line continuations (this iterator
218 // does not expect any).
219 class NET_EXPORT HeadersIterator {
220 public:
221 HeadersIterator(std::string::const_iterator headers_begin,
222 std::string::const_iterator headers_end,
223 const std::string& line_delimiter);
224 ~HeadersIterator();
226 // Advances the iterator to the next header, if any. Returns true if there
227 // is a next header. Use name* and values* methods to access the resultant
228 // header name and values.
229 bool GetNext();
231 // Iterates through the list of headers, starting with the current position
232 // and looks for the specified header. Note that the name _must_ be
233 // lower cased.
234 // If the header was found, the return value will be true and the current
235 // position points to the header. If the return value is false, the
236 // current position will be at the end of the headers.
237 bool AdvanceTo(const char* lowercase_name);
239 void Reset() {
240 lines_.Reset();
243 std::string::const_iterator name_begin() const {
244 return name_begin_;
246 std::string::const_iterator name_end() const {
247 return name_end_;
249 std::string name() const {
250 return std::string(name_begin_, name_end_);
253 std::string::const_iterator values_begin() const {
254 return values_begin_;
256 std::string::const_iterator values_end() const {
257 return values_end_;
259 std::string values() const {
260 return std::string(values_begin_, values_end_);
263 private:
264 base::StringTokenizer lines_;
265 std::string::const_iterator name_begin_;
266 std::string::const_iterator name_end_;
267 std::string::const_iterator values_begin_;
268 std::string::const_iterator values_end_;
271 // Iterates over delimited values in an HTTP header. HTTP LWS is
272 // automatically trimmed from the resulting values.
274 // When using this class to iterate over response header values, be aware that
275 // for some headers (e.g., Last-Modified), commas are not used as delimiters.
276 // This iterator should be avoided for headers like that which are considered
277 // non-coalescing (see IsNonCoalescingHeader).
279 // This iterator is careful to skip over delimiters found inside an HTTP
280 // quoted string.
282 class NET_EXPORT_PRIVATE ValuesIterator {
283 public:
284 ValuesIterator(std::string::const_iterator values_begin,
285 std::string::const_iterator values_end,
286 char delimiter);
287 ~ValuesIterator();
289 // Advances the iterator to the next value, if any. Returns true if there
290 // is a next value. Use value* methods to access the resultant value.
291 bool GetNext();
293 std::string::const_iterator value_begin() const {
294 return value_begin_;
296 std::string::const_iterator value_end() const {
297 return value_end_;
299 std::string value() const {
300 return std::string(value_begin_, value_end_);
303 private:
304 base::StringTokenizer values_;
305 std::string::const_iterator value_begin_;
306 std::string::const_iterator value_end_;
309 // Iterates over a delimited sequence of name-value pairs in an HTTP header.
310 // Each pair consists of a token (the name), an equals sign, and either a
311 // token or quoted-string (the value). Arbitrary HTTP LWS is permitted outside
312 // of and between names, values, and delimiters.
314 // String iterators returned from this class' methods may be invalidated upon
315 // calls to GetNext() or after the NameValuePairsIterator is destroyed.
316 class NET_EXPORT NameValuePairsIterator {
317 public:
318 // Whether or not values are optional. VALUES_OPTIONAL allows
319 // e.g. name1=value1;name2;name3=value3, whereas VALUES_NOT_OPTIONAL
320 // will treat it as a parse error because name2 does not have a
321 // corresponding equals sign.
322 enum OptionalValues { VALUES_OPTIONAL, VALUES_NOT_OPTIONAL };
324 NameValuePairsIterator(std::string::const_iterator begin,
325 std::string::const_iterator end,
326 char delimiter,
327 OptionalValues optional_values);
329 // Treats values as not optional by default (VALUES_NOT_OPTIONAL).
330 NameValuePairsIterator(std::string::const_iterator begin,
331 std::string::const_iterator end,
332 char delimiter);
334 ~NameValuePairsIterator();
336 // Advances the iterator to the next pair, if any. Returns true if there
337 // is a next pair. Use name* and value* methods to access the resultant
338 // value.
339 bool GetNext();
341 // Returns false if there was a parse error.
342 bool valid() const { return valid_; }
344 // The name of the current name-value pair.
345 std::string::const_iterator name_begin() const { return name_begin_; }
346 std::string::const_iterator name_end() const { return name_end_; }
347 std::string name() const { return std::string(name_begin_, name_end_); }
349 // The value of the current name-value pair.
350 std::string::const_iterator value_begin() const {
351 return value_is_quoted_ ? unquoted_value_.begin() : value_begin_;
353 std::string::const_iterator value_end() const {
354 return value_is_quoted_ ? unquoted_value_.end() : value_end_;
356 std::string value() const {
357 return value_is_quoted_ ? unquoted_value_ : std::string(value_begin_,
358 value_end_);
361 bool value_is_quoted() const { return value_is_quoted_; }
363 // The value before unquoting (if any).
364 std::string raw_value() const { return std::string(value_begin_,
365 value_end_); }
367 private:
368 HttpUtil::ValuesIterator props_;
369 bool valid_;
371 std::string::const_iterator name_begin_;
372 std::string::const_iterator name_end_;
374 std::string::const_iterator value_begin_;
375 std::string::const_iterator value_end_;
377 // Do not store iterators into this string. The NameValuePairsIterator
378 // is copyable/assignable, and if copied the copy's iterators would point
379 // into the original's unquoted_value_ member.
380 std::string unquoted_value_;
382 bool value_is_quoted_;
384 // True if values are required for each name/value pair; false if a
385 // name is permitted to appear without a corresponding value.
386 bool values_optional_;
390 } // namespace net
392 #endif // NET_HTTP_HTTP_UTIL_H_