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"
11 #include "base/files/file_path.h"
12 #include "base/format_macros.h"
13 #include "base/scoped_native_library.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/sys_byteorder.h"
19 #include "base/time/time.h"
20 #include "net/base/ip_endpoint.h"
22 #if !defined(OS_NACL) && !defined(OS_WIN)
24 #include <netinet/in.h>
25 #if defined(OS_MACOSX)
28 #include <netinet/in_var.h>
31 #endif // !OS_NACL && !OS_WIN
32 #include "testing/gtest/include/gtest/gtest.h"
38 #include "base/win/windows_version.h"
41 #if !defined(OS_MACOSX) && !defined(OS_NACL) && !defined(OS_WIN)
42 #include "net/base/address_tracker_linux.h"
43 #endif // !OS_MACOSX && !OS_NACL && !OS_WIN
46 #include "net/base/net_util_win.h"
48 #include "net/base/net_util_posix.h"
49 #if defined(OS_MACOSX)
50 #include "net/base/net_util_mac.h"
52 #include "net/base/net_util_linux.h"
56 using base::ASCIIToUTF16
;
57 using base::WideToUTF16
;
64 const char* const header_name
;
65 const char* const expected
;
68 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)
69 const char kWiFiSSID
[] = "TestWiFi";
70 const char kInterfaceWithDifferentSSID
[] = "wlan999";
72 std::string
TestGetInterfaceSSID(const std::string
& ifname
) {
73 return (ifname
== kInterfaceWithDifferentSSID
) ? "AnotherSSID" : kWiFiSSID
;
77 // Fills in sockaddr for the given 32-bit address (IPv4.)
78 // |bytes| should be an array of length 4.
79 void MakeIPv4Address(const uint8
* bytes
, int port
, SockaddrStorage
* storage
) {
80 memset(&storage
->addr_storage
, 0, sizeof(storage
->addr_storage
));
81 storage
->addr_len
= sizeof(struct sockaddr_in
);
82 struct sockaddr_in
* addr4
= reinterpret_cast<sockaddr_in
*>(storage
->addr
);
83 addr4
->sin_port
= base::HostToNet16(port
);
84 addr4
->sin_family
= AF_INET
;
85 memcpy(&addr4
->sin_addr
, bytes
, 4);
88 // Fills in sockaddr for the given 128-bit address (IPv6.)
89 // |bytes| should be an array of length 16.
90 void MakeIPv6Address(const uint8
* bytes
, int port
, SockaddrStorage
* storage
) {
91 memset(&storage
->addr_storage
, 0, sizeof(storage
->addr_storage
));
92 storage
->addr_len
= sizeof(struct sockaddr_in6
);
93 struct sockaddr_in6
* addr6
= reinterpret_cast<sockaddr_in6
*>(storage
->addr
);
94 addr6
->sin6_port
= base::HostToNet16(port
);
95 addr6
->sin6_family
= AF_INET6
;
96 memcpy(&addr6
->sin6_addr
, bytes
, 16);
99 // Helper to strignize an IP number (used to define expectations).
100 std::string
DumpIPNumber(const IPAddressNumber
& v
) {
102 for (size_t i
= 0; i
< v
.size(); ++i
) {
105 out
.append(base::IntToString(static_cast<int>(v
[i
])));
110 #if defined(OS_MACOSX)
111 class IPAttributesGetterTest
: public internal::IPAttributesGetterMac
{
113 IPAttributesGetterTest() : native_attributes_(0) {}
114 bool IsInitialized() const override
{ return true; }
115 bool GetIPAttributes(const char* ifname
,
116 const sockaddr
* sock_addr
,
117 int* native_attributes
) override
{
118 *native_attributes
= native_attributes_
;
121 void set_native_attributes(int native_attributes
) {
122 native_attributes_
= native_attributes
;
126 int native_attributes_
;
129 // Helper function to create a single valid ifaddrs
130 bool FillIfaddrs(ifaddrs
* interfaces
,
133 const IPAddressNumber
& ip_address
,
134 const IPAddressNumber
& ip_netmask
,
135 sockaddr_storage sock_addrs
[2]) {
136 interfaces
->ifa_next
= NULL
;
137 interfaces
->ifa_name
= const_cast<char*>(ifname
);
138 interfaces
->ifa_flags
= flags
;
140 socklen_t sock_len
= sizeof(sockaddr_storage
);
142 // Convert to sockaddr for next check.
143 if (!IPEndPoint(ip_address
, 0)
144 .ToSockAddr(reinterpret_cast<sockaddr
*>(&sock_addrs
[0]),
148 interfaces
->ifa_addr
= reinterpret_cast<sockaddr
*>(&sock_addrs
[0]);
150 sock_len
= sizeof(sockaddr_storage
);
151 if (!IPEndPoint(ip_netmask
, 0)
152 .ToSockAddr(reinterpret_cast<sockaddr
*>(&sock_addrs
[1]),
156 interfaces
->ifa_netmask
= reinterpret_cast<sockaddr
*>(&sock_addrs
[1]);
162 } // anonymous namespace
164 TEST(NetUtilTest
, GetIdentityFromURL
) {
166 const char* const input_url
;
167 const char* const expected_username
;
168 const char* const expected_password
;
171 "http://username:password@google.com",
175 { // Test for http://crbug.com/19200
176 "http://username:p@ssword@google.com",
180 { // Special URL characters should be unescaped.
181 "http://username:p%3fa%26s%2fs%23@google.com",
185 { // Username contains %20.
186 "http://use rname:password@google.com",
191 "http://use%00rname:password@google.com",
195 { // Use a '+' in the username.
196 "http://use+rname:password@google.com",
200 { // Use a '&' in the password.
201 "http://username:p&ssword@google.com",
206 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
207 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS
"]: %s", i
,
208 tests
[i
].input_url
));
209 GURL
url(tests
[i
].input_url
);
211 base::string16 username
, password
;
212 GetIdentityFromURL(url
, &username
, &password
);
214 EXPECT_EQ(ASCIIToUTF16(tests
[i
].expected_username
), username
);
215 EXPECT_EQ(ASCIIToUTF16(tests
[i
].expected_password
), password
);
219 // Try extracting a username which was encoded with UTF8.
220 TEST(NetUtilTest
, GetIdentityFromURL_UTF8
) {
221 GURL
url(WideToUTF16(L
"http://foo:\x4f60\x597d@blah.com"));
223 EXPECT_EQ("foo", url
.username());
224 EXPECT_EQ("%E4%BD%A0%E5%A5%BD", url
.password());
226 // Extract the unescaped identity.
227 base::string16 username
, password
;
228 GetIdentityFromURL(url
, &username
, &password
);
230 // Verify that it was decoded as UTF8.
231 EXPECT_EQ(ASCIIToUTF16("foo"), username
);
232 EXPECT_EQ(WideToUTF16(L
"\x4f60\x597d"), password
);
235 // Just a bunch of fake headers.
236 const char google_headers
[] =
238 "Content-TYPE: text/html; charset=utf-8\n"
239 "Content-disposition: attachment; filename=\"download.pdf\"\n"
240 "Content-Length: 378557\n"
241 "X-Google-Google1: 314159265\n"
242 "X-Google-Google2: aaaa2:7783,bbb21:9441\n"
243 "X-Google-Google4: home\n"
244 "Transfer-Encoding: chunked\n"
245 "Set-Cookie: HEHE_AT=6666x66beef666x6-66xx6666x66; Path=/mail\n"
246 "Set-Cookie: HEHE_HELP=owned:0;Path=/\n"
247 "Set-Cookie: S=gmail=Xxx-beefbeefbeef_beefb:gmail_yj=beefbeef000beefbee"
248 "fbee:gmproxy=bee-fbeefbe; Domain=.google.com; Path=/\n"
249 "X-Google-Google2: /one/two/three/four/five/six/seven-height/nine:9411\n"
251 "Transfer-Encoding: chunked\n"
252 "Date: Mon, 13 Nov 2006 21:38:09 GMT\n"
253 "Expires: Tue, 14 Nov 2006 19:23:58 GMT\n"
254 "X-Malformed: bla; arg=test\"\n"
255 "X-Malformed2: bla; arg=\n"
256 "X-Test: bla; arg1=val1; arg2=val2";
258 TEST(NetUtilTest
, GetSpecificHeader
) {
259 const HeaderCase tests
[] = {
260 {"content-type", "text/html; charset=utf-8"},
261 {"CONTENT-LENGTH", "378557"},
262 {"Date", "Mon, 13 Nov 2006 21:38:09 GMT"},
267 // Test first with google_headers.
268 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
270 GetSpecificHeader(google_headers
, tests
[i
].header_name
);
271 EXPECT_EQ(result
, tests
[i
].expected
);
274 // Test again with empty headers.
275 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
276 std::string result
= GetSpecificHeader(std::string(), tests
[i
].header_name
);
277 EXPECT_EQ(result
, std::string());
281 TEST(NetUtilTest
, CompliantHost
) {
282 struct CompliantHostCase
{
283 const char* const host
;
284 bool expected_output
;
287 const CompliantHostCase compliant_host_cases
[] = {
309 {"1.2.3.4.5.", true},
312 for (size_t i
= 0; i
< arraysize(compliant_host_cases
); ++i
) {
313 EXPECT_EQ(compliant_host_cases
[i
].expected_output
,
314 IsCanonicalizedHostCompliant(compliant_host_cases
[i
].host
));
318 TEST(NetUtilTest
, ParseHostAndPort
) {
320 const char* const input
;
322 const char* const expected_host
;
326 {"foo:10", true, "foo", 10},
327 {"foo", true, "foo", -1},
329 "[1080:0:0:0:8:800:200C:4171]:11",
331 "1080:0:0:0:8:800:200C:4171",
335 "[1080:0:0:0:8:800:200C:4171]",
337 "1080:0:0:0:8:800:200C:4171",
341 // Because no validation is done on the host, the following are accepted,
342 // even though they are invalid names.
343 {"]", true, "]", -1},
344 {"::1", true, ":", 1},
346 {"foo:bar", false, "", -1},
347 {"foo:", false, "", -1},
348 {":", false, "", -1},
349 {":80", false, "", -1},
351 {"porttoolong:300000", false, "", -1},
352 {"usrname@host", false, "", -1},
353 {"usrname:password@host", false, "", -1},
354 {":password@host", false, "", -1},
355 {":password@host:80", false, "", -1},
356 {":password@host", false, "", -1},
357 {"@host", false, "", -1},
358 {"[", false, "", -1},
359 {"[]", false, "", -1},
362 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
365 bool ok
= ParseHostAndPort(tests
[i
].input
, &host
, &port
);
367 EXPECT_EQ(tests
[i
].success
, ok
);
369 if (tests
[i
].success
) {
370 EXPECT_EQ(tests
[i
].expected_host
, host
);
371 EXPECT_EQ(tests
[i
].expected_port
, port
);
376 TEST(NetUtilTest
, GetHostAndPort
) {
379 const char* const expected_host_and_port
;
381 { GURL("http://www.foo.com/x"), "www.foo.com:80"},
382 { GURL("http://www.foo.com:21/x"), "www.foo.com:21"},
384 // For IPv6 literals should always include the brackets.
385 { GURL("http://[1::2]/x"), "[1::2]:80"},
386 { GURL("http://[::a]:33/x"), "[::a]:33"},
388 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
389 std::string host_and_port
= GetHostAndPort(tests
[i
].url
);
390 EXPECT_EQ(std::string(tests
[i
].expected_host_and_port
), host_and_port
);
394 TEST(NetUtilTest
, GetHostAndOptionalPort
) {
397 const char* const expected_host_and_port
;
399 { GURL("http://www.foo.com/x"), "www.foo.com"},
400 { GURL("http://www.foo.com:21/x"), "www.foo.com:21"},
402 // For IPv6 literals should always include the brackets.
403 { GURL("http://[1::2]/x"), "[1::2]"},
404 { GURL("http://[::a]:33/x"), "[::a]:33"},
406 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
407 std::string host_and_port
= GetHostAndOptionalPort(tests
[i
].url
);
408 EXPECT_EQ(std::string(tests
[i
].expected_host_and_port
), host_and_port
);
412 TEST(NetUtilTest
, IPAddressToString
) {
413 uint8 addr1
[4] = {0, 0, 0, 0};
414 EXPECT_EQ("0.0.0.0", IPAddressToString(addr1
, sizeof(addr1
)));
416 uint8 addr2
[4] = {192, 168, 0, 1};
417 EXPECT_EQ("192.168.0.1", IPAddressToString(addr2
, sizeof(addr2
)));
419 uint8 addr3
[16] = {0xFE, 0xDC, 0xBA, 0x98};
420 EXPECT_EQ("fedc:ba98::", IPAddressToString(addr3
, sizeof(addr3
)));
423 TEST(NetUtilTest
, IPAddressToStringWithPort
) {
424 uint8 addr1
[4] = {0, 0, 0, 0};
425 EXPECT_EQ("0.0.0.0:3", IPAddressToStringWithPort(addr1
, sizeof(addr1
), 3));
427 uint8 addr2
[4] = {192, 168, 0, 1};
428 EXPECT_EQ("192.168.0.1:99",
429 IPAddressToStringWithPort(addr2
, sizeof(addr2
), 99));
431 uint8 addr3
[16] = {0xFE, 0xDC, 0xBA, 0x98};
432 EXPECT_EQ("[fedc:ba98::]:8080",
433 IPAddressToStringWithPort(addr3
, sizeof(addr3
), 8080));
436 TEST(NetUtilTest
, NetAddressToString_IPv4
) {
439 const char* const result
;
441 {{0, 0, 0, 0}, "0.0.0.0"},
442 {{127, 0, 0, 1}, "127.0.0.1"},
443 {{192, 168, 0, 1}, "192.168.0.1"},
446 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
447 SockaddrStorage storage
;
448 MakeIPv4Address(tests
[i
].addr
, 80, &storage
);
449 std::string result
= NetAddressToString(storage
.addr
, storage
.addr_len
);
450 EXPECT_EQ(std::string(tests
[i
].result
), result
);
454 TEST(NetUtilTest
, NetAddressToString_IPv6
) {
457 const char* const result
;
459 {{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA,
460 0x98, 0x76, 0x54, 0x32, 0x10},
461 "fedc:ba98:7654:3210:fedc:ba98:7654:3210"},
464 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
465 SockaddrStorage storage
;
466 MakeIPv6Address(tests
[i
].addr
, 80, &storage
);
467 EXPECT_EQ(std::string(tests
[i
].result
),
468 NetAddressToString(storage
.addr
, storage
.addr_len
));
472 TEST(NetUtilTest
, NetAddressToStringWithPort_IPv4
) {
473 uint8 addr
[] = {127, 0, 0, 1};
474 SockaddrStorage storage
;
475 MakeIPv4Address(addr
, 166, &storage
);
476 std::string result
= NetAddressToStringWithPort(storage
.addr
,
478 EXPECT_EQ("127.0.0.1:166", result
);
481 TEST(NetUtilTest
, NetAddressToStringWithPort_IPv6
) {
483 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA,
484 0x98, 0x76, 0x54, 0x32, 0x10
486 SockaddrStorage storage
;
487 MakeIPv6Address(addr
, 361, &storage
);
488 std::string result
= NetAddressToStringWithPort(storage
.addr
,
491 // May fail on systems that don't support IPv6.
493 EXPECT_EQ("[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:361", result
);
496 TEST(NetUtilTest
, GetHostName
) {
497 // We can't check the result of GetHostName() directly, since the result
498 // will differ across machines. Our goal here is to simply exercise the
499 // code path, and check that things "look about right".
500 std::string hostname
= GetHostName();
501 EXPECT_FALSE(hostname
.empty());
504 TEST(NetUtilTest
, SimplifyUrlForRequest
) {
506 const char* const input_url
;
507 const char* const expected_simplified_url
;
510 // Reference section should be stripped.
511 "http://www.google.com:78/foobar?query=1#hash",
512 "http://www.google.com:78/foobar?query=1",
515 // Reference section can itself contain #.
516 "http://192.168.0.1?query=1#hash#10#11#13#14",
517 "http://192.168.0.1?query=1",
519 { // Strip username/password.
520 "http://user:pass@google.com",
521 "http://google.com/",
523 { // Strip both the reference and the username/password.
524 "http://user:pass@google.com:80/sup?yo#X#X",
525 "http://google.com/sup?yo",
527 { // Try an HTTPS URL -- strip both the reference and the username/password.
528 "https://user:pass@google.com:80/sup?yo#X#X",
529 "https://google.com:80/sup?yo",
531 { // Try an FTP URL -- strip both the reference and the username/password.
532 "ftp://user:pass@google.com:80/sup?yo#X#X",
533 "ftp://google.com:80/sup?yo",
535 { // Try a nonstandard URL
536 "foobar://user:pass@google.com:80/sup?yo#X#X",
537 "foobar://user:pass@google.com:80/sup?yo",
540 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
541 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS
"]: %s", i
,
542 tests
[i
].input_url
));
543 GURL
input_url(GURL(tests
[i
].input_url
));
544 GURL
expected_url(GURL(tests
[i
].expected_simplified_url
));
545 EXPECT_EQ(expected_url
, SimplifyUrlForRequest(input_url
));
549 TEST(NetUtilTest
, SetExplicitlyAllowedPortsTest
) {
550 std::string invalid
[] = { "1,2,a", "'1','2'", "1, 2, 3", "1 0,11,12" };
551 std::string valid
[] = { "", "1", "1,2", "1,2,3", "10,11,12,13" };
553 for (size_t i
= 0; i
< arraysize(invalid
); ++i
) {
554 SetExplicitlyAllowedPorts(invalid
[i
]);
555 EXPECT_EQ(0, static_cast<int>(GetCountOfExplicitlyAllowedPorts()));
558 for (size_t i
= 0; i
< arraysize(valid
); ++i
) {
559 SetExplicitlyAllowedPorts(valid
[i
]);
560 EXPECT_EQ(i
, GetCountOfExplicitlyAllowedPorts());
564 TEST(NetUtilTest
, GetHostOrSpecFromURL
) {
565 EXPECT_EQ("example.com",
566 GetHostOrSpecFromURL(GURL("http://example.com/test")));
567 EXPECT_EQ("example.com",
568 GetHostOrSpecFromURL(GURL("http://example.com./test")));
569 EXPECT_EQ("file:///tmp/test.html",
570 GetHostOrSpecFromURL(GURL("file:///tmp/test.html")));
573 TEST(NetUtilTest
, GetAddressFamily
) {
574 IPAddressNumber number
;
575 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &number
));
576 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, GetAddressFamily(number
));
577 EXPECT_TRUE(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number
));
578 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, GetAddressFamily(number
));
581 // Test that invalid IP literals fail to parse.
582 TEST(NetUtilTest
, ParseIPLiteralToNumber_FailParse
) {
583 IPAddressNumber number
;
585 EXPECT_FALSE(ParseIPLiteralToNumber("bad value", &number
));
586 EXPECT_FALSE(ParseIPLiteralToNumber("bad:value", &number
));
587 EXPECT_FALSE(ParseIPLiteralToNumber(std::string(), &number
));
588 EXPECT_FALSE(ParseIPLiteralToNumber("192.168.0.1:30", &number
));
589 EXPECT_FALSE(ParseIPLiteralToNumber(" 192.168.0.1 ", &number
));
590 EXPECT_FALSE(ParseIPLiteralToNumber("[::1]", &number
));
593 // Test parsing an IPv4 literal.
594 TEST(NetUtilTest
, ParseIPLiteralToNumber_IPv4
) {
595 IPAddressNumber number
;
596 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &number
));
597 EXPECT_EQ("192,168,0,1", DumpIPNumber(number
));
598 EXPECT_EQ("192.168.0.1", IPAddressToString(number
));
601 // Test parsing an IPv6 literal.
602 TEST(NetUtilTest
, ParseIPLiteralToNumber_IPv6
) {
603 IPAddressNumber number
;
604 EXPECT_TRUE(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number
));
605 EXPECT_EQ("0,1,171,205,0,0,0,0,0,0,0,3,0,4,0,255", DumpIPNumber(number
));
606 EXPECT_EQ("1:abcd::3:4:ff", IPAddressToString(number
));
609 // Test mapping an IPv4 address to an IPv6 address.
610 TEST(NetUtilTest
, ConvertIPv4NumberToIPv6Number
) {
611 IPAddressNumber ipv4_number
;
612 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number
));
614 IPAddressNumber ipv6_number
=
615 ConvertIPv4NumberToIPv6Number(ipv4_number
);
617 // ::ffff:192.168.0.1
618 EXPECT_EQ("0,0,0,0,0,0,0,0,0,0,255,255,192,168,0,1",
619 DumpIPNumber(ipv6_number
));
620 EXPECT_EQ("::ffff:c0a8:1", IPAddressToString(ipv6_number
));
623 TEST(NetUtilTest
, ParseURLHostnameToNumber_FailParse
) {
624 IPAddressNumber number
;
626 EXPECT_FALSE(ParseURLHostnameToNumber("bad value", &number
));
627 EXPECT_FALSE(ParseURLHostnameToNumber("bad:value", &number
));
628 EXPECT_FALSE(ParseURLHostnameToNumber(std::string(), &number
));
629 EXPECT_FALSE(ParseURLHostnameToNumber("192.168.0.1:30", &number
));
630 EXPECT_FALSE(ParseURLHostnameToNumber(" 192.168.0.1 ", &number
));
631 EXPECT_FALSE(ParseURLHostnameToNumber("::1", &number
));
634 TEST(NetUtilTest
, ParseURLHostnameToNumber_IPv4
) {
635 IPAddressNumber number
;
636 EXPECT_TRUE(ParseURLHostnameToNumber("192.168.0.1", &number
));
637 EXPECT_EQ("192,168,0,1", DumpIPNumber(number
));
638 EXPECT_EQ("192.168.0.1", IPAddressToString(number
));
641 TEST(NetUtilTest
, ParseURLHostnameToNumber_IPv6
) {
642 IPAddressNumber number
;
643 EXPECT_TRUE(ParseURLHostnameToNumber("[1:abcd::3:4:ff]", &number
));
644 EXPECT_EQ("0,1,171,205,0,0,0,0,0,0,0,3,0,4,0,255", DumpIPNumber(number
));
645 EXPECT_EQ("1:abcd::3:4:ff", IPAddressToString(number
));
648 TEST(NetUtilTest
, IsIPv4Mapped
) {
649 IPAddressNumber ipv4_number
;
650 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number
));
651 EXPECT_FALSE(IsIPv4Mapped(ipv4_number
));
653 IPAddressNumber ipv6_number
;
654 EXPECT_TRUE(ParseIPLiteralToNumber("::1", &ipv4_number
));
655 EXPECT_FALSE(IsIPv4Mapped(ipv6_number
));
657 IPAddressNumber ipv4mapped_number
;
658 EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number
));
659 EXPECT_TRUE(IsIPv4Mapped(ipv4mapped_number
));
662 TEST(NetUtilTest
, ConvertIPv4MappedToIPv4
) {
663 IPAddressNumber ipv4mapped_number
;
664 EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number
));
665 IPAddressNumber expected
;
666 EXPECT_TRUE(ParseIPLiteralToNumber("1.1.0.1", &expected
));
667 IPAddressNumber result
= ConvertIPv4MappedToIPv4(ipv4mapped_number
);
668 EXPECT_EQ(expected
, result
);
671 // Test parsing invalid CIDR notation literals.
672 TEST(NetUtilTest
, ParseCIDRBlock_Invalid
) {
673 const char* const bad_literals
[] = {
689 for (size_t i
= 0; i
< arraysize(bad_literals
); ++i
) {
690 IPAddressNumber ip_number
;
691 size_t prefix_length_in_bits
;
693 EXPECT_FALSE(ParseCIDRBlock(bad_literals
[i
],
695 &prefix_length_in_bits
));
699 // Test parsing a valid CIDR notation literal.
700 TEST(NetUtilTest
, ParseCIDRBlock_Valid
) {
701 IPAddressNumber ip_number
;
702 size_t prefix_length_in_bits
;
704 EXPECT_TRUE(ParseCIDRBlock("192.168.0.1/11",
706 &prefix_length_in_bits
));
708 EXPECT_EQ("192,168,0,1", DumpIPNumber(ip_number
));
709 EXPECT_EQ(11u, prefix_length_in_bits
);
712 TEST(NetUtilTest
, IPNumberMatchesPrefix
) {
714 const char* const cidr_literal
;
715 const char* const ip_literal
;
716 bool expected_to_match
;
718 // IPv4 prefix with IPv4 inputs.
735 // IPv6 prefix with IPv6 inputs.
747 // IPv6 prefix with IPv4 inputs.
754 "::ffff:192.168.0.1/112",
759 // IPv4 prefix with IPv6 inputs.
767 "::ffff:10.12.33.44",
771 for (size_t i
= 0; i
< arraysize(tests
); ++i
) {
772 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS
"]: %s, %s", i
,
773 tests
[i
].cidr_literal
,
774 tests
[i
].ip_literal
));
776 IPAddressNumber ip_number
;
777 EXPECT_TRUE(ParseIPLiteralToNumber(tests
[i
].ip_literal
, &ip_number
));
779 IPAddressNumber ip_prefix
;
780 size_t prefix_length_in_bits
;
782 EXPECT_TRUE(ParseCIDRBlock(tests
[i
].cidr_literal
,
784 &prefix_length_in_bits
));
786 EXPECT_EQ(tests
[i
].expected_to_match
,
787 IPNumberMatchesPrefix(ip_number
,
789 prefix_length_in_bits
));
793 TEST(NetUtilTest
, IsLocalhost
) {
794 EXPECT_TRUE(net::IsLocalhost("localhost"));
795 EXPECT_TRUE(net::IsLocalhost("localhost.localdomain"));
796 EXPECT_TRUE(net::IsLocalhost("localhost6"));
797 EXPECT_TRUE(net::IsLocalhost("localhost6.localdomain6"));
798 EXPECT_TRUE(net::IsLocalhost("127.0.0.1"));
799 EXPECT_TRUE(net::IsLocalhost("127.0.1.0"));
800 EXPECT_TRUE(net::IsLocalhost("127.1.0.0"));
801 EXPECT_TRUE(net::IsLocalhost("127.0.0.255"));
802 EXPECT_TRUE(net::IsLocalhost("127.0.255.0"));
803 EXPECT_TRUE(net::IsLocalhost("127.255.0.0"));
804 EXPECT_TRUE(net::IsLocalhost("::1"));
805 EXPECT_TRUE(net::IsLocalhost("0:0:0:0:0:0:0:1"));
807 EXPECT_FALSE(net::IsLocalhost("localhostx"));
808 EXPECT_FALSE(net::IsLocalhost("foo.localdomain"));
809 EXPECT_FALSE(net::IsLocalhost("localhost6x"));
810 EXPECT_FALSE(net::IsLocalhost("localhost.localdomain6"));
811 EXPECT_FALSE(net::IsLocalhost("localhost6.localdomain"));
812 EXPECT_FALSE(net::IsLocalhost("127.0.0.1.1"));
813 EXPECT_FALSE(net::IsLocalhost(".127.0.0.255"));
814 EXPECT_FALSE(net::IsLocalhost("::2"));
815 EXPECT_FALSE(net::IsLocalhost("::1:1"));
816 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:1:0:0:1"));
817 EXPECT_FALSE(net::IsLocalhost("::1:1"));
818 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:0:0:0:0:1"));
821 // Verify GetNetworkList().
822 TEST(NetUtilTest
, GetNetworkList
) {
823 NetworkInterfaceList list
;
824 ASSERT_TRUE(GetNetworkList(&list
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
));
825 for (NetworkInterfaceList::iterator it
= list
.begin();
826 it
!= list
.end(); ++it
) {
827 // Verify that the names are not empty.
828 EXPECT_FALSE(it
->name
.empty());
829 EXPECT_FALSE(it
->friendly_name
.empty());
831 // Verify that the address is correct.
832 EXPECT_TRUE(it
->address
.size() == kIPv4AddressSize
||
833 it
->address
.size() == kIPv6AddressSize
)
834 << "Invalid address of size " << it
->address
.size();
835 bool all_zeroes
= true;
836 for (size_t i
= 0; i
< it
->address
.size(); ++i
) {
837 if (it
->address
[i
] != 0) {
842 EXPECT_FALSE(all_zeroes
);
843 EXPECT_GT(it
->prefix_length
, 1u);
844 EXPECT_LE(it
->prefix_length
, it
->address
.size() * 8);
847 // On Windows |name| is NET_LUID.
848 base::ScopedNativeLibrary
phlpapi_lib(
849 base::FilePath(FILE_PATH_LITERAL("iphlpapi.dll")));
850 ASSERT_TRUE(phlpapi_lib
.is_valid());
851 typedef NETIO_STATUS (WINAPI
* ConvertInterfaceIndexToLuid
)(NET_IFINDEX
,
853 ConvertInterfaceIndexToLuid interface_to_luid
=
854 reinterpret_cast<ConvertInterfaceIndexToLuid
>(
855 phlpapi_lib
.GetFunctionPointer("ConvertInterfaceIndexToLuid"));
857 typedef NETIO_STATUS (WINAPI
* ConvertInterfaceLuidToGuid
)(NET_LUID
*,
859 ConvertInterfaceLuidToGuid luid_to_guid
=
860 reinterpret_cast<ConvertInterfaceLuidToGuid
>(
861 phlpapi_lib
.GetFunctionPointer("ConvertInterfaceLuidToGuid"));
863 if (interface_to_luid
&& luid_to_guid
) {
865 EXPECT_EQ(interface_to_luid(it
->interface_index
, &luid
), NO_ERROR
);
867 EXPECT_EQ(luid_to_guid(&luid
, &guid
), NO_ERROR
);
869 StringFromCLSID(guid
, &name
);
870 EXPECT_STREQ(base::UTF8ToWide(it
->name
).c_str(), name
);
874 EXPECT_LT(base::win::GetVersion(), base::win::VERSION_VISTA
);
875 EXPECT_LT(it
->interface_index
, 1u << 24u); // Must fit 0.x.x.x.
876 EXPECT_NE(it
->interface_index
, 0u); // 0 means to use default.
878 if (it
->type
== NetworkChangeNotifier::CONNECTION_WIFI
) {
879 EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE
, GetWifiPHYLayerProtocol());
881 #elif !defined(OS_ANDROID)
882 char name
[IF_NAMESIZE
];
883 EXPECT_TRUE(if_indextoname(it
->interface_index
, name
));
884 EXPECT_STREQ(it
->name
.c_str(), name
);
889 static const char ifname_em1
[] = "em1";
891 static const char ifname_vm
[] = "VMnet";
893 static const char ifname_vm
[] = "vmnet";
896 static const unsigned char kIPv6LocalAddr
[] = {
897 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
899 // The following 3 addresses need to be changed together. IPv6Addr is the IPv6
900 // address. IPv6Netmask is the mask address with as many leading bits set to 1
901 // as the prefix length. IPv6AddrPrefix needs to match IPv6Addr with the same
902 // number of bits as the prefix length.
903 static const unsigned char kIPv6Addr
[] =
904 {0x24, 0x01, 0xfa, 0x00, 0x00, 0x04, 0x10, 0x00, 0xbe, 0x30, 0x5b, 0xff,
905 0xfe, 0xe5, 0x00, 0xc3};
907 static const unsigned char kIPv6AddrPrefix
[] =
908 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
909 0x00, 0x00, 0x00, 0x00};
911 #if defined(OS_MACOSX)
912 static const unsigned char kIPv6Netmask
[] =
913 {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
914 0x00, 0x00, 0x00, 0x00};
917 #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_NACL)
919 char* CopyInterfaceName(const char* ifname
, int ifname_size
, char* output
) {
920 EXPECT_LT(ifname_size
, IF_NAMESIZE
);
921 memcpy(output
, ifname
, ifname_size
);
925 char* GetInterfaceName(int interface_index
, char* ifname
) {
926 return CopyInterfaceName(ifname_em1
, arraysize(ifname_em1
), ifname
);
929 char* GetInterfaceNameVM(int interface_index
, char* ifname
) {
930 return CopyInterfaceName(ifname_vm
, arraysize(ifname_vm
), ifname
);
933 TEST(NetUtilTest
, GetNetworkListTrimming
) {
934 IPAddressNumber
ipv6_local_address(
935 kIPv6LocalAddr
, kIPv6LocalAddr
+ arraysize(kIPv6LocalAddr
));
936 IPAddressNumber
ipv6_address(kIPv6Addr
, kIPv6Addr
+ arraysize(kIPv6Addr
));
938 NetworkInterfaceList results
;
939 ::base::hash_set
<int> online_links
;
940 net::internal::AddressTrackerLinux::AddressMap address_map
;
942 // Interface 1 is offline.
943 struct ifaddrmsg msg
= {
945 1, /* prefix length */
946 IFA_F_TEMPORARY
, /* address flags */
951 // Address of offline links should be ignored.
952 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
954 net::internal::GetNetworkListImpl(&results
,
955 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
959 EXPECT_EQ(results
.size(), 0ul);
961 // Mark interface 1 online.
962 online_links
.insert(1);
964 // Local address should be trimmed out.
967 address_map
.insert(std::make_pair(ipv6_local_address
, msg
)).second
);
969 net::internal::GetNetworkListImpl(&results
,
970 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
974 EXPECT_EQ(results
.size(), 0ul);
976 // vmware address should return by default.
978 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
980 net::internal::GetNetworkListImpl(&results
,
981 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
984 GetInterfaceNameVM
));
985 EXPECT_EQ(results
.size(), 1ul);
986 EXPECT_EQ(results
[0].name
, ifname_vm
);
987 EXPECT_EQ(results
[0].prefix_length
, 1ul);
988 EXPECT_EQ(results
[0].address
, ipv6_address
);
991 // vmware address should be trimmed out if policy specified so.
993 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
995 net::internal::GetNetworkListImpl(&results
,
996 EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
999 GetInterfaceNameVM
));
1000 EXPECT_EQ(results
.size(), 0ul);
1003 // Addresses with banned attributes should be ignored.
1004 address_map
.clear();
1005 msg
.ifa_flags
= IFA_F_TENTATIVE
;
1006 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1008 net::internal::GetNetworkListImpl(&results
,
1009 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1013 EXPECT_EQ(results
.size(), 0ul);
1016 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1017 // attributes should be translated correctly.
1018 address_map
.clear();
1019 msg
.ifa_flags
= IFA_F_TEMPORARY
;
1020 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1022 net::internal::GetNetworkListImpl(&results
,
1023 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1027 EXPECT_EQ(results
.size(), 1ul);
1028 EXPECT_EQ(results
[0].name
, ifname_em1
);
1029 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1030 EXPECT_EQ(results
[0].address
, ipv6_address
);
1031 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_TEMPORARY
);
1034 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1035 // attributes should be translated correctly.
1036 address_map
.clear();
1037 msg
.ifa_flags
= IFA_F_DEPRECATED
;
1038 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1040 net::internal::GetNetworkListImpl(&results
,
1041 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1045 EXPECT_EQ(results
.size(), 1ul);
1046 EXPECT_EQ(results
[0].name
, ifname_em1
);
1047 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1048 EXPECT_EQ(results
[0].address
, ipv6_address
);
1049 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_DEPRECATED
);
1053 #elif defined(OS_MACOSX)
1055 TEST(NetUtilTest
, GetNetworkListTrimming
) {
1056 IPAddressNumber
ipv6_local_address(
1057 kIPv6LocalAddr
, kIPv6LocalAddr
+ arraysize(kIPv6LocalAddr
));
1058 IPAddressNumber
ipv6_address(kIPv6Addr
, kIPv6Addr
+ arraysize(kIPv6Addr
));
1059 IPAddressNumber
ipv6_netmask(kIPv6Netmask
,
1060 kIPv6Netmask
+ arraysize(kIPv6Netmask
));
1062 NetworkInterfaceList results
;
1063 IPAttributesGetterTest ip_attributes_getter
;
1064 sockaddr_storage addresses
[2];
1067 // Address of offline links should be ignored.
1068 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_UP
, ipv6_address
,
1069 ipv6_netmask
, addresses
));
1070 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1071 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1072 &ip_attributes_getter
));
1073 EXPECT_EQ(results
.size(), 0ul);
1075 // Local address should be trimmed out.
1076 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
,
1077 ipv6_local_address
, ipv6_netmask
, addresses
));
1078 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1079 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1080 &ip_attributes_getter
));
1081 EXPECT_EQ(results
.size(), 0ul);
1083 // vmware address should return by default.
1084 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_vm
, IFF_RUNNING
, ipv6_address
,
1085 ipv6_netmask
, addresses
));
1086 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1087 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1088 &ip_attributes_getter
));
1089 EXPECT_EQ(results
.size(), 1ul);
1090 EXPECT_EQ(results
[0].name
, ifname_vm
);
1091 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1092 EXPECT_EQ(results
[0].address
, ipv6_address
);
1095 // vmware address should be trimmed out if policy specified so.
1096 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_vm
, IFF_RUNNING
, ipv6_address
,
1097 ipv6_netmask
, addresses
));
1098 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1099 &results
, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1100 &ip_attributes_getter
));
1101 EXPECT_EQ(results
.size(), 0ul);
1104 #if !defined(OS_IOS)
1105 // Addresses with banned attributes should be ignored.
1106 ip_attributes_getter
.set_native_attributes(IN6_IFF_ANYCAST
);
1107 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
, ipv6_address
,
1108 ipv6_netmask
, addresses
));
1109 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1110 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1111 &ip_attributes_getter
));
1112 EXPECT_EQ(results
.size(), 0ul);
1115 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1116 // attributes should be translated correctly.
1117 ip_attributes_getter
.set_native_attributes(IN6_IFF_TEMPORARY
);
1118 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
, ipv6_address
,
1119 ipv6_netmask
, addresses
));
1120 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1121 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1122 &ip_attributes_getter
));
1123 EXPECT_EQ(results
.size(), 1ul);
1124 EXPECT_EQ(results
[0].name
, ifname_em1
);
1125 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1126 EXPECT_EQ(results
[0].address
, ipv6_address
);
1127 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_TEMPORARY
);
1130 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1131 // attributes should be translated correctly.
1132 ip_attributes_getter
.set_native_attributes(IN6_IFF_DEPRECATED
);
1133 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
, ipv6_address
,
1134 ipv6_netmask
, addresses
));
1135 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1136 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1137 &ip_attributes_getter
));
1138 EXPECT_EQ(results
.size(), 1ul);
1139 EXPECT_EQ(results
[0].name
, ifname_em1
);
1140 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1141 EXPECT_EQ(results
[0].address
, ipv6_address
);
1142 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_DEPRECATED
);
1146 #elif defined(OS_WIN) // !OS_MACOSX && !OS_WIN && !OS_NACL
1148 // Helper function to create a valid IP_ADAPTER_ADDRESSES with reasonable
1149 // default value. The output is the |adapter_address|. All the rests are input
1150 // to fill the |adapter_address|. |sock_addrs| are temporary storage used by
1151 // |adapter_address| once the function is returned.
1152 bool FillAdapterAddress(IP_ADAPTER_ADDRESSES
* adapter_address
,
1154 const IPAddressNumber
& ip_address
,
1155 const IPAddressNumber
& ip_netmask
,
1156 sockaddr_storage sock_addrs
[2]) {
1157 adapter_address
->AdapterName
= const_cast<char*>(ifname
);
1158 adapter_address
->FriendlyName
= const_cast<PWCHAR
>(L
"interface");
1159 adapter_address
->IfType
= IF_TYPE_ETHERNET_CSMACD
;
1160 adapter_address
->OperStatus
= IfOperStatusUp
;
1161 adapter_address
->FirstUnicastAddress
->DadState
= IpDadStatePreferred
;
1162 adapter_address
->FirstUnicastAddress
->PrefixOrigin
= IpPrefixOriginOther
;
1163 adapter_address
->FirstUnicastAddress
->SuffixOrigin
= IpSuffixOriginOther
;
1164 adapter_address
->FirstUnicastAddress
->PreferredLifetime
= 100;
1165 adapter_address
->FirstUnicastAddress
->ValidLifetime
= 1000;
1167 socklen_t sock_len
= sizeof(sockaddr_storage
);
1169 // Convert to sockaddr for next check.
1170 if (!IPEndPoint(ip_address
, 0)
1171 .ToSockAddr(reinterpret_cast<sockaddr
*>(&sock_addrs
[0]),
1175 adapter_address
->FirstUnicastAddress
->Address
.lpSockaddr
=
1176 reinterpret_cast<sockaddr
*>(&sock_addrs
[0]);
1177 adapter_address
->FirstUnicastAddress
->Address
.iSockaddrLength
= sock_len
;
1178 adapter_address
->FirstUnicastAddress
->OnLinkPrefixLength
= 1;
1180 sock_len
= sizeof(sockaddr_storage
);
1181 if (!IPEndPoint(ip_netmask
, 0)
1182 .ToSockAddr(reinterpret_cast<sockaddr
*>(&sock_addrs
[1]),
1186 adapter_address
->FirstPrefix
->Address
.lpSockaddr
=
1187 reinterpret_cast<sockaddr
*>(&sock_addrs
[1]);
1188 adapter_address
->FirstPrefix
->Address
.iSockaddrLength
= sock_len
;
1189 adapter_address
->FirstPrefix
->PrefixLength
= 1;
1191 DCHECK_EQ(sock_addrs
[0].ss_family
, sock_addrs
[1].ss_family
);
1192 if (sock_addrs
[0].ss_family
== AF_INET6
) {
1193 adapter_address
->Ipv6IfIndex
= 0;
1195 DCHECK_EQ(sock_addrs
[0].ss_family
, AF_INET
);
1196 adapter_address
->IfIndex
= 0;
1202 TEST(NetUtilTest
, GetNetworkListTrimming
) {
1203 IPAddressNumber
ipv6_local_address(
1204 kIPv6LocalAddr
, kIPv6LocalAddr
+ arraysize(kIPv6LocalAddr
));
1205 IPAddressNumber
ipv6_address(kIPv6Addr
, kIPv6Addr
+ arraysize(kIPv6Addr
));
1206 IPAddressNumber
ipv6_prefix(kIPv6AddrPrefix
,
1207 kIPv6AddrPrefix
+ arraysize(kIPv6AddrPrefix
));
1209 NetworkInterfaceList results
;
1210 sockaddr_storage addresses
[2];
1211 IP_ADAPTER_ADDRESSES adapter_address
= {0};
1212 IP_ADAPTER_UNICAST_ADDRESS address
= {0};
1213 IP_ADAPTER_PREFIX adapter_prefix
= {0};
1214 adapter_address
.FirstUnicastAddress
= &address
;
1215 adapter_address
.FirstPrefix
= &adapter_prefix
;
1217 // Address of offline links should be ignored.
1218 ASSERT_TRUE(FillAdapterAddress(
1219 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1220 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1221 addresses
/* sock_addrs */));
1222 adapter_address
.OperStatus
= IfOperStatusDown
;
1224 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1225 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1227 EXPECT_EQ(results
.size(), 0ul);
1229 // Address on loopback interface should be trimmed out.
1230 ASSERT_TRUE(FillAdapterAddress(
1231 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1232 ipv6_local_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1233 addresses
/* sock_addrs */));
1234 adapter_address
.IfType
= IF_TYPE_SOFTWARE_LOOPBACK
;
1236 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1237 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1238 EXPECT_EQ(results
.size(), 0ul);
1240 // vmware address should return by default.
1241 ASSERT_TRUE(FillAdapterAddress(
1242 &adapter_address
/* adapter_address */, ifname_vm
/* ifname */,
1243 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1244 addresses
/* sock_addrs */));
1245 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1246 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1247 EXPECT_EQ(results
.size(), 1ul);
1248 EXPECT_EQ(results
[0].name
, ifname_vm
);
1249 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1250 EXPECT_EQ(results
[0].address
, ipv6_address
);
1251 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_NONE
);
1254 // vmware address should be trimmed out if policy specified so.
1255 ASSERT_TRUE(FillAdapterAddress(
1256 &adapter_address
/* adapter_address */, ifname_vm
/* ifname */,
1257 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1258 addresses
/* sock_addrs */));
1259 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1260 &results
, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1261 EXPECT_EQ(results
.size(), 0ul);
1264 // Addresses with incompleted DAD should be ignored.
1265 ASSERT_TRUE(FillAdapterAddress(
1266 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1267 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1268 addresses
/* sock_addrs */));
1269 adapter_address
.FirstUnicastAddress
->DadState
= IpDadStateTentative
;
1271 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1272 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1273 EXPECT_EQ(results
.size(), 0ul);
1276 // Addresses with allowed attribute IpSuffixOriginRandom should be returned
1277 // and attributes should be translated correctly to
1278 // IP_ADDRESS_ATTRIBUTE_TEMPORARY.
1279 ASSERT_TRUE(FillAdapterAddress(
1280 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1281 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1282 addresses
/* sock_addrs */));
1283 adapter_address
.FirstUnicastAddress
->PrefixOrigin
=
1284 IpPrefixOriginRouterAdvertisement
;
1285 adapter_address
.FirstUnicastAddress
->SuffixOrigin
= IpSuffixOriginRandom
;
1287 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1288 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1289 EXPECT_EQ(results
.size(), 1ul);
1290 EXPECT_EQ(results
[0].name
, ifname_em1
);
1291 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1292 EXPECT_EQ(results
[0].address
, ipv6_address
);
1293 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_TEMPORARY
);
1296 // Addresses with preferred lifetime 0 should be returned and
1297 // attributes should be translated correctly to
1298 // IP_ADDRESS_ATTRIBUTE_DEPRECATED.
1299 ASSERT_TRUE(FillAdapterAddress(
1300 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1301 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1302 addresses
/* sock_addrs */));
1303 adapter_address
.FirstUnicastAddress
->PreferredLifetime
= 0;
1304 adapter_address
.FriendlyName
= const_cast<PWCHAR
>(L
"FriendlyInterfaceName");
1305 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1306 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1307 EXPECT_EQ(results
.size(), 1ul);
1308 EXPECT_EQ(results
[0].friendly_name
, "FriendlyInterfaceName");
1309 EXPECT_EQ(results
[0].name
, ifname_em1
);
1310 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1311 EXPECT_EQ(results
[0].address
, ipv6_address
);
1312 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_DEPRECATED
);
1316 #endif // !OS_MACOSX && !OS_WIN && !OS_NACL
1318 TEST(NetUtilTest
, GetWifiSSID
) {
1319 // We can't check the result of GetWifiSSID() directly, since the result
1320 // will differ across machines. Simply exercise the code path and hope that it
1322 EXPECT_NE((const char*)NULL
, GetWifiSSID().c_str());
1325 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)
1326 TEST(NetUtilTest
, GetWifiSSIDFromInterfaceList
) {
1327 NetworkInterfaceList list
;
1328 EXPECT_EQ(std::string(), net::internal::GetWifiSSIDFromInterfaceListInternal(
1329 list
, TestGetInterfaceSSID
));
1331 NetworkInterface interface1
;
1332 interface1
.name
= "wlan0";
1333 interface1
.type
= NetworkChangeNotifier::CONNECTION_WIFI
;
1334 list
.push_back(interface1
);
1335 ASSERT_EQ(1u, list
.size());
1336 EXPECT_EQ(std::string(kWiFiSSID
),
1337 net::internal::GetWifiSSIDFromInterfaceListInternal(
1338 list
, TestGetInterfaceSSID
));
1340 NetworkInterface interface2
;
1341 interface2
.name
= "wlan1";
1342 interface2
.type
= NetworkChangeNotifier::CONNECTION_WIFI
;
1343 list
.push_back(interface2
);
1344 ASSERT_EQ(2u, list
.size());
1345 EXPECT_EQ(std::string(kWiFiSSID
),
1346 net::internal::GetWifiSSIDFromInterfaceListInternal(
1347 list
, TestGetInterfaceSSID
));
1349 NetworkInterface interface3
;
1350 interface3
.name
= kInterfaceWithDifferentSSID
;
1351 interface3
.type
= NetworkChangeNotifier::CONNECTION_WIFI
;
1352 list
.push_back(interface3
);
1353 ASSERT_EQ(3u, list
.size());
1354 EXPECT_EQ(std::string(), net::internal::GetWifiSSIDFromInterfaceListInternal(
1355 list
, TestGetInterfaceSSID
));
1358 NetworkInterface interface4
;
1359 interface4
.name
= "eth0";
1360 interface4
.type
= NetworkChangeNotifier::CONNECTION_ETHERNET
;
1361 list
.push_back(interface4
);
1362 ASSERT_EQ(3u, list
.size());
1363 EXPECT_EQ(std::string(), net::internal::GetWifiSSIDFromInterfaceListInternal(
1364 list
, TestGetInterfaceSSID
));
1371 bool read_int_or_bool(DWORD data_size
,
1373 switch (data_size
) {
1375 return !!*reinterpret_cast<uint8
*>(data
);
1377 return !!*reinterpret_cast<uint32
*>(data
);
1379 LOG(FATAL
) << "That is not a type I know!";
1384 int GetWifiOptions() {
1385 const internal::WlanApi
& wlanapi
= internal::WlanApi::GetInstance();
1386 if (!wlanapi
.initialized
)
1389 internal::WlanHandle client
;
1390 DWORD cur_version
= 0;
1391 const DWORD kMaxClientVersion
= 2;
1392 DWORD result
= wlanapi
.OpenHandle(
1393 kMaxClientVersion
, &cur_version
, &client
);
1394 if (result
!= ERROR_SUCCESS
)
1397 WLAN_INTERFACE_INFO_LIST
* interface_list_ptr
= NULL
;
1398 result
= wlanapi
.enum_interfaces_func(client
.Get(), NULL
,
1399 &interface_list_ptr
);
1400 if (result
!= ERROR_SUCCESS
)
1402 scoped_ptr
<WLAN_INTERFACE_INFO_LIST
, internal::WlanApiDeleter
> interface_list(
1403 interface_list_ptr
);
1405 for (unsigned i
= 0; i
< interface_list
->dwNumberOfItems
; ++i
) {
1406 WLAN_INTERFACE_INFO
* info
= &interface_list
->InterfaceInfo
[i
];
1410 result
= wlanapi
.query_interface_func(
1412 &info
->InterfaceGuid
,
1413 wlan_intf_opcode_background_scan_enabled
,
1418 if (result
!= ERROR_SUCCESS
)
1420 if (!read_int_or_bool(data_size
, data
)) {
1421 options
|= WIFI_OPTIONS_DISABLE_SCAN
;
1423 internal::WlanApi::GetInstance().free_memory_func(data
);
1425 result
= wlanapi
.query_interface_func(
1427 &info
->InterfaceGuid
,
1428 wlan_intf_opcode_media_streaming_mode
,
1433 if (result
!= ERROR_SUCCESS
)
1435 if (read_int_or_bool(data_size
, data
)) {
1436 options
|= WIFI_OPTIONS_MEDIA_STREAMING_MODE
;
1438 internal::WlanApi::GetInstance().free_memory_func(data
);
1440 // Just the the options from the first succesful
1445 // No wifi interface found.
1451 int GetWifiOptions() {
1458 void TryChangeWifiOptions(int options
) {
1459 int previous_options
= GetWifiOptions();
1460 scoped_ptr
<ScopedWifiOptions
> scoped_options
= SetWifiOptions(options
);
1461 EXPECT_EQ(previous_options
| options
, GetWifiOptions());
1462 scoped_options
.reset();
1463 EXPECT_EQ(previous_options
, GetWifiOptions());
1468 // Test SetWifiOptions().
1469 TEST(NetUtilTest
, SetWifiOptionsTest
) {
1470 TryChangeWifiOptions(0);
1471 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN
);
1472 TryChangeWifiOptions(WIFI_OPTIONS_MEDIA_STREAMING_MODE
);
1473 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN
|
1474 WIFI_OPTIONS_MEDIA_STREAMING_MODE
);
1477 struct NonUniqueNameTestData
{
1479 const char* const hostname
;
1482 // Google Test pretty-printer.
1483 void PrintTo(const NonUniqueNameTestData
& data
, std::ostream
* os
) {
1484 ASSERT_TRUE(data
.hostname
);
1485 *os
<< " hostname: " << testing::PrintToString(data
.hostname
)
1486 << "; is_unique: " << testing::PrintToString(data
.is_unique
);
1489 const NonUniqueNameTestData kNonUniqueNameTestData
[] = {
1490 // Domains under ICANN-assigned domains.
1491 { true, "google.com" },
1492 { true, "google.co.uk" },
1493 // Domains under private registries.
1494 { true, "appspot.com" },
1495 { true, "test.appspot.com" },
1496 // Unreserved IPv4 addresses (in various forms).
1497 { true, "8.8.8.8" },
1498 { true, "99.64.0.0" },
1499 { true, "212.15.0.0" },
1501 { true, "212.15.0" },
1502 { true, "3557752832" },
1503 // Reserved IPv4 addresses (in various forms).
1504 { false, "192.168.0.0" },
1505 { false, "192.168.0.6" },
1506 { false, "10.0.0.5" },
1508 { false, "10.0.0" },
1509 { false, "3232235526" },
1510 // Unreserved IPv6 addresses.
1511 { true, "FFC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1512 { true, "2000:ba98:7654:2301:EFCD:BA98:7654:3210" },
1513 // Reserved IPv6 addresses.
1514 { false, "::192.9.5.5" },
1515 { false, "FEED::BEEF" },
1516 { false, "FEC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1517 // 'internal'/non-IANA assigned domains.
1518 { false, "intranet" },
1519 { false, "intranet." },
1520 { false, "intranet.example" },
1521 { false, "host.intranet.example" },
1522 // gTLDs under discussion, but not yet assigned.
1523 { false, "intranet.corp" },
1524 { false, "example.tech" },
1525 { false, "intranet.internal" },
1526 // Invalid host names are treated as unique - but expected to be
1527 // filtered out before then.
1528 { true, "junk)(£)$*!@~#" },
1529 { true, "w$w.example.com" },
1530 { true, "nocolonsallowed:example" },
1531 { true, "[::4.5.6.9]" },
1534 class NetUtilNonUniqueNameTest
1535 : public testing::TestWithParam
<NonUniqueNameTestData
> {
1537 virtual ~NetUtilNonUniqueNameTest() {}
1540 bool IsUnique(const std::string
& hostname
) {
1541 return !IsHostnameNonUnique(hostname
);
1545 // Test that internal/non-unique names are properly identified as such, but
1546 // that IP addresses and hosts beneath registry-controlled domains are flagged
1548 TEST_P(NetUtilNonUniqueNameTest
, IsHostnameNonUnique
) {
1549 const NonUniqueNameTestData
& test_data
= GetParam();
1551 EXPECT_EQ(test_data
.is_unique
, IsUnique(test_data
.hostname
));
1554 INSTANTIATE_TEST_CASE_P(, NetUtilNonUniqueNameTest
,
1555 testing::ValuesIn(kNonUniqueNameTestData
));