Fix for Geolocation webTCT failures
[platform/framework/web/chromium-efl.git] / url / url_canon_internal.h
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.
65 inline bool IsCharOfType(unsigned char c, SharedCharTypes type) {
66   return !!(kSharedCharTypeTable[c] & type);
67 }
68 inline bool IsQueryChar(unsigned char c) {
69   return IsCharOfType(c, CHAR_QUERY);
70 }
71 inline bool IsIPv4Char(unsigned char c) {
72   return IsCharOfType(c, CHAR_IPV4);
73 }
74 inline bool IsHexChar(unsigned char c) {
75   return IsCharOfType(c, CHAR_HEX);
76 }
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.
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>
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>
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*)>
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.
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.
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.
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.
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.
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.
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 // Given a '%' character at |*begin| in the string |spec|, this will decode
294 // the escaped value and put it into |*unescaped_value| on success (returns
295 // true). On failure, this will return false, and will not write into
296 // |*unescaped_value|.
297 //
298 // |*begin| will be updated to point to the last character of the escape
299 // sequence so that when called with the index of a for loop, the next time
300 // through it will point to the next character to be considered. On failure,
301 // |*begin| will be unchanged.
302 inline bool Is8BitChar(char c) {
303   return true;  // this case is specialized to avoid a warning
304 }
305 inline bool Is8BitChar(char16_t c) {
306   return c <= 255;
307 }
308
309 template <typename CHAR>
310 inline bool DecodeEscaped(const CHAR* spec,
311                           size_t* begin,
312                           size_t end,
313                           unsigned char* unescaped_value) {
314   if (*begin + 3 > end || !Is8BitChar(spec[*begin + 1]) ||
315       !Is8BitChar(spec[*begin + 2])) {
316     // Invalid escape sequence because there's not enough room, or the
317     // digits are not ASCII.
318     return false;
319   }
320
321   unsigned char first = static_cast<unsigned char>(spec[*begin + 1]);
322   unsigned char second = static_cast<unsigned char>(spec[*begin + 2]);
323   if (!IsHexChar(first) || !IsHexChar(second)) {
324     // Invalid hex digits, fail.
325     return false;
326   }
327
328   // Valid escape sequence.
329   *unescaped_value = static_cast<unsigned char>((HexCharToValue(first) << 4) +
330                                                 HexCharToValue(second));
331   *begin += 2;
332   return true;
333 }
334
335 // Appends the given substring to the output, escaping "some" characters that
336 // it feels may not be safe. It assumes the input values are all contained in
337 // 8-bit although it allows any type.
338 //
339 // This is used in error cases to append invalid output so that it looks
340 // approximately correct. Non-error cases should not call this function since
341 // the escaping rules are not guaranteed!
342 void AppendInvalidNarrowString(const char* spec,
343                                size_t begin,
344                                size_t end,
345                                CanonOutput* output);
346 void AppendInvalidNarrowString(const char16_t* spec,
347                                size_t begin,
348                                size_t end,
349                                CanonOutput* output);
350
351 // Misc canonicalization helpers ----------------------------------------------
352
353 // Converts between UTF-8 and UTF-16, returning true on successful conversion.
354 // The output will be appended to the given canonicalizer output (so make sure
355 // it's empty if you want to replace).
356 //
357 // On invalid input, this will still write as much output as possible,
358 // replacing the invalid characters with the "invalid character". It will
359 // return false in the failure case, and the caller should not continue as
360 // normal.
361 COMPONENT_EXPORT(URL)
362 bool ConvertUTF16ToUTF8(const char16_t* input,
363                         size_t input_len,
364                         CanonOutput* output);
365 COMPONENT_EXPORT(URL)
366 bool ConvertUTF8ToUTF16(const char* input,
367                         size_t input_len,
368                         CanonOutputT<char16_t>* output);
369
370 // Converts from UTF-16 to 8-bit using the character set converter. If the
371 // converter is NULL, this will use UTF-8.
372 void ConvertUTF16ToQueryEncoding(const char16_t* input,
373                                  const Component& query,
374                                  CharsetConverter* converter,
375                                  CanonOutput* output);
376
377 // Applies the replacements to the given component source. The component source
378 // should be pre-initialized to the "old" base. That is, all pointers will
379 // point to the spec of the old URL, and all of the Parsed components will
380 // be indices into that string.
381 //
382 // The pointers and components in the |source| for all non-NULL strings in the
383 // |repl| (replacements) will be updated to reference those strings.
384 // Canonicalizing with the new |source| and |parsed| can then combine URL
385 // components from many different strings.
386 void SetupOverrideComponents(const char* base,
387                              const Replacements<char>& repl,
388                              URLComponentSource<char>* source,
389                              Parsed* parsed);
390
391 // Like the above 8-bit version, except that it additionally converts the
392 // UTF-16 input to UTF-8 before doing the overrides.
393 //
394 // The given utf8_buffer is used to store the converted components. They will
395 // be appended one after another, with the parsed structure identifying the
396 // appropriate substrings. This buffer is a parameter because the source has
397 // no storage, so the buffer must have the same lifetime as the source
398 // parameter owned by the caller.
399 //
400 // THE CALLER MUST NOT ADD TO THE |utf8_buffer| AFTER THIS CALL. Members of
401 // |source| will point into this buffer, which could be invalidated if
402 // additional data is added and the CanonOutput resizes its buffer.
403 //
404 // Returns true on success. False means that the input was not valid UTF-16,
405 // although we will have still done the override with "invalid characters" in
406 // place of errors.
407 bool SetupUTF16OverrideComponents(const char* base,
408                                   const Replacements<char16_t>& repl,
409                                   CanonOutput* utf8_buffer,
410                                   URLComponentSource<char>* source,
411                                   Parsed* parsed);
412
413 // Implemented in url_canon_path.cc, these are required by the relative URL
414 // resolver as well, so we declare them here.
415 bool CanonicalizePartialPathInternal(const char* spec,
416                                      const Component& path,
417                                      size_t path_begin_in_output,
418                                      CanonOutput* output);
419 bool CanonicalizePartialPathInternal(const char16_t* spec,
420                                      const Component& path,
421                                      size_t path_begin_in_output,
422                                      CanonOutput* output);
423
424 // Find the position of a bona fide Windows drive letter in the given path. If
425 // no leading drive letter is found, -1 is returned. This function correctly
426 // treats /c:/foo and /./c:/foo as having drive letters, and /def/c:/foo as not
427 // having a drive letter.
428 //
429 // Exported for tests.
430 COMPONENT_EXPORT(URL)
431 int FindWindowsDriveLetter(const char* spec, int begin, int end);
432 COMPONENT_EXPORT(URL)
433 int FindWindowsDriveLetter(const char16_t* spec, int begin, int end);
434
435 #ifndef WIN32
436
437 // Implementations of Windows' int-to-string conversions
438 COMPONENT_EXPORT(URL)
439 int _itoa_s(int value, char* buffer, size_t size_in_chars, int radix);
440 COMPONENT_EXPORT(URL)
441 int _itow_s(int value, char16_t* buffer, size_t size_in_chars, int radix);
442
443 // Secure template overloads for these functions
444 template <size_t N>
445 inline int _itoa_s(int value, char (&buffer)[N], int radix) {
446   return _itoa_s(value, buffer, N, radix);
447 }
448
449 template <size_t N>
450 inline int _itow_s(int value, char16_t (&buffer)[N], int radix) {
451   return _itow_s(value, buffer, N, radix);
452 }
453
454 // _strtoui64 and strtoull behave the same
455 inline unsigned long long _strtoui64(const char* nptr,
456                                      char** endptr,
457                                      int base) {
458   return strtoull(nptr, endptr, base);
459 }
460
461 #endif  // WIN32
462
463 // The threshold we set to consider SIMD processing, in bytes; there is
464 // no deep theory here, it's just set empirically to a value that seems
465 // to be good. (We don't really know why there's a slowdown for zero;
466 // but a guess would be that there's no need in going into a complex loop
467 // with a lot of setup for a five-byte string.)
468 static constexpr int kMinimumLengthForSIMD = 50;
469
470 }  // namespace url
471
472 #endif  // URL_URL_CANON_INTERNAL_H_