Home | History | Annotate | Download | only in url
      1 // Copyright 2013 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "url/url_canon_ip.h"
      6 
      7 #include <stdlib.h>
      8 
      9 #include "base/basictypes.h"
     10 #include "base/logging.h"
     11 #include "url/url_canon_internal.h"
     12 
     13 namespace url {
     14 
     15 namespace {
     16 
     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;
     29   }
     30 }
     31 
     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;
     38 
     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);
     47 
     48       // The next component starts after the dot.
     49       cur_component_begin = i + 1;
     50       cur_component++;
     51 
     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;
     58 
     59       if (i >= end)
     60         break;  // End of the input.
     61 
     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;
     68       }
     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;
     73     }
     74   }
     75 
     76   // Fill in any unused components.
     77   while (cur_component < 4)
     78     components[cur_component++] = Component();
     79   return true;
     80 }
     81 
     82 // Converts an IPv4 component to a 32-bit number, while checking for overflow.
     83 //
     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.
     88 //
     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;
    110     }
    111   } else {
    112     base = CHAR_DEC;
    113   }
    114 
    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++;
    119 
    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]);
    131 
    132     // Validate that this character is OK for the given base.
    133     if (!IsCharOfType(input, base))
    134       return CanonHostInfo::NEUTRAL;
    135 
    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;
    140   }
    141 
    142   buf[dest_i] = '\0';
    143 
    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));
    147 
    148   // Check for 32-bit overflow.
    149   if (num > kuint32max)
    150     return CanonHostInfo::BROKEN;
    151 
    152   // No overflow.  Success!
    153   *number = static_cast<uint32>(num);
    154   return CanonHostInfo::IPV4;
    155 }
    156 
    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;
    167 
    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;
    172 
    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]);
    182 
    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;
    188     }
    189 
    190     existing_components++;
    191   }
    192 
    193   if (broken)
    194     return CanonHostInfo::BROKEN;
    195 
    196   // Use that sequence of numbers to fill out the 4-component IP address.
    197 
    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]);
    204   }
    205 
    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;
    219   }
    220 
    221   // If the last component has residual bits, report overflow.
    222   if (last_value != 0)
    223     return CanonHostInfo::BROKEN;
    224 
    225   // Tell the caller how many components we saw.
    226   *num_ipv4_components = existing_components;
    227 
    228   // Success!
    229   return CanonHostInfo::IPV4;
    230 }
    231 
    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);
    241 
    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;
    255   }
    256 }
    257 
    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:
    260 //
    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)
    267 //
    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)
    277 //
    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"
    283 //
    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)
    289 //
    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"
    294 //
    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();
    301   }
    302 
    303   // There can be up to 8 hex components (colon separated) in the literal.
    304   Component hex_components[8];
    305 
    306   // The count of hex components present. Ranges from [0,8].
    307   int num_hex_components;
    308 
    309   // The index of the hex component that the "::" contraction precedes, or
    310   // -1 if there is no contraction.
    311   int index_of_contraction;
    312 
    313   // The range of characters which are an IPv4 literal.
    314   Component ipv4_component;
    315 };
    316 
    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();
    324 
    325   if (!host.is_nonempty())
    326     return false;
    327 
    328   // The index for start and end of address range (no brackets).
    329   int begin = host.begin;
    330   int end = host.end();
    331 
    332   int cur_component_begin = begin;  // Start of the current component.
    333 
    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] == ':';
    339 
    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;
    345 
    346       // A component should not have more than 4 hex digits.
    347       if (component_len > 4)
    348         return false;
    349 
    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;
    357       }
    358 
    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;
    364 
    365         parsed->hex_components[parsed->num_hex_components++] =
    366             Component(cur_component_begin, component_len);
    367       }
    368     }
    369 
    370     if (i == end)
    371       break;  // Reached the end of the input, DONE.
    372 
    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.
    380     }
    381 
    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.
    389 
    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;
    403         }
    404       }
    405     }
    406   }
    407 
    408   return true;
    409 }
    410 
    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;
    421 
    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;
    425 
    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;
    433   }
    434 
    435   // Check that the numbers add up.
    436   if (num_bytes_without_contraction + num_bytes_of_contraction != 16)
    437     return false;
    438 
    439   *out_num_bytes_of_contraction = num_bytes_of_contraction;
    440   return true;
    441 }
    442 
    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);
    449 
    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';
    455 
    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));
    459 }
    460 
    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;
    471 
    472   // Exclude the square brackets.
    473   Component ipv6_comp(host.begin + 1, host.len - 2);
    474 
    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;
    480 
    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;
    487 
    488   int cur_index_in_address = 0;
    489 
    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;
    496     }
    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);
    505     }
    506   }
    507 
    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;
    519   }
    520 
    521   return true;
    522 }
    523 
    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;
    531 
    532   // The current run of zeros in |address| being iterated over.
    533   Component cur_range;
    534 
    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);
    538 
    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;
    544     }
    545 
    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;
    551       }
    552       cur_range.reset();
    553     }
    554   }
    555   *contraction_range = max_range;
    556 }
    557 
    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;
    576       }
    577     }
    578 
    579     // No invalid characters.  Could still be IPv4 or a hostname.
    580     host_info->family = CanonHostInfo::NEUTRAL;
    581     return false;
    582   }
    583 
    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;
    589 
    590   host_info->family = CanonHostInfo::IPV6;
    591   return true;
    592 }
    593 
    594 }  // namespace
    595 
    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);
    600 
    601     for (int ch = 0; str[ch] != 0; ch++)
    602       output->push_back(str[ch]);
    603 
    604     if (i != 3)
    605       output->push_back('.');
    606   }
    607 }
    608 
    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
    612 
    613   // Start by finding where to place the "::" contraction (if any).
    614   Component contraction_range;
    615   ChooseIPv6ContractionRange(address, &contraction_range);
    616 
    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];
    629 
    630       i += 2;
    631 
    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]);
    637 
    638       // Put a colon after each number, except the last.
    639       if (i < 16)
    640         output->push_back(':');
    641     }
    642   }
    643 }
    644 
    645 bool FindIPv4Components(const char* spec,
    646                         const Component& host,
    647                         Component components[4]) {
    648   return DoFindIPv4Components<char, unsigned char>(spec, host, components);
    649 }
    650 
    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);
    656 }
    657 
    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;
    668 }
    669 
    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;
    680 }
    681 
    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);
    687 }
    688 
    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);
    695 }
    696 
    697 bool IPv6AddressToNumber(const char* spec,
    698                          const Component& host,
    699                          unsigned char address[16]) {
    700   return DoIPv6AddressToNumber<char, unsigned char>(spec, host, address);
    701 }
    702 
    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);
    707 }
    708 
    709 }  // namespace url
    710