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