Revert of Fix lsan failure with ManifestParserTest.* (patchset #1 id:1 of https:...
[chromium-blink-merge.git] / url / url_canon_ip.cc
blob45f95de0d474bf16a2a64cb928ba0c8517b0b1a3
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 // Work around a gcc 4.9 bug. crbug.com/392872
208 #if ((__GNUC__ == 4 && __GNUC_MINOR__ >= 9) || __GNUC__ > 4)
209 #pragma GCC diagnostic push
210 #pragma GCC diagnostic ignored "-Warray-bounds"
211 #endif
212 uint32 last_value = component_values[existing_components - 1];
213 #if ((__GNUC__ == 4 && __GNUC_MINOR__ >= 9) || __GNUC__ > 4)
214 #pragma GCC diagnostic pop
215 #endif
216 for (int i = 3; i >= existing_components - 1; i--) {
217 address[i] = static_cast<unsigned char>(last_value);
218 last_value >>= 8;
221 // If the last component has residual bits, report overflow.
222 if (last_value != 0)
223 return CanonHostInfo::BROKEN;
225 // Tell the caller how many components we saw.
226 *num_ipv4_components = existing_components;
228 // Success!
229 return CanonHostInfo::IPV4;
232 // Return true if we've made a final IPV4/BROKEN decision, false if the result
233 // is NEUTRAL, and we could use a second opinion.
234 template<typename CHAR, typename UCHAR>
235 bool DoCanonicalizeIPv4Address(const CHAR* spec,
236 const Component& host,
237 CanonOutput* output,
238 CanonHostInfo* host_info) {
239 host_info->family = IPv4AddressToNumber(
240 spec, host, host_info->address, &host_info->num_ipv4_components);
242 switch (host_info->family) {
243 case CanonHostInfo::IPV4:
244 // Definitely an IPv4 address.
245 host_info->out_host.begin = output->length();
246 AppendIPv4Address(host_info->address, output);
247 host_info->out_host.len = output->length() - host_info->out_host.begin;
248 return true;
249 case CanonHostInfo::BROKEN:
250 // Definitely broken.
251 return true;
252 default:
253 // Could be IPv6 or a hostname.
254 return false;
258 // Helper class that describes the main components of an IPv6 input string.
259 // See the following examples to understand how it breaks up an input string:
261 // [Example 1]: input = "[::aa:bb]"
262 // ==> num_hex_components = 2
263 // ==> hex_components[0] = Component(3,2) "aa"
264 // ==> hex_components[1] = Component(6,2) "bb"
265 // ==> index_of_contraction = 0
266 // ==> ipv4_component = Component(0, -1)
268 // [Example 2]: input = "[1:2::3:4:5]"
269 // ==> num_hex_components = 5
270 // ==> hex_components[0] = Component(1,1) "1"
271 // ==> hex_components[1] = Component(3,1) "2"
272 // ==> hex_components[2] = Component(6,1) "3"
273 // ==> hex_components[3] = Component(8,1) "4"
274 // ==> hex_components[4] = Component(10,1) "5"
275 // ==> index_of_contraction = 2
276 // ==> ipv4_component = Component(0, -1)
278 // [Example 3]: input = "[::ffff:192.168.0.1]"
279 // ==> num_hex_components = 1
280 // ==> hex_components[0] = Component(3,4) "ffff"
281 // ==> index_of_contraction = 0
282 // ==> ipv4_component = Component(8, 11) "192.168.0.1"
284 // [Example 4]: input = "[1::]"
285 // ==> num_hex_components = 1
286 // ==> hex_components[0] = Component(1,1) "1"
287 // ==> index_of_contraction = 1
288 // ==> ipv4_component = Component(0, -1)
290 // [Example 5]: input = "[::192.168.0.1]"
291 // ==> num_hex_components = 0
292 // ==> index_of_contraction = 0
293 // ==> ipv4_component = Component(8, 11) "192.168.0.1"
295 struct IPv6Parsed {
296 // Zero-out the parse information.
297 void reset() {
298 num_hex_components = 0;
299 index_of_contraction = -1;
300 ipv4_component.reset();
303 // There can be up to 8 hex components (colon separated) in the literal.
304 Component hex_components[8];
306 // The count of hex components present. Ranges from [0,8].
307 int num_hex_components;
309 // The index of the hex component that the "::" contraction precedes, or
310 // -1 if there is no contraction.
311 int index_of_contraction;
313 // The range of characters which are an IPv4 literal.
314 Component ipv4_component;
317 // Parse the IPv6 input string. If parsing succeeded returns true and fills
318 // |parsed| with the information. If parsing failed (because the input is
319 // invalid) returns false.
320 template<typename CHAR, typename UCHAR>
321 bool DoParseIPv6(const CHAR* spec, const Component& host, IPv6Parsed* parsed) {
322 // Zero-out the info.
323 parsed->reset();
325 if (!host.is_nonempty())
326 return false;
328 // The index for start and end of address range (no brackets).
329 int begin = host.begin;
330 int end = host.end();
332 int cur_component_begin = begin; // Start of the current component.
334 // Scan through the input, searching for hex components, "::" contractions,
335 // and IPv4 components.
336 for (int i = begin; /* i <= end */; i++) {
337 bool is_colon = spec[i] == ':';
338 bool is_contraction = is_colon && i < end - 1 && spec[i + 1] == ':';
340 // We reached the end of the current component if we encounter a colon
341 // (separator between hex components, or start of a contraction), or end of
342 // input.
343 if (is_colon || i == end) {
344 int component_len = i - cur_component_begin;
346 // A component should not have more than 4 hex digits.
347 if (component_len > 4)
348 return false;
350 // Don't allow empty components.
351 if (component_len == 0) {
352 // The exception is when contractions appear at beginning of the
353 // input or at the end of the input.
354 if (!((is_contraction && i == begin) || (i == end &&
355 parsed->index_of_contraction == parsed->num_hex_components)))
356 return false;
359 // Add the hex component we just found to running list.
360 if (component_len > 0) {
361 // Can't have more than 8 components!
362 if (parsed->num_hex_components >= 8)
363 return false;
365 parsed->hex_components[parsed->num_hex_components++] =
366 Component(cur_component_begin, component_len);
370 if (i == end)
371 break; // Reached the end of the input, DONE.
373 // We found a "::" contraction.
374 if (is_contraction) {
375 // There can be at most one contraction in the literal.
376 if (parsed->index_of_contraction != -1)
377 return false;
378 parsed->index_of_contraction = parsed->num_hex_components;
379 ++i; // Consume the colon we peeked.
382 if (is_colon) {
383 // Colons are separators between components, keep track of where the
384 // current component started (after this colon).
385 cur_component_begin = i + 1;
386 } else {
387 if (static_cast<UCHAR>(spec[i]) >= 0x80)
388 return false; // Not ASCII.
390 if (!IsHexChar(static_cast<unsigned char>(spec[i]))) {
391 // Regular components are hex numbers. It is also possible for
392 // a component to be an IPv4 address in dotted form.
393 if (IsIPv4Char(static_cast<unsigned char>(spec[i]))) {
394 // Since IPv4 address can only appear at the end, assume the rest
395 // of the string is an IPv4 address. (We will parse this separately
396 // later).
397 parsed->ipv4_component =
398 Component(cur_component_begin, end - cur_component_begin);
399 break;
400 } else {
401 // The character was neither a hex digit, nor an IPv4 character.
402 return false;
408 return true;
411 // Verifies the parsed IPv6 information, checking that the various components
412 // add up to the right number of bits (hex components are 16 bits, while
413 // embedded IPv4 formats are 32 bits, and contractions are placeholdes for
414 // 16 or more bits). Returns true if sizes match up, false otherwise. On
415 // success writes the length of the contraction (if any) to
416 // |out_num_bytes_of_contraction|.
417 bool CheckIPv6ComponentsSize(const IPv6Parsed& parsed,
418 int* out_num_bytes_of_contraction) {
419 // Each group of four hex digits contributes 16 bits.
420 int num_bytes_without_contraction = parsed.num_hex_components * 2;
422 // If an IPv4 address was embedded at the end, it contributes 32 bits.
423 if (parsed.ipv4_component.is_valid())
424 num_bytes_without_contraction += 4;
426 // If there was a "::" contraction, its size is going to be:
427 // MAX([16bits], [128bits] - num_bytes_without_contraction).
428 int num_bytes_of_contraction = 0;
429 if (parsed.index_of_contraction != -1) {
430 num_bytes_of_contraction = 16 - num_bytes_without_contraction;
431 if (num_bytes_of_contraction < 2)
432 num_bytes_of_contraction = 2;
435 // Check that the numbers add up.
436 if (num_bytes_without_contraction + num_bytes_of_contraction != 16)
437 return false;
439 *out_num_bytes_of_contraction = num_bytes_of_contraction;
440 return true;
443 // Converts a hex comonent into a number. This cannot fail since the caller has
444 // already verified that each character in the string was a hex digit, and
445 // that there were no more than 4 characters.
446 template<typename CHAR>
447 uint16 IPv6HexComponentToNumber(const CHAR* spec, const Component& component) {
448 DCHECK(component.len <= 4);
450 // Copy the hex string into a C-string.
451 char buf[5];
452 for (int i = 0; i < component.len; ++i)
453 buf[i] = static_cast<char>(spec[component.begin + i]);
454 buf[component.len] = '\0';
456 // Convert it to a number (overflow is not possible, since with 4 hex
457 // characters we can at most have a 16 bit number).
458 return static_cast<uint16>(_strtoui64(buf, NULL, 16));
461 // Converts an IPv6 address to a 128-bit number (network byte order), returning
462 // true on success. False means that the input was not a valid IPv6 address.
463 template<typename CHAR, typename UCHAR>
464 bool DoIPv6AddressToNumber(const CHAR* spec,
465 const Component& host,
466 unsigned char address[16]) {
467 // Make sure the component is bounded by '[' and ']'.
468 int end = host.end();
469 if (!host.is_nonempty() || spec[host.begin] != '[' || spec[end - 1] != ']')
470 return false;
472 // Exclude the square brackets.
473 Component ipv6_comp(host.begin + 1, host.len - 2);
475 // Parse the IPv6 address -- identify where all the colon separated hex
476 // components are, the "::" contraction, and the embedded IPv4 address.
477 IPv6Parsed ipv6_parsed;
478 if (!DoParseIPv6<CHAR, UCHAR>(spec, ipv6_comp, &ipv6_parsed))
479 return false;
481 // Do some basic size checks to make sure that the address doesn't
482 // specify more than 128 bits or fewer than 128 bits. This also resolves
483 // how may zero bytes the "::" contraction represents.
484 int num_bytes_of_contraction;
485 if (!CheckIPv6ComponentsSize(ipv6_parsed, &num_bytes_of_contraction))
486 return false;
488 int cur_index_in_address = 0;
490 // Loop through each hex components, and contraction in order.
491 for (int i = 0; i <= ipv6_parsed.num_hex_components; ++i) {
492 // Append the contraction if it appears before this component.
493 if (i == ipv6_parsed.index_of_contraction) {
494 for (int j = 0; j < num_bytes_of_contraction; ++j)
495 address[cur_index_in_address++] = 0;
497 // Append the hex component's value.
498 if (i != ipv6_parsed.num_hex_components) {
499 // Get the 16-bit value for this hex component.
500 uint16 number = IPv6HexComponentToNumber<CHAR>(
501 spec, ipv6_parsed.hex_components[i]);
502 // Append to |address|, in network byte order.
503 address[cur_index_in_address++] = (number & 0xFF00) >> 8;
504 address[cur_index_in_address++] = (number & 0x00FF);
508 // If there was an IPv4 section, convert it into a 32-bit number and append
509 // it to |address|.
510 if (ipv6_parsed.ipv4_component.is_valid()) {
511 // Append the 32-bit number to |address|.
512 int ignored_num_ipv4_components;
513 if (CanonHostInfo::IPV4 !=
514 IPv4AddressToNumber(spec,
515 ipv6_parsed.ipv4_component,
516 &address[cur_index_in_address],
517 &ignored_num_ipv4_components))
518 return false;
521 return true;
524 // Searches for the longest sequence of zeros in |address|, and writes the
525 // range into |contraction_range|. The run of zeros must be at least 16 bits,
526 // and if there is a tie the first is chosen.
527 void ChooseIPv6ContractionRange(const unsigned char address[16],
528 Component* contraction_range) {
529 // The longest run of zeros in |address| seen so far.
530 Component max_range;
532 // The current run of zeros in |address| being iterated over.
533 Component cur_range;
535 for (int i = 0; i < 16; i += 2) {
536 // Test for 16 bits worth of zero.
537 bool is_zero = (address[i] == 0 && address[i + 1] == 0);
539 if (is_zero) {
540 // Add the zero to the current range (or start a new one).
541 if (!cur_range.is_valid())
542 cur_range = Component(i, 0);
543 cur_range.len += 2;
546 if (!is_zero || i == 14) {
547 // Just completed a run of zeros. If the run is greater than 16 bits,
548 // it is a candidate for the contraction.
549 if (cur_range.len > 2 && cur_range.len > max_range.len) {
550 max_range = cur_range;
552 cur_range.reset();
555 *contraction_range = max_range;
558 // Return true if we've made a final IPV6/BROKEN decision, false if the result
559 // is NEUTRAL, and we could use a second opinion.
560 template<typename CHAR, typename UCHAR>
561 bool DoCanonicalizeIPv6Address(const CHAR* spec,
562 const Component& host,
563 CanonOutput* output,
564 CanonHostInfo* host_info) {
565 // Turn the IP address into a 128 bit number.
566 if (!IPv6AddressToNumber(spec, host, host_info->address)) {
567 // If it's not an IPv6 address, scan for characters that should *only*
568 // exist in an IPv6 address.
569 for (int i = host.begin; i < host.end(); i++) {
570 switch (spec[i]) {
571 case '[':
572 case ']':
573 case ':':
574 host_info->family = CanonHostInfo::BROKEN;
575 return true;
579 // No invalid characters. Could still be IPv4 or a hostname.
580 host_info->family = CanonHostInfo::NEUTRAL;
581 return false;
584 host_info->out_host.begin = output->length();
585 output->push_back('[');
586 AppendIPv6Address(host_info->address, output);
587 output->push_back(']');
588 host_info->out_host.len = output->length() - host_info->out_host.begin;
590 host_info->family = CanonHostInfo::IPV6;
591 return true;
594 } // namespace
596 void AppendIPv4Address(const unsigned char address[4], CanonOutput* output) {
597 for (int i = 0; i < 4; i++) {
598 char str[16];
599 _itoa_s(address[i], str, 10);
601 for (int ch = 0; str[ch] != 0; ch++)
602 output->push_back(str[ch]);
604 if (i != 3)
605 output->push_back('.');
609 void AppendIPv6Address(const unsigned char address[16], CanonOutput* output) {
610 // We will output the address according to the rules in:
611 // http://tools.ietf.org/html/draft-kawamura-ipv6-text-representation-01#section-4
613 // Start by finding where to place the "::" contraction (if any).
614 Component contraction_range;
615 ChooseIPv6ContractionRange(address, &contraction_range);
617 for (int i = 0; i <= 14;) {
618 // We check 2 bytes at a time, from bytes (0, 1) to (14, 15), inclusive.
619 DCHECK(i % 2 == 0);
620 if (i == contraction_range.begin && contraction_range.len > 0) {
621 // Jump over the contraction.
622 if (i == 0)
623 output->push_back(':');
624 output->push_back(':');
625 i = contraction_range.end();
626 } else {
627 // Consume the next 16 bits from |address|.
628 int x = address[i] << 8 | address[i + 1];
630 i += 2;
632 // Stringify the 16 bit number (at most requires 4 hex digits).
633 char str[5];
634 _itoa_s(x, str, 16);
635 for (int ch = 0; str[ch] != 0; ++ch)
636 output->push_back(str[ch]);
638 // Put a colon after each number, except the last.
639 if (i < 16)
640 output->push_back(':');
645 bool FindIPv4Components(const char* spec,
646 const Component& host,
647 Component components[4]) {
648 return DoFindIPv4Components<char, unsigned char>(spec, host, components);
651 bool FindIPv4Components(const base::char16* spec,
652 const Component& host,
653 Component components[4]) {
654 return DoFindIPv4Components<base::char16, base::char16>(
655 spec, host, components);
658 void CanonicalizeIPAddress(const char* spec,
659 const Component& host,
660 CanonOutput* output,
661 CanonHostInfo* host_info) {
662 if (DoCanonicalizeIPv4Address<char, unsigned char>(
663 spec, host, output, host_info))
664 return;
665 if (DoCanonicalizeIPv6Address<char, unsigned char>(
666 spec, host, output, host_info))
667 return;
670 void CanonicalizeIPAddress(const base::char16* spec,
671 const Component& host,
672 CanonOutput* output,
673 CanonHostInfo* host_info) {
674 if (DoCanonicalizeIPv4Address<base::char16, base::char16>(
675 spec, host, output, host_info))
676 return;
677 if (DoCanonicalizeIPv6Address<base::char16, base::char16>(
678 spec, host, output, host_info))
679 return;
682 CanonHostInfo::Family IPv4AddressToNumber(const char* spec,
683 const Component& host,
684 unsigned char address[4],
685 int* num_ipv4_components) {
686 return DoIPv4AddressToNumber<char>(spec, host, address, num_ipv4_components);
689 CanonHostInfo::Family IPv4AddressToNumber(const base::char16* spec,
690 const Component& host,
691 unsigned char address[4],
692 int* num_ipv4_components) {
693 return DoIPv4AddressToNumber<base::char16>(
694 spec, host, address, num_ipv4_components);
697 bool IPv6AddressToNumber(const char* spec,
698 const Component& host,
699 unsigned char address[16]) {
700 return DoIPv6AddressToNumber<char, unsigned char>(spec, host, address);
703 bool IPv6AddressToNumber(const base::char16* spec,
704 const Component& host,
705 unsigned char address[16]) {
706 return DoIPv6AddressToNumber<base::char16, base::char16>(spec, host, address);
709 } // namespace url