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/net_util.h"
13 #include "build/build_config.h"
20 #pragma comment(lib, "iphlpapi.lib")
21 #elif defined(OS_POSIX)
24 #include <netinet/in.h>
28 #if !defined(OS_ANDROID)
30 #endif // !defined(OS_NACL)
31 #endif // !defined(OS_ANDROID)
32 #endif // defined(OS_POSIX)
34 #include "base/basictypes.h"
35 #include "base/json/string_escape.h"
36 #include "base/lazy_instance.h"
37 #include "base/logging.h"
38 #include "base/strings/string_number_conversions.h"
39 #include "base/strings/string_piece.h"
40 #include "base/strings/string_split.h"
41 #include "base/strings/string_util.h"
42 #include "base/strings/stringprintf.h"
43 #include "base/strings/utf_string_conversions.h"
44 #include "base/sys_byteorder.h"
45 #include "base/values.h"
46 #include "grit/net_resources.h"
48 #include "url/url_canon.h"
49 #include "url/url_canon_ip.h"
50 #include "url/url_parse.h"
51 #include "net/base/dns_util.h"
52 #include "net/base/net_module.h"
53 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
54 #include "net/http/http_content_disposition.h"
56 #if defined(OS_ANDROID)
57 #include "net/android/network_library.h"
60 #include "net/base/winsock_init.h"
67 // The general list of blocked ports. Will be blocked unless a specific
68 // protocol overrides it. (Ex: ftp can use ports 20 and 21)
69 static const int kRestrictedPorts[] = {
103 135, // loc-srv /epmap
126 3659, // apple-sasl / PasswordServer
129 6665, // Alternate IRC [Apple addition]
130 6666, // Alternate IRC [Apple addition]
131 6667, // Standard IRC [Apple addition]
132 6668, // Alternate IRC [Apple addition]
133 6669, // Alternate IRC [Apple addition]
134 0xFFFF, // Used to block all invalid port numbers (see
135 // third_party/WebKit/Source/platform/weborigin/KURL.cpp,
139 // FTP overrides the following restricted ports.
140 static const int kAllowedFtpPorts[] = {
145 bool IPNumberPrefixCheck(const IPAddressNumber& ip_number,
146 const unsigned char* ip_prefix,
147 size_t prefix_length_in_bits) {
148 // Compare all the bytes that fall entirely within the prefix.
149 int num_entire_bytes_in_prefix = prefix_length_in_bits / 8;
150 for (int i = 0; i < num_entire_bytes_in_prefix; ++i) {
151 if (ip_number[i] != ip_prefix[i])
155 // In case the prefix was not a multiple of 8, there will be 1 byte
156 // which is only partially masked.
157 int remaining_bits = prefix_length_in_bits % 8;
158 if (remaining_bits != 0) {
159 unsigned char mask = 0xFF << (8 - remaining_bits);
160 int i = num_entire_bytes_in_prefix;
161 if ((ip_number[i] & mask) != (ip_prefix[i] & mask))
169 static base::LazyInstance<std::multiset<int> >::Leaky
170 g_explicitly_allowed_ports = LAZY_INSTANCE_INITIALIZER;
172 size_t GetCountOfExplicitlyAllowedPorts() {
173 return g_explicitly_allowed_ports.Get().size();
176 std::string GetSpecificHeader(const std::string& headers,
177 const std::string& name) {
178 // We want to grab the Value from the "Key: Value" pairs in the headers,
179 // which should look like this (no leading spaces, \n-separated) (we format
180 // them this way in url_request_inet.cc):
182 // ETag: "6d0b8-947-24f35ec0"\n
183 // Content-Length: 2375\n
184 // Content-Type: text/html; charset=UTF-8\n
185 // Last-Modified: Sun, 03 Sep 2006 04:34:43 GMT\n
187 return std::string();
189 std::string match('\n' + name + ':');
191 std::string::const_iterator begin =
192 std::search(headers.begin(), headers.end(), match.begin(), match.end(),
193 base::CaseInsensitiveCompareASCII<char>());
195 if (begin == headers.end())
196 return std::string();
198 begin += match.length();
201 base::TrimWhitespace(std::string(begin,
202 std::find(begin, headers.end(), '\n')),
203 base::TRIM_ALL, &ret);
207 std::string CanonicalizeHost(const std::string& host,
208 url::CanonHostInfo* host_info) {
209 // Try to canonicalize the host.
210 const url::Component raw_host_component(0, static_cast<int>(host.length()));
211 std::string canon_host;
212 url::StdStringCanonOutput canon_host_output(&canon_host);
213 url::CanonicalizeHostVerbose(host.c_str(), raw_host_component,
214 &canon_host_output, host_info);
216 if (host_info->out_host.is_nonempty() &&
217 host_info->family != url::CanonHostInfo::BROKEN) {
218 // Success! Assert that there's no extra garbage.
219 canon_host_output.Complete();
220 DCHECK_EQ(host_info->out_host.len, static_cast<int>(canon_host.length()));
222 // Empty host, or canonicalization failed. We'll return empty.
229 std::string GetDirectoryListingHeader(const base::string16& title) {
230 static const base::StringPiece header(
231 NetModule::GetResource(IDR_DIR_HEADER_HTML));
232 // This can be null in unit tests.
233 DLOG_IF(WARNING, header.empty()) <<
234 "Missing resource: directory listing header";
238 result.assign(header.data(), header.size());
240 result.append("<script>start(");
241 base::EscapeJSONString(title, true, &result);
242 result.append(");</script>\n");
247 inline bool IsHostCharAlphanumeric(char c) {
248 // We can just check lowercase because uppercase characters have already been
250 return ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'));
253 bool IsCanonicalizedHostCompliant(const std::string& host,
254 const std::string& desired_tld) {
258 bool in_component = false;
259 bool most_recent_component_started_alphanumeric = false;
260 bool last_char_was_underscore = false;
262 for (std::string::const_iterator i(host.begin()); i != host.end(); ++i) {
265 most_recent_component_started_alphanumeric = IsHostCharAlphanumeric(c);
266 if (!most_recent_component_started_alphanumeric && (c != '-'))
271 if (last_char_was_underscore)
273 in_component = false;
274 } else if (IsHostCharAlphanumeric(c) || (c == '-')) {
275 last_char_was_underscore = false;
276 } else if (c == '_') {
277 last_char_was_underscore = true;
284 return most_recent_component_started_alphanumeric ||
285 (!desired_tld.empty() && IsHostCharAlphanumeric(desired_tld[0]));
288 base::string16 StripWWW(const base::string16& text) {
289 const base::string16 www(base::ASCIIToUTF16("www."));
290 return StartsWith(text, www, true) ? text.substr(www.length()) : text;
293 base::string16 StripWWWFromHost(const GURL& url) {
294 DCHECK(url.is_valid());
295 return StripWWW(base::ASCIIToUTF16(url.host()));
298 bool IsPortAllowedByDefault(int port) {
299 int array_size = arraysize(kRestrictedPorts);
300 for (int i = 0; i < array_size; i++) {
301 if (kRestrictedPorts[i] == port) {
308 bool IsPortAllowedByFtp(int port) {
309 int array_size = arraysize(kAllowedFtpPorts);
310 for (int i = 0; i < array_size; i++) {
311 if (kAllowedFtpPorts[i] == port) {
315 // Port not explicitly allowed by FTP, so return the default restrictions.
316 return IsPortAllowedByDefault(port);
319 bool IsPortAllowedByOverride(int port) {
320 if (g_explicitly_allowed_ports.Get().empty())
323 return g_explicitly_allowed_ports.Get().count(port) > 0;
326 int SetNonBlocking(int fd) {
328 unsigned long no_block = 1;
329 return ioctlsocket(fd, FIONBIO, &no_block);
330 #elif defined(OS_POSIX)
331 int flags = fcntl(fd, F_GETFL, 0);
334 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
338 bool ParseHostAndPort(std::string::const_iterator host_and_port_begin,
339 std::string::const_iterator host_and_port_end,
342 if (host_and_port_begin >= host_and_port_end)
345 // When using url, we use char*.
346 const char* auth_begin = &(*host_and_port_begin);
347 int auth_len = host_and_port_end - host_and_port_begin;
349 url::Component auth_component(0, auth_len);
350 url::Component username_component;
351 url::Component password_component;
352 url::Component hostname_component;
353 url::Component port_component;
355 url::ParseAuthority(auth_begin, auth_component, &username_component,
356 &password_component, &hostname_component, &port_component);
358 // There shouldn't be a username/password.
359 if (username_component.is_valid() || password_component.is_valid())
362 if (!hostname_component.is_nonempty())
363 return false; // Failed parsing.
365 int parsed_port_number = -1;
366 if (port_component.is_nonempty()) {
367 parsed_port_number = url::ParsePort(auth_begin, port_component);
369 // If parsing failed, port_number will be either PORT_INVALID or
370 // PORT_UNSPECIFIED, both of which are negative.
371 if (parsed_port_number < 0)
372 return false; // Failed parsing the port number.
375 if (port_component.len == 0)
376 return false; // Reject inputs like "foo:"
378 // Pass results back to caller.
379 host->assign(auth_begin + hostname_component.begin, hostname_component.len);
380 *port = parsed_port_number;
382 return true; // Success.
385 bool ParseHostAndPort(const std::string& host_and_port,
388 return ParseHostAndPort(
389 host_and_port.begin(), host_and_port.end(), host, port);
392 std::string GetHostAndPort(const GURL& url) {
393 // For IPv6 literals, GURL::host() already includes the brackets so it is
394 // safe to just append a colon.
395 return base::StringPrintf("%s:%d", url.host().c_str(),
396 url.EffectiveIntPort());
399 std::string GetHostAndOptionalPort(const GURL& url) {
400 // For IPv6 literals, GURL::host() already includes the brackets
401 // so it is safe to just append a colon.
403 return base::StringPrintf("%s:%s", url.host().c_str(), url.port().c_str());
407 bool IsHostnameNonUnique(const std::string& hostname) {
408 // CanonicalizeHost requires surrounding brackets to parse an IPv6 address.
409 const std::string host_or_ip = hostname.find(':') != std::string::npos ?
410 "[" + hostname + "]" : hostname;
411 url::CanonHostInfo host_info;
412 std::string canonical_name = CanonicalizeHost(host_or_ip, &host_info);
414 // If canonicalization fails, then the input is truly malformed. However,
415 // to avoid mis-reporting bad inputs as "non-unique", treat them as unique.
416 if (canonical_name.empty())
419 // If |hostname| is an IP address, check to see if it's in an IANA-reserved
421 if (host_info.IsIPAddress()) {
422 IPAddressNumber host_addr;
423 if (!ParseIPLiteralToNumber(hostname.substr(host_info.out_host.begin,
424 host_info.out_host.len),
428 switch (host_info.family) {
429 case url::CanonHostInfo::IPV4:
430 case url::CanonHostInfo::IPV6:
431 return IsIPAddressReserved(host_addr);
432 case url::CanonHostInfo::NEUTRAL:
433 case url::CanonHostInfo::BROKEN:
438 // Check for a registry controlled portion of |hostname|, ignoring private
439 // registries, as they already chain to ICANN-administered registries,
440 // and explicitly ignoring unknown registries.
442 // Note: This means that as new gTLDs are introduced on the Internet, they
443 // will be treated as non-unique until the registry controlled domain list
444 // is updated. However, because gTLDs are expected to provide significant
445 // advance notice to deprecate older versions of this code, this an
446 // acceptable tradeoff.
447 return 0 == registry_controlled_domains::GetRegistryLength(
449 registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
450 registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
453 // Don't compare IPv4 and IPv6 addresses (they have different range
454 // reservations). Keep separate reservation arrays for each IP type, and
455 // consolidate adjacent reserved ranges within a reservation array when
458 // www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
459 // www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
460 // They're formatted here with the prefix as the last element. For example:
461 // 10.0.0.0/8 becomes 10,0,0,0,8 and fec0::/10 becomes 0xfe,0xc0,0,0,0...,10.
462 bool IsIPAddressReserved(const IPAddressNumber& host_addr) {
463 static const unsigned char kReservedIPv4[][5] = {
464 { 0,0,0,0,8 }, { 10,0,0,0,8 }, { 100,64,0,0,10 }, { 127,0,0,0,8 },
465 { 169,254,0,0,16 }, { 172,16,0,0,12 }, { 192,0,2,0,24 },
466 { 192,88,99,0,24 }, { 192,168,0,0,16 }, { 198,18,0,0,15 },
467 { 198,51,100,0,24 }, { 203,0,113,0,24 }, { 224,0,0,0,3 }
469 static const unsigned char kReservedIPv6[][17] = {
470 { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8 },
471 { 0x40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
472 { 0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
473 { 0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3 },
474 { 0xe0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4 },
475 { 0xf0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5 },
476 { 0xf8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6 },
477 { 0xfc,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7 },
478 { 0xfe,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9 },
479 { 0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
480 { 0xfe,0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
482 size_t array_size = 0;
483 const unsigned char* array = NULL;
484 switch (host_addr.size()) {
485 case kIPv4AddressSize:
486 array_size = arraysize(kReservedIPv4);
487 array = kReservedIPv4[0];
489 case kIPv6AddressSize:
490 array_size = arraysize(kReservedIPv6);
491 array = kReservedIPv6[0];
496 size_t width = host_addr.size() + 1;
497 for (size_t i = 0; i < array_size; ++i, array += width) {
498 if (IPNumberPrefixCheck(host_addr, array, array[width-1]))
504 // Extracts the address and port portions of a sockaddr.
505 bool GetIPAddressFromSockAddr(const struct sockaddr* sock_addr,
506 socklen_t sock_addr_len,
507 const uint8** address,
510 if (sock_addr->sa_family == AF_INET) {
511 if (sock_addr_len < static_cast<socklen_t>(sizeof(struct sockaddr_in)))
513 const struct sockaddr_in* addr =
514 reinterpret_cast<const struct sockaddr_in*>(sock_addr);
515 *address = reinterpret_cast<const uint8*>(&addr->sin_addr);
516 *address_len = kIPv4AddressSize;
518 *port = base::NetToHost16(addr->sin_port);
522 if (sock_addr->sa_family == AF_INET6) {
523 if (sock_addr_len < static_cast<socklen_t>(sizeof(struct sockaddr_in6)))
525 const struct sockaddr_in6* addr =
526 reinterpret_cast<const struct sockaddr_in6*>(sock_addr);
527 *address = reinterpret_cast<const uint8*>(&addr->sin6_addr);
528 *address_len = kIPv6AddressSize;
530 *port = base::NetToHost16(addr->sin6_port);
535 if (sock_addr->sa_family == AF_BTH) {
536 if (sock_addr_len < static_cast<socklen_t>(sizeof(SOCKADDR_BTH)))
538 const SOCKADDR_BTH* addr =
539 reinterpret_cast<const SOCKADDR_BTH*>(sock_addr);
540 *address = reinterpret_cast<const uint8*>(&addr->btAddr);
541 *address_len = kBluetoothAddressSize;
548 return false; // Unrecognized |sa_family|.
551 std::string IPAddressToString(const uint8* address,
552 size_t address_len) {
554 url::StdStringCanonOutput output(&str);
556 if (address_len == kIPv4AddressSize) {
557 url::AppendIPv4Address(address, &output);
558 } else if (address_len == kIPv6AddressSize) {
559 url::AppendIPv6Address(address, &output);
561 CHECK(false) << "Invalid IP address with length: " << address_len;
568 std::string IPAddressToStringWithPort(const uint8* address,
571 std::string address_str = IPAddressToString(address, address_len);
573 if (address_len == kIPv6AddressSize) {
574 // Need to bracket IPv6 addresses since they contain colons.
575 return base::StringPrintf("[%s]:%d", address_str.c_str(), port);
577 return base::StringPrintf("%s:%d", address_str.c_str(), port);
580 std::string NetAddressToString(const struct sockaddr* sa,
581 socklen_t sock_addr_len) {
582 const uint8* address;
584 if (!GetIPAddressFromSockAddr(sa, sock_addr_len, &address,
585 &address_len, NULL)) {
587 return std::string();
589 return IPAddressToString(address, address_len);
592 std::string NetAddressToStringWithPort(const struct sockaddr* sa,
593 socklen_t sock_addr_len) {
594 const uint8* address;
597 if (!GetIPAddressFromSockAddr(sa, sock_addr_len, &address,
598 &address_len, &port)) {
600 return std::string();
602 return IPAddressToStringWithPort(address, address_len, port);
605 std::string IPAddressToString(const IPAddressNumber& addr) {
606 return IPAddressToString(&addr.front(), addr.size());
609 std::string IPAddressToStringWithPort(const IPAddressNumber& addr,
611 return IPAddressToStringWithPort(&addr.front(), addr.size(), port);
614 std::string IPAddressToPackedString(const IPAddressNumber& addr) {
615 return std::string(reinterpret_cast<const char *>(&addr.front()),
619 std::string GetHostName() {
622 return std::string();
623 #else // defined(OS_NACL)
628 // Host names are limited to 255 bytes.
630 int result = gethostname(buffer, sizeof(buffer));
632 DVLOG(1) << "gethostname() failed with " << result;
635 return std::string(buffer);
636 #endif // !defined(OS_NACL)
639 void GetIdentityFromURL(const GURL& url,
640 base::string16* username,
641 base::string16* password) {
642 UnescapeRule::Type flags =
643 UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS;
644 *username = UnescapeAndDecodeUTF8URLComponent(url.username(), flags);
645 *password = UnescapeAndDecodeUTF8URLComponent(url.password(), flags);
648 std::string GetHostOrSpecFromURL(const GURL& url) {
649 return url.has_host() ? TrimEndingDot(url.host()) : url.spec();
652 bool CanStripTrailingSlash(const GURL& url) {
653 // Omit the path only for standard, non-file URLs with nothing but "/" after
655 return url.IsStandard() && !url.SchemeIsFile() &&
656 !url.SchemeIsFileSystem() && !url.has_query() && !url.has_ref()
657 && url.path() == "/";
660 GURL SimplifyUrlForRequest(const GURL& url) {
661 DCHECK(url.is_valid());
662 GURL::Replacements replacements;
663 replacements.ClearUsername();
664 replacements.ClearPassword();
665 replacements.ClearRef();
666 return url.ReplaceComponents(replacements);
669 // Specifies a comma separated list of port numbers that should be accepted
670 // despite bans. If the string is invalid no allowed ports are stored.
671 void SetExplicitlyAllowedPorts(const std::string& allowed_ports) {
672 if (allowed_ports.empty())
675 std::multiset<int> ports;
677 size_t size = allowed_ports.size();
678 // The comma delimiter.
679 const std::string::value_type kComma = ',';
681 // Overflow is still possible for evil user inputs.
682 for (size_t i = 0; i <= size; ++i) {
683 // The string should be composed of only digits and commas.
684 if (i != size && !IsAsciiDigit(allowed_ports[i]) &&
685 (allowed_ports[i] != kComma))
687 if (i == size || allowed_ports[i] == kComma) {
690 base::StringToInt(base::StringPiece(allowed_ports.begin() + last,
691 allowed_ports.begin() + i),
698 g_explicitly_allowed_ports.Get() = ports;
701 ScopedPortException::ScopedPortException(int port) : port_(port) {
702 g_explicitly_allowed_ports.Get().insert(port);
705 ScopedPortException::~ScopedPortException() {
706 std::multiset<int>::iterator it =
707 g_explicitly_allowed_ports.Get().find(port_);
708 if (it != g_explicitly_allowed_ports.Get().end())
709 g_explicitly_allowed_ports.Get().erase(it);
714 bool HaveOnlyLoopbackAddresses() {
715 #if defined(OS_ANDROID)
716 return android::HaveOnlyLoopbackAddresses();
717 #elif defined(OS_NACL)
720 #elif defined(OS_POSIX)
721 struct ifaddrs* interface_addr = NULL;
722 int rv = getifaddrs(&interface_addr);
724 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
729 for (struct ifaddrs* interface = interface_addr;
731 interface = interface->ifa_next) {
732 if (!(IFF_UP & interface->ifa_flags))
734 if (IFF_LOOPBACK & interface->ifa_flags)
736 const struct sockaddr* addr = interface->ifa_addr;
739 if (addr->sa_family == AF_INET6) {
740 // Safe cast since this is AF_INET6.
741 const struct sockaddr_in6* addr_in6 =
742 reinterpret_cast<const struct sockaddr_in6*>(addr);
743 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
744 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
747 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
753 freeifaddrs(interface_addr);
755 #elif defined(OS_WIN)
756 // TODO(wtc): implement with the GetAdaptersAddresses function.
762 #endif // defined(various platforms)
765 AddressFamily GetAddressFamily(const IPAddressNumber& address) {
766 switch (address.size()) {
767 case kIPv4AddressSize:
768 return ADDRESS_FAMILY_IPV4;
769 case kIPv6AddressSize:
770 return ADDRESS_FAMILY_IPV6;
772 return ADDRESS_FAMILY_UNSPECIFIED;
776 int ConvertAddressFamily(AddressFamily address_family) {
777 switch (address_family) {
778 case ADDRESS_FAMILY_UNSPECIFIED:
780 case ADDRESS_FAMILY_IPV4:
782 case ADDRESS_FAMILY_IPV6:
789 bool ParseIPLiteralToNumber(const std::string& ip_literal,
790 IPAddressNumber* ip_number) {
791 // |ip_literal| could be either a IPv4 or an IPv6 literal. If it contains
792 // a colon however, it must be an IPv6 address.
793 if (ip_literal.find(':') != std::string::npos) {
794 // GURL expects IPv6 hostnames to be surrounded with brackets.
795 std::string host_brackets = "[" + ip_literal + "]";
796 url::Component host_comp(0, host_brackets.size());
798 // Try parsing the hostname as an IPv6 literal.
799 ip_number->resize(16); // 128 bits.
800 return url::IPv6AddressToNumber(host_brackets.data(), host_comp,
804 // Otherwise the string is an IPv4 address.
805 ip_number->resize(4); // 32 bits.
806 url::Component host_comp(0, ip_literal.size());
808 url::CanonHostInfo::Family family = url::IPv4AddressToNumber(
809 ip_literal.data(), host_comp, &(*ip_number)[0], &num_components);
810 return family == url::CanonHostInfo::IPV4;
815 const unsigned char kIPv4MappedPrefix[] =
816 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
819 IPAddressNumber ConvertIPv4NumberToIPv6Number(
820 const IPAddressNumber& ipv4_number) {
821 DCHECK(ipv4_number.size() == 4);
823 // IPv4-mapped addresses are formed by:
824 // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>.
825 IPAddressNumber ipv6_number;
826 ipv6_number.reserve(16);
827 ipv6_number.insert(ipv6_number.end(),
829 kIPv4MappedPrefix + arraysize(kIPv4MappedPrefix));
830 ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end());
834 bool IsIPv4Mapped(const IPAddressNumber& address) {
835 if (address.size() != kIPv6AddressSize)
837 return std::equal(address.begin(),
838 address.begin() + arraysize(kIPv4MappedPrefix),
842 IPAddressNumber ConvertIPv4MappedToIPv4(const IPAddressNumber& address) {
843 DCHECK(IsIPv4Mapped(address));
844 return IPAddressNumber(address.begin() + arraysize(kIPv4MappedPrefix),
848 bool ParseCIDRBlock(const std::string& cidr_literal,
849 IPAddressNumber* ip_number,
850 size_t* prefix_length_in_bits) {
851 // We expect CIDR notation to match one of these two templates:
852 // <IPv4-literal> "/" <number of bits>
853 // <IPv6-literal> "/" <number of bits>
855 std::vector<std::string> parts;
856 base::SplitString(cidr_literal, '/', &parts);
857 if (parts.size() != 2)
860 // Parse the IP address.
861 if (!ParseIPLiteralToNumber(parts[0], ip_number))
864 // Parse the prefix length.
865 int number_of_bits = -1;
866 if (!base::StringToInt(parts[1], &number_of_bits))
869 // Make sure the prefix length is in a valid range.
870 if (number_of_bits < 0 ||
871 number_of_bits > static_cast<int>(ip_number->size() * 8))
874 *prefix_length_in_bits = static_cast<size_t>(number_of_bits);
878 bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number,
879 const IPAddressNumber& ip_prefix,
880 size_t prefix_length_in_bits) {
881 // Both the input IP address and the prefix IP address should be
882 // either IPv4 or IPv6.
883 DCHECK(ip_number.size() == 4 || ip_number.size() == 16);
884 DCHECK(ip_prefix.size() == 4 || ip_prefix.size() == 16);
886 DCHECK_LE(prefix_length_in_bits, ip_prefix.size() * 8);
888 // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to
889 // IPv6 addresses in order to do the comparison.
890 if (ip_number.size() != ip_prefix.size()) {
891 if (ip_number.size() == 4) {
892 return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number),
893 ip_prefix, prefix_length_in_bits);
895 return IPNumberMatchesPrefix(ip_number,
896 ConvertIPv4NumberToIPv6Number(ip_prefix),
897 96 + prefix_length_in_bits);
900 return IPNumberPrefixCheck(ip_number, &ip_prefix[0], prefix_length_in_bits);
903 const uint16* GetPortFieldFromSockaddr(const struct sockaddr* address,
904 socklen_t address_len) {
905 if (address->sa_family == AF_INET) {
906 DCHECK_LE(sizeof(sockaddr_in), static_cast<size_t>(address_len));
907 const struct sockaddr_in* sockaddr =
908 reinterpret_cast<const struct sockaddr_in*>(address);
909 return &sockaddr->sin_port;
910 } else if (address->sa_family == AF_INET6) {
911 DCHECK_LE(sizeof(sockaddr_in6), static_cast<size_t>(address_len));
912 const struct sockaddr_in6* sockaddr =
913 reinterpret_cast<const struct sockaddr_in6*>(address);
914 return &sockaddr->sin6_port;
921 int GetPortFromSockaddr(const struct sockaddr* address, socklen_t address_len) {
922 const uint16* port_field = GetPortFieldFromSockaddr(address, address_len);
925 return base::NetToHost16(*port_field);
928 bool IsLocalhost(const std::string& host) {
929 if (host == "localhost" ||
930 host == "localhost.localdomain" ||
931 host == "localhost6" ||
932 host == "localhost6.localdomain6")
935 IPAddressNumber ip_number;
936 if (ParseIPLiteralToNumber(host, &ip_number)) {
937 size_t size = ip_number.size();
939 case kIPv4AddressSize: {
940 IPAddressNumber localhost_prefix;
941 localhost_prefix.push_back(127);
942 for (int i = 0; i < 3; ++i) {
943 localhost_prefix.push_back(0);
945 return IPNumberMatchesPrefix(ip_number, localhost_prefix, 8);
948 case kIPv6AddressSize: {
949 struct in6_addr sin6_addr;
950 memcpy(&sin6_addr, &ip_number[0], kIPv6AddressSize);
951 return !!IN6_IS_ADDR_LOOPBACK(&sin6_addr);
962 NetworkInterface::NetworkInterface()
963 : type(NetworkChangeNotifier::CONNECTION_UNKNOWN),
967 NetworkInterface::NetworkInterface(const std::string& name,
968 const std::string& friendly_name,
969 uint32 interface_index,
970 NetworkChangeNotifier::ConnectionType type,
971 const IPAddressNumber& address,
972 size_t network_prefix)
974 friendly_name(friendly_name),
975 interface_index(interface_index),
978 network_prefix(network_prefix) {
981 NetworkInterface::~NetworkInterface() {
984 unsigned CommonPrefixLength(const IPAddressNumber& a1,
985 const IPAddressNumber& a2) {
986 DCHECK_EQ(a1.size(), a2.size());
987 for (size_t i = 0; i < a1.size(); ++i) {
988 unsigned diff = a1[i] ^ a2[i];
991 for (unsigned j = 0; j < CHAR_BIT; ++j) {
992 if (diff & (1 << (CHAR_BIT - 1)))
993 return i * CHAR_BIT + j;
998 return a1.size() * CHAR_BIT;
1001 unsigned MaskPrefixLength(const IPAddressNumber& mask) {
1002 IPAddressNumber all_ones(mask.size(), 0xFF);
1003 return CommonPrefixLength(mask, all_ones);