Update V8 to version 4.7.42.
[chromium-blink-merge.git] / net / base / ip_address_number.cc
blob61af0679529f7cfbb1a69488c74252978ce6ca5d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/base/ip_address_number.h"
7 #include "base/logging.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/string_piece.h"
10 #include "base/strings/string_split.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/stringprintf.h"
13 #include "url/gurl.h"
14 #include "url/url_canon_ip.h"
16 namespace net {
18 namespace {
20 bool IPNumberPrefixCheck(const IPAddressNumber& ip_number,
21 const unsigned char* ip_prefix,
22 size_t prefix_length_in_bits) {
23 // Compare all the bytes that fall entirely within the prefix.
24 int num_entire_bytes_in_prefix = prefix_length_in_bits / 8;
25 for (int i = 0; i < num_entire_bytes_in_prefix; ++i) {
26 if (ip_number[i] != ip_prefix[i])
27 return false;
30 // In case the prefix was not a multiple of 8, there will be 1 byte
31 // which is only partially masked.
32 int remaining_bits = prefix_length_in_bits % 8;
33 if (remaining_bits != 0) {
34 unsigned char mask = 0xFF << (8 - remaining_bits);
35 int i = num_entire_bytes_in_prefix;
36 if ((ip_number[i] & mask) != (ip_prefix[i] & mask))
37 return false;
39 return true;
42 } // namespace
44 // Don't compare IPv4 and IPv6 addresses (they have different range
45 // reservations). Keep separate reservation arrays for each IP type, and
46 // consolidate adjacent reserved ranges within a reservation array when
47 // possible.
48 // Sources for info:
49 // www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
50 // www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
51 // They're formatted here with the prefix as the last element. For example:
52 // 10.0.0.0/8 becomes 10,0,0,0,8 and fec0::/10 becomes 0xfe,0xc0,0,0,0...,10.
53 bool IsIPAddressReserved(const IPAddressNumber& host_addr) {
54 static const unsigned char kReservedIPv4[][5] = {
55 { 0,0,0,0,8 }, { 10,0,0,0,8 }, { 100,64,0,0,10 }, { 127,0,0,0,8 },
56 { 169,254,0,0,16 }, { 172,16,0,0,12 }, { 192,0,2,0,24 },
57 { 192,88,99,0,24 }, { 192,168,0,0,16 }, { 198,18,0,0,15 },
58 { 198,51,100,0,24 }, { 203,0,113,0,24 }, { 224,0,0,0,3 }
60 static const unsigned char kReservedIPv6[][17] = {
61 { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8 },
62 { 0x40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
63 { 0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
64 { 0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3 },
65 { 0xe0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4 },
66 { 0xf0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5 },
67 { 0xf8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6 },
68 { 0xfc,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7 },
69 { 0xfe,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9 },
70 { 0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
71 { 0xfe,0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
73 size_t array_size = 0;
74 const unsigned char* array = NULL;
75 switch (host_addr.size()) {
76 case kIPv4AddressSize:
77 array_size = arraysize(kReservedIPv4);
78 array = kReservedIPv4[0];
79 break;
80 case kIPv6AddressSize:
81 array_size = arraysize(kReservedIPv6);
82 array = kReservedIPv6[0];
83 break;
85 if (!array)
86 return false;
87 size_t width = host_addr.size() + 1;
88 for (size_t i = 0; i < array_size; ++i, array += width) {
89 if (IPNumberPrefixCheck(host_addr, array, array[width-1]))
90 return true;
92 return false;
95 std::string IPAddressToString(const uint8_t* address, size_t address_len) {
96 std::string str;
97 url::StdStringCanonOutput output(&str);
99 if (address_len == kIPv4AddressSize) {
100 url::AppendIPv4Address(address, &output);
101 } else if (address_len == kIPv6AddressSize) {
102 url::AppendIPv6Address(address, &output);
103 } else {
104 CHECK(false) << "Invalid IP address with length: " << address_len;
107 output.Complete();
108 return str;
111 std::string IPAddressToStringWithPort(const uint8_t* address,
112 size_t address_len,
113 uint16_t port) {
114 std::string address_str = IPAddressToString(address, address_len);
116 if (address_len == kIPv6AddressSize) {
117 // Need to bracket IPv6 addresses since they contain colons.
118 return base::StringPrintf("[%s]:%d", address_str.c_str(), port);
120 return base::StringPrintf("%s:%d", address_str.c_str(), port);
123 std::string IPAddressToString(const IPAddressNumber& addr) {
124 return IPAddressToString(&addr.front(), addr.size());
127 std::string IPAddressToStringWithPort(const IPAddressNumber& addr,
128 uint16_t port) {
129 return IPAddressToStringWithPort(&addr.front(), addr.size(), port);
132 std::string IPAddressToPackedString(const IPAddressNumber& addr) {
133 return std::string(reinterpret_cast<const char *>(&addr.front()),
134 addr.size());
137 bool ParseURLHostnameToNumber(const std::string& hostname,
138 IPAddressNumber* ip_number) {
139 // |hostname| is an already canoncalized hostname, conforming to RFC 3986.
140 // For an IP address, this is defined in Section 3.2.2 of RFC 3986, with
141 // the canonical form for IPv6 addresses defined in Section 4 of RFC 5952.
142 url::Component host_comp(0, hostname.size());
144 // If it has a bracket, try parsing it as an IPv6 address.
145 if (hostname[0] == '[') {
146 ip_number->resize(16); // 128 bits.
147 return url::IPv6AddressToNumber(
148 hostname.data(), host_comp, &(*ip_number)[0]);
151 // Otherwise, try IPv4.
152 ip_number->resize(4); // 32 bits.
153 int num_components;
154 url::CanonHostInfo::Family family = url::IPv4AddressToNumber(
155 hostname.data(), host_comp, &(*ip_number)[0], &num_components);
156 return family == url::CanonHostInfo::IPV4;
159 bool ParseIPLiteralToNumber(const base::StringPiece& ip_literal,
160 IPAddressNumber* ip_number) {
161 // |ip_literal| could be either a IPv4 or an IPv6 literal. If it contains
162 // a colon however, it must be an IPv6 address.
163 if (ip_literal.find(':') != base::StringPiece::npos) {
164 // GURL expects IPv6 hostnames to be surrounded with brackets.
165 std::string host_brackets = "[";
166 ip_literal.AppendToString(&host_brackets);
167 host_brackets.push_back(']');
168 url::Component host_comp(0, host_brackets.size());
170 // Try parsing the hostname as an IPv6 literal.
171 ip_number->resize(16); // 128 bits.
172 return url::IPv6AddressToNumber(host_brackets.data(), host_comp,
173 &(*ip_number)[0]);
176 // Otherwise the string is an IPv4 address.
177 ip_number->resize(4); // 32 bits.
178 url::Component host_comp(0, ip_literal.size());
179 int num_components;
180 url::CanonHostInfo::Family family = url::IPv4AddressToNumber(
181 ip_literal.data(), host_comp, &(*ip_number)[0], &num_components);
182 return family == url::CanonHostInfo::IPV4;
185 namespace {
187 const unsigned char kIPv4MappedPrefix[] =
188 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
191 IPAddressNumber ConvertIPv4NumberToIPv6Number(
192 const IPAddressNumber& ipv4_number) {
193 DCHECK(ipv4_number.size() == 4);
195 // IPv4-mapped addresses are formed by:
196 // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>.
197 IPAddressNumber ipv6_number;
198 ipv6_number.reserve(16);
199 ipv6_number.insert(ipv6_number.end(),
200 kIPv4MappedPrefix,
201 kIPv4MappedPrefix + arraysize(kIPv4MappedPrefix));
202 ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end());
203 return ipv6_number;
206 bool IsIPv4Mapped(const IPAddressNumber& address) {
207 if (address.size() != kIPv6AddressSize)
208 return false;
209 return std::equal(address.begin(),
210 address.begin() + arraysize(kIPv4MappedPrefix),
211 kIPv4MappedPrefix);
214 IPAddressNumber ConvertIPv4MappedToIPv4(const IPAddressNumber& address) {
215 DCHECK(IsIPv4Mapped(address));
216 return IPAddressNumber(address.begin() + arraysize(kIPv4MappedPrefix),
217 address.end());
220 bool ParseCIDRBlock(const std::string& cidr_literal,
221 IPAddressNumber* ip_number,
222 size_t* prefix_length_in_bits) {
223 // We expect CIDR notation to match one of these two templates:
224 // <IPv4-literal> "/" <number of bits>
225 // <IPv6-literal> "/" <number of bits>
227 std::vector<base::StringPiece> parts = base::SplitStringPiece(
228 cidr_literal, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
229 if (parts.size() != 2)
230 return false;
232 // Parse the IP address.
233 if (!ParseIPLiteralToNumber(parts[0], ip_number))
234 return false;
236 // Parse the prefix length.
237 int number_of_bits = -1;
238 if (!base::StringToInt(parts[1], &number_of_bits))
239 return false;
241 // Make sure the prefix length is in a valid range.
242 if (number_of_bits < 0 ||
243 number_of_bits > static_cast<int>(ip_number->size() * 8))
244 return false;
246 *prefix_length_in_bits = static_cast<size_t>(number_of_bits);
247 return true;
250 bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number,
251 const IPAddressNumber& ip_prefix,
252 size_t prefix_length_in_bits) {
253 // Both the input IP address and the prefix IP address should be
254 // either IPv4 or IPv6.
255 DCHECK(ip_number.size() == 4 || ip_number.size() == 16);
256 DCHECK(ip_prefix.size() == 4 || ip_prefix.size() == 16);
258 DCHECK_LE(prefix_length_in_bits, ip_prefix.size() * 8);
260 // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to
261 // IPv6 addresses in order to do the comparison.
262 if (ip_number.size() != ip_prefix.size()) {
263 if (ip_number.size() == 4) {
264 return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number),
265 ip_prefix, prefix_length_in_bits);
267 return IPNumberMatchesPrefix(ip_number,
268 ConvertIPv4NumberToIPv6Number(ip_prefix),
269 96 + prefix_length_in_bits);
272 return IPNumberPrefixCheck(ip_number, &ip_prefix[0], prefix_length_in_bits);
275 unsigned CommonPrefixLength(const IPAddressNumber& a1,
276 const IPAddressNumber& a2) {
277 DCHECK_EQ(a1.size(), a2.size());
278 for (size_t i = 0; i < a1.size(); ++i) {
279 unsigned diff = a1[i] ^ a2[i];
280 if (!diff)
281 continue;
282 for (unsigned j = 0; j < CHAR_BIT; ++j) {
283 if (diff & (1 << (CHAR_BIT - 1)))
284 return i * CHAR_BIT + j;
285 diff <<= 1;
287 NOTREACHED();
289 return a1.size() * CHAR_BIT;
292 unsigned MaskPrefixLength(const IPAddressNumber& mask) {
293 IPAddressNumber all_ones(mask.size(), 0xFF);
294 return CommonPrefixLength(mask, all_ones);
297 } // namespace net