Roll src/third_party/WebKit 8121bc6:918aba1 (svn 188871:188878)
[chromium-blink-merge.git] / net / base / net_util_unittest.cc
blobcb9ec1ffc4d8f96ccdb38906ca2e1e162e053eb3
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"
7 #include <string.h>
9 #include <ostream>
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)
23 #include <net/if.h>
24 #include <netinet/in.h>
25 #if defined(OS_MACOSX)
26 #include <ifaddrs.h>
27 #if !defined(OS_IOS)
28 #include <netinet/in_var.h>
29 #endif // !OS_IOS
30 #endif // OS_MACOSX
31 #endif // !OS_NACL && !OS_WIN
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "url/gurl.h"
35 #if defined(OS_WIN)
36 #include <iphlpapi.h>
37 #include <objbase.h>
38 #include "base/win/windows_version.h"
39 #endif // OS_WIN
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
45 #if defined(OS_WIN)
46 #include "net/base/net_util_win.h"
47 #else // OS_WIN
48 #include "net/base/net_util_posix.h"
49 #if defined(OS_MACOSX)
50 #include "net/base/net_util_mac.h"
51 #else // OS_MACOSX
52 #include "net/base/net_util_linux.h"
53 #endif // OS_MACOSX
54 #endif // OS_WIN
56 using base::ASCIIToUTF16;
57 using base::WideToUTF16;
59 namespace net {
61 namespace {
63 struct HeaderCase {
64 const char* header_name;
65 const char* expected;
68 // Fills in sockaddr for the given 32-bit address (IPv4.)
69 // |bytes| should be an array of length 4.
70 void MakeIPv4Address(const uint8* bytes, int port, SockaddrStorage* storage) {
71 memset(&storage->addr_storage, 0, sizeof(storage->addr_storage));
72 storage->addr_len = sizeof(struct sockaddr_in);
73 struct sockaddr_in* addr4 = reinterpret_cast<sockaddr_in*>(storage->addr);
74 addr4->sin_port = base::HostToNet16(port);
75 addr4->sin_family = AF_INET;
76 memcpy(&addr4->sin_addr, bytes, 4);
79 // Fills in sockaddr for the given 128-bit address (IPv6.)
80 // |bytes| should be an array of length 16.
81 void MakeIPv6Address(const uint8* bytes, int port, SockaddrStorage* storage) {
82 memset(&storage->addr_storage, 0, sizeof(storage->addr_storage));
83 storage->addr_len = sizeof(struct sockaddr_in6);
84 struct sockaddr_in6* addr6 = reinterpret_cast<sockaddr_in6*>(storage->addr);
85 addr6->sin6_port = base::HostToNet16(port);
86 addr6->sin6_family = AF_INET6;
87 memcpy(&addr6->sin6_addr, bytes, 16);
90 // Helper to strignize an IP number (used to define expectations).
91 std::string DumpIPNumber(const IPAddressNumber& v) {
92 std::string out;
93 for (size_t i = 0; i < v.size(); ++i) {
94 if (i != 0)
95 out.append(",");
96 out.append(base::IntToString(static_cast<int>(v[i])));
98 return out;
101 #if defined(OS_MACOSX)
102 class IPAttributesGetterTest : public internal::IPAttributesGetterMac {
103 public:
104 IPAttributesGetterTest() : native_attributes_(0) {}
105 bool IsInitialized() const override { return true; }
106 bool GetIPAttributes(const char* ifname,
107 const sockaddr* sock_addr,
108 int* native_attributes) override {
109 *native_attributes = native_attributes_;
110 return true;
112 void set_native_attributes(int native_attributes) {
113 native_attributes_ = native_attributes;
116 private:
117 int native_attributes_;
120 // Helper function to create a single valid ifaddrs
121 bool FillIfaddrs(ifaddrs* interfaces,
122 const char* ifname,
123 uint flags,
124 const IPAddressNumber& ip_address,
125 const IPAddressNumber& ip_netmask,
126 sockaddr_storage sock_addrs[2]) {
127 interfaces->ifa_next = NULL;
128 interfaces->ifa_name = const_cast<char*>(ifname);
129 interfaces->ifa_flags = flags;
131 socklen_t sock_len = sizeof(sockaddr_storage);
133 // Convert to sockaddr for next check.
134 if (!IPEndPoint(ip_address, 0)
135 .ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[0]),
136 &sock_len)) {
137 return false;
139 interfaces->ifa_addr = reinterpret_cast<sockaddr*>(&sock_addrs[0]);
141 sock_len = sizeof(sockaddr_storage);
142 if (!IPEndPoint(ip_netmask, 0)
143 .ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[1]),
144 &sock_len)) {
145 return false;
147 interfaces->ifa_netmask = reinterpret_cast<sockaddr*>(&sock_addrs[1]);
149 return true;
151 #endif // OS_MACOSX
153 } // anonymous namespace
155 TEST(NetUtilTest, GetIdentityFromURL) {
156 struct {
157 const char* input_url;
158 const char* expected_username;
159 const char* expected_password;
160 } tests[] = {
162 "http://username:password@google.com",
163 "username",
164 "password",
166 { // Test for http://crbug.com/19200
167 "http://username:p@ssword@google.com",
168 "username",
169 "p@ssword",
171 { // Special URL characters should be unescaped.
172 "http://username:p%3fa%26s%2fs%23@google.com",
173 "username",
174 "p?a&s/s#",
176 { // Username contains %20.
177 "http://use rname:password@google.com",
178 "use rname",
179 "password",
181 { // Keep %00 as is.
182 "http://use%00rname:password@google.com",
183 "use%00rname",
184 "password",
186 { // Use a '+' in the username.
187 "http://use+rname:password@google.com",
188 "use+rname",
189 "password",
191 { // Use a '&' in the password.
192 "http://username:p&ssword@google.com",
193 "username",
194 "p&ssword",
197 for (size_t i = 0; i < arraysize(tests); ++i) {
198 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i,
199 tests[i].input_url));
200 GURL url(tests[i].input_url);
202 base::string16 username, password;
203 GetIdentityFromURL(url, &username, &password);
205 EXPECT_EQ(ASCIIToUTF16(tests[i].expected_username), username);
206 EXPECT_EQ(ASCIIToUTF16(tests[i].expected_password), password);
210 // Try extracting a username which was encoded with UTF8.
211 TEST(NetUtilTest, GetIdentityFromURL_UTF8) {
212 GURL url(WideToUTF16(L"http://foo:\x4f60\x597d@blah.com"));
214 EXPECT_EQ("foo", url.username());
215 EXPECT_EQ("%E4%BD%A0%E5%A5%BD", url.password());
217 // Extract the unescaped identity.
218 base::string16 username, password;
219 GetIdentityFromURL(url, &username, &password);
221 // Verify that it was decoded as UTF8.
222 EXPECT_EQ(ASCIIToUTF16("foo"), username);
223 EXPECT_EQ(WideToUTF16(L"\x4f60\x597d"), password);
226 // Just a bunch of fake headers.
227 const char* google_headers =
228 "HTTP/1.1 200 OK\n"
229 "Content-TYPE: text/html; charset=utf-8\n"
230 "Content-disposition: attachment; filename=\"download.pdf\"\n"
231 "Content-Length: 378557\n"
232 "X-Google-Google1: 314159265\n"
233 "X-Google-Google2: aaaa2:7783,bbb21:9441\n"
234 "X-Google-Google4: home\n"
235 "Transfer-Encoding: chunked\n"
236 "Set-Cookie: HEHE_AT=6666x66beef666x6-66xx6666x66; Path=/mail\n"
237 "Set-Cookie: HEHE_HELP=owned:0;Path=/\n"
238 "Set-Cookie: S=gmail=Xxx-beefbeefbeef_beefb:gmail_yj=beefbeef000beefbee"
239 "fbee:gmproxy=bee-fbeefbe; Domain=.google.com; Path=/\n"
240 "X-Google-Google2: /one/two/three/four/five/six/seven-height/nine:9411\n"
241 "Server: GFE/1.3\n"
242 "Transfer-Encoding: chunked\n"
243 "Date: Mon, 13 Nov 2006 21:38:09 GMT\n"
244 "Expires: Tue, 14 Nov 2006 19:23:58 GMT\n"
245 "X-Malformed: bla; arg=test\"\n"
246 "X-Malformed2: bla; arg=\n"
247 "X-Test: bla; arg1=val1; arg2=val2";
249 TEST(NetUtilTest, GetSpecificHeader) {
250 const HeaderCase tests[] = {
251 {"content-type", "text/html; charset=utf-8"},
252 {"CONTENT-LENGTH", "378557"},
253 {"Date", "Mon, 13 Nov 2006 21:38:09 GMT"},
254 {"Bad-Header", ""},
255 {"", ""},
258 // Test first with google_headers.
259 for (size_t i = 0; i < arraysize(tests); ++i) {
260 std::string result =
261 GetSpecificHeader(google_headers, tests[i].header_name);
262 EXPECT_EQ(result, tests[i].expected);
265 // Test again with empty headers.
266 for (size_t i = 0; i < arraysize(tests); ++i) {
267 std::string result = GetSpecificHeader(std::string(), tests[i].header_name);
268 EXPECT_EQ(result, std::string());
272 TEST(NetUtilTest, CompliantHost) {
273 struct CompliantHostCase {
274 const char* host;
275 bool expected_output;
278 const CompliantHostCase compliant_host_cases[] = {
279 {"", false},
280 {"a", true},
281 {"-", false},
282 {".", false},
283 {"9", true},
284 {"9a", true},
285 {"a.", true},
286 {"a.a", true},
287 {"9.a", true},
288 {"a.9", true},
289 {"_9a", false},
290 {"-9a", false},
291 {"a.a9", true},
292 {"a.-a9", false},
293 {"a+9a", false},
294 {"-a.a9", true},
295 {"1-.a-b", true},
296 {"1_.a-b", false},
297 {"1-2.a_b", true},
298 {"a.b.c.d.e", true},
299 {"1.2.3.4.5", true},
300 {"1.2.3.4.5.", true},
303 for (size_t i = 0; i < arraysize(compliant_host_cases); ++i) {
304 EXPECT_EQ(compliant_host_cases[i].expected_output,
305 IsCanonicalizedHostCompliant(compliant_host_cases[i].host));
309 TEST(NetUtilTest, ParseHostAndPort) {
310 const struct {
311 const char* input;
312 bool success;
313 const char* expected_host;
314 int expected_port;
315 } tests[] = {
316 // Valid inputs:
317 {"foo:10", true, "foo", 10},
318 {"foo", true, "foo", -1},
320 "[1080:0:0:0:8:800:200C:4171]:11",
321 true,
322 "1080:0:0:0:8:800:200C:4171",
326 "[1080:0:0:0:8:800:200C:4171]",
327 true,
328 "1080:0:0:0:8:800:200C:4171",
332 // Because no validation is done on the host, the following are accepted,
333 // even though they are invalid names.
334 {"]", true, "]", -1},
335 {"::1", true, ":", 1},
336 // Invalid inputs:
337 {"foo:bar", false, "", -1},
338 {"foo:", false, "", -1},
339 {":", false, "", -1},
340 {":80", false, "", -1},
341 {"", false, "", -1},
342 {"porttoolong:300000", false, "", -1},
343 {"usrname@host", false, "", -1},
344 {"usrname:password@host", false, "", -1},
345 {":password@host", false, "", -1},
346 {":password@host:80", false, "", -1},
347 {":password@host", false, "", -1},
348 {"@host", false, "", -1},
349 {"[", false, "", -1},
350 {"[]", false, "", -1},
353 for (size_t i = 0; i < arraysize(tests); ++i) {
354 std::string host;
355 int port;
356 bool ok = ParseHostAndPort(tests[i].input, &host, &port);
358 EXPECT_EQ(tests[i].success, ok);
360 if (tests[i].success) {
361 EXPECT_EQ(tests[i].expected_host, host);
362 EXPECT_EQ(tests[i].expected_port, port);
367 TEST(NetUtilTest, GetHostAndPort) {
368 const struct {
369 GURL url;
370 const char* expected_host_and_port;
371 } tests[] = {
372 { GURL("http://www.foo.com/x"), "www.foo.com:80"},
373 { GURL("http://www.foo.com:21/x"), "www.foo.com:21"},
375 // For IPv6 literals should always include the brackets.
376 { GURL("http://[1::2]/x"), "[1::2]:80"},
377 { GURL("http://[::a]:33/x"), "[::a]:33"},
379 for (size_t i = 0; i < arraysize(tests); ++i) {
380 std::string host_and_port = GetHostAndPort(tests[i].url);
381 EXPECT_EQ(std::string(tests[i].expected_host_and_port), host_and_port);
385 TEST(NetUtilTest, GetHostAndOptionalPort) {
386 const struct {
387 GURL url;
388 const char* expected_host_and_port;
389 } tests[] = {
390 { GURL("http://www.foo.com/x"), "www.foo.com"},
391 { GURL("http://www.foo.com:21/x"), "www.foo.com:21"},
393 // For IPv6 literals should always include the brackets.
394 { GURL("http://[1::2]/x"), "[1::2]"},
395 { GURL("http://[::a]:33/x"), "[::a]:33"},
397 for (size_t i = 0; i < arraysize(tests); ++i) {
398 std::string host_and_port = GetHostAndOptionalPort(tests[i].url);
399 EXPECT_EQ(std::string(tests[i].expected_host_and_port), host_and_port);
403 TEST(NetUtilTest, IPAddressToString) {
404 uint8 addr1[4] = {0, 0, 0, 0};
405 EXPECT_EQ("0.0.0.0", IPAddressToString(addr1, sizeof(addr1)));
407 uint8 addr2[4] = {192, 168, 0, 1};
408 EXPECT_EQ("192.168.0.1", IPAddressToString(addr2, sizeof(addr2)));
410 uint8 addr3[16] = {0xFE, 0xDC, 0xBA, 0x98};
411 EXPECT_EQ("fedc:ba98::", IPAddressToString(addr3, sizeof(addr3)));
414 TEST(NetUtilTest, IPAddressToStringWithPort) {
415 uint8 addr1[4] = {0, 0, 0, 0};
416 EXPECT_EQ("0.0.0.0:3", IPAddressToStringWithPort(addr1, sizeof(addr1), 3));
418 uint8 addr2[4] = {192, 168, 0, 1};
419 EXPECT_EQ("192.168.0.1:99",
420 IPAddressToStringWithPort(addr2, sizeof(addr2), 99));
422 uint8 addr3[16] = {0xFE, 0xDC, 0xBA, 0x98};
423 EXPECT_EQ("[fedc:ba98::]:8080",
424 IPAddressToStringWithPort(addr3, sizeof(addr3), 8080));
427 TEST(NetUtilTest, NetAddressToString_IPv4) {
428 const struct {
429 uint8 addr[4];
430 const char* result;
431 } tests[] = {
432 {{0, 0, 0, 0}, "0.0.0.0"},
433 {{127, 0, 0, 1}, "127.0.0.1"},
434 {{192, 168, 0, 1}, "192.168.0.1"},
437 for (size_t i = 0; i < arraysize(tests); ++i) {
438 SockaddrStorage storage;
439 MakeIPv4Address(tests[i].addr, 80, &storage);
440 std::string result = NetAddressToString(storage.addr, storage.addr_len);
441 EXPECT_EQ(std::string(tests[i].result), result);
445 TEST(NetUtilTest, NetAddressToString_IPv6) {
446 const struct {
447 uint8 addr[16];
448 const char* result;
449 } tests[] = {
450 {{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA,
451 0x98, 0x76, 0x54, 0x32, 0x10},
452 "fedc:ba98:7654:3210:fedc:ba98:7654:3210"},
455 for (size_t i = 0; i < arraysize(tests); ++i) {
456 SockaddrStorage storage;
457 MakeIPv6Address(tests[i].addr, 80, &storage);
458 EXPECT_EQ(std::string(tests[i].result),
459 NetAddressToString(storage.addr, storage.addr_len));
463 TEST(NetUtilTest, NetAddressToStringWithPort_IPv4) {
464 uint8 addr[] = {127, 0, 0, 1};
465 SockaddrStorage storage;
466 MakeIPv4Address(addr, 166, &storage);
467 std::string result = NetAddressToStringWithPort(storage.addr,
468 storage.addr_len);
469 EXPECT_EQ("127.0.0.1:166", result);
472 TEST(NetUtilTest, NetAddressToStringWithPort_IPv6) {
473 uint8 addr[] = {
474 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA,
475 0x98, 0x76, 0x54, 0x32, 0x10
477 SockaddrStorage storage;
478 MakeIPv6Address(addr, 361, &storage);
479 std::string result = NetAddressToStringWithPort(storage.addr,
480 storage.addr_len);
482 // May fail on systems that don't support IPv6.
483 if (!result.empty())
484 EXPECT_EQ("[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:361", result);
487 TEST(NetUtilTest, GetHostName) {
488 // We can't check the result of GetHostName() directly, since the result
489 // will differ across machines. Our goal here is to simply exercise the
490 // code path, and check that things "look about right".
491 std::string hostname = GetHostName();
492 EXPECT_FALSE(hostname.empty());
495 TEST(NetUtilTest, SimplifyUrlForRequest) {
496 struct {
497 const char* input_url;
498 const char* expected_simplified_url;
499 } tests[] = {
501 // Reference section should be stripped.
502 "http://www.google.com:78/foobar?query=1#hash",
503 "http://www.google.com:78/foobar?query=1",
506 // Reference section can itself contain #.
507 "http://192.168.0.1?query=1#hash#10#11#13#14",
508 "http://192.168.0.1?query=1",
510 { // Strip username/password.
511 "http://user:pass@google.com",
512 "http://google.com/",
514 { // Strip both the reference and the username/password.
515 "http://user:pass@google.com:80/sup?yo#X#X",
516 "http://google.com/sup?yo",
518 { // Try an HTTPS URL -- strip both the reference and the username/password.
519 "https://user:pass@google.com:80/sup?yo#X#X",
520 "https://google.com:80/sup?yo",
522 { // Try an FTP URL -- strip both the reference and the username/password.
523 "ftp://user:pass@google.com:80/sup?yo#X#X",
524 "ftp://google.com:80/sup?yo",
526 { // Try a nonstandard URL
527 "foobar://user:pass@google.com:80/sup?yo#X#X",
528 "foobar://user:pass@google.com:80/sup?yo",
531 for (size_t i = 0; i < arraysize(tests); ++i) {
532 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i,
533 tests[i].input_url));
534 GURL input_url(GURL(tests[i].input_url));
535 GURL expected_url(GURL(tests[i].expected_simplified_url));
536 EXPECT_EQ(expected_url, SimplifyUrlForRequest(input_url));
540 TEST(NetUtilTest, SetExplicitlyAllowedPortsTest) {
541 std::string invalid[] = { "1,2,a", "'1','2'", "1, 2, 3", "1 0,11,12" };
542 std::string valid[] = { "", "1", "1,2", "1,2,3", "10,11,12,13" };
544 for (size_t i = 0; i < arraysize(invalid); ++i) {
545 SetExplicitlyAllowedPorts(invalid[i]);
546 EXPECT_EQ(0, static_cast<int>(GetCountOfExplicitlyAllowedPorts()));
549 for (size_t i = 0; i < arraysize(valid); ++i) {
550 SetExplicitlyAllowedPorts(valid[i]);
551 EXPECT_EQ(i, GetCountOfExplicitlyAllowedPorts());
555 TEST(NetUtilTest, GetHostOrSpecFromURL) {
556 EXPECT_EQ("example.com",
557 GetHostOrSpecFromURL(GURL("http://example.com/test")));
558 EXPECT_EQ("example.com",
559 GetHostOrSpecFromURL(GURL("http://example.com./test")));
560 EXPECT_EQ("file:///tmp/test.html",
561 GetHostOrSpecFromURL(GURL("file:///tmp/test.html")));
564 TEST(NetUtilTest, GetAddressFamily) {
565 IPAddressNumber number;
566 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &number));
567 EXPECT_EQ(ADDRESS_FAMILY_IPV4, GetAddressFamily(number));
568 EXPECT_TRUE(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number));
569 EXPECT_EQ(ADDRESS_FAMILY_IPV6, GetAddressFamily(number));
572 // Test that invalid IP literals fail to parse.
573 TEST(NetUtilTest, ParseIPLiteralToNumber_FailParse) {
574 IPAddressNumber number;
576 EXPECT_FALSE(ParseIPLiteralToNumber("bad value", &number));
577 EXPECT_FALSE(ParseIPLiteralToNumber("bad:value", &number));
578 EXPECT_FALSE(ParseIPLiteralToNumber(std::string(), &number));
579 EXPECT_FALSE(ParseIPLiteralToNumber("192.168.0.1:30", &number));
580 EXPECT_FALSE(ParseIPLiteralToNumber(" 192.168.0.1 ", &number));
581 EXPECT_FALSE(ParseIPLiteralToNumber("[::1]", &number));
584 // Test parsing an IPv4 literal.
585 TEST(NetUtilTest, ParseIPLiteralToNumber_IPv4) {
586 IPAddressNumber number;
587 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &number));
588 EXPECT_EQ("192,168,0,1", DumpIPNumber(number));
589 EXPECT_EQ("192.168.0.1", IPAddressToString(number));
592 // Test parsing an IPv6 literal.
593 TEST(NetUtilTest, ParseIPLiteralToNumber_IPv6) {
594 IPAddressNumber number;
595 EXPECT_TRUE(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number));
596 EXPECT_EQ("0,1,171,205,0,0,0,0,0,0,0,3,0,4,0,255", DumpIPNumber(number));
597 EXPECT_EQ("1:abcd::3:4:ff", IPAddressToString(number));
600 // Test mapping an IPv4 address to an IPv6 address.
601 TEST(NetUtilTest, ConvertIPv4NumberToIPv6Number) {
602 IPAddressNumber ipv4_number;
603 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number));
605 IPAddressNumber ipv6_number =
606 ConvertIPv4NumberToIPv6Number(ipv4_number);
608 // ::ffff:192.168.0.1
609 EXPECT_EQ("0,0,0,0,0,0,0,0,0,0,255,255,192,168,0,1",
610 DumpIPNumber(ipv6_number));
611 EXPECT_EQ("::ffff:c0a8:1", IPAddressToString(ipv6_number));
614 TEST(NetUtilTest, ParseURLHostnameToNumber_FailParse) {
615 IPAddressNumber number;
617 EXPECT_FALSE(ParseURLHostnameToNumber("bad value", &number));
618 EXPECT_FALSE(ParseURLHostnameToNumber("bad:value", &number));
619 EXPECT_FALSE(ParseURLHostnameToNumber(std::string(), &number));
620 EXPECT_FALSE(ParseURLHostnameToNumber("192.168.0.1:30", &number));
621 EXPECT_FALSE(ParseURLHostnameToNumber(" 192.168.0.1 ", &number));
622 EXPECT_FALSE(ParseURLHostnameToNumber("::1", &number));
625 TEST(NetUtilTest, ParseURLHostnameToNumber_IPv4) {
626 IPAddressNumber number;
627 EXPECT_TRUE(ParseURLHostnameToNumber("192.168.0.1", &number));
628 EXPECT_EQ("192,168,0,1", DumpIPNumber(number));
629 EXPECT_EQ("192.168.0.1", IPAddressToString(number));
632 TEST(NetUtilTest, ParseURLHostnameToNumber_IPv6) {
633 IPAddressNumber number;
634 EXPECT_TRUE(ParseURLHostnameToNumber("[1:abcd::3:4:ff]", &number));
635 EXPECT_EQ("0,1,171,205,0,0,0,0,0,0,0,3,0,4,0,255", DumpIPNumber(number));
636 EXPECT_EQ("1:abcd::3:4:ff", IPAddressToString(number));
639 TEST(NetUtilTest, IsIPv4Mapped) {
640 IPAddressNumber ipv4_number;
641 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number));
642 EXPECT_FALSE(IsIPv4Mapped(ipv4_number));
644 IPAddressNumber ipv6_number;
645 EXPECT_TRUE(ParseIPLiteralToNumber("::1", &ipv4_number));
646 EXPECT_FALSE(IsIPv4Mapped(ipv6_number));
648 IPAddressNumber ipv4mapped_number;
649 EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number));
650 EXPECT_TRUE(IsIPv4Mapped(ipv4mapped_number));
653 TEST(NetUtilTest, ConvertIPv4MappedToIPv4) {
654 IPAddressNumber ipv4mapped_number;
655 EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number));
656 IPAddressNumber expected;
657 EXPECT_TRUE(ParseIPLiteralToNumber("1.1.0.1", &expected));
658 IPAddressNumber result = ConvertIPv4MappedToIPv4(ipv4mapped_number);
659 EXPECT_EQ(expected, result);
662 // Test parsing invalid CIDR notation literals.
663 TEST(NetUtilTest, ParseCIDRBlock_Invalid) {
664 const char* bad_literals[] = {
665 "foobar",
667 "192.168.0.1",
668 "::1",
669 "/",
670 "/1",
671 "1",
672 "192.168.1.1/-1",
673 "192.168.1.1/33",
674 "::1/-3",
675 "a::3/129",
676 "::1/x",
677 "192.168.0.1//11"
680 for (size_t i = 0; i < arraysize(bad_literals); ++i) {
681 IPAddressNumber ip_number;
682 size_t prefix_length_in_bits;
684 EXPECT_FALSE(ParseCIDRBlock(bad_literals[i],
685 &ip_number,
686 &prefix_length_in_bits));
690 // Test parsing a valid CIDR notation literal.
691 TEST(NetUtilTest, ParseCIDRBlock_Valid) {
692 IPAddressNumber ip_number;
693 size_t prefix_length_in_bits;
695 EXPECT_TRUE(ParseCIDRBlock("192.168.0.1/11",
696 &ip_number,
697 &prefix_length_in_bits));
699 EXPECT_EQ("192,168,0,1", DumpIPNumber(ip_number));
700 EXPECT_EQ(11u, prefix_length_in_bits);
703 TEST(NetUtilTest, IPNumberMatchesPrefix) {
704 struct {
705 const char* cidr_literal;
706 const char* ip_literal;
707 bool expected_to_match;
708 } tests[] = {
709 // IPv4 prefix with IPv4 inputs.
711 "10.10.1.32/27",
712 "10.10.1.44",
713 true
716 "10.10.1.32/27",
717 "10.10.1.90",
718 false
721 "10.10.1.32/27",
722 "10.10.1.90",
723 false
726 // IPv6 prefix with IPv6 inputs.
728 "2001:db8::/32",
729 "2001:DB8:3:4::5",
730 true
733 "2001:db8::/32",
734 "2001:c8::",
735 false
738 // IPv6 prefix with IPv4 inputs.
740 "2001:db8::/33",
741 "192.168.0.1",
742 false
745 "::ffff:192.168.0.1/112",
746 "192.168.33.77",
747 true
750 // IPv4 prefix with IPv6 inputs.
752 "10.11.33.44/16",
753 "::ffff:0a0b:89",
754 true
757 "10.11.33.44/16",
758 "::ffff:10.12.33.44",
759 false
762 for (size_t i = 0; i < arraysize(tests); ++i) {
763 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s, %s", i,
764 tests[i].cidr_literal,
765 tests[i].ip_literal));
767 IPAddressNumber ip_number;
768 EXPECT_TRUE(ParseIPLiteralToNumber(tests[i].ip_literal, &ip_number));
770 IPAddressNumber ip_prefix;
771 size_t prefix_length_in_bits;
773 EXPECT_TRUE(ParseCIDRBlock(tests[i].cidr_literal,
774 &ip_prefix,
775 &prefix_length_in_bits));
777 EXPECT_EQ(tests[i].expected_to_match,
778 IPNumberMatchesPrefix(ip_number,
779 ip_prefix,
780 prefix_length_in_bits));
784 TEST(NetUtilTest, IsLocalhost) {
785 EXPECT_TRUE(net::IsLocalhost("localhost"));
786 EXPECT_TRUE(net::IsLocalhost("localhost.localdomain"));
787 EXPECT_TRUE(net::IsLocalhost("localhost6"));
788 EXPECT_TRUE(net::IsLocalhost("localhost6.localdomain6"));
789 EXPECT_TRUE(net::IsLocalhost("127.0.0.1"));
790 EXPECT_TRUE(net::IsLocalhost("127.0.1.0"));
791 EXPECT_TRUE(net::IsLocalhost("127.1.0.0"));
792 EXPECT_TRUE(net::IsLocalhost("127.0.0.255"));
793 EXPECT_TRUE(net::IsLocalhost("127.0.255.0"));
794 EXPECT_TRUE(net::IsLocalhost("127.255.0.0"));
795 EXPECT_TRUE(net::IsLocalhost("::1"));
796 EXPECT_TRUE(net::IsLocalhost("0:0:0:0:0:0:0:1"));
798 EXPECT_FALSE(net::IsLocalhost("localhostx"));
799 EXPECT_FALSE(net::IsLocalhost("foo.localdomain"));
800 EXPECT_FALSE(net::IsLocalhost("localhost6x"));
801 EXPECT_FALSE(net::IsLocalhost("localhost.localdomain6"));
802 EXPECT_FALSE(net::IsLocalhost("localhost6.localdomain"));
803 EXPECT_FALSE(net::IsLocalhost("127.0.0.1.1"));
804 EXPECT_FALSE(net::IsLocalhost(".127.0.0.255"));
805 EXPECT_FALSE(net::IsLocalhost("::2"));
806 EXPECT_FALSE(net::IsLocalhost("::1:1"));
807 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:1:0:0:1"));
808 EXPECT_FALSE(net::IsLocalhost("::1:1"));
809 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:0:0:0:0:1"));
812 // Verify GetNetworkList().
813 TEST(NetUtilTest, GetNetworkList) {
814 NetworkInterfaceList list;
815 ASSERT_TRUE(GetNetworkList(&list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES));
816 for (NetworkInterfaceList::iterator it = list.begin();
817 it != list.end(); ++it) {
818 // Verify that the names are not empty.
819 EXPECT_FALSE(it->name.empty());
820 EXPECT_FALSE(it->friendly_name.empty());
822 // Verify that the address is correct.
823 EXPECT_TRUE(it->address.size() == kIPv4AddressSize ||
824 it->address.size() == kIPv6AddressSize)
825 << "Invalid address of size " << it->address.size();
826 bool all_zeroes = true;
827 for (size_t i = 0; i < it->address.size(); ++i) {
828 if (it->address[i] != 0) {
829 all_zeroes = false;
830 break;
833 EXPECT_FALSE(all_zeroes);
834 EXPECT_GT(it->prefix_length, 1u);
835 EXPECT_LE(it->prefix_length, it->address.size() * 8);
837 #if defined(OS_WIN)
838 // On Windows |name| is NET_LUID.
839 base::ScopedNativeLibrary phlpapi_lib(
840 base::FilePath(FILE_PATH_LITERAL("iphlpapi.dll")));
841 ASSERT_TRUE(phlpapi_lib.is_valid());
842 typedef NETIO_STATUS (WINAPI* ConvertInterfaceIndexToLuid)(NET_IFINDEX,
843 PNET_LUID);
844 ConvertInterfaceIndexToLuid interface_to_luid =
845 reinterpret_cast<ConvertInterfaceIndexToLuid>(
846 phlpapi_lib.GetFunctionPointer("ConvertInterfaceIndexToLuid"));
848 typedef NETIO_STATUS (WINAPI* ConvertInterfaceLuidToGuid)(NET_LUID*,
849 GUID*);
850 ConvertInterfaceLuidToGuid luid_to_guid =
851 reinterpret_cast<ConvertInterfaceLuidToGuid>(
852 phlpapi_lib.GetFunctionPointer("ConvertInterfaceLuidToGuid"));
854 if (interface_to_luid && luid_to_guid) {
855 NET_LUID luid;
856 EXPECT_EQ(interface_to_luid(it->interface_index, &luid), NO_ERROR);
857 GUID guid;
858 EXPECT_EQ(luid_to_guid(&luid, &guid), NO_ERROR);
859 LPOLESTR name;
860 StringFromCLSID(guid, &name);
861 EXPECT_STREQ(base::UTF8ToWide(it->name).c_str(), name);
862 CoTaskMemFree(name);
863 continue;
864 } else {
865 EXPECT_LT(base::win::GetVersion(), base::win::VERSION_VISTA);
866 EXPECT_LT(it->interface_index, 1u << 24u); // Must fit 0.x.x.x.
867 EXPECT_NE(it->interface_index, 0u); // 0 means to use default.
869 if (it->type == NetworkChangeNotifier::CONNECTION_WIFI) {
870 EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE, GetWifiPHYLayerProtocol());
872 #elif !defined(OS_ANDROID)
873 char name[IF_NAMESIZE];
874 EXPECT_TRUE(if_indextoname(it->interface_index, name));
875 EXPECT_STREQ(it->name.c_str(), name);
876 #endif
880 static const char ifname_em1[] = "em1";
881 #if defined(OS_WIN)
882 static const char ifname_vm[] = "VMnet";
883 #else
884 static const char ifname_vm[] = "vmnet";
885 #endif // OS_WIN
887 static const unsigned char kIPv6LocalAddr[] = {
888 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
890 // The following 3 addresses need to be changed together. IPv6Addr is the IPv6
891 // address. IPv6Netmask is the mask address with as many leading bits set to 1
892 // as the prefix length. IPv6AddrPrefix needs to match IPv6Addr with the same
893 // number of bits as the prefix length.
894 static const unsigned char kIPv6Addr[] =
895 {0x24, 0x01, 0xfa, 0x00, 0x00, 0x04, 0x10, 0x00, 0xbe, 0x30, 0x5b, 0xff,
896 0xfe, 0xe5, 0x00, 0xc3};
897 #if defined(OS_WIN)
898 static const unsigned char kIPv6AddrPrefix[] =
899 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
900 0x00, 0x00, 0x00, 0x00};
901 #endif // OS_WIN
902 #if defined(OS_MACOSX)
903 static const unsigned char kIPv6Netmask[] =
904 {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
905 0x00, 0x00, 0x00, 0x00};
906 #endif // OS_MACOSX
908 #if !defined(OS_MACOSX) && !defined(OS_WIN) && !defined(OS_NACL)
910 char* CopyInterfaceName(const char* ifname, int ifname_size, char* output) {
911 EXPECT_LT(ifname_size, IF_NAMESIZE);
912 memcpy(output, ifname, ifname_size);
913 return output;
916 char* GetInterfaceName(unsigned int interface_index, char* ifname) {
917 return CopyInterfaceName(ifname_em1, arraysize(ifname_em1), ifname);
920 char* GetInterfaceNameVM(unsigned int interface_index, char* ifname) {
921 return CopyInterfaceName(ifname_vm, arraysize(ifname_vm), ifname);
924 TEST(NetUtilTest, GetNetworkListTrimming) {
925 IPAddressNumber ipv6_local_address(
926 kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
927 IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
929 NetworkInterfaceList results;
930 ::base::hash_set<int> online_links;
931 net::internal::AddressTrackerLinux::AddressMap address_map;
933 // Interface 1 is offline.
934 struct ifaddrmsg msg = {
935 AF_INET6,
936 1, /* prefix length */
937 IFA_F_TEMPORARY, /* address flags */
938 0, /* link scope */
939 1 /* link index */
942 // Address of offline links should be ignored.
943 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
944 EXPECT_TRUE(
945 net::internal::GetNetworkListImpl(&results,
946 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
947 online_links,
948 address_map,
949 GetInterfaceName));
950 EXPECT_EQ(results.size(), 0ul);
952 // Mark interface 1 online.
953 online_links.insert(1);
955 // Local address should be trimmed out.
956 address_map.clear();
957 ASSERT_TRUE(
958 address_map.insert(std::make_pair(ipv6_local_address, msg)).second);
959 EXPECT_TRUE(
960 net::internal::GetNetworkListImpl(&results,
961 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
962 online_links,
963 address_map,
964 GetInterfaceName));
965 EXPECT_EQ(results.size(), 0ul);
967 // vmware address should return by default.
968 address_map.clear();
969 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
970 EXPECT_TRUE(
971 net::internal::GetNetworkListImpl(&results,
972 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
973 online_links,
974 address_map,
975 GetInterfaceNameVM));
976 EXPECT_EQ(results.size(), 1ul);
977 EXPECT_EQ(results[0].name, ifname_vm);
978 EXPECT_EQ(results[0].prefix_length, 1ul);
979 EXPECT_EQ(results[0].address, ipv6_address);
980 results.clear();
982 // vmware address should be trimmed out if policy specified so.
983 address_map.clear();
984 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
985 EXPECT_TRUE(
986 net::internal::GetNetworkListImpl(&results,
987 EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
988 online_links,
989 address_map,
990 GetInterfaceNameVM));
991 EXPECT_EQ(results.size(), 0ul);
992 results.clear();
994 // Addresses with banned attributes should be ignored.
995 address_map.clear();
996 msg.ifa_flags = IFA_F_TENTATIVE;
997 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
998 EXPECT_TRUE(
999 net::internal::GetNetworkListImpl(&results,
1000 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
1001 online_links,
1002 address_map,
1003 GetInterfaceName));
1004 EXPECT_EQ(results.size(), 0ul);
1005 results.clear();
1007 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1008 // attributes should be translated correctly.
1009 address_map.clear();
1010 msg.ifa_flags = IFA_F_TEMPORARY;
1011 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
1012 EXPECT_TRUE(
1013 net::internal::GetNetworkListImpl(&results,
1014 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
1015 online_links,
1016 address_map,
1017 GetInterfaceName));
1018 EXPECT_EQ(results.size(), 1ul);
1019 EXPECT_EQ(results[0].name, ifname_em1);
1020 EXPECT_EQ(results[0].prefix_length, 1ul);
1021 EXPECT_EQ(results[0].address, ipv6_address);
1022 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
1023 results.clear();
1025 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1026 // attributes should be translated correctly.
1027 address_map.clear();
1028 msg.ifa_flags = IFA_F_DEPRECATED;
1029 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
1030 EXPECT_TRUE(
1031 net::internal::GetNetworkListImpl(&results,
1032 INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES,
1033 online_links,
1034 address_map,
1035 GetInterfaceName));
1036 EXPECT_EQ(results.size(), 1ul);
1037 EXPECT_EQ(results[0].name, ifname_em1);
1038 EXPECT_EQ(results[0].prefix_length, 1ul);
1039 EXPECT_EQ(results[0].address, ipv6_address);
1040 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
1041 results.clear();
1044 #elif defined(OS_MACOSX)
1046 TEST(NetUtilTest, GetNetworkListTrimming) {
1047 IPAddressNumber ipv6_local_address(
1048 kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
1049 IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
1050 IPAddressNumber ipv6_netmask(kIPv6Netmask,
1051 kIPv6Netmask + arraysize(kIPv6Netmask));
1053 NetworkInterfaceList results;
1054 IPAttributesGetterTest ip_attributes_getter;
1055 sockaddr_storage addresses[2];
1056 ifaddrs interface;
1058 // Address of offline links should be ignored.
1059 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_UP, ipv6_address,
1060 ipv6_netmask, addresses));
1061 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1062 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1063 &ip_attributes_getter));
1064 EXPECT_EQ(results.size(), 0ul);
1066 // Local address should be trimmed out.
1067 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING,
1068 ipv6_local_address, ipv6_netmask, addresses));
1069 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1070 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1071 &ip_attributes_getter));
1072 EXPECT_EQ(results.size(), 0ul);
1074 // vmware address should return by default.
1075 ASSERT_TRUE(FillIfaddrs(&interface, ifname_vm, IFF_RUNNING, ipv6_address,
1076 ipv6_netmask, addresses));
1077 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1078 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1079 &ip_attributes_getter));
1080 EXPECT_EQ(results.size(), 1ul);
1081 EXPECT_EQ(results[0].name, ifname_vm);
1082 EXPECT_EQ(results[0].prefix_length, 1ul);
1083 EXPECT_EQ(results[0].address, ipv6_address);
1084 results.clear();
1086 // vmware address should be trimmed out if policy specified so.
1087 ASSERT_TRUE(FillIfaddrs(&interface, ifname_vm, IFF_RUNNING, ipv6_address,
1088 ipv6_netmask, addresses));
1089 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1090 &results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1091 &ip_attributes_getter));
1092 EXPECT_EQ(results.size(), 0ul);
1093 results.clear();
1095 #if !defined(OS_IOS)
1096 // Addresses with banned attributes should be ignored.
1097 ip_attributes_getter.set_native_attributes(IN6_IFF_ANYCAST);
1098 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
1099 ipv6_netmask, addresses));
1100 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1101 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1102 &ip_attributes_getter));
1103 EXPECT_EQ(results.size(), 0ul);
1104 results.clear();
1106 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1107 // attributes should be translated correctly.
1108 ip_attributes_getter.set_native_attributes(IN6_IFF_TEMPORARY);
1109 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
1110 ipv6_netmask, addresses));
1111 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1112 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1113 &ip_attributes_getter));
1114 EXPECT_EQ(results.size(), 1ul);
1115 EXPECT_EQ(results[0].name, ifname_em1);
1116 EXPECT_EQ(results[0].prefix_length, 1ul);
1117 EXPECT_EQ(results[0].address, ipv6_address);
1118 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
1119 results.clear();
1121 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1122 // attributes should be translated correctly.
1123 ip_attributes_getter.set_native_attributes(IN6_IFF_DEPRECATED);
1124 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
1125 ipv6_netmask, addresses));
1126 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1127 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1128 &ip_attributes_getter));
1129 EXPECT_EQ(results.size(), 1ul);
1130 EXPECT_EQ(results[0].name, ifname_em1);
1131 EXPECT_EQ(results[0].prefix_length, 1ul);
1132 EXPECT_EQ(results[0].address, ipv6_address);
1133 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
1134 results.clear();
1135 #endif // !OS_IOS
1137 #elif defined(OS_WIN) // !OS_MACOSX && !OS_WIN && !OS_NACL
1139 // Helper function to create a valid IP_ADAPTER_ADDRESSES with reasonable
1140 // default value. The output is the |adapter_address|. All the rests are input
1141 // to fill the |adapter_address|. |sock_addrs| are temporary storage used by
1142 // |adapter_address| once the function is returned.
1143 bool FillAdapterAddress(IP_ADAPTER_ADDRESSES* adapter_address,
1144 const char* ifname,
1145 const IPAddressNumber& ip_address,
1146 const IPAddressNumber& ip_netmask,
1147 sockaddr_storage sock_addrs[2]) {
1148 adapter_address->AdapterName = const_cast<char*>(ifname);
1149 adapter_address->FriendlyName = const_cast<PWCHAR>(L"interface");
1150 adapter_address->IfType = IF_TYPE_ETHERNET_CSMACD;
1151 adapter_address->OperStatus = IfOperStatusUp;
1152 adapter_address->FirstUnicastAddress->DadState = IpDadStatePreferred;
1153 adapter_address->FirstUnicastAddress->PrefixOrigin = IpPrefixOriginOther;
1154 adapter_address->FirstUnicastAddress->SuffixOrigin = IpSuffixOriginOther;
1155 adapter_address->FirstUnicastAddress->PreferredLifetime = 100;
1156 adapter_address->FirstUnicastAddress->ValidLifetime = 1000;
1158 socklen_t sock_len = sizeof(sockaddr_storage);
1160 // Convert to sockaddr for next check.
1161 if (!IPEndPoint(ip_address, 0)
1162 .ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[0]),
1163 &sock_len)) {
1164 return false;
1166 adapter_address->FirstUnicastAddress->Address.lpSockaddr =
1167 reinterpret_cast<sockaddr*>(&sock_addrs[0]);
1168 adapter_address->FirstUnicastAddress->Address.iSockaddrLength = sock_len;
1169 adapter_address->FirstUnicastAddress->OnLinkPrefixLength = 1;
1171 sock_len = sizeof(sockaddr_storage);
1172 if (!IPEndPoint(ip_netmask, 0)
1173 .ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[1]),
1174 &sock_len)) {
1175 return false;
1177 adapter_address->FirstPrefix->Address.lpSockaddr =
1178 reinterpret_cast<sockaddr*>(&sock_addrs[1]);
1179 adapter_address->FirstPrefix->Address.iSockaddrLength = sock_len;
1180 adapter_address->FirstPrefix->PrefixLength = 1;
1182 DCHECK_EQ(sock_addrs[0].ss_family, sock_addrs[1].ss_family);
1183 if (sock_addrs[0].ss_family == AF_INET6) {
1184 adapter_address->Ipv6IfIndex = 0;
1185 } else {
1186 DCHECK_EQ(sock_addrs[0].ss_family, AF_INET);
1187 adapter_address->IfIndex = 0;
1190 return true;
1193 TEST(NetUtilTest, GetNetworkListTrimming) {
1194 IPAddressNumber ipv6_local_address(
1195 kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
1196 IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
1197 IPAddressNumber ipv6_prefix(kIPv6AddrPrefix,
1198 kIPv6AddrPrefix + arraysize(kIPv6AddrPrefix));
1200 NetworkInterfaceList results;
1201 sockaddr_storage addresses[2];
1202 IP_ADAPTER_ADDRESSES adapter_address = {0};
1203 IP_ADAPTER_UNICAST_ADDRESS address = {0};
1204 IP_ADAPTER_PREFIX adapter_prefix = {0};
1205 adapter_address.FirstUnicastAddress = &address;
1206 adapter_address.FirstPrefix = &adapter_prefix;
1208 // Address of offline links should be ignored.
1209 ASSERT_TRUE(FillAdapterAddress(
1210 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1211 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1212 addresses /* sock_addrs */));
1213 adapter_address.OperStatus = IfOperStatusDown;
1215 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1216 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1218 EXPECT_EQ(results.size(), 0ul);
1220 // Address on loopback interface should be trimmed out.
1221 ASSERT_TRUE(FillAdapterAddress(
1222 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1223 ipv6_local_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1224 addresses /* sock_addrs */));
1225 adapter_address.IfType = IF_TYPE_SOFTWARE_LOOPBACK;
1227 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1228 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1229 EXPECT_EQ(results.size(), 0ul);
1231 // vmware address should return by default.
1232 ASSERT_TRUE(FillAdapterAddress(
1233 &adapter_address /* adapter_address */, ifname_vm /* ifname */,
1234 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1235 addresses /* sock_addrs */));
1236 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1237 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1238 EXPECT_EQ(results.size(), 1ul);
1239 EXPECT_EQ(results[0].name, ifname_vm);
1240 EXPECT_EQ(results[0].prefix_length, 1ul);
1241 EXPECT_EQ(results[0].address, ipv6_address);
1242 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_NONE);
1243 results.clear();
1245 // vmware address should be trimmed out if policy specified so.
1246 ASSERT_TRUE(FillAdapterAddress(
1247 &adapter_address /* adapter_address */, ifname_vm /* ifname */,
1248 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1249 addresses /* sock_addrs */));
1250 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1251 &results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1252 EXPECT_EQ(results.size(), 0ul);
1253 results.clear();
1255 // Addresses with incompleted DAD should be ignored.
1256 ASSERT_TRUE(FillAdapterAddress(
1257 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1258 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1259 addresses /* sock_addrs */));
1260 adapter_address.FirstUnicastAddress->DadState = IpDadStateTentative;
1262 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1263 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1264 EXPECT_EQ(results.size(), 0ul);
1265 results.clear();
1267 // Addresses with allowed attribute IpSuffixOriginRandom should be returned
1268 // and attributes should be translated correctly to
1269 // IP_ADDRESS_ATTRIBUTE_TEMPORARY.
1270 ASSERT_TRUE(FillAdapterAddress(
1271 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1272 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1273 addresses /* sock_addrs */));
1274 adapter_address.FirstUnicastAddress->PrefixOrigin =
1275 IpPrefixOriginRouterAdvertisement;
1276 adapter_address.FirstUnicastAddress->SuffixOrigin = IpSuffixOriginRandom;
1278 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1279 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1280 EXPECT_EQ(results.size(), 1ul);
1281 EXPECT_EQ(results[0].name, ifname_em1);
1282 EXPECT_EQ(results[0].prefix_length, 1ul);
1283 EXPECT_EQ(results[0].address, ipv6_address);
1284 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
1285 results.clear();
1287 // Addresses with preferred lifetime 0 should be returned and
1288 // attributes should be translated correctly to
1289 // IP_ADDRESS_ATTRIBUTE_DEPRECATED.
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->PreferredLifetime = 0;
1295 adapter_address.FriendlyName = const_cast<PWCHAR>(L"FriendlyInterfaceName");
1296 EXPECT_TRUE(net::internal::GetNetworkListImpl(
1297 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1298 EXPECT_EQ(results.size(), 1ul);
1299 EXPECT_EQ(results[0].friendly_name, "FriendlyInterfaceName");
1300 EXPECT_EQ(results[0].name, ifname_em1);
1301 EXPECT_EQ(results[0].prefix_length, 1ul);
1302 EXPECT_EQ(results[0].address, ipv6_address);
1303 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
1304 results.clear();
1307 #endif // !OS_MACOSX && !OS_WIN && !OS_NACL
1309 namespace {
1311 #if defined(OS_WIN)
1312 bool read_int_or_bool(DWORD data_size,
1313 PVOID data) {
1314 switch (data_size) {
1315 case 1:
1316 return !!*reinterpret_cast<uint8*>(data);
1317 case 4:
1318 return !!*reinterpret_cast<uint32*>(data);
1319 default:
1320 LOG(FATAL) << "That is not a type I know!";
1321 return false;
1325 int GetWifiOptions() {
1326 const internal::WlanApi& wlanapi = internal::WlanApi::GetInstance();
1327 if (!wlanapi.initialized)
1328 return -1;
1330 internal::WlanHandle client;
1331 DWORD cur_version = 0;
1332 const DWORD kMaxClientVersion = 2;
1333 DWORD result = wlanapi.OpenHandle(
1334 kMaxClientVersion, &cur_version, &client);
1335 if (result != ERROR_SUCCESS)
1336 return -1;
1338 WLAN_INTERFACE_INFO_LIST* interface_list_ptr = NULL;
1339 result = wlanapi.enum_interfaces_func(client.Get(), NULL,
1340 &interface_list_ptr);
1341 if (result != ERROR_SUCCESS)
1342 return -1;
1343 scoped_ptr<WLAN_INTERFACE_INFO_LIST, internal::WlanApiDeleter> interface_list(
1344 interface_list_ptr);
1346 for (unsigned i = 0; i < interface_list->dwNumberOfItems; ++i) {
1347 WLAN_INTERFACE_INFO* info = &interface_list->InterfaceInfo[i];
1348 DWORD data_size;
1349 PVOID data;
1350 int options = 0;
1351 result = wlanapi.query_interface_func(
1352 client.Get(),
1353 &info->InterfaceGuid,
1354 wlan_intf_opcode_background_scan_enabled,
1355 NULL,
1356 &data_size,
1357 &data,
1358 NULL);
1359 if (result != ERROR_SUCCESS)
1360 continue;
1361 if (!read_int_or_bool(data_size, data)) {
1362 options |= WIFI_OPTIONS_DISABLE_SCAN;
1364 internal::WlanApi::GetInstance().free_memory_func(data);
1366 result = wlanapi.query_interface_func(
1367 client.Get(),
1368 &info->InterfaceGuid,
1369 wlan_intf_opcode_media_streaming_mode,
1370 NULL,
1371 &data_size,
1372 &data,
1373 NULL);
1374 if (result != ERROR_SUCCESS)
1375 continue;
1376 if (read_int_or_bool(data_size, data)) {
1377 options |= WIFI_OPTIONS_MEDIA_STREAMING_MODE;
1379 internal::WlanApi::GetInstance().free_memory_func(data);
1381 // Just the the options from the first succesful
1382 // interface.
1383 return options;
1386 // No wifi interface found.
1387 return -1;
1390 #else // OS_WIN
1392 int GetWifiOptions() {
1393 // Not supported.
1394 return -1;
1397 #endif // OS_WIN
1399 void TryChangeWifiOptions(int options) {
1400 int previous_options = GetWifiOptions();
1401 scoped_ptr<ScopedWifiOptions> scoped_options = SetWifiOptions(options);
1402 EXPECT_EQ(previous_options | options, GetWifiOptions());
1403 scoped_options.reset();
1404 EXPECT_EQ(previous_options, GetWifiOptions());
1407 }; // namespace
1409 // Test SetWifiOptions().
1410 TEST(NetUtilTest, SetWifiOptionsTest) {
1411 TryChangeWifiOptions(0);
1412 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN);
1413 TryChangeWifiOptions(WIFI_OPTIONS_MEDIA_STREAMING_MODE);
1414 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN |
1415 WIFI_OPTIONS_MEDIA_STREAMING_MODE);
1418 struct NonUniqueNameTestData {
1419 bool is_unique;
1420 const char* hostname;
1423 // Google Test pretty-printer.
1424 void PrintTo(const NonUniqueNameTestData& data, std::ostream* os) {
1425 ASSERT_TRUE(data.hostname);
1426 *os << " hostname: " << testing::PrintToString(data.hostname)
1427 << "; is_unique: " << testing::PrintToString(data.is_unique);
1430 const NonUniqueNameTestData kNonUniqueNameTestData[] = {
1431 // Domains under ICANN-assigned domains.
1432 { true, "google.com" },
1433 { true, "google.co.uk" },
1434 // Domains under private registries.
1435 { true, "appspot.com" },
1436 { true, "test.appspot.com" },
1437 // Unreserved IPv4 addresses (in various forms).
1438 { true, "8.8.8.8" },
1439 { true, "99.64.0.0" },
1440 { true, "212.15.0.0" },
1441 { true, "212.15" },
1442 { true, "212.15.0" },
1443 { true, "3557752832" },
1444 // Reserved IPv4 addresses (in various forms).
1445 { false, "192.168.0.0" },
1446 { false, "192.168.0.6" },
1447 { false, "10.0.0.5" },
1448 { false, "10.0" },
1449 { false, "10.0.0" },
1450 { false, "3232235526" },
1451 // Unreserved IPv6 addresses.
1452 { true, "FFC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1453 { true, "2000:ba98:7654:2301:EFCD:BA98:7654:3210" },
1454 // Reserved IPv6 addresses.
1455 { false, "::192.9.5.5" },
1456 { false, "FEED::BEEF" },
1457 { false, "FEC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1458 // 'internal'/non-IANA assigned domains.
1459 { false, "intranet" },
1460 { false, "intranet." },
1461 { false, "intranet.example" },
1462 { false, "host.intranet.example" },
1463 // gTLDs under discussion, but not yet assigned.
1464 { false, "intranet.corp" },
1465 { false, "example.tech" },
1466 { false, "intranet.internal" },
1467 // Invalid host names are treated as unique - but expected to be
1468 // filtered out before then.
1469 { true, "junk)(£)$*!@~#" },
1470 { true, "w$w.example.com" },
1471 { true, "nocolonsallowed:example" },
1472 { true, "[::4.5.6.9]" },
1475 class NetUtilNonUniqueNameTest
1476 : public testing::TestWithParam<NonUniqueNameTestData> {
1477 public:
1478 virtual ~NetUtilNonUniqueNameTest() {}
1480 protected:
1481 bool IsUnique(const std::string& hostname) {
1482 return !IsHostnameNonUnique(hostname);
1486 // Test that internal/non-unique names are properly identified as such, but
1487 // that IP addresses and hosts beneath registry-controlled domains are flagged
1488 // as unique names.
1489 TEST_P(NetUtilNonUniqueNameTest, IsHostnameNonUnique) {
1490 const NonUniqueNameTestData& test_data = GetParam();
1492 EXPECT_EQ(test_data.is_unique, IsUnique(test_data.hostname));
1495 INSTANTIATE_TEST_CASE_P(, NetUtilNonUniqueNameTest,
1496 testing::ValuesIn(kNonUniqueNameTestData));
1498 } // namespace net