cc: Update draw properties on external root scroll
[chromium-blink-merge.git] / url / url_canon_ip.cc
blob6ed8ba7203e9cc3c6a52e5286f25ae0a925d3658
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.
5 #include "url/url_canon_ip.h"
7 #include <stdlib.h>
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "url/url_canon_internal.h"
13 namespace url {
15 namespace {
17 // Converts one of the character types that represent a numerical base to the
18 // corresponding base.
19 int BaseForType(SharedCharTypes type) {
20 switch (type) {
21 case CHAR_HEX:
22 return 16;
23 case CHAR_DEC:
24 return 10;
25 case CHAR_OCT:
26 return 8;
27 default:
28 return 0;
32 template<typename CHAR, typename UCHAR>
33 bool DoFindIPv4Components(const CHAR* spec,
34 const Component& host,
35 Component components[4]) {
36 if (!host.is_nonempty())
37 return false;
39 int cur_component = 0; // Index of the component we're working on.
40 int cur_component_begin = host.begin; // Start of the current component.
41 int end = host.end();
42 for (int i = host.begin; /* nothing */; i++) {
43 if (i >= end || spec[i] == '.') {
44 // Found the end of the current component.
45 int component_len = i - cur_component_begin;
46 components[cur_component] = Component(cur_component_begin, component_len);
48 // The next component starts after the dot.
49 cur_component_begin = i + 1;
50 cur_component++;
52 // Don't allow empty components (two dots in a row), except we may
53 // allow an empty component at the end (this would indicate that the
54 // input ends in a dot). We also want to error if the component is
55 // empty and it's the only component (cur_component == 1).
56 if (component_len == 0 && (i < end || cur_component == 1))
57 return false;
59 if (i >= end)
60 break; // End of the input.
62 if (cur_component == 4) {
63 // Anything else after the 4th component is an error unless it is a
64 // dot that would otherwise be treated as the end of input.
65 if (spec[i] == '.' && i + 1 == end)
66 break;
67 return false;
69 } else if (static_cast<UCHAR>(spec[i]) >= 0x80 ||
70 !IsIPv4Char(static_cast<unsigned char>(spec[i]))) {
71 // Invalid character for an IPv4 address.
72 return false;
76 // Fill in any unused components.
77 while (cur_component < 4)
78 components[cur_component++] = Component();
79 return true;
82 // Converts an IPv4 component to a 32-bit number, while checking for overflow.
84 // Possible return values:
85 // - IPV4 - The number was valid, and did not overflow.
86 // - BROKEN - The input was numeric, but too large for a 32-bit field.
87 // - NEUTRAL - Input was not numeric.
89 // The input is assumed to be ASCII. FindIPv4Components should have stripped
90 // out any input that is greater than 7 bits. The components are assumed
91 // to be non-empty.
92 template<typename CHAR>
93 CanonHostInfo::Family IPv4ComponentToNumber(const CHAR* spec,
94 const Component& component,
95 uint32* number) {
96 // Figure out the base
97 SharedCharTypes base;
98 int base_prefix_len = 0; // Size of the prefix for this base.
99 if (spec[component.begin] == '0') {
100 // Either hex or dec, or a standalone zero.
101 if (component.len == 1) {
102 base = CHAR_DEC;
103 } else if (spec[component.begin + 1] == 'X' ||
104 spec[component.begin + 1] == 'x') {
105 base = CHAR_HEX;
106 base_prefix_len = 2;
107 } else {
108 base = CHAR_OCT;
109 base_prefix_len = 1;
111 } else {
112 base = CHAR_DEC;
115 // Extend the prefix to consume all leading zeros.
116 while (base_prefix_len < component.len &&
117 spec[component.begin + base_prefix_len] == '0')
118 base_prefix_len++;
120 // Put the component, minus any base prefix, into a NULL-terminated buffer so
121 // we can call the standard library. Because leading zeros have already been
122 // discarded, filling the entire buffer is guaranteed to trigger the 32-bit
123 // overflow check.
124 const int kMaxComponentLen = 16;
125 char buf[kMaxComponentLen + 1]; // digits + '\0'
126 int dest_i = 0;
127 for (int i = component.begin + base_prefix_len; i < component.end(); i++) {
128 // We know the input is 7-bit, so convert to narrow (if this is the wide
129 // version of the template) by casting.
130 char input = static_cast<char>(spec[i]);
132 // Validate that this character is OK for the given base.
133 if (!IsCharOfType(input, base))
134 return CanonHostInfo::NEUTRAL;
136 // Fill the buffer, if there's space remaining. This check allows us to
137 // verify that all characters are numeric, even those that don't fit.
138 if (dest_i < kMaxComponentLen)
139 buf[dest_i++] = input;
142 buf[dest_i] = '\0';
144 // Use the 64-bit strtoi so we get a big number (no hex, decimal, or octal
145 // number can overflow a 64-bit number in <= 16 characters).
146 uint64 num = _strtoui64(buf, NULL, BaseForType(base));
148 // Check for 32-bit overflow.
149 if (num > kuint32max)
150 return CanonHostInfo::BROKEN;
152 // No overflow. Success!
153 *number = static_cast<uint32>(num);
154 return CanonHostInfo::IPV4;
157 // See declaration of IPv4AddressToNumber for documentation.
158 template<typename CHAR>
159 CanonHostInfo::Family DoIPv4AddressToNumber(const CHAR* spec,
160 const Component& host,
161 unsigned char address[4],
162 int* num_ipv4_components) {
163 // The identified components. Not all may exist.
164 Component components[4];
165 if (!FindIPv4Components(spec, host, components))
166 return CanonHostInfo::NEUTRAL;
168 // Convert existing components to digits. Values up to
169 // |existing_components| will be valid.
170 uint32 component_values[4];
171 int existing_components = 0;
173 // Set to true if one or more components are BROKEN. BROKEN is only
174 // returned if all components are IPV4 or BROKEN, so, for example,
175 // 12345678912345.de returns NEUTRAL rather than broken.
176 bool broken = false;
177 for (int i = 0; i < 4; i++) {
178 if (components[i].len <= 0)
179 continue;
180 CanonHostInfo::Family family = IPv4ComponentToNumber(
181 spec, components[i], &component_values[existing_components]);
183 if (family == CanonHostInfo::BROKEN) {
184 broken = true;
185 } else if (family != CanonHostInfo::IPV4) {
186 // Stop if we hit a non-BROKEN invalid non-empty component.
187 return family;
190 existing_components++;
193 if (broken)
194 return CanonHostInfo::BROKEN;
196 // Use that sequence of numbers to fill out the 4-component IP address.
198 // First, process all components but the last, while making sure each fits
199 // within an 8-bit field.
200 for (int i = 0; i < existing_components - 1; i++) {
201 if (component_values[i] > kuint8max)
202 return CanonHostInfo::BROKEN;
203 address[i] = static_cast<unsigned char>(component_values[i]);
206 // Next, consume the last component to fill in the remaining bytes.
207 uint32 last_value = component_values[existing_components - 1];
208 for (int i = 3; i >= existing_components - 1; i--) {
209 address[i] = static_cast<unsigned char>(last_value);
210 last_value >>= 8;
213 // If the last component has residual bits, report overflow.
214 if (last_value != 0)
215 return CanonHostInfo::BROKEN;
217 // Tell the caller how many components we saw.
218 *num_ipv4_components = existing_components;
220 // Success!
221 return CanonHostInfo::IPV4;
224 // Return true if we've made a final IPV4/BROKEN decision, false if the result
225 // is NEUTRAL, and we could use a second opinion.
226 template<typename CHAR, typename UCHAR>
227 bool DoCanonicalizeIPv4Address(const CHAR* spec,
228 const Component& host,
229 CanonOutput* output,
230 CanonHostInfo* host_info) {
231 host_info->family = IPv4AddressToNumber(
232 spec, host, host_info->address, &host_info->num_ipv4_components);
234 switch (host_info->family) {
235 case CanonHostInfo::IPV4:
236 // Definitely an IPv4 address.
237 host_info->out_host.begin = output->length();
238 AppendIPv4Address(host_info->address, output);
239 host_info->out_host.len = output->length() - host_info->out_host.begin;
240 return true;
241 case CanonHostInfo::BROKEN:
242 // Definitely broken.
243 return true;
244 default:
245 // Could be IPv6 or a hostname.
246 return false;
250 // Helper class that describes the main components of an IPv6 input string.
251 // See the following examples to understand how it breaks up an input string:
253 // [Example 1]: input = "[::aa:bb]"
254 // ==> num_hex_components = 2
255 // ==> hex_components[0] = Component(3,2) "aa"
256 // ==> hex_components[1] = Component(6,2) "bb"
257 // ==> index_of_contraction = 0
258 // ==> ipv4_component = Component(0, -1)
260 // [Example 2]: input = "[1:2::3:4:5]"
261 // ==> num_hex_components = 5
262 // ==> hex_components[0] = Component(1,1) "1"
263 // ==> hex_components[1] = Component(3,1) "2"
264 // ==> hex_components[2] = Component(6,1) "3"
265 // ==> hex_components[3] = Component(8,1) "4"
266 // ==> hex_components[4] = Component(10,1) "5"
267 // ==> index_of_contraction = 2
268 // ==> ipv4_component = Component(0, -1)
270 // [Example 3]: input = "[::ffff:192.168.0.1]"
271 // ==> num_hex_components = 1
272 // ==> hex_components[0] = Component(3,4) "ffff"
273 // ==> index_of_contraction = 0
274 // ==> ipv4_component = Component(8, 11) "192.168.0.1"
276 // [Example 4]: input = "[1::]"
277 // ==> num_hex_components = 1
278 // ==> hex_components[0] = Component(1,1) "1"
279 // ==> index_of_contraction = 1
280 // ==> ipv4_component = Component(0, -1)
282 // [Example 5]: input = "[::192.168.0.1]"
283 // ==> num_hex_components = 0
284 // ==> index_of_contraction = 0
285 // ==> ipv4_component = Component(8, 11) "192.168.0.1"
287 struct IPv6Parsed {
288 // Zero-out the parse information.
289 void reset() {
290 num_hex_components = 0;
291 index_of_contraction = -1;
292 ipv4_component.reset();
295 // There can be up to 8 hex components (colon separated) in the literal.
296 Component hex_components[8];
298 // The count of hex components present. Ranges from [0,8].
299 int num_hex_components;
301 // The index of the hex component that the "::" contraction precedes, or
302 // -1 if there is no contraction.
303 int index_of_contraction;
305 // The range of characters which are an IPv4 literal.
306 Component ipv4_component;
309 // Parse the IPv6 input string. If parsing succeeded returns true and fills
310 // |parsed| with the information. If parsing failed (because the input is
311 // invalid) returns false.
312 template<typename CHAR, typename UCHAR>
313 bool DoParseIPv6(const CHAR* spec, const Component& host, IPv6Parsed* parsed) {
314 // Zero-out the info.
315 parsed->reset();
317 if (!host.is_nonempty())
318 return false;
320 // The index for start and end of address range (no brackets).
321 int begin = host.begin;
322 int end = host.end();
324 int cur_component_begin = begin; // Start of the current component.
326 // Scan through the input, searching for hex components, "::" contractions,
327 // and IPv4 components.
328 for (int i = begin; /* i <= end */; i++) {
329 bool is_colon = spec[i] == ':';
330 bool is_contraction = is_colon && i < end - 1 && spec[i + 1] == ':';
332 // We reached the end of the current component if we encounter a colon
333 // (separator between hex components, or start of a contraction), or end of
334 // input.
335 if (is_colon || i == end) {
336 int component_len = i - cur_component_begin;
338 // A component should not have more than 4 hex digits.
339 if (component_len > 4)
340 return false;
342 // Don't allow empty components.
343 if (component_len == 0) {
344 // The exception is when contractions appear at beginning of the
345 // input or at the end of the input.
346 if (!((is_contraction && i == begin) || (i == end &&
347 parsed->index_of_contraction == parsed->num_hex_components)))
348 return false;
351 // Add the hex component we just found to running list.
352 if (component_len > 0) {
353 // Can't have more than 8 components!
354 if (parsed->num_hex_components >= 8)
355 return false;
357 parsed->hex_components[parsed->num_hex_components++] =
358 Component(cur_component_begin, component_len);
362 if (i == end)
363 break; // Reached the end of the input, DONE.
365 // We found a "::" contraction.
366 if (is_contraction) {
367 // There can be at most one contraction in the literal.
368 if (parsed->index_of_contraction != -1)
369 return false;
370 parsed->index_of_contraction = parsed->num_hex_components;
371 ++i; // Consume the colon we peeked.
374 if (is_colon) {
375 // Colons are separators between components, keep track of where the
376 // current component started (after this colon).
377 cur_component_begin = i + 1;
378 } else {
379 if (static_cast<UCHAR>(spec[i]) >= 0x80)
380 return false; // Not ASCII.
382 if (!IsHexChar(static_cast<unsigned char>(spec[i]))) {
383 // Regular components are hex numbers. It is also possible for
384 // a component to be an IPv4 address in dotted form.
385 if (IsIPv4Char(static_cast<unsigned char>(spec[i]))) {
386 // Since IPv4 address can only appear at the end, assume the rest
387 // of the string is an IPv4 address. (We will parse this separately
388 // later).
389 parsed->ipv4_component =
390 Component(cur_component_begin, end - cur_component_begin);
391 break;
392 } else {
393 // The character was neither a hex digit, nor an IPv4 character.
394 return false;
400 return true;
403 // Verifies the parsed IPv6 information, checking that the various components
404 // add up to the right number of bits (hex components are 16 bits, while
405 // embedded IPv4 formats are 32 bits, and contractions are placeholdes for
406 // 16 or more bits). Returns true if sizes match up, false otherwise. On
407 // success writes the length of the contraction (if any) to
408 // |out_num_bytes_of_contraction|.
409 bool CheckIPv6ComponentsSize(const IPv6Parsed& parsed,
410 int* out_num_bytes_of_contraction) {
411 // Each group of four hex digits contributes 16 bits.
412 int num_bytes_without_contraction = parsed.num_hex_components * 2;
414 // If an IPv4 address was embedded at the end, it contributes 32 bits.
415 if (parsed.ipv4_component.is_valid())
416 num_bytes_without_contraction += 4;
418 // If there was a "::" contraction, its size is going to be:
419 // MAX([16bits], [128bits] - num_bytes_without_contraction).
420 int num_bytes_of_contraction = 0;
421 if (parsed.index_of_contraction != -1) {
422 num_bytes_of_contraction = 16 - num_bytes_without_contraction;
423 if (num_bytes_of_contraction < 2)
424 num_bytes_of_contraction = 2;
427 // Check that the numbers add up.
428 if (num_bytes_without_contraction + num_bytes_of_contraction != 16)
429 return false;
431 *out_num_bytes_of_contraction = num_bytes_of_contraction;
432 return true;
435 // Converts a hex comonent into a number. This cannot fail since the caller has
436 // already verified that each character in the string was a hex digit, and
437 // that there were no more than 4 characters.
438 template<typename CHAR>
439 uint16 IPv6HexComponentToNumber(const CHAR* spec, const Component& component) {
440 DCHECK(component.len <= 4);
442 // Copy the hex string into a C-string.
443 char buf[5];
444 for (int i = 0; i < component.len; ++i)
445 buf[i] = static_cast<char>(spec[component.begin + i]);
446 buf[component.len] = '\0';
448 // Convert it to a number (overflow is not possible, since with 4 hex
449 // characters we can at most have a 16 bit number).
450 return static_cast<uint16>(_strtoui64(buf, NULL, 16));
453 // Converts an IPv6 address to a 128-bit number (network byte order), returning
454 // true on success. False means that the input was not a valid IPv6 address.
455 template<typename CHAR, typename UCHAR>
456 bool DoIPv6AddressToNumber(const CHAR* spec,
457 const Component& host,
458 unsigned char address[16]) {
459 // Make sure the component is bounded by '[' and ']'.
460 int end = host.end();
461 if (!host.is_nonempty() || spec[host.begin] != '[' || spec[end - 1] != ']')
462 return false;
464 // Exclude the square brackets.
465 Component ipv6_comp(host.begin + 1, host.len - 2);
467 // Parse the IPv6 address -- identify where all the colon separated hex
468 // components are, the "::" contraction, and the embedded IPv4 address.
469 IPv6Parsed ipv6_parsed;
470 if (!DoParseIPv6<CHAR, UCHAR>(spec, ipv6_comp, &ipv6_parsed))
471 return false;
473 // Do some basic size checks to make sure that the address doesn't
474 // specify more than 128 bits or fewer than 128 bits. This also resolves
475 // how may zero bytes the "::" contraction represents.
476 int num_bytes_of_contraction;
477 if (!CheckIPv6ComponentsSize(ipv6_parsed, &num_bytes_of_contraction))
478 return false;
480 int cur_index_in_address = 0;
482 // Loop through each hex components, and contraction in order.
483 for (int i = 0; i <= ipv6_parsed.num_hex_components; ++i) {
484 // Append the contraction if it appears before this component.
485 if (i == ipv6_parsed.index_of_contraction) {
486 for (int j = 0; j < num_bytes_of_contraction; ++j)
487 address[cur_index_in_address++] = 0;
489 // Append the hex component's value.
490 if (i != ipv6_parsed.num_hex_components) {
491 // Get the 16-bit value for this hex component.
492 uint16 number = IPv6HexComponentToNumber<CHAR>(
493 spec, ipv6_parsed.hex_components[i]);
494 // Append to |address|, in network byte order.
495 address[cur_index_in_address++] = (number & 0xFF00) >> 8;
496 address[cur_index_in_address++] = (number & 0x00FF);
500 // If there was an IPv4 section, convert it into a 32-bit number and append
501 // it to |address|.
502 if (ipv6_parsed.ipv4_component.is_valid()) {
503 // Append the 32-bit number to |address|.
504 int ignored_num_ipv4_components;
505 if (CanonHostInfo::IPV4 !=
506 IPv4AddressToNumber(spec,
507 ipv6_parsed.ipv4_component,
508 &address[cur_index_in_address],
509 &ignored_num_ipv4_components))
510 return false;
513 return true;
516 // Searches for the longest sequence of zeros in |address|, and writes the
517 // range into |contraction_range|. The run of zeros must be at least 16 bits,
518 // and if there is a tie the first is chosen.
519 void ChooseIPv6ContractionRange(const unsigned char address[16],
520 Component* contraction_range) {
521 // The longest run of zeros in |address| seen so far.
522 Component max_range;
524 // The current run of zeros in |address| being iterated over.
525 Component cur_range;
527 for (int i = 0; i < 16; i += 2) {
528 // Test for 16 bits worth of zero.
529 bool is_zero = (address[i] == 0 && address[i + 1] == 0);
531 if (is_zero) {
532 // Add the zero to the current range (or start a new one).
533 if (!cur_range.is_valid())
534 cur_range = Component(i, 0);
535 cur_range.len += 2;
538 if (!is_zero || i == 14) {
539 // Just completed a run of zeros. If the run is greater than 16 bits,
540 // it is a candidate for the contraction.
541 if (cur_range.len > 2 && cur_range.len > max_range.len) {
542 max_range = cur_range;
544 cur_range.reset();
547 *contraction_range = max_range;
550 // Return true if we've made a final IPV6/BROKEN decision, false if the result
551 // is NEUTRAL, and we could use a second opinion.
552 template<typename CHAR, typename UCHAR>
553 bool DoCanonicalizeIPv6Address(const CHAR* spec,
554 const Component& host,
555 CanonOutput* output,
556 CanonHostInfo* host_info) {
557 // Turn the IP address into a 128 bit number.
558 if (!IPv6AddressToNumber(spec, host, host_info->address)) {
559 // If it's not an IPv6 address, scan for characters that should *only*
560 // exist in an IPv6 address.
561 for (int i = host.begin; i < host.end(); i++) {
562 switch (spec[i]) {
563 case '[':
564 case ']':
565 case ':':
566 host_info->family = CanonHostInfo::BROKEN;
567 return true;
571 // No invalid characters. Could still be IPv4 or a hostname.
572 host_info->family = CanonHostInfo::NEUTRAL;
573 return false;
576 host_info->out_host.begin = output->length();
577 output->push_back('[');
578 AppendIPv6Address(host_info->address, output);
579 output->push_back(']');
580 host_info->out_host.len = output->length() - host_info->out_host.begin;
582 host_info->family = CanonHostInfo::IPV6;
583 return true;
586 } // namespace
588 void AppendIPv4Address(const unsigned char address[4], CanonOutput* output) {
589 for (int i = 0; i < 4; i++) {
590 char str[16];
591 _itoa_s(address[i], str, 10);
593 for (int ch = 0; str[ch] != 0; ch++)
594 output->push_back(str[ch]);
596 if (i != 3)
597 output->push_back('.');
601 void AppendIPv6Address(const unsigned char address[16], CanonOutput* output) {
602 // We will output the address according to the rules in:
603 // http://tools.ietf.org/html/draft-kawamura-ipv6-text-representation-01#section-4
605 // Start by finding where to place the "::" contraction (if any).
606 Component contraction_range;
607 ChooseIPv6ContractionRange(address, &contraction_range);
609 for (int i = 0; i <= 14;) {
610 // We check 2 bytes at a time, from bytes (0, 1) to (14, 15), inclusive.
611 DCHECK(i % 2 == 0);
612 if (i == contraction_range.begin && contraction_range.len > 0) {
613 // Jump over the contraction.
614 if (i == 0)
615 output->push_back(':');
616 output->push_back(':');
617 i = contraction_range.end();
618 } else {
619 // Consume the next 16 bits from |address|.
620 int x = address[i] << 8 | address[i + 1];
622 i += 2;
624 // Stringify the 16 bit number (at most requires 4 hex digits).
625 char str[5];
626 _itoa_s(x, str, 16);
627 for (int ch = 0; str[ch] != 0; ++ch)
628 output->push_back(str[ch]);
630 // Put a colon after each number, except the last.
631 if (i < 16)
632 output->push_back(':');
637 bool FindIPv4Components(const char* spec,
638 const Component& host,
639 Component components[4]) {
640 return DoFindIPv4Components<char, unsigned char>(spec, host, components);
643 bool FindIPv4Components(const base::char16* spec,
644 const Component& host,
645 Component components[4]) {
646 return DoFindIPv4Components<base::char16, base::char16>(
647 spec, host, components);
650 void CanonicalizeIPAddress(const char* spec,
651 const Component& host,
652 CanonOutput* output,
653 CanonHostInfo* host_info) {
654 if (DoCanonicalizeIPv4Address<char, unsigned char>(
655 spec, host, output, host_info))
656 return;
657 if (DoCanonicalizeIPv6Address<char, unsigned char>(
658 spec, host, output, host_info))
659 return;
662 void CanonicalizeIPAddress(const base::char16* spec,
663 const Component& host,
664 CanonOutput* output,
665 CanonHostInfo* host_info) {
666 if (DoCanonicalizeIPv4Address<base::char16, base::char16>(
667 spec, host, output, host_info))
668 return;
669 if (DoCanonicalizeIPv6Address<base::char16, base::char16>(
670 spec, host, output, host_info))
671 return;
674 CanonHostInfo::Family IPv4AddressToNumber(const char* spec,
675 const Component& host,
676 unsigned char address[4],
677 int* num_ipv4_components) {
678 return DoIPv4AddressToNumber<char>(spec, host, address, num_ipv4_components);
681 CanonHostInfo::Family IPv4AddressToNumber(const base::char16* spec,
682 const Component& host,
683 unsigned char address[4],
684 int* num_ipv4_components) {
685 return DoIPv4AddressToNumber<base::char16>(
686 spec, host, address, num_ipv4_components);
689 bool IPv6AddressToNumber(const char* spec,
690 const Component& host,
691 unsigned char address[16]) {
692 return DoIPv6AddressToNumber<char, unsigned char>(spec, host, address);
695 bool IPv6AddressToNumber(const base::char16* spec,
696 const Component& host,
697 unsigned char address[16]) {
698 return DoIPv6AddressToNumber<base::char16, base::char16>(spec, host, address);
701 } // namespace url