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