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