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