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"));
806 EXPECT_TRUE(net::IsLocalhost("foo.localhost"));
808 EXPECT_FALSE(net::IsLocalhost("localhostx"));
809 EXPECT_FALSE(net::IsLocalhost("foo.localdomain"));
810 EXPECT_FALSE(net::IsLocalhost("localhost6x"));
811 EXPECT_FALSE(net::IsLocalhost("localhost.localdomain6"));
812 EXPECT_FALSE(net::IsLocalhost("localhost6.localdomain"));
813 EXPECT_FALSE(net::IsLocalhost("127.0.0.1.1"));
814 EXPECT_FALSE(net::IsLocalhost(".127.0.0.255"));
815 EXPECT_FALSE(net::IsLocalhost("::2"));
816 EXPECT_FALSE(net::IsLocalhost("::1:1"));
817 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:1:0:0:1"));
818 EXPECT_FALSE(net::IsLocalhost("::1:1"));
819 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:0:0:0:0:1"));
820 EXPECT_FALSE(net::IsLocalhost("foo.localhost.com"));
821 EXPECT_FALSE(net::IsLocalhost("foo.localhoste"));
824 TEST(NetUtilTest
, IsLocalhostTLD
) {
825 EXPECT_TRUE(net::IsLocalhostTLD("foo.localhost"));
826 EXPECT_TRUE(net::IsLocalhostTLD("foo.localhost."));
827 EXPECT_FALSE(net::IsLocalhostTLD("foo.localhos"));
828 EXPECT_FALSE(net::IsLocalhostTLD("foo.localhost.com"));
829 EXPECT_FALSE(net::IsLocalhost("foo.localhoste"));
832 // Verify GetNetworkList().
833 TEST(NetUtilTest
, GetNetworkList
) {
834 NetworkInterfaceList list
;
835 ASSERT_TRUE(GetNetworkList(&list
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
));
836 for (NetworkInterfaceList::iterator it
= list
.begin();
837 it
!= list
.end(); ++it
) {
838 // Verify that the names are not empty.
839 EXPECT_FALSE(it
->name
.empty());
840 EXPECT_FALSE(it
->friendly_name
.empty());
842 // Verify that the address is correct.
843 EXPECT_TRUE(it
->address
.size() == kIPv4AddressSize
||
844 it
->address
.size() == kIPv6AddressSize
)
845 << "Invalid address of size " << it
->address
.size();
846 bool all_zeroes
= true;
847 for (size_t i
= 0; i
< it
->address
.size(); ++i
) {
848 if (it
->address
[i
] != 0) {
853 EXPECT_FALSE(all_zeroes
);
854 EXPECT_GT(it
->prefix_length
, 1u);
855 EXPECT_LE(it
->prefix_length
, it
->address
.size() * 8);
858 // On Windows |name| is NET_LUID.
859 base::ScopedNativeLibrary
phlpapi_lib(
860 base::FilePath(FILE_PATH_LITERAL("iphlpapi.dll")));
861 ASSERT_TRUE(phlpapi_lib
.is_valid());
862 typedef NETIO_STATUS (WINAPI
* ConvertInterfaceIndexToLuid
)(NET_IFINDEX
,
864 ConvertInterfaceIndexToLuid interface_to_luid
=
865 reinterpret_cast<ConvertInterfaceIndexToLuid
>(
866 phlpapi_lib
.GetFunctionPointer("ConvertInterfaceIndexToLuid"));
868 typedef NETIO_STATUS (WINAPI
* ConvertInterfaceLuidToGuid
)(NET_LUID
*,
870 ConvertInterfaceLuidToGuid luid_to_guid
=
871 reinterpret_cast<ConvertInterfaceLuidToGuid
>(
872 phlpapi_lib
.GetFunctionPointer("ConvertInterfaceLuidToGuid"));
874 if (interface_to_luid
&& luid_to_guid
) {
876 EXPECT_EQ(interface_to_luid(it
->interface_index
, &luid
), NO_ERROR
);
878 EXPECT_EQ(luid_to_guid(&luid
, &guid
), NO_ERROR
);
880 StringFromCLSID(guid
, &name
);
881 EXPECT_STREQ(base::UTF8ToWide(it
->name
).c_str(), name
);
885 EXPECT_LT(base::win::GetVersion(), base::win::VERSION_VISTA
);
886 EXPECT_LT(it
->interface_index
, 1u << 24u); // Must fit 0.x.x.x.
887 EXPECT_NE(it
->interface_index
, 0u); // 0 means to use default.
889 if (it
->type
== NetworkChangeNotifier::CONNECTION_WIFI
) {
890 EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE
, GetWifiPHYLayerProtocol());
892 #elif !defined(OS_ANDROID)
893 char name
[IF_NAMESIZE
];
894 EXPECT_TRUE(if_indextoname(it
->interface_index
, name
));
895 EXPECT_STREQ(it
->name
.c_str(), name
);
900 static const char ifname_em1
[] = "em1";
902 static const char ifname_vm
[] = "VMnet";
904 static const char ifname_vm
[] = "vmnet";
907 static const unsigned char kIPv6LocalAddr
[] = {
908 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
910 // The following 3 addresses need to be changed together. IPv6Addr is the IPv6
911 // address. IPv6Netmask is the mask address with as many leading bits set to 1
912 // as the prefix length. IPv6AddrPrefix needs to match IPv6Addr with the same
913 // number of bits as the prefix length.
914 static const unsigned char kIPv6Addr
[] =
915 {0x24, 0x01, 0xfa, 0x00, 0x00, 0x04, 0x10, 0x00, 0xbe, 0x30, 0x5b, 0xff,
916 0xfe, 0xe5, 0x00, 0xc3};
918 static const unsigned char kIPv6AddrPrefix
[] =
919 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
920 0x00, 0x00, 0x00, 0x00};
922 #if defined(OS_MACOSX)
923 static const unsigned char kIPv6Netmask
[] =
924 {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
925 0x00, 0x00, 0x00, 0x00};
928 #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_NACL)
930 char* CopyInterfaceName(const char* ifname
, int ifname_size
, char* output
) {
931 EXPECT_LT(ifname_size
, IF_NAMESIZE
);
932 memcpy(output
, ifname
, ifname_size
);
936 char* GetInterfaceName(int interface_index
, char* ifname
) {
937 return CopyInterfaceName(ifname_em1
, arraysize(ifname_em1
), ifname
);
940 char* GetInterfaceNameVM(int interface_index
, char* ifname
) {
941 return CopyInterfaceName(ifname_vm
, arraysize(ifname_vm
), ifname
);
944 TEST(NetUtilTest
, GetNetworkListTrimming
) {
945 IPAddressNumber
ipv6_local_address(
946 kIPv6LocalAddr
, kIPv6LocalAddr
+ arraysize(kIPv6LocalAddr
));
947 IPAddressNumber
ipv6_address(kIPv6Addr
, kIPv6Addr
+ arraysize(kIPv6Addr
));
949 NetworkInterfaceList results
;
950 ::base::hash_set
<int> online_links
;
951 net::internal::AddressTrackerLinux::AddressMap address_map
;
953 // Interface 1 is offline.
954 struct ifaddrmsg msg
= {
956 1, /* prefix length */
957 IFA_F_TEMPORARY
, /* address flags */
962 // Address of offline links should be ignored.
963 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
965 net::internal::GetNetworkListImpl(&results
,
966 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
970 EXPECT_EQ(results
.size(), 0ul);
972 // Mark interface 1 online.
973 online_links
.insert(1);
975 // Local address should be trimmed out.
978 address_map
.insert(std::make_pair(ipv6_local_address
, msg
)).second
);
980 net::internal::GetNetworkListImpl(&results
,
981 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
985 EXPECT_EQ(results
.size(), 0ul);
987 // vmware address should return by default.
989 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
991 net::internal::GetNetworkListImpl(&results
,
992 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
995 GetInterfaceNameVM
));
996 EXPECT_EQ(results
.size(), 1ul);
997 EXPECT_EQ(results
[0].name
, ifname_vm
);
998 EXPECT_EQ(results
[0].prefix_length
, 1ul);
999 EXPECT_EQ(results
[0].address
, ipv6_address
);
1002 // vmware address should be trimmed out if policy specified so.
1003 address_map
.clear();
1004 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1006 net::internal::GetNetworkListImpl(&results
,
1007 EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1010 GetInterfaceNameVM
));
1011 EXPECT_EQ(results
.size(), 0ul);
1014 // Addresses with banned attributes should be ignored.
1015 address_map
.clear();
1016 msg
.ifa_flags
= IFA_F_TENTATIVE
;
1017 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1019 net::internal::GetNetworkListImpl(&results
,
1020 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1024 EXPECT_EQ(results
.size(), 0ul);
1027 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1028 // attributes should be translated correctly.
1029 address_map
.clear();
1030 msg
.ifa_flags
= IFA_F_TEMPORARY
;
1031 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1033 net::internal::GetNetworkListImpl(&results
,
1034 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1038 EXPECT_EQ(results
.size(), 1ul);
1039 EXPECT_EQ(results
[0].name
, ifname_em1
);
1040 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1041 EXPECT_EQ(results
[0].address
, ipv6_address
);
1042 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_TEMPORARY
);
1045 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1046 // attributes should be translated correctly.
1047 address_map
.clear();
1048 msg
.ifa_flags
= IFA_F_DEPRECATED
;
1049 ASSERT_TRUE(address_map
.insert(std::make_pair(ipv6_address
, msg
)).second
);
1051 net::internal::GetNetworkListImpl(&results
,
1052 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
,
1056 EXPECT_EQ(results
.size(), 1ul);
1057 EXPECT_EQ(results
[0].name
, ifname_em1
);
1058 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1059 EXPECT_EQ(results
[0].address
, ipv6_address
);
1060 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_DEPRECATED
);
1064 #elif defined(OS_MACOSX)
1066 TEST(NetUtilTest
, GetNetworkListTrimming
) {
1067 IPAddressNumber
ipv6_local_address(
1068 kIPv6LocalAddr
, kIPv6LocalAddr
+ arraysize(kIPv6LocalAddr
));
1069 IPAddressNumber
ipv6_address(kIPv6Addr
, kIPv6Addr
+ arraysize(kIPv6Addr
));
1070 IPAddressNumber
ipv6_netmask(kIPv6Netmask
,
1071 kIPv6Netmask
+ arraysize(kIPv6Netmask
));
1073 NetworkInterfaceList results
;
1074 IPAttributesGetterTest ip_attributes_getter
;
1075 sockaddr_storage addresses
[2];
1078 // Address of offline links should be ignored.
1079 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_UP
, ipv6_address
,
1080 ipv6_netmask
, addresses
));
1081 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1082 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1083 &ip_attributes_getter
));
1084 EXPECT_EQ(results
.size(), 0ul);
1086 // Local address should be trimmed out.
1087 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
,
1088 ipv6_local_address
, ipv6_netmask
, addresses
));
1089 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1090 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1091 &ip_attributes_getter
));
1092 EXPECT_EQ(results
.size(), 0ul);
1094 // vmware address should return by default.
1095 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_vm
, IFF_RUNNING
, ipv6_address
,
1096 ipv6_netmask
, addresses
));
1097 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1098 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1099 &ip_attributes_getter
));
1100 EXPECT_EQ(results
.size(), 1ul);
1101 EXPECT_EQ(results
[0].name
, ifname_vm
);
1102 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1103 EXPECT_EQ(results
[0].address
, ipv6_address
);
1106 // vmware address should be trimmed out if policy specified so.
1107 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_vm
, IFF_RUNNING
, ipv6_address
,
1108 ipv6_netmask
, addresses
));
1109 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1110 &results
, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1111 &ip_attributes_getter
));
1112 EXPECT_EQ(results
.size(), 0ul);
1115 #if !defined(OS_IOS)
1116 // Addresses with banned attributes should be ignored.
1117 ip_attributes_getter
.set_native_attributes(IN6_IFF_ANYCAST
);
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(), 0ul);
1126 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1127 // attributes should be translated correctly.
1128 ip_attributes_getter
.set_native_attributes(IN6_IFF_TEMPORARY
);
1129 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
, ipv6_address
,
1130 ipv6_netmask
, addresses
));
1131 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1132 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1133 &ip_attributes_getter
));
1134 EXPECT_EQ(results
.size(), 1ul);
1135 EXPECT_EQ(results
[0].name
, ifname_em1
);
1136 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1137 EXPECT_EQ(results
[0].address
, ipv6_address
);
1138 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_TEMPORARY
);
1141 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1142 // attributes should be translated correctly.
1143 ip_attributes_getter
.set_native_attributes(IN6_IFF_DEPRECATED
);
1144 ASSERT_TRUE(FillIfaddrs(&interface
, ifname_em1
, IFF_RUNNING
, ipv6_address
,
1145 ipv6_netmask
, addresses
));
1146 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1147 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, &interface
,
1148 &ip_attributes_getter
));
1149 EXPECT_EQ(results
.size(), 1ul);
1150 EXPECT_EQ(results
[0].name
, ifname_em1
);
1151 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1152 EXPECT_EQ(results
[0].address
, ipv6_address
);
1153 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_DEPRECATED
);
1157 #elif defined(OS_WIN) // !OS_MACOSX && !OS_WIN && !OS_NACL
1159 // Helper function to create a valid IP_ADAPTER_ADDRESSES with reasonable
1160 // default value. The output is the |adapter_address|. All the rests are input
1161 // to fill the |adapter_address|. |sock_addrs| are temporary storage used by
1162 // |adapter_address| once the function is returned.
1163 bool FillAdapterAddress(IP_ADAPTER_ADDRESSES
* adapter_address
,
1165 const IPAddressNumber
& ip_address
,
1166 const IPAddressNumber
& ip_netmask
,
1167 sockaddr_storage sock_addrs
[2]) {
1168 adapter_address
->AdapterName
= const_cast<char*>(ifname
);
1169 adapter_address
->FriendlyName
= const_cast<PWCHAR
>(L
"interface");
1170 adapter_address
->IfType
= IF_TYPE_ETHERNET_CSMACD
;
1171 adapter_address
->OperStatus
= IfOperStatusUp
;
1172 adapter_address
->FirstUnicastAddress
->DadState
= IpDadStatePreferred
;
1173 adapter_address
->FirstUnicastAddress
->PrefixOrigin
= IpPrefixOriginOther
;
1174 adapter_address
->FirstUnicastAddress
->SuffixOrigin
= IpSuffixOriginOther
;
1175 adapter_address
->FirstUnicastAddress
->PreferredLifetime
= 100;
1176 adapter_address
->FirstUnicastAddress
->ValidLifetime
= 1000;
1178 socklen_t sock_len
= sizeof(sockaddr_storage
);
1180 // Convert to sockaddr for next check.
1181 if (!IPEndPoint(ip_address
, 0)
1182 .ToSockAddr(reinterpret_cast<sockaddr
*>(&sock_addrs
[0]),
1186 adapter_address
->FirstUnicastAddress
->Address
.lpSockaddr
=
1187 reinterpret_cast<sockaddr
*>(&sock_addrs
[0]);
1188 adapter_address
->FirstUnicastAddress
->Address
.iSockaddrLength
= sock_len
;
1189 adapter_address
->FirstUnicastAddress
->OnLinkPrefixLength
= 1;
1191 sock_len
= sizeof(sockaddr_storage
);
1192 if (!IPEndPoint(ip_netmask
, 0)
1193 .ToSockAddr(reinterpret_cast<sockaddr
*>(&sock_addrs
[1]),
1197 adapter_address
->FirstPrefix
->Address
.lpSockaddr
=
1198 reinterpret_cast<sockaddr
*>(&sock_addrs
[1]);
1199 adapter_address
->FirstPrefix
->Address
.iSockaddrLength
= sock_len
;
1200 adapter_address
->FirstPrefix
->PrefixLength
= 1;
1202 DCHECK_EQ(sock_addrs
[0].ss_family
, sock_addrs
[1].ss_family
);
1203 if (sock_addrs
[0].ss_family
== AF_INET6
) {
1204 adapter_address
->Ipv6IfIndex
= 0;
1206 DCHECK_EQ(sock_addrs
[0].ss_family
, AF_INET
);
1207 adapter_address
->IfIndex
= 0;
1213 TEST(NetUtilTest
, GetNetworkListTrimming
) {
1214 IPAddressNumber
ipv6_local_address(
1215 kIPv6LocalAddr
, kIPv6LocalAddr
+ arraysize(kIPv6LocalAddr
));
1216 IPAddressNumber
ipv6_address(kIPv6Addr
, kIPv6Addr
+ arraysize(kIPv6Addr
));
1217 IPAddressNumber
ipv6_prefix(kIPv6AddrPrefix
,
1218 kIPv6AddrPrefix
+ arraysize(kIPv6AddrPrefix
));
1220 NetworkInterfaceList results
;
1221 sockaddr_storage addresses
[2];
1222 IP_ADAPTER_ADDRESSES adapter_address
= {0};
1223 IP_ADAPTER_UNICAST_ADDRESS address
= {0};
1224 IP_ADAPTER_PREFIX adapter_prefix
= {0};
1225 adapter_address
.FirstUnicastAddress
= &address
;
1226 adapter_address
.FirstPrefix
= &adapter_prefix
;
1228 // Address of offline links should be ignored.
1229 ASSERT_TRUE(FillAdapterAddress(
1230 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1231 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1232 addresses
/* sock_addrs */));
1233 adapter_address
.OperStatus
= IfOperStatusDown
;
1235 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1236 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1238 EXPECT_EQ(results
.size(), 0ul);
1240 // Address on loopback interface should be trimmed out.
1241 ASSERT_TRUE(FillAdapterAddress(
1242 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1243 ipv6_local_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1244 addresses
/* sock_addrs */));
1245 adapter_address
.IfType
= IF_TYPE_SOFTWARE_LOOPBACK
;
1247 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1248 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1249 EXPECT_EQ(results
.size(), 0ul);
1251 // vmware address should return by default.
1252 ASSERT_TRUE(FillAdapterAddress(
1253 &adapter_address
/* adapter_address */, ifname_vm
/* ifname */,
1254 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1255 addresses
/* sock_addrs */));
1256 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1257 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1258 EXPECT_EQ(results
.size(), 1ul);
1259 EXPECT_EQ(results
[0].name
, ifname_vm
);
1260 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1261 EXPECT_EQ(results
[0].address
, ipv6_address
);
1262 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_NONE
);
1265 // vmware address should be trimmed out if policy specified so.
1266 ASSERT_TRUE(FillAdapterAddress(
1267 &adapter_address
/* adapter_address */, ifname_vm
/* ifname */,
1268 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1269 addresses
/* sock_addrs */));
1270 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1271 &results
, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1272 EXPECT_EQ(results
.size(), 0ul);
1275 // Addresses with incompleted DAD should be ignored.
1276 ASSERT_TRUE(FillAdapterAddress(
1277 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1278 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1279 addresses
/* sock_addrs */));
1280 adapter_address
.FirstUnicastAddress
->DadState
= IpDadStateTentative
;
1282 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1283 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1284 EXPECT_EQ(results
.size(), 0ul);
1287 // Addresses with allowed attribute IpSuffixOriginRandom should be returned
1288 // and attributes should be translated correctly to
1289 // IP_ADDRESS_ATTRIBUTE_TEMPORARY.
1290 ASSERT_TRUE(FillAdapterAddress(
1291 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1292 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1293 addresses
/* sock_addrs */));
1294 adapter_address
.FirstUnicastAddress
->PrefixOrigin
=
1295 IpPrefixOriginRouterAdvertisement
;
1296 adapter_address
.FirstUnicastAddress
->SuffixOrigin
= IpSuffixOriginRandom
;
1298 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1299 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1300 EXPECT_EQ(results
.size(), 1ul);
1301 EXPECT_EQ(results
[0].name
, ifname_em1
);
1302 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1303 EXPECT_EQ(results
[0].address
, ipv6_address
);
1304 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_TEMPORARY
);
1307 // Addresses with preferred lifetime 0 should be returned and
1308 // attributes should be translated correctly to
1309 // IP_ADDRESS_ATTRIBUTE_DEPRECATED.
1310 ASSERT_TRUE(FillAdapterAddress(
1311 &adapter_address
/* adapter_address */, ifname_em1
/* ifname */,
1312 ipv6_address
/* ip_address */, ipv6_prefix
/* ip_netmask */,
1313 addresses
/* sock_addrs */));
1314 adapter_address
.FirstUnicastAddress
->PreferredLifetime
= 0;
1315 adapter_address
.FriendlyName
= const_cast<PWCHAR
>(L
"FriendlyInterfaceName");
1316 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1317 &results
, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES
, true, &adapter_address
));
1318 EXPECT_EQ(results
.size(), 1ul);
1319 EXPECT_EQ(results
[0].friendly_name
, "FriendlyInterfaceName");
1320 EXPECT_EQ(results
[0].name
, ifname_em1
);
1321 EXPECT_EQ(results
[0].prefix_length
, 1ul);
1322 EXPECT_EQ(results
[0].address
, ipv6_address
);
1323 EXPECT_EQ(results
[0].ip_address_attributes
, IP_ADDRESS_ATTRIBUTE_DEPRECATED
);
1327 #endif // !OS_MACOSX && !OS_WIN && !OS_NACL
1329 TEST(NetUtilTest
, GetWifiSSID
) {
1330 // We can't check the result of GetWifiSSID() directly, since the result
1331 // will differ across machines. Simply exercise the code path and hope that it
1333 EXPECT_NE((const char*)NULL
, GetWifiSSID().c_str());
1336 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)
1337 TEST(NetUtilTest
, GetWifiSSIDFromInterfaceList
) {
1338 NetworkInterfaceList list
;
1339 EXPECT_EQ(std::string(), net::internal::GetWifiSSIDFromInterfaceListInternal(
1340 list
, TestGetInterfaceSSID
));
1342 NetworkInterface interface1
;
1343 interface1
.name
= "wlan0";
1344 interface1
.type
= NetworkChangeNotifier::CONNECTION_WIFI
;
1345 list
.push_back(interface1
);
1346 ASSERT_EQ(1u, list
.size());
1347 EXPECT_EQ(std::string(kWiFiSSID
),
1348 net::internal::GetWifiSSIDFromInterfaceListInternal(
1349 list
, TestGetInterfaceSSID
));
1351 NetworkInterface interface2
;
1352 interface2
.name
= "wlan1";
1353 interface2
.type
= NetworkChangeNotifier::CONNECTION_WIFI
;
1354 list
.push_back(interface2
);
1355 ASSERT_EQ(2u, list
.size());
1356 EXPECT_EQ(std::string(kWiFiSSID
),
1357 net::internal::GetWifiSSIDFromInterfaceListInternal(
1358 list
, TestGetInterfaceSSID
));
1360 NetworkInterface interface3
;
1361 interface3
.name
= kInterfaceWithDifferentSSID
;
1362 interface3
.type
= NetworkChangeNotifier::CONNECTION_WIFI
;
1363 list
.push_back(interface3
);
1364 ASSERT_EQ(3u, list
.size());
1365 EXPECT_EQ(std::string(), net::internal::GetWifiSSIDFromInterfaceListInternal(
1366 list
, TestGetInterfaceSSID
));
1369 NetworkInterface interface4
;
1370 interface4
.name
= "eth0";
1371 interface4
.type
= NetworkChangeNotifier::CONNECTION_ETHERNET
;
1372 list
.push_back(interface4
);
1373 ASSERT_EQ(3u, list
.size());
1374 EXPECT_EQ(std::string(), net::internal::GetWifiSSIDFromInterfaceListInternal(
1375 list
, TestGetInterfaceSSID
));
1382 bool read_int_or_bool(DWORD data_size
,
1384 switch (data_size
) {
1386 return !!*reinterpret_cast<uint8
*>(data
);
1388 return !!*reinterpret_cast<uint32
*>(data
);
1390 LOG(FATAL
) << "That is not a type I know!";
1395 int GetWifiOptions() {
1396 const internal::WlanApi
& wlanapi
= internal::WlanApi::GetInstance();
1397 if (!wlanapi
.initialized
)
1400 internal::WlanHandle client
;
1401 DWORD cur_version
= 0;
1402 const DWORD kMaxClientVersion
= 2;
1403 DWORD result
= wlanapi
.OpenHandle(
1404 kMaxClientVersion
, &cur_version
, &client
);
1405 if (result
!= ERROR_SUCCESS
)
1408 WLAN_INTERFACE_INFO_LIST
* interface_list_ptr
= NULL
;
1409 result
= wlanapi
.enum_interfaces_func(client
.Get(), NULL
,
1410 &interface_list_ptr
);
1411 if (result
!= ERROR_SUCCESS
)
1413 scoped_ptr
<WLAN_INTERFACE_INFO_LIST
, internal::WlanApiDeleter
> interface_list(
1414 interface_list_ptr
);
1416 for (unsigned i
= 0; i
< interface_list
->dwNumberOfItems
; ++i
) {
1417 WLAN_INTERFACE_INFO
* info
= &interface_list
->InterfaceInfo
[i
];
1421 result
= wlanapi
.query_interface_func(
1423 &info
->InterfaceGuid
,
1424 wlan_intf_opcode_background_scan_enabled
,
1429 if (result
!= ERROR_SUCCESS
)
1431 if (!read_int_or_bool(data_size
, data
)) {
1432 options
|= WIFI_OPTIONS_DISABLE_SCAN
;
1434 internal::WlanApi::GetInstance().free_memory_func(data
);
1436 result
= wlanapi
.query_interface_func(
1438 &info
->InterfaceGuid
,
1439 wlan_intf_opcode_media_streaming_mode
,
1444 if (result
!= ERROR_SUCCESS
)
1446 if (read_int_or_bool(data_size
, data
)) {
1447 options
|= WIFI_OPTIONS_MEDIA_STREAMING_MODE
;
1449 internal::WlanApi::GetInstance().free_memory_func(data
);
1451 // Just the the options from the first succesful
1456 // No wifi interface found.
1462 int GetWifiOptions() {
1469 void TryChangeWifiOptions(int options
) {
1470 int previous_options
= GetWifiOptions();
1471 scoped_ptr
<ScopedWifiOptions
> scoped_options
= SetWifiOptions(options
);
1472 EXPECT_EQ(previous_options
| options
, GetWifiOptions());
1473 scoped_options
.reset();
1474 EXPECT_EQ(previous_options
, GetWifiOptions());
1479 // Test SetWifiOptions().
1480 TEST(NetUtilTest
, SetWifiOptionsTest
) {
1481 TryChangeWifiOptions(0);
1482 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN
);
1483 TryChangeWifiOptions(WIFI_OPTIONS_MEDIA_STREAMING_MODE
);
1484 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN
|
1485 WIFI_OPTIONS_MEDIA_STREAMING_MODE
);
1488 struct NonUniqueNameTestData
{
1490 const char* const hostname
;
1493 // Google Test pretty-printer.
1494 void PrintTo(const NonUniqueNameTestData
& data
, std::ostream
* os
) {
1495 ASSERT_TRUE(data
.hostname
);
1496 *os
<< " hostname: " << testing::PrintToString(data
.hostname
)
1497 << "; is_unique: " << testing::PrintToString(data
.is_unique
);
1500 const NonUniqueNameTestData kNonUniqueNameTestData
[] = {
1501 // Domains under ICANN-assigned domains.
1502 { true, "google.com" },
1503 { true, "google.co.uk" },
1504 // Domains under private registries.
1505 { true, "appspot.com" },
1506 { true, "test.appspot.com" },
1507 // Unreserved IPv4 addresses (in various forms).
1508 { true, "8.8.8.8" },
1509 { true, "99.64.0.0" },
1510 { true, "212.15.0.0" },
1512 { true, "212.15.0" },
1513 { true, "3557752832" },
1514 // Reserved IPv4 addresses (in various forms).
1515 { false, "192.168.0.0" },
1516 { false, "192.168.0.6" },
1517 { false, "10.0.0.5" },
1519 { false, "10.0.0" },
1520 { false, "3232235526" },
1521 // Unreserved IPv6 addresses.
1522 { true, "FFC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1523 { true, "2000:ba98:7654:2301:EFCD:BA98:7654:3210" },
1524 // Reserved IPv6 addresses.
1525 { false, "::192.9.5.5" },
1526 { false, "FEED::BEEF" },
1527 { false, "FEC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1528 // 'internal'/non-IANA assigned domains.
1529 { false, "intranet" },
1530 { false, "intranet." },
1531 { false, "intranet.example" },
1532 { false, "host.intranet.example" },
1533 // gTLDs under discussion, but not yet assigned.
1534 { false, "intranet.corp" },
1535 { false, "intranet.internal" },
1536 // Invalid host names are treated as unique - but expected to be
1537 // filtered out before then.
1538 { true, "junk)(£)$*!@~#" },
1539 { true, "w$w.example.com" },
1540 { true, "nocolonsallowed:example" },
1541 { true, "[::4.5.6.9]" },
1544 class NetUtilNonUniqueNameTest
1545 : public testing::TestWithParam
<NonUniqueNameTestData
> {
1547 virtual ~NetUtilNonUniqueNameTest() {}
1550 bool IsUnique(const std::string
& hostname
) {
1551 return !IsHostnameNonUnique(hostname
);
1555 // Test that internal/non-unique names are properly identified as such, but
1556 // that IP addresses and hosts beneath registry-controlled domains are flagged
1558 TEST_P(NetUtilNonUniqueNameTest
, IsHostnameNonUnique
) {
1559 const NonUniqueNameTestData
& test_data
= GetParam();
1561 EXPECT_EQ(test_data
.is_unique
, IsUnique(test_data
.hostname
));
1564 INSTANTIATE_TEST_CASE_P(, NetUtilNonUniqueNameTest
,
1565 testing::ValuesIn(kNonUniqueNameTestData
));