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_UTIL_H_
6 #define NET_HTTP_HTTP_UTIL_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <set>
12 #include <string>
13 #include <vector>
14 
15 #include "base/macros.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/string_tokenizer.h"
19 #include "base/time/time.h"
20 #include "net/base/net_export.h"
21 #include "net/http/http_byte_range.h"
22 #include "net/http/http_version.h"
23 #include "url/gurl.h"
24 #include "url/origin.h"
25 
26 // This is a macro to support extending this string literal at compile time.
27 // Please excuse me polluting your global namespace!
28 #define HTTP_LWS " \t"
29 
30 namespace net {
31 
32 class NET_EXPORT HttpUtil {
33  public:
34   // Returns the absolute URL, to be used for the http request. This url is
35   // made up of the protocol, host, [port], path, [query]. Everything else
36   // is stripped (username, password, reference).
37   static std::string SpecForRequest(const GURL& url);
38 
39   // Parses the value of a Content-Type header.  |mime_type|, |charset|, and
40   // |had_charset| output parameters must be valid pointers.  |boundary| may be
41   // nullptr.  |*mime_type| and |*charset| should be empty and |*had_charset|
42   // false when called with the first Content-Type header value in a given
43   // header list.
44   //
45   // ParseContentType() supports parsing multiple Content-Type headers in the
46   // same header list.  For this operation, subsequent calls should pass in the
47   // same |mime_type|, |charset|, and |had_charset| arguments without clearing
48   // them.
49   //
50   // The resulting mime_type and charset values are normalized to lowercase.
51   // The mime_type and charset output values are only modified if the
52   // content_type_str contains a mime type and charset value, respectively.  If
53   // |boundary| is not null, then |*boundary| will be assigned the (unquoted)
54   // value of the boundary parameter, if any.
55   static void ParseContentType(const std::string& content_type_str,
56                                std::string* mime_type,
57                                std::string* charset,
58                                bool* had_charset,
59                                std::string* boundary);
60 
61   // Parses the value of a "Range" header as defined in RFC 7233 Section 2.1.
62   // https://tools.ietf.org/html/rfc7233#section-2.1
63   // Returns false on failure.
64   static bool ParseRangeHeader(const std::string& range_specifier,
65                                std::vector<HttpByteRange>* ranges);
66 
67   // Extracts the values in a Content-Range header and returns true if all three
68   // values are present and valid for a 206 response; otherwise returns false.
69   // The following values will be outputted:
70   // |*first_byte_position| = inclusive position of the first byte of the range
71   // |*last_byte_position| = inclusive position of the last byte of the range
72   // |*instance_length| = size in bytes of the object requested
73   // If this method returns false, then all of the outputs will be -1.
74   static bool ParseContentRangeHeaderFor206(
75       base::StringPiece content_range_spec,
76       int64_t* first_byte_position,
77       int64_t* last_byte_position,
78       int64_t* instance_length);
79 
80   // Parses a Retry-After header that is either an absolute date/time or a
81   // number of seconds in the future. Interprets absolute times as relative to
82   // |now|. If |retry_after_string| is successfully parsed and indicates a time
83   // that is not in the past, fills in |*retry_after| and returns true;
84   // otherwise, returns false.
85   static bool ParseRetryAfterHeader(const std::string& retry_after_string,
86                                     base::Time now,
87                                     base::TimeDelta* retry_after);
88 
89   // Returns true if the request method is "safe" (per section 4.2.1 of
90   // RFC 7231).
91   static bool IsMethodSafe(base::StringPiece method);
92 
93   // Returns true if the request method is idempotent (per section 4.2.2 of
94   // RFC 7231).
95   static bool IsMethodIdempotent(base::StringPiece method);
96 
97   // Returns true if it is safe to allow users and scripts to specify the header
98   // named |name|. Returns true for headers not in the list at
99   // https://fetch.spec.whatwg.org/#forbidden-header-name. Does not check header
100   // validity.
101   static bool IsSafeHeader(base::StringPiece name);
102 
103   // Returns true if |name| is a valid HTTP header name.
104   static bool IsValidHeaderName(base::StringPiece name);
105 
106   // Returns false if |value| contains NUL or CRLF. This method does not perform
107   // a fully RFC-2616-compliant header value validation.
108   static bool IsValidHeaderValue(base::StringPiece value);
109 
110   // Multiple occurances of some headers cannot be coalesced into a comma-
111   // separated list since their values are (or contain) unquoted HTTP-date
112   // values, which may contain a comma (see RFC 2616 section 3.3.1).
113   static bool IsNonCoalescingHeader(base::StringPiece name);
114 
115   // Return true if the character is HTTP "linear white space" (SP | HT).
116   // This definition corresponds with the HTTP_LWS macro, and does not match
117   // newlines.
118   static bool IsLWS(char c);
119 
120   // Trim HTTP_LWS chars from the beginning and end of the string.
121   static void TrimLWS(std::string::const_iterator* begin,
122                       std::string::const_iterator* end);
123   static base::StringPiece TrimLWS(const base::StringPiece& string);
124 
125   // Whether the character is a valid |tchar| as defined in RFC 7230 Sec 3.2.6.
126   static bool IsTokenChar(char c);
127   // Whether the string is a valid |token| as defined in RFC 7230 Sec 3.2.6.
128   static bool IsToken(base::StringPiece str);
129 
130   // Whether the string is a valid |parmname| as defined in RFC 5987 Sec 3.2.1.
131   static bool IsParmName(base::StringPiece str);
132 
133   // RFC 2616 Sec 2.2:
134   // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
135   // Unquote() strips the surrounding quotemarks off a string, and unescapes
136   // any quoted-pair to obtain the value contained by the quoted-string.
137   // If the input is not quoted, then it works like the identity function.
138   static std::string Unquote(base::StringPiece str);
139 
140   // Similar to Unquote(), but additionally validates that the string being
141   // unescaped actually is a valid quoted string. Returns false for an empty
142   // string, a string without quotes, a string with mismatched quotes, and
143   // a string with unescaped embeded quotes.
144   static bool StrictUnquote(base::StringPiece str,
145                             std::string* out) WARN_UNUSED_RESULT;
146 
147   // The reverse of Unquote() -- escapes and surrounds with "
148   static std::string Quote(base::StringPiece str);
149 
150   // Returns the start of the status line, or std::string::npos if no status
151   // line was found. This allows for 4 bytes of junk to precede the status line
152   // (which is what Mozilla does too).
153   static size_t LocateStartOfStatusLine(const char* buf, size_t buf_len);
154 
155   // Returns index beyond the end-of-headers marker or std::string::npos if not
156   // found.  RFC 2616 defines the end-of-headers marker as a double CRLF;
157   // however, some servers only send back LFs (e.g., Unix-based CGI scripts
158   // written using the ASIS Apache module).  This function therefore accepts the
159   // pattern LF[CR]LF as end-of-headers (just like Mozilla). The first line of
160   // |buf| is considered the status line, even if empty. The parameter |i| is
161   // the offset within |buf| to begin searching from.
162   static size_t LocateEndOfHeaders(const char* buf,
163                                    size_t buf_len,
164                                    size_t i = 0);
165 
166   // Same as |LocateEndOfHeaders|, but does not expect a status line, so can be
167   // used on multi-part responses or HTTP/1.x trailers.  As a result, if |buf|
168   // starts with a single [CR]LF,  it is considered an empty header list, as
169   // opposed to an empty status line above a header list.
170   static size_t LocateEndOfAdditionalHeaders(const char* buf,
171                                              size_t buf_len,
172                                              size_t i = 0);
173 
174   // Assemble "raw headers" in the format required by HttpResponseHeaders.
175   // This involves normalizing line terminators, converting [CR]LF to \0 and
176   // handling HTTP line continuations (i.e., lines starting with LWS are
177   // continuations of the previous line). |buf| should end at the
178   // end-of-headers marker as defined by LocateEndOfHeaders. If a \0 appears
179   // within the headers themselves, it will be stripped. This is a workaround to
180   // avoid later code from incorrectly interpreting it as a line terminator.
181   //
182   // TODO(crbug.com/671799): Should remove or internalize this to
183   //                         HttpResponseHeaders.
184   static std::string AssembleRawHeaders(base::StringPiece buf);
185 
186   // Converts assembled "raw headers" back to the HTTP response format. That is
187   // convert each \0 occurence to CRLF. This is used by DevTools.
188   // Since all line continuations info is already lost at this point, the result
189   // consists of status line and then one line for each header.
190   static std::string ConvertHeadersBackToHTTPResponse(const std::string& str);
191 
192   // Given a comma separated ordered list of language codes, return an expanded
193   // list by adding the base language from language-region pair if it doesn't
194   // already exist. This increases the chances of language matching in many
195   // cases as explained at this w3c doc:
196   // https://www.w3.org/International/questions/qa-lang-priorities#langtagdetail
197   // Note that we do not support Q values (e.g. ;q=0.9) in |language_prefs|.
198   static std::string ExpandLanguageList(const std::string& language_prefs);
199 
200   // Given a comma separated ordered list of language codes, return
201   // the list with a qvalue appended to each language.
202   // The way qvalues are assigned is rather simple. The qvalue
203   // starts with 1.0 and is decremented by 0.1 for each successive entry
204   // in the list until it reaches 0.1. All the entries after that are
205   // assigned the same qvalue of 0.1. Also, note that the 1st language
206   // will not have a qvalue added because the absence of a qvalue implicitly
207   // means q=1.0.
208   //
209   // When making a http request, this should be used to determine what
210   // to put in Accept-Language header. If a comma separated list of language
211   // codes *without* qvalue is sent, web servers regard all
212   // of them as having q=1.0 and pick one of them even though it may not
213   // be at the beginning of the list (see http://crbug.com/5899).
214   static std::string GenerateAcceptLanguageHeader(
215       const std::string& raw_language_list);
216 
217   // Returns true if the parameters describe a response with a strong etag or
218   // last-modified header.  See section 13.3.3 of RFC 2616.
219   // An empty string should be passed for missing headers.
220   static bool HasStrongValidators(HttpVersion version,
221                                   const std::string& etag_header,
222                                   const std::string& last_modified_header,
223                                   const std::string& date_header);
224 
225   // Returns true if this response has any validator (either a Last-Modified or
226   // an ETag) regardless of whether it is strong or weak.  See section 13.3.3 of
227   // RFC 2616.
228   // An empty string should be passed for missing headers.
229   static bool HasValidators(HttpVersion version,
230                             const std::string& etag_header,
231                             const std::string& last_modified_header);
232 
233   // Gets a vector of common HTTP status codes for histograms of status
234   // codes.  Currently returns everything in the range [100, 600), plus 0
235   // (for invalid responses/status codes).
236   static std::vector<int> GetStatusCodesForHistogram();
237 
238   // Maps an HTTP status code to one of the status codes in the vector
239   // returned by GetStatusCodesForHistogram.
240   static int MapStatusCodeForHistogram(int code);
241 
242   // Returns true if |accept_encoding| is well-formed.  Parsed encodings turned
243   // to lower case, are placed to provided string-set. Resulting set is
244   // augmented to fulfill the RFC 2616 and RFC 7231 recommendations, e.g. if
245   // there is no encodings specified, then {"*"} is returned to denote that
246   // client has to encoding preferences (but it does not imply that the
247   // user agent will be able to correctly process all encodings).
248   static bool ParseAcceptEncoding(const std::string& accept_encoding,
249                                   std::set<std::string>* allowed_encodings);
250 
251   // Returns true if |content_encoding| is well-formed.  Parsed encodings turned
252   // to lower case, are placed to provided string-set. See sections 14.11 and
253   // 3.5 of RFC 2616.
254   static bool ParseContentEncoding(const std::string& content_encoding,
255                                    std::set<std::string>* used_encodings);
256 
257   // Used to iterate over the name/value pairs of HTTP headers.  To iterate
258   // over the values in a multi-value header, use ValuesIterator.
259   // See AssembleRawHeaders for joining line continuations (this iterator
260   // does not expect any).
261   class NET_EXPORT HeadersIterator {
262    public:
263     HeadersIterator(std::string::const_iterator headers_begin,
264                     std::string::const_iterator headers_end,
265                     const std::string& line_delimiter);
266     ~HeadersIterator();
267 
268     // Advances the iterator to the next header, if any.  Returns true if there
269     // is a next header.  Use name* and values* methods to access the resultant
270     // header name and values.
271     bool GetNext();
272 
273     // Iterates through the list of headers, starting with the current position
274     // and looks for the specified header.  Note that the name _must_ be
275     // lower cased.
276     // If the header was found, the return value will be true and the current
277     // position points to the header.  If the return value is false, the
278     // current position will be at the end of the headers.
279     bool AdvanceTo(const char* lowercase_name);
280 
Reset()281     void Reset() {
282       lines_.Reset();
283     }
284 
name_begin()285     std::string::const_iterator name_begin() const {
286       return name_begin_;
287     }
name_end()288     std::string::const_iterator name_end() const {
289       return name_end_;
290     }
name()291     std::string name() const {
292       return std::string(name_begin_, name_end_);
293     }
name_piece()294     base::StringPiece name_piece() const {
295       return base::StringPiece(name_begin_, name_end_);
296     }
297 
values_begin()298     std::string::const_iterator values_begin() const {
299       return values_begin_;
300     }
values_end()301     std::string::const_iterator values_end() const {
302       return values_end_;
303     }
values()304     std::string values() const {
305       return std::string(values_begin_, values_end_);
306     }
values_piece()307     base::StringPiece values_piece() const {
308       return base::StringPiece(values_begin_, values_end_);
309     }
310 
311    private:
312     base::StringTokenizer lines_;
313     std::string::const_iterator name_begin_;
314     std::string::const_iterator name_end_;
315     std::string::const_iterator values_begin_;
316     std::string::const_iterator values_end_;
317   };
318 
319   // Iterates over delimited values in an HTTP header.  HTTP LWS is
320   // automatically trimmed from the resulting values.
321   //
322   // When using this class to iterate over response header values, be aware that
323   // for some headers (e.g., Last-Modified), commas are not used as delimiters.
324   // This iterator should be avoided for headers like that which are considered
325   // non-coalescing (see IsNonCoalescingHeader).
326   //
327   // This iterator is careful to skip over delimiters found inside an HTTP
328   // quoted string.
329   class NET_EXPORT_PRIVATE ValuesIterator {
330    public:
331     ValuesIterator(std::string::const_iterator values_begin,
332                    std::string::const_iterator values_end,
333                    char delimiter,
334                    bool ignore_empty_values = true);
335     ValuesIterator(const ValuesIterator& other);
336     ~ValuesIterator();
337 
338     // Advances the iterator to the next value, if any.  Returns true if there
339     // is a next value.  Use value* methods to access the resultant value.
340     bool GetNext();
341 
value_begin()342     std::string::const_iterator value_begin() const {
343       return value_begin_;
344     }
value_end()345     std::string::const_iterator value_end() const {
346       return value_end_;
347     }
value()348     std::string value() const {
349       return std::string(value_begin_, value_end_);
350     }
value_piece()351     base::StringPiece value_piece() const {
352       return base::StringPiece(value_begin_, value_end_);
353     }
354 
355    private:
356     base::StringTokenizer values_;
357     std::string::const_iterator value_begin_;
358     std::string::const_iterator value_end_;
359     bool ignore_empty_values_;
360   };
361 
362   // Iterates over a delimited sequence of name-value pairs in an HTTP header.
363   // Each pair consists of a token (the name), an equals sign, and either a
364   // token or quoted-string (the value). Arbitrary HTTP LWS is permitted outside
365   // of and between names, values, and delimiters.
366   //
367   // String iterators returned from this class' methods may be invalidated upon
368   // calls to GetNext() or after the NameValuePairsIterator is destroyed.
369   class NET_EXPORT NameValuePairsIterator {
370    public:
371     // Whether or not values are optional. Values::NOT_REQUIRED allows
372     // e.g. name1=value1;name2;name3=value3, whereas Vaues::REQUIRED
373     // will treat it as a parse error because name2 does not have a
374     // corresponding equals sign.
375     enum class Values { NOT_REQUIRED, REQUIRED };
376 
377     // Whether or not unmatched quotes should be considered a failure. By
378     // default this class is pretty lenient and does a best effort to parse
379     // values with mismatched quotes. When set to STRICT_QUOTES a value with
380     // mismatched or otherwise invalid quotes is considered a parse error.
381     enum class Quotes { STRICT_QUOTES, NOT_STRICT };
382 
383     NameValuePairsIterator(std::string::const_iterator begin,
384                            std::string::const_iterator end,
385                            char delimiter,
386                            Values optional_values,
387                            Quotes strict_quotes);
388 
389     // Treats values as not optional by default (Values::REQUIRED) and
390     // treats quotes as not strict.
391     NameValuePairsIterator(std::string::const_iterator begin,
392                            std::string::const_iterator end,
393                            char delimiter);
394 
395     NameValuePairsIterator(const NameValuePairsIterator& other);
396 
397     ~NameValuePairsIterator();
398 
399     // Advances the iterator to the next pair, if any.  Returns true if there
400     // is a next pair.  Use name* and value* methods to access the resultant
401     // value.
402     bool GetNext();
403 
404     // Returns false if there was a parse error.
valid()405     bool valid() const { return valid_; }
406 
407     // The name of the current name-value pair.
name_begin()408     std::string::const_iterator name_begin() const { return name_begin_; }
name_end()409     std::string::const_iterator name_end() const { return name_end_; }
name()410     std::string name() const { return std::string(name_begin_, name_end_); }
name_piece()411     base::StringPiece name_piece() const {
412       return base::StringPiece(name_begin_, name_end_);
413     }
414 
415     // The value of the current name-value pair.
value_begin()416     std::string::const_iterator value_begin() const {
417       return value_is_quoted_ ? unquoted_value_.begin() : value_begin_;
418     }
value_end()419     std::string::const_iterator value_end() const {
420       return value_is_quoted_ ? unquoted_value_.end() : value_end_;
421     }
value()422     std::string value() const {
423       return value_is_quoted_ ? unquoted_value_ : std::string(value_begin_,
424                                                               value_end_);
425     }
value_piece()426     base::StringPiece value_piece() const {
427       return value_is_quoted_ ? unquoted_value_
428                               : base::StringPiece(value_begin_, value_end_);
429     }
430 
value_is_quoted()431     bool value_is_quoted() const { return value_is_quoted_; }
432 
433     // The value before unquoting (if any).
raw_value()434     std::string raw_value() const { return std::string(value_begin_,
435                                                        value_end_); }
436 
437    private:
438     HttpUtil::ValuesIterator props_;
439     bool valid_;
440 
441     std::string::const_iterator name_begin_;
442     std::string::const_iterator name_end_;
443 
444     std::string::const_iterator value_begin_;
445     std::string::const_iterator value_end_;
446 
447     // Do not store iterators into this string. The NameValuePairsIterator
448     // is copyable/assignable, and if copied the copy's iterators would point
449     // into the original's unquoted_value_ member.
450     std::string unquoted_value_;
451 
452     bool value_is_quoted_;
453 
454     // True if values are required for each name/value pair; false if a
455     // name is permitted to appear without a corresponding value.
456     bool values_optional_;
457 
458     // True if quotes values are required to be properly quoted; false if
459     // mismatched quotes and other problems with quoted values should be more
460     // or less gracefully treated as valid.
461     bool strict_quotes_;
462   };
463 };
464 
465 }  // namespace net
466 
467 #endif  // NET_HTTP_HTTP_UTIL_H_
468