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