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