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"
15 #include "build/build_config.h"
22 #pragma comment(lib, "iphlpapi.lib")
23 #elif defined(OS_POSIX)
26 #include <netinet/in.h>
30 #if !defined(OS_ANDROID)
32 #endif // !defined(OS_NACL)
33 #endif // !defined(OS_ANDROID)
34 #endif // defined(OS_POSIX)
36 #include "base/basictypes.h"
37 #include "base/json/string_escape.h"
38 #include "base/lazy_instance.h"
39 #include "base/logging.h"
40 #include "base/strings/string_number_conversions.h"
41 #include "base/strings/string_piece.h"
42 #include "base/strings/string_split.h"
43 #include "base/strings/string_util.h"
44 #include "base/strings/stringprintf.h"
45 #include "base/strings/utf_string_conversions.h"
46 #include "base/sys_byteorder.h"
47 #include "base/values.h"
49 #include "url/url_canon.h"
50 #include "url/url_canon_ip.h"
51 #include "url/url_parse.h"
52 #include "net/base/dns_util.h"
53 #include "net/base/net_module.h"
54 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
55 #include "net/grit/net_resources.h"
56 #include "net/http/http_content_disposition.h"
58 #if defined(OS_ANDROID)
59 #include "net/android/network_library.h"
62 #include "net/base/winsock_init.h"
69 // The general list of blocked ports. Will be blocked unless a specific
70 // protocol overrides it. (Ex: ftp can use ports 20 and 21)
71 static const int kRestrictedPorts
[] = {
105 135, // loc-srv /epmap
128 3659, // apple-sasl / PasswordServer
131 6665, // Alternate IRC [Apple addition]
132 6666, // Alternate IRC [Apple addition]
133 6667, // Standard IRC [Apple addition]
134 6668, // Alternate IRC [Apple addition]
135 6669, // Alternate IRC [Apple addition]
136 0xFFFF, // Used to block all invalid port numbers (see
137 // third_party/WebKit/Source/platform/weborigin/KURL.cpp,
141 // FTP overrides the following restricted ports.
142 static const int kAllowedFtpPorts
[] = {
147 bool IPNumberPrefixCheck(const IPAddressNumber
& ip_number
,
148 const unsigned char* ip_prefix
,
149 size_t prefix_length_in_bits
) {
150 // Compare all the bytes that fall entirely within the prefix.
151 int num_entire_bytes_in_prefix
= prefix_length_in_bits
/ 8;
152 for (int i
= 0; i
< num_entire_bytes_in_prefix
; ++i
) {
153 if (ip_number
[i
] != ip_prefix
[i
])
157 // In case the prefix was not a multiple of 8, there will be 1 byte
158 // which is only partially masked.
159 int remaining_bits
= prefix_length_in_bits
% 8;
160 if (remaining_bits
!= 0) {
161 unsigned char mask
= 0xFF << (8 - remaining_bits
);
162 int i
= num_entire_bytes_in_prefix
;
163 if ((ip_number
[i
] & mask
) != (ip_prefix
[i
] & mask
))
171 static base::LazyInstance
<std::multiset
<int> >::Leaky
172 g_explicitly_allowed_ports
= LAZY_INSTANCE_INITIALIZER
;
174 size_t GetCountOfExplicitlyAllowedPorts() {
175 return g_explicitly_allowed_ports
.Get().size();
178 std::string
GetSpecificHeader(const std::string
& headers
,
179 const std::string
& name
) {
180 // We want to grab the Value from the "Key: Value" pairs in the headers,
181 // which should look like this (no leading spaces, \n-separated) (we format
182 // them this way in url_request_inet.cc):
184 // ETag: "6d0b8-947-24f35ec0"\n
185 // Content-Length: 2375\n
186 // Content-Type: text/html; charset=UTF-8\n
187 // Last-Modified: Sun, 03 Sep 2006 04:34:43 GMT\n
189 return std::string();
191 std::string
match('\n' + name
+ ':');
193 std::string::const_iterator begin
=
194 std::search(headers
.begin(), headers
.end(), match
.begin(), match
.end(),
195 base::CaseInsensitiveCompareASCII
<char>());
197 if (begin
== headers
.end())
198 return std::string();
200 begin
+= match
.length();
203 base::TrimWhitespace(std::string(begin
,
204 std::find(begin
, headers
.end(), '\n')),
205 base::TRIM_ALL
, &ret
);
209 std::string
CanonicalizeHost(const std::string
& host
,
210 url::CanonHostInfo
* host_info
) {
211 // Try to canonicalize the host.
212 const url::Component
raw_host_component(0, static_cast<int>(host
.length()));
213 std::string canon_host
;
214 url::StdStringCanonOutput
canon_host_output(&canon_host
);
215 url::CanonicalizeHostVerbose(host
.c_str(), raw_host_component
,
216 &canon_host_output
, host_info
);
218 if (host_info
->out_host
.is_nonempty() &&
219 host_info
->family
!= url::CanonHostInfo::BROKEN
) {
220 // Success! Assert that there's no extra garbage.
221 canon_host_output
.Complete();
222 DCHECK_EQ(host_info
->out_host
.len
, static_cast<int>(canon_host
.length()));
224 // Empty host, or canonicalization failed. We'll return empty.
231 std::string
GetDirectoryListingHeader(const base::string16
& title
) {
232 static const base::StringPiece
header(
233 NetModule::GetResource(IDR_DIR_HEADER_HTML
));
234 // This can be null in unit tests.
235 DLOG_IF(WARNING
, header
.empty()) <<
236 "Missing resource: directory listing header";
240 result
.assign(header
.data(), header
.size());
242 result
.append("<script>start(");
243 base::EscapeJSONString(title
, true, &result
);
244 result
.append(");</script>\n");
249 inline bool IsHostCharAlphanumeric(char c
) {
250 // We can just check lowercase because uppercase characters have already been
252 return ((c
>= 'a') && (c
<= 'z')) || ((c
>= '0') && (c
<= '9'));
255 bool IsCanonicalizedHostCompliant(const std::string
& host
) {
259 bool in_component
= false;
260 bool most_recent_component_started_alphanumeric
= false;
261 bool last_char_was_underscore
= false;
263 for (std::string::const_iterator
i(host
.begin()); i
!= host
.end(); ++i
) {
266 most_recent_component_started_alphanumeric
= IsHostCharAlphanumeric(c
);
267 if (!most_recent_component_started_alphanumeric
&& (c
!= '-'))
272 if (last_char_was_underscore
)
274 in_component
= false;
275 } else if (IsHostCharAlphanumeric(c
) || (c
== '-')) {
276 last_char_was_underscore
= false;
277 } else if (c
== '_') {
278 last_char_was_underscore
= true;
285 return most_recent_component_started_alphanumeric
;
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 IsPortValid(int port
) {
299 return port
>= 0 && port
<= std::numeric_limits
<uint16
>::max();
302 bool IsPortAllowedByDefault(int port
) {
303 int array_size
= arraysize(kRestrictedPorts
);
304 for (int i
= 0; i
< array_size
; i
++) {
305 if (kRestrictedPorts
[i
] == port
) {
309 return IsPortValid(port
);
312 bool IsPortAllowedByFtp(int port
) {
313 int array_size
= arraysize(kAllowedFtpPorts
);
314 for (int i
= 0; i
< array_size
; i
++) {
315 if (kAllowedFtpPorts
[i
] == port
) {
319 // Port not explicitly allowed by FTP, so return the default restrictions.
320 return IsPortAllowedByDefault(port
);
323 bool IsPortAllowedByOverride(int port
) {
324 if (g_explicitly_allowed_ports
.Get().empty())
327 return g_explicitly_allowed_ports
.Get().count(port
) > 0;
330 int SetNonBlocking(int fd
) {
332 unsigned long no_block
= 1;
333 return ioctlsocket(fd
, FIONBIO
, &no_block
);
334 #elif defined(OS_POSIX)
335 int flags
= fcntl(fd
, F_GETFL
, 0);
338 return fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
342 bool ParseHostAndPort(std::string::const_iterator host_and_port_begin
,
343 std::string::const_iterator host_and_port_end
,
346 if (host_and_port_begin
>= host_and_port_end
)
349 // When using url, we use char*.
350 const char* auth_begin
= &(*host_and_port_begin
);
351 int auth_len
= host_and_port_end
- host_and_port_begin
;
353 url::Component
auth_component(0, auth_len
);
354 url::Component username_component
;
355 url::Component password_component
;
356 url::Component hostname_component
;
357 url::Component port_component
;
359 url::ParseAuthority(auth_begin
, auth_component
, &username_component
,
360 &password_component
, &hostname_component
, &port_component
);
362 // There shouldn't be a username/password.
363 if (username_component
.is_valid() || password_component
.is_valid())
366 if (!hostname_component
.is_nonempty())
367 return false; // Failed parsing.
369 int parsed_port_number
= -1;
370 if (port_component
.is_nonempty()) {
371 parsed_port_number
= url::ParsePort(auth_begin
, port_component
);
373 // If parsing failed, port_number will be either PORT_INVALID or
374 // PORT_UNSPECIFIED, both of which are negative.
375 if (parsed_port_number
< 0)
376 return false; // Failed parsing the port number.
379 if (port_component
.len
== 0)
380 return false; // Reject inputs like "foo:"
382 unsigned char tmp_ipv6_addr
[16];
384 // If the hostname starts with a bracket, it is either an IPv6 literal or
385 // invalid. If it is an IPv6 literal then strip the brackets.
386 if (hostname_component
.len
> 0 &&
387 auth_begin
[hostname_component
.begin
] == '[') {
388 if (auth_begin
[hostname_component
.end() - 1] == ']' &&
389 url::IPv6AddressToNumber(
390 auth_begin
, hostname_component
, tmp_ipv6_addr
)) {
391 // Strip the brackets.
392 hostname_component
.begin
++;
393 hostname_component
.len
-= 2;
399 // Pass results back to caller.
400 host
->assign(auth_begin
+ hostname_component
.begin
, hostname_component
.len
);
401 *port
= parsed_port_number
;
403 return true; // Success.
406 bool ParseHostAndPort(const std::string
& host_and_port
,
409 return ParseHostAndPort(
410 host_and_port
.begin(), host_and_port
.end(), host
, port
);
413 std::string
GetHostAndPort(const GURL
& url
) {
414 // For IPv6 literals, GURL::host() already includes the brackets so it is
415 // safe to just append a colon.
416 return base::StringPrintf("%s:%d", url
.host().c_str(),
417 url
.EffectiveIntPort());
420 std::string
GetHostAndOptionalPort(const GURL
& url
) {
421 // For IPv6 literals, GURL::host() already includes the brackets
422 // so it is safe to just append a colon.
424 return base::StringPrintf("%s:%s", url
.host().c_str(), url
.port().c_str());
428 bool IsHostnameNonUnique(const std::string
& hostname
) {
429 // CanonicalizeHost requires surrounding brackets to parse an IPv6 address.
430 const std::string host_or_ip
= hostname
.find(':') != std::string::npos
?
431 "[" + hostname
+ "]" : hostname
;
432 url::CanonHostInfo host_info
;
433 std::string canonical_name
= CanonicalizeHost(host_or_ip
, &host_info
);
435 // If canonicalization fails, then the input is truly malformed. However,
436 // to avoid mis-reporting bad inputs as "non-unique", treat them as unique.
437 if (canonical_name
.empty())
440 // If |hostname| is an IP address, check to see if it's in an IANA-reserved
442 if (host_info
.IsIPAddress()) {
443 IPAddressNumber host_addr
;
444 if (!ParseIPLiteralToNumber(hostname
.substr(host_info
.out_host
.begin
,
445 host_info
.out_host
.len
),
449 switch (host_info
.family
) {
450 case url::CanonHostInfo::IPV4
:
451 case url::CanonHostInfo::IPV6
:
452 return IsIPAddressReserved(host_addr
);
453 case url::CanonHostInfo::NEUTRAL
:
454 case url::CanonHostInfo::BROKEN
:
459 // Check for a registry controlled portion of |hostname|, ignoring private
460 // registries, as they already chain to ICANN-administered registries,
461 // and explicitly ignoring unknown registries.
463 // Note: This means that as new gTLDs are introduced on the Internet, they
464 // will be treated as non-unique until the registry controlled domain list
465 // is updated. However, because gTLDs are expected to provide significant
466 // advance notice to deprecate older versions of this code, this an
467 // acceptable tradeoff.
468 return 0 == registry_controlled_domains::GetRegistryLength(
470 registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES
,
471 registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
);
474 // Don't compare IPv4 and IPv6 addresses (they have different range
475 // reservations). Keep separate reservation arrays for each IP type, and
476 // consolidate adjacent reserved ranges within a reservation array when
479 // www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
480 // www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
481 // They're formatted here with the prefix as the last element. For example:
482 // 10.0.0.0/8 becomes 10,0,0,0,8 and fec0::/10 becomes 0xfe,0xc0,0,0,0...,10.
483 bool IsIPAddressReserved(const IPAddressNumber
& host_addr
) {
484 static const unsigned char kReservedIPv4
[][5] = {
485 { 0,0,0,0,8 }, { 10,0,0,0,8 }, { 100,64,0,0,10 }, { 127,0,0,0,8 },
486 { 169,254,0,0,16 }, { 172,16,0,0,12 }, { 192,0,2,0,24 },
487 { 192,88,99,0,24 }, { 192,168,0,0,16 }, { 198,18,0,0,15 },
488 { 198,51,100,0,24 }, { 203,0,113,0,24 }, { 224,0,0,0,3 }
490 static const unsigned char kReservedIPv6
[][17] = {
491 { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8 },
492 { 0x40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
493 { 0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
494 { 0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3 },
495 { 0xe0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4 },
496 { 0xf0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5 },
497 { 0xf8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6 },
498 { 0xfc,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7 },
499 { 0xfe,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9 },
500 { 0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
501 { 0xfe,0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
503 size_t array_size
= 0;
504 const unsigned char* array
= NULL
;
505 switch (host_addr
.size()) {
506 case kIPv4AddressSize
:
507 array_size
= arraysize(kReservedIPv4
);
508 array
= kReservedIPv4
[0];
510 case kIPv6AddressSize
:
511 array_size
= arraysize(kReservedIPv6
);
512 array
= kReservedIPv6
[0];
517 size_t width
= host_addr
.size() + 1;
518 for (size_t i
= 0; i
< array_size
; ++i
, array
+= width
) {
519 if (IPNumberPrefixCheck(host_addr
, array
, array
[width
-1]))
525 SockaddrStorage::SockaddrStorage(const SockaddrStorage
& other
)
526 : addr_len(other
.addr_len
),
527 addr(reinterpret_cast<struct sockaddr
*>(&addr_storage
)) {
528 memcpy(addr
, other
.addr
, addr_len
);
531 void SockaddrStorage::operator=(const SockaddrStorage
& other
) {
532 addr_len
= other
.addr_len
;
533 // addr is already set to &this->addr_storage by default ctor.
534 memcpy(addr
, other
.addr
, addr_len
);
537 // Extracts the address and port portions of a sockaddr.
538 bool GetIPAddressFromSockAddr(const struct sockaddr
* sock_addr
,
539 socklen_t sock_addr_len
,
540 const uint8
** address
,
543 if (sock_addr
->sa_family
== AF_INET
) {
544 if (sock_addr_len
< static_cast<socklen_t
>(sizeof(struct sockaddr_in
)))
546 const struct sockaddr_in
* addr
=
547 reinterpret_cast<const struct sockaddr_in
*>(sock_addr
);
548 *address
= reinterpret_cast<const uint8
*>(&addr
->sin_addr
);
549 *address_len
= kIPv4AddressSize
;
551 *port
= base::NetToHost16(addr
->sin_port
);
555 if (sock_addr
->sa_family
== AF_INET6
) {
556 if (sock_addr_len
< static_cast<socklen_t
>(sizeof(struct sockaddr_in6
)))
558 const struct sockaddr_in6
* addr
=
559 reinterpret_cast<const struct sockaddr_in6
*>(sock_addr
);
560 *address
= reinterpret_cast<const uint8
*>(&addr
->sin6_addr
);
561 *address_len
= kIPv6AddressSize
;
563 *port
= base::NetToHost16(addr
->sin6_port
);
568 if (sock_addr
->sa_family
== AF_BTH
) {
569 if (sock_addr_len
< static_cast<socklen_t
>(sizeof(SOCKADDR_BTH
)))
571 const SOCKADDR_BTH
* addr
=
572 reinterpret_cast<const SOCKADDR_BTH
*>(sock_addr
);
573 *address
= reinterpret_cast<const uint8
*>(&addr
->btAddr
);
574 *address_len
= kBluetoothAddressSize
;
576 *port
= static_cast<uint16
>(addr
->port
);
581 return false; // Unrecognized |sa_family|.
584 std::string
IPAddressToString(const uint8
* address
,
585 size_t address_len
) {
587 url::StdStringCanonOutput
output(&str
);
589 if (address_len
== kIPv4AddressSize
) {
590 url::AppendIPv4Address(address
, &output
);
591 } else if (address_len
== kIPv6AddressSize
) {
592 url::AppendIPv6Address(address
, &output
);
594 CHECK(false) << "Invalid IP address with length: " << address_len
;
601 std::string
IPAddressToStringWithPort(const uint8
* address
,
604 std::string address_str
= IPAddressToString(address
, address_len
);
606 if (address_len
== kIPv6AddressSize
) {
607 // Need to bracket IPv6 addresses since they contain colons.
608 return base::StringPrintf("[%s]:%d", address_str
.c_str(), port
);
610 return base::StringPrintf("%s:%d", address_str
.c_str(), port
);
613 std::string
NetAddressToString(const struct sockaddr
* sa
,
614 socklen_t sock_addr_len
) {
615 const uint8
* address
;
617 if (!GetIPAddressFromSockAddr(sa
, sock_addr_len
, &address
,
618 &address_len
, NULL
)) {
620 return std::string();
622 return IPAddressToString(address
, address_len
);
625 std::string
NetAddressToStringWithPort(const struct sockaddr
* sa
,
626 socklen_t sock_addr_len
) {
627 const uint8
* address
;
630 if (!GetIPAddressFromSockAddr(sa
, sock_addr_len
, &address
,
631 &address_len
, &port
)) {
633 return std::string();
635 return IPAddressToStringWithPort(address
, address_len
, port
);
638 std::string
IPAddressToString(const IPAddressNumber
& addr
) {
639 return IPAddressToString(&addr
.front(), addr
.size());
642 std::string
IPAddressToStringWithPort(const IPAddressNumber
& addr
,
644 return IPAddressToStringWithPort(&addr
.front(), addr
.size(), port
);
647 std::string
IPAddressToPackedString(const IPAddressNumber
& addr
) {
648 return std::string(reinterpret_cast<const char *>(&addr
.front()),
652 std::string
GetHostName() {
655 return std::string();
656 #else // defined(OS_NACL)
661 // Host names are limited to 255 bytes.
663 int result
= gethostname(buffer
, sizeof(buffer
));
665 DVLOG(1) << "gethostname() failed with " << result
;
668 return std::string(buffer
);
669 #endif // !defined(OS_NACL)
672 void GetIdentityFromURL(const GURL
& url
,
673 base::string16
* username
,
674 base::string16
* password
) {
675 UnescapeRule::Type flags
=
676 UnescapeRule::SPACES
| UnescapeRule::URL_SPECIAL_CHARS
;
677 *username
= UnescapeAndDecodeUTF8URLComponent(url
.username(), flags
);
678 *password
= UnescapeAndDecodeUTF8URLComponent(url
.password(), flags
);
681 std::string
GetHostOrSpecFromURL(const GURL
& url
) {
682 return url
.has_host() ? TrimEndingDot(url
.host()) : url
.spec();
685 bool CanStripTrailingSlash(const GURL
& url
) {
686 // Omit the path only for standard, non-file URLs with nothing but "/" after
688 return url
.IsStandard() && !url
.SchemeIsFile() &&
689 !url
.SchemeIsFileSystem() && !url
.has_query() && !url
.has_ref()
690 && url
.path() == "/";
693 GURL
SimplifyUrlForRequest(const GURL
& url
) {
694 DCHECK(url
.is_valid());
695 GURL::Replacements replacements
;
696 replacements
.ClearUsername();
697 replacements
.ClearPassword();
698 replacements
.ClearRef();
699 return url
.ReplaceComponents(replacements
);
702 // Specifies a comma separated list of port numbers that should be accepted
703 // despite bans. If the string is invalid no allowed ports are stored.
704 void SetExplicitlyAllowedPorts(const std::string
& allowed_ports
) {
705 if (allowed_ports
.empty())
708 std::multiset
<int> ports
;
710 size_t size
= allowed_ports
.size();
711 // The comma delimiter.
712 const std::string::value_type kComma
= ',';
714 // Overflow is still possible for evil user inputs.
715 for (size_t i
= 0; i
<= size
; ++i
) {
716 // The string should be composed of only digits and commas.
717 if (i
!= size
&& !IsAsciiDigit(allowed_ports
[i
]) &&
718 (allowed_ports
[i
] != kComma
))
720 if (i
== size
|| allowed_ports
[i
] == kComma
) {
723 base::StringToInt(base::StringPiece(allowed_ports
.begin() + last
,
724 allowed_ports
.begin() + i
),
731 g_explicitly_allowed_ports
.Get() = ports
;
734 ScopedPortException::ScopedPortException(int port
) : port_(port
) {
735 g_explicitly_allowed_ports
.Get().insert(port
);
738 ScopedPortException::~ScopedPortException() {
739 std::multiset
<int>::iterator it
=
740 g_explicitly_allowed_ports
.Get().find(port_
);
741 if (it
!= g_explicitly_allowed_ports
.Get().end())
742 g_explicitly_allowed_ports
.Get().erase(it
);
747 bool HaveOnlyLoopbackAddresses() {
748 #if defined(OS_ANDROID)
749 return android::HaveOnlyLoopbackAddresses();
750 #elif defined(OS_NACL)
753 #elif defined(OS_POSIX)
754 struct ifaddrs
* interface_addr
= NULL
;
755 int rv
= getifaddrs(&interface_addr
);
757 DVLOG(1) << "getifaddrs() failed with errno = " << errno
;
762 for (struct ifaddrs
* interface
= interface_addr
;
764 interface
= interface
->ifa_next
) {
765 if (!(IFF_UP
& interface
->ifa_flags
))
767 if (IFF_LOOPBACK
& interface
->ifa_flags
)
769 const struct sockaddr
* addr
= interface
->ifa_addr
;
772 if (addr
->sa_family
== AF_INET6
) {
773 // Safe cast since this is AF_INET6.
774 const struct sockaddr_in6
* addr_in6
=
775 reinterpret_cast<const struct sockaddr_in6
*>(addr
);
776 const struct in6_addr
* sin6_addr
= &addr_in6
->sin6_addr
;
777 if (IN6_IS_ADDR_LOOPBACK(sin6_addr
) || IN6_IS_ADDR_LINKLOCAL(sin6_addr
))
780 if (addr
->sa_family
!= AF_INET6
&& addr
->sa_family
!= AF_INET
)
786 freeifaddrs(interface_addr
);
788 #elif defined(OS_WIN)
789 // TODO(wtc): implement with the GetAdaptersAddresses function.
795 #endif // defined(various platforms)
798 AddressFamily
GetAddressFamily(const IPAddressNumber
& address
) {
799 switch (address
.size()) {
800 case kIPv4AddressSize
:
801 return ADDRESS_FAMILY_IPV4
;
802 case kIPv6AddressSize
:
803 return ADDRESS_FAMILY_IPV6
;
805 return ADDRESS_FAMILY_UNSPECIFIED
;
809 int ConvertAddressFamily(AddressFamily address_family
) {
810 switch (address_family
) {
811 case ADDRESS_FAMILY_UNSPECIFIED
:
813 case ADDRESS_FAMILY_IPV4
:
815 case ADDRESS_FAMILY_IPV6
:
822 bool ParseURLHostnameToNumber(const std::string
& hostname
,
823 IPAddressNumber
* ip_number
) {
824 // |hostname| is an already canoncalized hostname, conforming to RFC 3986.
825 // For an IP address, this is defined in Section 3.2.2 of RFC 3986, with
826 // the canonical form for IPv6 addresses defined in Section 4 of RFC 5952.
827 url::Component
host_comp(0, hostname
.size());
829 // If it has a bracket, try parsing it as an IPv6 address.
830 if (hostname
[0] == '[') {
831 ip_number
->resize(16); // 128 bits.
832 return url::IPv6AddressToNumber(
833 hostname
.data(), host_comp
, &(*ip_number
)[0]);
836 // Otherwise, try IPv4.
837 ip_number
->resize(4); // 32 bits.
839 url::CanonHostInfo::Family family
= url::IPv4AddressToNumber(
840 hostname
.data(), host_comp
, &(*ip_number
)[0], &num_components
);
841 return family
== url::CanonHostInfo::IPV4
;
844 bool ParseIPLiteralToNumber(const std::string
& ip_literal
,
845 IPAddressNumber
* ip_number
) {
846 // |ip_literal| could be either a IPv4 or an IPv6 literal. If it contains
847 // a colon however, it must be an IPv6 address.
848 if (ip_literal
.find(':') != std::string::npos
) {
849 // GURL expects IPv6 hostnames to be surrounded with brackets.
850 std::string host_brackets
= "[" + ip_literal
+ "]";
851 url::Component
host_comp(0, host_brackets
.size());
853 // Try parsing the hostname as an IPv6 literal.
854 ip_number
->resize(16); // 128 bits.
855 return url::IPv6AddressToNumber(host_brackets
.data(), host_comp
,
859 // Otherwise the string is an IPv4 address.
860 ip_number
->resize(4); // 32 bits.
861 url::Component
host_comp(0, ip_literal
.size());
863 url::CanonHostInfo::Family family
= url::IPv4AddressToNumber(
864 ip_literal
.data(), host_comp
, &(*ip_number
)[0], &num_components
);
865 return family
== url::CanonHostInfo::IPV4
;
870 const unsigned char kIPv4MappedPrefix
[] =
871 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
874 IPAddressNumber
ConvertIPv4NumberToIPv6Number(
875 const IPAddressNumber
& ipv4_number
) {
876 DCHECK(ipv4_number
.size() == 4);
878 // IPv4-mapped addresses are formed by:
879 // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>.
880 IPAddressNumber ipv6_number
;
881 ipv6_number
.reserve(16);
882 ipv6_number
.insert(ipv6_number
.end(),
884 kIPv4MappedPrefix
+ arraysize(kIPv4MappedPrefix
));
885 ipv6_number
.insert(ipv6_number
.end(), ipv4_number
.begin(), ipv4_number
.end());
889 bool IsIPv4Mapped(const IPAddressNumber
& address
) {
890 if (address
.size() != kIPv6AddressSize
)
892 return std::equal(address
.begin(),
893 address
.begin() + arraysize(kIPv4MappedPrefix
),
897 IPAddressNumber
ConvertIPv4MappedToIPv4(const IPAddressNumber
& address
) {
898 DCHECK(IsIPv4Mapped(address
));
899 return IPAddressNumber(address
.begin() + arraysize(kIPv4MappedPrefix
),
903 bool ParseCIDRBlock(const std::string
& cidr_literal
,
904 IPAddressNumber
* ip_number
,
905 size_t* prefix_length_in_bits
) {
906 // We expect CIDR notation to match one of these two templates:
907 // <IPv4-literal> "/" <number of bits>
908 // <IPv6-literal> "/" <number of bits>
910 std::vector
<std::string
> parts
;
911 base::SplitString(cidr_literal
, '/', &parts
);
912 if (parts
.size() != 2)
915 // Parse the IP address.
916 if (!ParseIPLiteralToNumber(parts
[0], ip_number
))
919 // Parse the prefix length.
920 int number_of_bits
= -1;
921 if (!base::StringToInt(parts
[1], &number_of_bits
))
924 // Make sure the prefix length is in a valid range.
925 if (number_of_bits
< 0 ||
926 number_of_bits
> static_cast<int>(ip_number
->size() * 8))
929 *prefix_length_in_bits
= static_cast<size_t>(number_of_bits
);
933 bool IPNumberMatchesPrefix(const IPAddressNumber
& ip_number
,
934 const IPAddressNumber
& ip_prefix
,
935 size_t prefix_length_in_bits
) {
936 // Both the input IP address and the prefix IP address should be
937 // either IPv4 or IPv6.
938 DCHECK(ip_number
.size() == 4 || ip_number
.size() == 16);
939 DCHECK(ip_prefix
.size() == 4 || ip_prefix
.size() == 16);
941 DCHECK_LE(prefix_length_in_bits
, ip_prefix
.size() * 8);
943 // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to
944 // IPv6 addresses in order to do the comparison.
945 if (ip_number
.size() != ip_prefix
.size()) {
946 if (ip_number
.size() == 4) {
947 return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number
),
948 ip_prefix
, prefix_length_in_bits
);
950 return IPNumberMatchesPrefix(ip_number
,
951 ConvertIPv4NumberToIPv6Number(ip_prefix
),
952 96 + prefix_length_in_bits
);
955 return IPNumberPrefixCheck(ip_number
, &ip_prefix
[0], prefix_length_in_bits
);
958 const uint16
* GetPortFieldFromSockaddr(const struct sockaddr
* address
,
959 socklen_t address_len
) {
960 if (address
->sa_family
== AF_INET
) {
961 DCHECK_LE(sizeof(sockaddr_in
), static_cast<size_t>(address_len
));
962 const struct sockaddr_in
* sockaddr
=
963 reinterpret_cast<const struct sockaddr_in
*>(address
);
964 return &sockaddr
->sin_port
;
965 } else if (address
->sa_family
== AF_INET6
) {
966 DCHECK_LE(sizeof(sockaddr_in6
), static_cast<size_t>(address_len
));
967 const struct sockaddr_in6
* sockaddr
=
968 reinterpret_cast<const struct sockaddr_in6
*>(address
);
969 return &sockaddr
->sin6_port
;
976 int GetPortFromSockaddr(const struct sockaddr
* address
, socklen_t address_len
) {
977 const uint16
* port_field
= GetPortFieldFromSockaddr(address
, address_len
);
980 return base::NetToHost16(*port_field
);
983 bool IsLocalhost(const std::string
& host
) {
984 if (host
== "localhost" || host
== "localhost.localdomain" ||
985 host
== "localhost6" || host
== "localhost6.localdomain6" ||
986 IsLocalhostTLD(host
))
989 IPAddressNumber ip_number
;
990 if (ParseIPLiteralToNumber(host
, &ip_number
)) {
991 size_t size
= ip_number
.size();
993 case kIPv4AddressSize
: {
994 IPAddressNumber localhost_prefix
;
995 localhost_prefix
.push_back(127);
996 for (int i
= 0; i
< 3; ++i
) {
997 localhost_prefix
.push_back(0);
999 return IPNumberMatchesPrefix(ip_number
, localhost_prefix
, 8);
1002 case kIPv6AddressSize
: {
1003 struct in6_addr sin6_addr
;
1004 memcpy(&sin6_addr
, &ip_number
[0], kIPv6AddressSize
);
1005 return !!IN6_IS_ADDR_LOOPBACK(&sin6_addr
);
1016 bool IsLocalhostTLD(const std::string
& host
) {
1017 const char kLocalhostTLD
[] = ".localhost";
1018 const size_t kLocalhostTLDLength
= arraysize(kLocalhostTLD
) - 1;
1023 size_t host_len
= host
.size();
1024 if (*host
.rbegin() == '.')
1026 if (host_len
< kLocalhostTLDLength
)
1029 const char* host_suffix
= host
.data() + host_len
- kLocalhostTLDLength
;
1030 return base::strncasecmp(host_suffix
, kLocalhostTLD
, kLocalhostTLDLength
) ==
1034 NetworkInterface::NetworkInterface()
1035 : type(NetworkChangeNotifier::CONNECTION_UNKNOWN
), prefix_length(0) {
1038 NetworkInterface::NetworkInterface(const std::string
& name
,
1039 const std::string
& friendly_name
,
1040 uint32 interface_index
,
1041 NetworkChangeNotifier::ConnectionType type
,
1042 const IPAddressNumber
& address
,
1043 uint32 prefix_length
,
1044 int ip_address_attributes
)
1046 friendly_name(friendly_name
),
1047 interface_index(interface_index
),
1050 prefix_length(prefix_length
),
1051 ip_address_attributes(ip_address_attributes
) {
1054 NetworkInterface::~NetworkInterface() {
1057 unsigned CommonPrefixLength(const IPAddressNumber
& a1
,
1058 const IPAddressNumber
& a2
) {
1059 DCHECK_EQ(a1
.size(), a2
.size());
1060 for (size_t i
= 0; i
< a1
.size(); ++i
) {
1061 unsigned diff
= a1
[i
] ^ a2
[i
];
1064 for (unsigned j
= 0; j
< CHAR_BIT
; ++j
) {
1065 if (diff
& (1 << (CHAR_BIT
- 1)))
1066 return i
* CHAR_BIT
+ j
;
1071 return a1
.size() * CHAR_BIT
;
1074 unsigned MaskPrefixLength(const IPAddressNumber
& mask
) {
1075 IPAddressNumber
all_ones(mask
.size(), 0xFF);
1076 return CommonPrefixLength(mask
, all_ones
);
1079 ScopedWifiOptions::~ScopedWifiOptions() {