Bump libaddressinput version
[chromium-blink-merge.git] / net / http / http_util.h
blob79a41acd193cccddc4152fabb50e0760ba06b385
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 // Locates the next occurance of delimiter in line, skipping over quoted
33 // strings (e.g., commas will not be treated as delimiters if they appear
34 // within a quoted string). Returns the offset of the found delimiter or
35 // line.size() if no delimiter was found.
36 static size_t FindDelimiter(const std::string& line,
37 size_t search_start,
38 char delimiter);
40 // Parses the value of a Content-Type header. The resulting mime_type and
41 // charset values are normalized to lowercase. The mime_type and charset
42 // output values are only modified if the content_type_str contains a mime
43 // type and charset value, respectively. The boundary output value is
44 // optional and will be assigned the (quoted) value of the boundary
45 // paramter, if any.
46 static void ParseContentType(const std::string& content_type_str,
47 std::string* mime_type,
48 std::string* charset,
49 bool* had_charset,
50 std::string* boundary);
52 // Scans the headers and look for the first "Range" header in |headers|,
53 // if "Range" exists and the first one of it is well formatted then returns
54 // true, |ranges| will contain a list of valid ranges. If return
55 // value is false then values in |ranges| should not be used. The format of
56 // "Range" header is defined in RFC 7233 Section 2.1.
57 // https://tools.ietf.org/html/rfc7233#section-2.1
58 static bool ParseRanges(const std::string& headers,
59 std::vector<HttpByteRange>* ranges);
61 // Same thing as ParseRanges except the Range header is known and its value
62 // is directly passed in, rather than requiring searching through a string.
63 static bool ParseRangeHeader(const std::string& range_specifier,
64 std::vector<HttpByteRange>* ranges);
66 // Parses a Retry-After header that is either an absolute date/time or a
67 // number of seconds in the future. Interprets absolute times as relative to
68 // |now|. If |retry_after_string| is successfully parsed and indicates a time
69 // that is not in the past, fills in |*retry_after| and returns true;
70 // otherwise, returns false.
71 static bool ParseRetryAfterHeader(const std::string& retry_after_string,
72 base::Time now,
73 base::TimeDelta* retry_after);
75 // Scans the '\r\n'-delimited headers for the given header name. Returns
76 // true if a match is found. Input is assumed to be well-formed.
77 // TODO(darin): kill this
78 static bool HasHeader(const std::string& headers, const char* name);
80 // Returns true if it is safe to allow users and scripts to specify the header
81 // named |name|.
82 static bool IsSafeHeader(const std::string& name);
84 // Returns true if |name| is a valid HTTP header name.
85 static bool IsValidHeaderName(const std::string& name);
87 // Returns false if |value| contains NUL or CRLF. This method does not perform
88 // a fully RFC-2616-compliant header value validation.
89 static bool IsValidHeaderValue(const std::string& value);
91 // Strips all header lines from |headers| whose name matches
92 // |headers_to_remove|. |headers_to_remove| is a list of null-terminated
93 // lower-case header names, with array length |headers_to_remove_len|.
94 // Returns the stripped header lines list, separated by "\r\n".
95 static std::string StripHeaders(const std::string& headers,
96 const char* const headers_to_remove[],
97 size_t headers_to_remove_len);
99 // Multiple occurances of some headers cannot be coalesced into a comma-
100 // separated list since their values are (or contain) unquoted HTTP-date
101 // values, which may contain a comma (see RFC 2616 section 3.3.1).
102 static bool IsNonCoalescingHeader(std::string::const_iterator name_begin,
103 std::string::const_iterator name_end);
104 static bool IsNonCoalescingHeader(const std::string& name) {
105 return IsNonCoalescingHeader(name.begin(), name.end());
108 // Return true if the character is HTTP "linear white space" (SP | HT).
109 // This definition corresponds with the HTTP_LWS macro, and does not match
110 // newlines.
111 static bool IsLWS(char c);
113 // Trim HTTP_LWS chars from the beginning and end of the string.
114 static void TrimLWS(std::string::const_iterator* begin,
115 std::string::const_iterator* end);
117 // Whether the character is the start of a quotation mark.
118 static bool IsQuote(char c);
120 // Whether the string is a valid |token| as defined in RFC 2616 Sec 2.2.
121 static bool IsToken(std::string::const_iterator begin,
122 std::string::const_iterator end);
123 static bool IsToken(const std::string& str) {
124 return IsToken(str.begin(), str.end());
127 // RFC 2616 Sec 2.2:
128 // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
129 // Unquote() strips the surrounding quotemarks off a string, and unescapes
130 // any quoted-pair to obtain the value contained by the quoted-string.
131 // If the input is not quoted, then it works like the identity function.
132 static std::string Unquote(std::string::const_iterator begin,
133 std::string::const_iterator end);
135 // Same as above.
136 static std::string Unquote(const std::string& str);
138 // The reverse of Unquote() -- escapes and surrounds with "
139 static std::string Quote(const std::string& str);
141 // Returns the start of the status line, or -1 if no status line was found.
142 // This allows for 4 bytes of junk to precede the status line (which is what
143 // mozilla does too).
144 static int LocateStartOfStatusLine(const char* buf, int buf_len);
146 // Returns index beyond the end-of-headers marker or -1 if not found. RFC
147 // 2616 defines the end-of-headers marker as a double CRLF; however, some
148 // servers only send back LFs (e.g., Unix-based CGI scripts written using the
149 // ASIS Apache module). This function therefore accepts the pattern LF[CR]LF
150 // as end-of-headers (just like Mozilla). The first line of |buf| is
151 // considered the status line, even if empty.
152 // The parameter |i| is the offset within |buf| to begin searching from.
153 static int LocateEndOfHeaders(const char* buf, int buf_len, int i = 0);
155 // Same as |LocateEndOfHeaders|, but does not expect a status line, so can be
156 // used on multi-part responses or HTTP/1.x trailers. As a result, if |buf|
157 // starts with a single [CR]LF, it is considered an empty header list, as
158 // opposed to an empty status line above a header list.
159 static int LocateEndOfAdditionalHeaders(const char* buf,
160 int buf_len,
161 int i = 0);
163 // Assemble "raw headers" in the format required by HttpResponseHeaders.
164 // This involves normalizing line terminators, converting [CR]LF to \0 and
165 // handling HTTP line continuations (i.e., lines starting with LWS are
166 // continuations of the previous line). |buf_len| indicates the position of
167 // the end-of-headers marker as defined by LocateEndOfHeaders.
168 // If a \0 appears within the headers themselves, it will be stripped. This
169 // is a workaround to avoid later code from incorrectly interpreting it as
170 // a line terminator.
172 // TODO(eroman): we should use \n as the canonical line separator rather than
173 // \0 to avoid this problem. Unfortunately the persistence layer
174 // is already dependent on newlines being replaced by NULL so
175 // this is hard to change without breaking things.
176 static std::string AssembleRawHeaders(const char* buf, int buf_len);
178 // Converts assembled "raw headers" back to the HTTP response format. That is
179 // convert each \0 occurence to CRLF. This is used by DevTools.
180 // Since all line continuations info is already lost at this point, the result
181 // consists of status line and then one line for each header.
182 static std::string ConvertHeadersBackToHTTPResponse(const std::string& str);
184 // Given a comma separated ordered list of language codes, return
185 // the list with a qvalue appended to each language.
186 // The way qvalues are assigned is rather simple. The qvalue
187 // starts with 1.0 and is decremented by 0.2 for each successive entry
188 // in the list until it reaches 0.2. All the entries after that are
189 // assigned the same qvalue of 0.2. Also, note that the 1st language
190 // will not have a qvalue added because the absence of a qvalue implicitly
191 // means q=1.0.
193 // When making a http request, this should be used to determine what
194 // to put in Accept-Language header. If a comma separated list of language
195 // codes *without* qvalue is sent, web servers regard all
196 // of them as having q=1.0 and pick one of them even though it may not
197 // be at the beginning of the list (see http://crbug.com/5899).
198 static std::string GenerateAcceptLanguageHeader(
199 const std::string& raw_language_list);
201 // Helper. If |*headers| already contains |header_name| do nothing,
202 // otherwise add <header_name> ": " <header_value> to the end of the list.
203 static void AppendHeaderIfMissing(const char* header_name,
204 const std::string& header_value,
205 std::string* headers);
207 // Returns true if the parameters describe a response with a strong etag or
208 // last-modified header. See section 13.3.3 of RFC 2616.
209 static bool HasStrongValidators(HttpVersion version,
210 const std::string& etag_header,
211 const std::string& last_modified_header,
212 const std::string& date_header);
214 // Gets a vector of common HTTP status codes for histograms of status
215 // codes. Currently returns everything in the range [100, 600), plus 0
216 // (for invalid responses/status codes).
217 static std::vector<int> GetStatusCodesForHistogram();
219 // Maps an HTTP status code to one of the status codes in the vector
220 // returned by GetStatusCodesForHistogram.
221 static int MapStatusCodeForHistogram(int code);
223 // Used to iterate over the name/value pairs of HTTP headers. To iterate
224 // over the values in a multi-value header, use ValuesIterator.
225 // See AssembleRawHeaders for joining line continuations (this iterator
226 // does not expect any).
227 class NET_EXPORT HeadersIterator {
228 public:
229 HeadersIterator(std::string::const_iterator headers_begin,
230 std::string::const_iterator headers_end,
231 const std::string& line_delimiter);
232 ~HeadersIterator();
234 // Advances the iterator to the next header, if any. Returns true if there
235 // is a next header. Use name* and values* methods to access the resultant
236 // header name and values.
237 bool GetNext();
239 // Iterates through the list of headers, starting with the current position
240 // and looks for the specified header. Note that the name _must_ be
241 // lower cased.
242 // If the header was found, the return value will be true and the current
243 // position points to the header. If the return value is false, the
244 // current position will be at the end of the headers.
245 bool AdvanceTo(const char* lowercase_name);
247 void Reset() {
248 lines_.Reset();
251 std::string::const_iterator name_begin() const {
252 return name_begin_;
254 std::string::const_iterator name_end() const {
255 return name_end_;
257 std::string name() const {
258 return std::string(name_begin_, name_end_);
261 std::string::const_iterator values_begin() const {
262 return values_begin_;
264 std::string::const_iterator values_end() const {
265 return values_end_;
267 std::string values() const {
268 return std::string(values_begin_, values_end_);
271 private:
272 base::StringTokenizer lines_;
273 std::string::const_iterator name_begin_;
274 std::string::const_iterator name_end_;
275 std::string::const_iterator values_begin_;
276 std::string::const_iterator values_end_;
279 // Iterates over delimited values in an HTTP header. HTTP LWS is
280 // automatically trimmed from the resulting values.
282 // When using this class to iterate over response header values, be aware that
283 // for some headers (e.g., Last-Modified), commas are not used as delimiters.
284 // This iterator should be avoided for headers like that which are considered
285 // non-coalescing (see IsNonCoalescingHeader).
287 // This iterator is careful to skip over delimiters found inside an HTTP
288 // quoted string.
290 class NET_EXPORT_PRIVATE ValuesIterator {
291 public:
292 ValuesIterator(std::string::const_iterator values_begin,
293 std::string::const_iterator values_end,
294 char delimiter);
295 ~ValuesIterator();
297 // Advances the iterator to the next value, if any. Returns true if there
298 // is a next value. Use value* methods to access the resultant value.
299 bool GetNext();
301 std::string::const_iterator value_begin() const {
302 return value_begin_;
304 std::string::const_iterator value_end() const {
305 return value_end_;
307 std::string value() const {
308 return std::string(value_begin_, value_end_);
311 private:
312 base::StringTokenizer values_;
313 std::string::const_iterator value_begin_;
314 std::string::const_iterator value_end_;
317 // Iterates over a delimited sequence of name-value pairs in an HTTP header.
318 // Each pair consists of a token (the name), an equals sign, and either a
319 // token or quoted-string (the value). Arbitrary HTTP LWS is permitted outside
320 // of and between names, values, and delimiters.
322 // String iterators returned from this class' methods may be invalidated upon
323 // calls to GetNext() or after the NameValuePairsIterator is destroyed.
324 class NET_EXPORT NameValuePairsIterator {
325 public:
326 NameValuePairsIterator(std::string::const_iterator begin,
327 std::string::const_iterator end,
328 char delimiter);
329 ~NameValuePairsIterator();
331 // Advances the iterator to the next pair, if any. Returns true if there
332 // is a next pair. Use name* and value* methods to access the resultant
333 // value.
334 bool GetNext();
336 // Returns false if there was a parse error.
337 bool valid() const { return valid_; }
339 // The name of the current name-value pair.
340 std::string::const_iterator name_begin() const { return name_begin_; }
341 std::string::const_iterator name_end() const { return name_end_; }
342 std::string name() const { return std::string(name_begin_, name_end_); }
344 // The value of the current name-value pair.
345 std::string::const_iterator value_begin() const {
346 return value_is_quoted_ ? unquoted_value_.begin() : value_begin_;
348 std::string::const_iterator value_end() const {
349 return value_is_quoted_ ? unquoted_value_.end() : value_end_;
351 std::string value() const {
352 return value_is_quoted_ ? unquoted_value_ : std::string(value_begin_,
353 value_end_);
356 // The value before unquoting (if any).
357 std::string raw_value() const { return std::string(value_begin_,
358 value_end_); }
360 private:
361 HttpUtil::ValuesIterator props_;
362 bool valid_;
364 std::string::const_iterator name_begin_;
365 std::string::const_iterator name_end_;
367 std::string::const_iterator value_begin_;
368 std::string::const_iterator value_end_;
370 // Do not store iterators into this string. The NameValuePairsIterator
371 // is copyable/assignable, and if copied the copy's iterators would point
372 // into the original's unquoted_value_ member.
373 std::string unquoted_value_;
375 bool value_is_quoted_;
379 } // namespace net
381 #endif // NET_HTTP_HTTP_UTIL_H_