• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/350788890): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #ifndef URL_URL_CANON_INTERNAL_H_
11 #define URL_URL_CANON_INTERNAL_H_
12 
13 // This file is intended to be included in another C++ file where the character
14 // types are defined. This allows us to write mostly generic code, but not have
15 // template bloat because everything is inlined when anybody calls any of our
16 // functions.
17 
18 #include <stddef.h>
19 #include <stdlib.h>
20 
21 #include <string>
22 
23 #include "base/component_export.h"
24 #include "base/notreached.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/third_party/icu/icu_utf.h"
27 #include "url/url_canon.h"
28 
29 namespace url {
30 
31 // Character type handling -----------------------------------------------------
32 
33 // Bits that identify different character types. These types identify different
34 // bits that are set for each 8-bit character in the kSharedCharTypeTable.
35 enum SharedCharTypes {
36   // Characters that do not require escaping in queries. Characters that do
37   // not have this flag will be escaped; see url_canon_query.cc
38   CHAR_QUERY = 1,
39 
40   // Valid in the username/password field.
41   CHAR_USERINFO = 2,
42 
43   // Valid in a IPv4 address (digits plus dot and 'x' for hex).
44   CHAR_IPV4 = 4,
45 
46   // Valid in an ASCII-representation of a hex digit (as in %-escaped).
47   CHAR_HEX = 8,
48 
49   // Valid in an ASCII-representation of a decimal digit.
50   CHAR_DEC = 16,
51 
52   // Valid in an ASCII-representation of an octal digit.
53   CHAR_OCT = 32,
54 
55   // Characters that do not require escaping in encodeURIComponent. Characters
56   // that do not have this flag will be escaped; see url_util.cc.
57   CHAR_COMPONENT = 64,
58 };
59 
60 // This table contains the flags in SharedCharTypes for each 8-bit character.
61 // Some canonicalization functions have their own specialized lookup table.
62 // For those with simple requirements, we have collected the flags in one
63 // place so there are fewer lookup tables to load into the CPU cache.
64 //
65 // Using an unsigned char type has a small but measurable performance benefit
66 // over using a 32-bit number.
67 extern const unsigned char kSharedCharTypeTable[0x100];
68 
69 // More readable wrappers around the character type lookup table.
IsCharOfType(unsigned char c,SharedCharTypes type)70 inline bool IsCharOfType(unsigned char c, SharedCharTypes type) {
71   return !!(kSharedCharTypeTable[c] & type);
72 }
IsQueryChar(unsigned char c)73 inline bool IsQueryChar(unsigned char c) {
74   return IsCharOfType(c, CHAR_QUERY);
75 }
IsIPv4Char(unsigned char c)76 inline bool IsIPv4Char(unsigned char c) {
77   return IsCharOfType(c, CHAR_IPV4);
78 }
IsHexChar(unsigned char c)79 inline bool IsHexChar(unsigned char c) {
80   return IsCharOfType(c, CHAR_HEX);
81 }
IsComponentChar(unsigned char c)82 inline bool IsComponentChar(unsigned char c) {
83   return IsCharOfType(c, CHAR_COMPONENT);
84 }
85 
86 // Appends the given string to the output, escaping characters that do not
87 // match the given |type| in SharedCharTypes.
88 void AppendStringOfType(const char* source,
89                         size_t length,
90                         SharedCharTypes type,
91                         CanonOutput* output);
92 void AppendStringOfType(const char16_t* source,
93                         size_t length,
94                         SharedCharTypes type,
95                         CanonOutput* output);
96 
97 // This lookup table allows fast conversion between ASCII hex letters and their
98 // corresponding numerical value. The 8-bit range is divided up into 8
99 // regions of 0x20 characters each. Each of the three character types (numbers,
100 // uppercase, lowercase) falls into different regions of this range. The table
101 // contains the amount to subtract from characters in that range to get at
102 // the corresponding numerical value.
103 //
104 // See HexDigitToValue for the lookup.
105 extern const char kCharToHexLookup[8];
106 
107 // Assumes the input is a valid hex digit! Call IsHexChar before using this.
HexCharToValue(unsigned char c)108 inline int HexCharToValue(unsigned char c) {
109   return c - kCharToHexLookup[c / 0x20];
110 }
111 
112 // Indicates if the given character is a dot or dot equivalent, returning the
113 // number of characters taken by it. This will be one for a literal dot, 3 for
114 // an escaped dot. If the character is not a dot, this will return 0.
115 template <typename CHAR>
IsDot(const CHAR * spec,size_t offset,size_t end)116 inline size_t IsDot(const CHAR* spec, size_t offset, size_t end) {
117   if (spec[offset] == '.') {
118     return 1;
119   } else if (spec[offset] == '%' && offset + 3 <= end &&
120              spec[offset + 1] == '2' &&
121              (spec[offset + 2] == 'e' || spec[offset + 2] == 'E')) {
122     // Found "%2e"
123     return 3;
124   }
125   return 0;
126 }
127 
128 // Returns the canonicalized version of the input character according to scheme
129 // rules. This is implemented alongside the scheme canonicalizer, and is
130 // required for relative URL resolving to test for scheme equality.
131 //
132 // Returns 0 if the input character is not a valid scheme character.
133 char CanonicalSchemeChar(char16_t ch);
134 
135 // Write a single character, escaped, to the output. This always escapes: it
136 // does no checking that thee character requires escaping.
137 // Escaping makes sense only 8 bit chars, so code works in all cases of
138 // input parameters (8/16bit).
139 template <typename UINCHAR, typename OUTCHAR>
AppendEscapedChar(UINCHAR ch,CanonOutputT<OUTCHAR> * output)140 inline void AppendEscapedChar(UINCHAR ch, CanonOutputT<OUTCHAR>* output) {
141   output->push_back('%');
142   std::string hex;
143   base::AppendHexEncodedByte(static_cast<uint8_t>(ch), hex);
144   output->push_back(static_cast<OUTCHAR>(hex[0]));
145   output->push_back(static_cast<OUTCHAR>(hex[1]));
146 }
147 
148 // The character we'll substitute for undecodable or invalid characters.
149 extern const base_icu::UChar32 kUnicodeReplacementCharacter;
150 
151 // UTF-8 functions ------------------------------------------------------------
152 
153 // Reads one character in UTF-8 starting at |*begin| in |str|, places
154 // the decoded value into |*code_point|, and returns true on success.
155 // Otherwise, we'll return false and put the kUnicodeReplacementCharacter
156 // into |*code_point|.
157 //
158 // |*begin| will be updated to point to the last character consumed so it
159 // can be incremented in a loop and will be ready for the next character.
160 // (for a single-byte ASCII character, it will not be changed).
161 COMPONENT_EXPORT(URL)
162 bool ReadUTFCharLossy(const char* str,
163                       size_t* begin,
164                       size_t length,
165                       base_icu::UChar32* code_point_out);
166 
167 // Generic To-UTF-8 converter. This will call the given append method for each
168 // character that should be appended, with the given output method. Wrappers
169 // are provided below for escaped and non-escaped versions of this.
170 //
171 // The char_value must have already been checked that it's a valid Unicode
172 // character.
173 template <class Output, void Appender(unsigned char, Output*)>
DoAppendUTF8(base_icu::UChar32 char_value,Output * output)174 inline void DoAppendUTF8(base_icu::UChar32 char_value, Output* output) {
175   DCHECK(char_value >= 0);
176   DCHECK(char_value <= 0x10FFFF);
177   if (char_value <= 0x7f) {
178     Appender(static_cast<unsigned char>(char_value), output);
179   } else if (char_value <= 0x7ff) {
180     // 110xxxxx 10xxxxxx
181     Appender(static_cast<unsigned char>(0xC0 | (char_value >> 6)), output);
182     Appender(static_cast<unsigned char>(0x80 | (char_value & 0x3f)), output);
183   } else if (char_value <= 0xffff) {
184     // 1110xxxx 10xxxxxx 10xxxxxx
185     Appender(static_cast<unsigned char>(0xe0 | (char_value >> 12)), output);
186     Appender(static_cast<unsigned char>(0x80 | ((char_value >> 6) & 0x3f)),
187              output);
188     Appender(static_cast<unsigned char>(0x80 | (char_value & 0x3f)), output);
189   } else {
190     // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
191     Appender(static_cast<unsigned char>(0xf0 | (char_value >> 18)), output);
192     Appender(static_cast<unsigned char>(0x80 | ((char_value >> 12) & 0x3f)),
193              output);
194     Appender(static_cast<unsigned char>(0x80 | ((char_value >> 6) & 0x3f)),
195              output);
196     Appender(static_cast<unsigned char>(0x80 | (char_value & 0x3f)), output);
197   }
198 }
199 
200 // Helper used by AppendUTF8Value below. We use an unsigned parameter so there
201 // are no funny sign problems with the input, but then have to convert it to
202 // a regular char for appending.
AppendCharToOutput(unsigned char ch,CanonOutput * output)203 inline void AppendCharToOutput(unsigned char ch, CanonOutput* output) {
204   output->push_back(static_cast<char>(ch));
205 }
206 
207 // Writes the given character to the output as UTF-8. This does NO checking
208 // of the validity of the Unicode characters; the caller should ensure that
209 // the value it is appending is valid to append.
AppendUTF8Value(base_icu::UChar32 char_value,CanonOutput * output)210 inline void AppendUTF8Value(base_icu::UChar32 char_value, CanonOutput* output) {
211   DoAppendUTF8<CanonOutput, AppendCharToOutput>(char_value, output);
212 }
213 
214 // Writes the given character to the output as UTF-8, escaping ALL
215 // characters (even when they are ASCII). This does NO checking of the
216 // validity of the Unicode characters; the caller should ensure that the value
217 // it is appending is valid to append.
AppendUTF8EscapedValue(base_icu::UChar32 char_value,CanonOutput * output)218 inline void AppendUTF8EscapedValue(base_icu::UChar32 char_value,
219                                    CanonOutput* output) {
220   DoAppendUTF8<CanonOutput, AppendEscapedChar>(char_value, output);
221 }
222 
223 // UTF-16 functions -----------------------------------------------------------
224 
225 // Reads one character in UTF-16 starting at |*begin| in |str|, places
226 // the decoded value into |*code_point|, and returns true on success.
227 // Otherwise, we'll return false and put the kUnicodeReplacementCharacter
228 // into |*code_point|.
229 //
230 // |*begin| will be updated to point to the last character consumed so it
231 // can be incremented in a loop and will be ready for the next character.
232 // (for a single-16-bit-word character, it will not be changed).
233 COMPONENT_EXPORT(URL)
234 bool ReadUTFCharLossy(const char16_t* str,
235                       size_t* begin,
236                       size_t length,
237                       base_icu::UChar32* code_point_out);
238 
239 // Equivalent to U16_APPEND_UNSAFE in ICU but uses our output method.
AppendUTF16Value(base_icu::UChar32 code_point,CanonOutputT<char16_t> * output)240 inline void AppendUTF16Value(base_icu::UChar32 code_point,
241                              CanonOutputT<char16_t>* output) {
242   if (code_point > 0xffff) {
243     output->push_back(static_cast<char16_t>((code_point >> 10) + 0xd7c0));
244     output->push_back(static_cast<char16_t>((code_point & 0x3ff) | 0xdc00));
245   } else {
246     output->push_back(static_cast<char16_t>(code_point));
247   }
248 }
249 
250 // Escaping functions ---------------------------------------------------------
251 
252 // Writes the given character to the output as UTF-8, escaped. Call this
253 // function only when the input is wide. Returns true on success. Failure
254 // means there was some problem with the encoding, we'll still try to
255 // update the |*begin| pointer and add a placeholder character to the
256 // output so processing can continue.
257 //
258 // We will append the character starting at ch[begin] with the buffer ch
259 // being |length|. |*begin| will be updated to point to the last character
260 // consumed (we may consume more than one for UTF-16) so that if called in
261 // a loop, incrementing the pointer will move to the next character.
262 //
263 // Every single output character will be escaped. This means that if you
264 // give it an ASCII character as input, it will be escaped. Some code uses
265 // this when it knows that a character is invalid according to its rules
266 // for validity. If you don't want escaping for ASCII characters, you will
267 // have to filter them out prior to calling this function.
268 //
269 // Assumes that ch[begin] is within range in the array, but does not assume
270 // that any following characters are.
AppendUTF8EscapedChar(const char16_t * str,size_t * begin,size_t length,CanonOutput * output)271 inline bool AppendUTF8EscapedChar(const char16_t* str,
272                                   size_t* begin,
273                                   size_t length,
274                                   CanonOutput* output) {
275   // UTF-16 input. ReadUTFCharLossy will handle invalid characters for us and
276   // give us the kUnicodeReplacementCharacter, so we don't have to do special
277   // checking after failure, just pass through the failure to the caller.
278   base_icu::UChar32 char_value;
279   bool success = ReadUTFCharLossy(str, begin, length, &char_value);
280   AppendUTF8EscapedValue(char_value, output);
281   return success;
282 }
283 
284 // Handles UTF-8 input. See the wide version above for usage.
AppendUTF8EscapedChar(const char * str,size_t * begin,size_t length,CanonOutput * output)285 inline bool AppendUTF8EscapedChar(const char* str,
286                                   size_t* begin,
287                                   size_t length,
288                                   CanonOutput* output) {
289   // ReadUTFCharLossy will handle invalid characters for us and give us the
290   // kUnicodeReplacementCharacter, so we don't have to do special checking
291   // after failure, just pass through the failure to the caller.
292   base_icu::UChar32 ch;
293   bool success = ReadUTFCharLossy(str, begin, length, &ch);
294   AppendUTF8EscapedValue(ch, output);
295   return success;
296 }
297 
298 // URL Standard: https://url.spec.whatwg.org/#c0-control-percent-encode-set
299 template <typename CHAR>
IsInC0ControlPercentEncodeSet(CHAR ch)300 bool IsInC0ControlPercentEncodeSet(CHAR ch) {
301   return ch < 0x20 || ch > 0x7E;
302 }
303 
304 // Given a '%' character at |*begin| in the string |spec|, this will decode
305 // the escaped value and put it into |*unescaped_value| on success (returns
306 // true). On failure, this will return false, and will not write into
307 // |*unescaped_value|.
308 //
309 // |*begin| will be updated to point to the last character of the escape
310 // sequence so that when called with the index of a for loop, the next time
311 // through it will point to the next character to be considered. On failure,
312 // |*begin| will be unchanged.
Is8BitChar(char c)313 inline bool Is8BitChar(char c) {
314   return true;  // this case is specialized to avoid a warning
315 }
Is8BitChar(char16_t c)316 inline bool Is8BitChar(char16_t c) {
317   return c <= 255;
318 }
319 
320 template <typename CHAR>
DecodeEscaped(const CHAR * spec,size_t * begin,size_t end,unsigned char * unescaped_value)321 inline bool DecodeEscaped(const CHAR* spec,
322                           size_t* begin,
323                           size_t end,
324                           unsigned char* unescaped_value) {
325   if (*begin + 3 > end || !Is8BitChar(spec[*begin + 1]) ||
326       !Is8BitChar(spec[*begin + 2])) {
327     // Invalid escape sequence because there's not enough room, or the
328     // digits are not ASCII.
329     return false;
330   }
331 
332   unsigned char first = static_cast<unsigned char>(spec[*begin + 1]);
333   unsigned char second = static_cast<unsigned char>(spec[*begin + 2]);
334   if (!IsHexChar(first) || !IsHexChar(second)) {
335     // Invalid hex digits, fail.
336     return false;
337   }
338 
339   // Valid escape sequence.
340   *unescaped_value = static_cast<unsigned char>((HexCharToValue(first) << 4) +
341                                                 HexCharToValue(second));
342   *begin += 2;
343   return true;
344 }
345 
346 // Appends the given substring to the output, escaping "some" characters that
347 // it feels may not be safe. It assumes the input values are all contained in
348 // 8-bit although it allows any type.
349 //
350 // This is used in error cases to append invalid output so that it looks
351 // approximately correct. Non-error cases should not call this function since
352 // the escaping rules are not guaranteed!
353 void AppendInvalidNarrowString(const char* spec,
354                                size_t begin,
355                                size_t end,
356                                CanonOutput* output);
357 void AppendInvalidNarrowString(const char16_t* spec,
358                                size_t begin,
359                                size_t end,
360                                CanonOutput* output);
361 
362 // Misc canonicalization helpers ----------------------------------------------
363 
364 // Converts between UTF-8 and UTF-16, returning true on successful conversion.
365 // The output will be appended to the given canonicalizer output (so make sure
366 // it's empty if you want to replace).
367 //
368 // On invalid input, this will still write as much output as possible,
369 // replacing the invalid characters with the "invalid character". It will
370 // return false in the failure case, and the caller should not continue as
371 // normal.
372 COMPONENT_EXPORT(URL)
373 bool ConvertUTF16ToUTF8(const char16_t* input,
374                         size_t input_len,
375                         CanonOutput* output);
376 COMPONENT_EXPORT(URL)
377 bool ConvertUTF8ToUTF16(const char* input,
378                         size_t input_len,
379                         CanonOutputT<char16_t>* output);
380 
381 // Converts from UTF-16 to 8-bit using the character set converter. If the
382 // converter is NULL, this will use UTF-8.
383 void ConvertUTF16ToQueryEncoding(const char16_t* input,
384                                  const Component& query,
385                                  CharsetConverter* converter,
386                                  CanonOutput* output);
387 
388 // Applies the replacements to the given component source. The component source
389 // should be pre-initialized to the "old" base. That is, all pointers will
390 // point to the spec of the old URL, and all of the Parsed components will
391 // be indices into that string.
392 //
393 // The pointers and components in the |source| for all non-NULL strings in the
394 // |repl| (replacements) will be updated to reference those strings.
395 // Canonicalizing with the new |source| and |parsed| can then combine URL
396 // components from many different strings.
397 void SetupOverrideComponents(const char* base,
398                              const Replacements<char>& repl,
399                              URLComponentSource<char>* source,
400                              Parsed* parsed);
401 
402 // Like the above 8-bit version, except that it additionally converts the
403 // UTF-16 input to UTF-8 before doing the overrides.
404 //
405 // The given utf8_buffer is used to store the converted components. They will
406 // be appended one after another, with the parsed structure identifying the
407 // appropriate substrings. This buffer is a parameter because the source has
408 // no storage, so the buffer must have the same lifetime as the source
409 // parameter owned by the caller.
410 //
411 // THE CALLER MUST NOT ADD TO THE |utf8_buffer| AFTER THIS CALL. Members of
412 // |source| will point into this buffer, which could be invalidated if
413 // additional data is added and the CanonOutput resizes its buffer.
414 //
415 // Returns true on success. False means that the input was not valid UTF-16,
416 // although we will have still done the override with "invalid characters" in
417 // place of errors.
418 bool SetupUTF16OverrideComponents(const char* base,
419                                   const Replacements<char16_t>& repl,
420                                   CanonOutput* utf8_buffer,
421                                   URLComponentSource<char>* source,
422                                   Parsed* parsed);
423 
424 // Implemented in url_canon_path.cc, these are required by the relative URL
425 // resolver as well, so we declare them here.
426 bool CanonicalizePartialPathInternal(const char* spec,
427                                      const Component& path,
428                                      size_t path_begin_in_output,
429                                      CanonMode canon_mode,
430                                      CanonOutput* output);
431 bool CanonicalizePartialPathInternal(const char16_t* spec,
432                                      const Component& path,
433                                      size_t path_begin_in_output,
434                                      CanonMode canon_mode,
435                                      CanonOutput* output);
436 
437 // Find the position of a bona fide Windows drive letter in the given path. If
438 // no leading drive letter is found, -1 is returned. This function correctly
439 // treats /c:/foo and /./c:/foo as having drive letters, and /def/c:/foo as not
440 // having a drive letter.
441 //
442 // Exported for tests.
443 COMPONENT_EXPORT(URL)
444 int FindWindowsDriveLetter(const char* spec, int begin, int end);
445 COMPONENT_EXPORT(URL)
446 int FindWindowsDriveLetter(const char16_t* spec, int begin, int end);
447 
448 #ifndef WIN32
449 
450 // Implementations of Windows' int-to-string conversions
451 COMPONENT_EXPORT(URL)
452 int _itoa_s(int value, char* buffer, size_t size_in_chars, int radix);
453 COMPONENT_EXPORT(URL)
454 int _itow_s(int value, char16_t* buffer, size_t size_in_chars, int radix);
455 
456 // Secure template overloads for these functions
457 template <size_t N>
_itoa_s(int value,char (& buffer)[N],int radix)458 inline int _itoa_s(int value, char (&buffer)[N], int radix) {
459   return _itoa_s(value, buffer, N, radix);
460 }
461 
462 template <size_t N>
_itow_s(int value,char16_t (& buffer)[N],int radix)463 inline int _itow_s(int value, char16_t (&buffer)[N], int radix) {
464   return _itow_s(value, buffer, N, radix);
465 }
466 
467 // _strtoui64 and strtoull behave the same
_strtoui64(const char * nptr,char ** endptr,int base)468 inline unsigned long long _strtoui64(const char* nptr,
469                                      char** endptr,
470                                      int base) {
471   return strtoull(nptr, endptr, base);
472 }
473 
474 #endif  // WIN32
475 
476 // The threshold we set to consider SIMD processing, in bytes; there is
477 // no deep theory here, it's just set empirically to a value that seems
478 // to be good. (We don't really know why there's a slowdown for zero;
479 // but a guess would be that there's no need in going into a complex loop
480 // with a lot of setup for a five-byte string.)
481 static constexpr int kMinimumLengthForSIMD = 50;
482 
483 }  // namespace url
484 
485 #endif  // URL_URL_CANON_INTERNAL_H_
486