components: Fix 'gn check' errors for user_prefs.
[chromium-blink-merge.git] / net / base / ip_address_number.cc
blob06fc3ac29fba3925ff3ebeea7ff01c32e7848208
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 std::string& 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(':') != std::string::npos) {
164 // GURL expects IPv6 hostnames to be surrounded with brackets.
165 std::string host_brackets = "[" + ip_literal + "]";
166 url::Component host_comp(0, host_brackets.size());
168 // Try parsing the hostname as an IPv6 literal.
169 ip_number->resize(16); // 128 bits.
170 return url::IPv6AddressToNumber(host_brackets.data(), host_comp,
171 &(*ip_number)[0]);
174 // Otherwise the string is an IPv4 address.
175 ip_number->resize(4); // 32 bits.
176 url::Component host_comp(0, ip_literal.size());
177 int num_components;
178 url::CanonHostInfo::Family family = url::IPv4AddressToNumber(
179 ip_literal.data(), host_comp, &(*ip_number)[0], &num_components);
180 return family == url::CanonHostInfo::IPV4;
183 namespace {
185 const unsigned char kIPv4MappedPrefix[] =
186 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
189 IPAddressNumber ConvertIPv4NumberToIPv6Number(
190 const IPAddressNumber& ipv4_number) {
191 DCHECK(ipv4_number.size() == 4);
193 // IPv4-mapped addresses are formed by:
194 // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>.
195 IPAddressNumber ipv6_number;
196 ipv6_number.reserve(16);
197 ipv6_number.insert(ipv6_number.end(),
198 kIPv4MappedPrefix,
199 kIPv4MappedPrefix + arraysize(kIPv4MappedPrefix));
200 ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end());
201 return ipv6_number;
204 bool IsIPv4Mapped(const IPAddressNumber& address) {
205 if (address.size() != kIPv6AddressSize)
206 return false;
207 return std::equal(address.begin(),
208 address.begin() + arraysize(kIPv4MappedPrefix),
209 kIPv4MappedPrefix);
212 IPAddressNumber ConvertIPv4MappedToIPv4(const IPAddressNumber& address) {
213 DCHECK(IsIPv4Mapped(address));
214 return IPAddressNumber(address.begin() + arraysize(kIPv4MappedPrefix),
215 address.end());
218 bool ParseCIDRBlock(const std::string& cidr_literal,
219 IPAddressNumber* ip_number,
220 size_t* prefix_length_in_bits) {
221 // We expect CIDR notation to match one of these two templates:
222 // <IPv4-literal> "/" <number of bits>
223 // <IPv6-literal> "/" <number of bits>
225 std::vector<std::string> parts;
226 base::SplitString(cidr_literal, '/', &parts);
227 if (parts.size() != 2)
228 return false;
230 // Parse the IP address.
231 if (!ParseIPLiteralToNumber(parts[0], ip_number))
232 return false;
234 // Parse the prefix length.
235 int number_of_bits = -1;
236 if (!base::StringToInt(parts[1], &number_of_bits))
237 return false;
239 // Make sure the prefix length is in a valid range.
240 if (number_of_bits < 0 ||
241 number_of_bits > static_cast<int>(ip_number->size() * 8))
242 return false;
244 *prefix_length_in_bits = static_cast<size_t>(number_of_bits);
245 return true;
248 bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number,
249 const IPAddressNumber& ip_prefix,
250 size_t prefix_length_in_bits) {
251 // Both the input IP address and the prefix IP address should be
252 // either IPv4 or IPv6.
253 DCHECK(ip_number.size() == 4 || ip_number.size() == 16);
254 DCHECK(ip_prefix.size() == 4 || ip_prefix.size() == 16);
256 DCHECK_LE(prefix_length_in_bits, ip_prefix.size() * 8);
258 // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to
259 // IPv6 addresses in order to do the comparison.
260 if (ip_number.size() != ip_prefix.size()) {
261 if (ip_number.size() == 4) {
262 return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number),
263 ip_prefix, prefix_length_in_bits);
265 return IPNumberMatchesPrefix(ip_number,
266 ConvertIPv4NumberToIPv6Number(ip_prefix),
267 96 + prefix_length_in_bits);
270 return IPNumberPrefixCheck(ip_number, &ip_prefix[0], prefix_length_in_bits);
273 unsigned CommonPrefixLength(const IPAddressNumber& a1,
274 const IPAddressNumber& a2) {
275 DCHECK_EQ(a1.size(), a2.size());
276 for (size_t i = 0; i < a1.size(); ++i) {
277 unsigned diff = a1[i] ^ a2[i];
278 if (!diff)
279 continue;
280 for (unsigned j = 0; j < CHAR_BIT; ++j) {
281 if (diff & (1 << (CHAR_BIT - 1)))
282 return i * CHAR_BIT + j;
283 diff <<= 1;
285 NOTREACHED();
287 return a1.size() * CHAR_BIT;
290 unsigned MaskPrefixLength(const IPAddressNumber& mask) {
291 IPAddressNumber all_ones(mask.size(), 0xFF);
292 return CommonPrefixLength(mask, all_ones);
295 } // namespace net