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