net cleanup: Remove unnecessary namespace prefixes.
[chromium-blink-merge.git] / net / base / net_util_unittest.cc
blob5f999afc767bac5ece5ee3576682f521f24f8ad7
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* 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;
75 #endif
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) {
101 std::string out;
102 for (size_t i = 0; i < v.size(); ++i) {
103 if (i != 0)
104 out.append(",");
105 out.append(base::IntToString(static_cast<int>(v[i])));
107 return out;
110 #if defined(OS_MACOSX)
111 class IPAttributesGetterTest : public internal::IPAttributesGetterMac {
112 public:
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_;
119 return true;
121 void set_native_attributes(int native_attributes) {
122 native_attributes_ = native_attributes;
125 private:
126 int native_attributes_;
129 // Helper function to create a single valid ifaddrs
130 bool FillIfaddrs(ifaddrs* interfaces,
131 const char* ifname,
132 uint flags,
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]),
145 &sock_len)) {
146 return false;
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]),
153 &sock_len)) {
154 return false;
156 interfaces->ifa_netmask = reinterpret_cast<sockaddr*>(&sock_addrs[1]);
158 return true;
160 #endif // OS_MACOSX
162 } // anonymous namespace
164 TEST(NetUtilTest, GetIdentityFromURL) {
165 struct {
166 const char* const input_url;
167 const char* const expected_username;
168 const char* const expected_password;
169 } tests[] = {
171 "http://username:password@google.com",
172 "username",
173 "password",
175 { // Test for http://crbug.com/19200
176 "http://username:p@ssword@google.com",
177 "username",
178 "p@ssword",
180 { // Special URL characters should be unescaped.
181 "http://username:p%3fa%26s%2fs%23@google.com",
182 "username",
183 "p?a&s/s#",
185 { // Username contains %20.
186 "http://use rname:password@google.com",
187 "use rname",
188 "password",
190 { // Keep %00 as is.
191 "http://use%00rname:password@google.com",
192 "use%00rname",
193 "password",
195 { // Use a '+' in the username.
196 "http://use+rname:password@google.com",
197 "use+rname",
198 "password",
200 { // Use a '&' in the password.
201 "http://username:p&ssword@google.com",
202 "username",
203 "p&ssword",
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[] =
237 "HTTP/1.1 200 OK\n"
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"
250 "Server: GFE/1.3\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"},
263 {"Bad-Header", ""},
264 {"", ""},
267 // Test first with google_headers.
268 for (size_t i = 0; i < arraysize(tests); ++i) {
269 std::string result =
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[] = {
288 {"", false},
289 {"a", true},
290 {"-", false},
291 {".", false},
292 {"9", true},
293 {"9a", true},
294 {"a.", true},
295 {"a.a", true},
296 {"9.a", true},
297 {"a.9", true},
298 {"_9a", false},
299 {"-9a", false},
300 {"a.a9", true},
301 {"a.-a9", false},
302 {"a+9a", false},
303 {"-a.a9", true},
304 {"1-.a-b", true},
305 {"1_.a-b", false},
306 {"1-2.a_b", true},
307 {"a.b.c.d.e", true},
308 {"1.2.3.4.5", true},
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) {
319 const struct {
320 const char* const input;
321 bool success;
322 const char* const expected_host;
323 int expected_port;
324 } tests[] = {
325 // Valid inputs:
326 {"foo:10", true, "foo", 10},
327 {"foo", true, "foo", -1},
329 "[1080:0:0:0:8:800:200C:4171]:11",
330 true,
331 "1080:0:0:0:8:800:200C:4171",
335 "[1080:0:0:0:8:800:200C:4171]",
336 true,
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},
345 // Invalid inputs:
346 {"foo:bar", false, "", -1},
347 {"foo:", false, "", -1},
348 {":", false, "", -1},
349 {":80", false, "", -1},
350 {"", 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) {
363 std::string host;
364 int port;
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) {
377 const struct {
378 GURL url;
379 const char* const expected_host_and_port;
380 } tests[] = {
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) {
395 const struct {
396 GURL url;
397 const char* const expected_host_and_port;
398 } tests[] = {
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) {
437 const struct {
438 uint8 addr[4];
439 const char* const result;
440 } tests[] = {
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) {
455 const struct {
456 uint8 addr[16];
457 const char* const result;
458 } tests[] = {
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,
477 storage.addr_len);
478 EXPECT_EQ("127.0.0.1:166", result);
481 TEST(NetUtilTest, NetAddressToStringWithPort_IPv6) {
482 uint8 addr[] = {
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,
489 storage.addr_len);
491 // May fail on systems that don't support IPv6.
492 if (!result.empty())
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) {
505 struct {
506 const char* const input_url;
507 const char* const expected_simplified_url;
508 } tests[] = {
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[] = {
674 "foobar",
676 "192.168.0.1",
677 "::1",
678 "/",
679 "/1",
680 "1",
681 "192.168.1.1/-1",
682 "192.168.1.1/33",
683 "::1/-3",
684 "a::3/129",
685 "::1/x",
686 "192.168.0.1//11"
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],
694 &ip_number,
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",
705 &ip_number,
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) {
713 struct {
714 const char* const cidr_literal;
715 const char* const ip_literal;
716 bool expected_to_match;
717 } tests[] = {
718 // IPv4 prefix with IPv4 inputs.
720 "10.10.1.32/27",
721 "10.10.1.44",
722 true
725 "10.10.1.32/27",
726 "10.10.1.90",
727 false
730 "10.10.1.32/27",
731 "10.10.1.90",
732 false
735 // IPv6 prefix with IPv6 inputs.
737 "2001:db8::/32",
738 "2001:DB8:3:4::5",
739 true
742 "2001:db8::/32",
743 "2001:c8::",
744 false
747 // IPv6 prefix with IPv4 inputs.
749 "2001:db8::/33",
750 "192.168.0.1",
751 false
754 "::ffff:192.168.0.1/112",
755 "192.168.33.77",
756 true
759 // IPv4 prefix with IPv6 inputs.
761 "10.11.33.44/16",
762 "::ffff:0a0b:89",
763 true
766 "10.11.33.44/16",
767 "::ffff:10.12.33.44",
768 false
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,
783 &ip_prefix,
784 &prefix_length_in_bits));
786 EXPECT_EQ(tests[i].expected_to_match,
787 IPNumberMatchesPrefix(ip_number,
788 ip_prefix,
789 prefix_length_in_bits));
793 TEST(NetUtilTest, IsLocalhost) {
794 EXPECT_TRUE(IsLocalhost("localhost"));
795 EXPECT_TRUE(IsLocalhost("localhost.localdomain"));
796 EXPECT_TRUE(IsLocalhost("localhost6"));
797 EXPECT_TRUE(IsLocalhost("localhost6.localdomain6"));
798 EXPECT_TRUE(IsLocalhost("127.0.0.1"));
799 EXPECT_TRUE(IsLocalhost("127.0.1.0"));
800 EXPECT_TRUE(IsLocalhost("127.1.0.0"));
801 EXPECT_TRUE(IsLocalhost("127.0.0.255"));
802 EXPECT_TRUE(IsLocalhost("127.0.255.0"));
803 EXPECT_TRUE(IsLocalhost("127.255.0.0"));
804 EXPECT_TRUE(IsLocalhost("::1"));
805 EXPECT_TRUE(IsLocalhost("0:0:0:0:0:0:0:1"));
806 EXPECT_TRUE(IsLocalhost("foo.localhost"));
808 EXPECT_FALSE(IsLocalhost("localhostx"));
809 EXPECT_FALSE(IsLocalhost("foo.localdomain"));
810 EXPECT_FALSE(IsLocalhost("localhost6x"));
811 EXPECT_FALSE(IsLocalhost("localhost.localdomain6"));
812 EXPECT_FALSE(IsLocalhost("localhost6.localdomain"));
813 EXPECT_FALSE(IsLocalhost("127.0.0.1.1"));
814 EXPECT_FALSE(IsLocalhost(".127.0.0.255"));
815 EXPECT_FALSE(IsLocalhost("::2"));
816 EXPECT_FALSE(IsLocalhost("::1:1"));
817 EXPECT_FALSE(IsLocalhost("0:0:0:0:1:0:0:1"));
818 EXPECT_FALSE(IsLocalhost("::1:1"));
819 EXPECT_FALSE(IsLocalhost("0:0:0:0:0:0:0:0:1"));
820 EXPECT_FALSE(IsLocalhost("foo.localhost.com"));
821 EXPECT_FALSE(IsLocalhost("foo.localhoste"));
824 TEST(NetUtilTest, IsLocalhostTLD) {
825 EXPECT_TRUE(IsLocalhostTLD("foo.localhost"));
826 EXPECT_TRUE(IsLocalhostTLD("foo.localhost."));
827 EXPECT_FALSE(IsLocalhostTLD("foo.localhos"));
828 EXPECT_FALSE(IsLocalhostTLD("foo.localhost.com"));
829 EXPECT_FALSE(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) {
849 all_zeroes = false;
850 break;
853 EXPECT_FALSE(all_zeroes);
854 EXPECT_GT(it->prefix_length, 1u);
855 EXPECT_LE(it->prefix_length, it->address.size() * 8);
857 #if defined(OS_WIN)
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,
863 PNET_LUID);
864 ConvertInterfaceIndexToLuid interface_to_luid =
865 reinterpret_cast<ConvertInterfaceIndexToLuid>(
866 phlpapi_lib.GetFunctionPointer("ConvertInterfaceIndexToLuid"));
868 typedef NETIO_STATUS (WINAPI* ConvertInterfaceLuidToGuid)(NET_LUID*,
869 GUID*);
870 ConvertInterfaceLuidToGuid luid_to_guid =
871 reinterpret_cast<ConvertInterfaceLuidToGuid>(
872 phlpapi_lib.GetFunctionPointer("ConvertInterfaceLuidToGuid"));
874 if (interface_to_luid && luid_to_guid) {
875 NET_LUID luid;
876 EXPECT_EQ(interface_to_luid(it->interface_index, &luid), NO_ERROR);
877 GUID guid;
878 EXPECT_EQ(luid_to_guid(&luid, &guid), NO_ERROR);
879 LPOLESTR name;
880 StringFromCLSID(guid, &name);
881 EXPECT_STREQ(base::UTF8ToWide(it->name).c_str(), name);
882 CoTaskMemFree(name);
883 continue;
884 } else {
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);
896 #endif
900 static const char ifname_em1[] = "em1";
901 #if defined(OS_WIN)
902 static const char ifname_vm[] = "VMnet";
903 #else
904 static const char ifname_vm[] = "vmnet";
905 #endif // OS_WIN
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};
917 #if defined(OS_WIN)
918 static const unsigned char kIPv6AddrPrefix[] =
919 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
920 0x00, 0x00, 0x00, 0x00};
921 #endif // OS_WIN
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};
926 #endif // OS_MACOSX
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);
933 return output;
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 internal::AddressTrackerLinux::AddressMap address_map;
953 // Interface 1 is offline.
954 struct ifaddrmsg msg = {
955 AF_INET6,
956 1, /* prefix length */
957 IFA_F_TEMPORARY, /* address flags */
958 0, /* link scope */
959 1 /* link index */
962 // Address of offline links should be ignored.
963 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
964 EXPECT_TRUE(internal::GetNetworkListImpl(
965 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
966 address_map, GetInterfaceName));
967 EXPECT_EQ(results.size(), 0ul);
969 // Mark interface 1 online.
970 online_links.insert(1);
972 // Local address should be trimmed out.
973 address_map.clear();
974 ASSERT_TRUE(
975 address_map.insert(std::make_pair(ipv6_local_address, msg)).second);
976 EXPECT_TRUE(internal::GetNetworkListImpl(
977 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
978 address_map, GetInterfaceName));
979 EXPECT_EQ(results.size(), 0ul);
981 // vmware address should return by default.
982 address_map.clear();
983 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
984 EXPECT_TRUE(internal::GetNetworkListImpl(
985 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
986 address_map, GetInterfaceNameVM));
987 EXPECT_EQ(results.size(), 1ul);
988 EXPECT_EQ(results[0].name, ifname_vm);
989 EXPECT_EQ(results[0].prefix_length, 1ul);
990 EXPECT_EQ(results[0].address, ipv6_address);
991 results.clear();
993 // vmware address should be trimmed out if policy specified so.
994 address_map.clear();
995 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
996 EXPECT_TRUE(internal::GetNetworkListImpl(
997 &results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
998 address_map, GetInterfaceNameVM));
999 EXPECT_EQ(results.size(), 0ul);
1000 results.clear();
1002 // Addresses with banned attributes should be ignored.
1003 address_map.clear();
1004 msg.ifa_flags = IFA_F_TENTATIVE;
1005 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
1006 EXPECT_TRUE(internal::GetNetworkListImpl(
1007 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
1008 address_map, GetInterfaceName));
1009 EXPECT_EQ(results.size(), 0ul);
1010 results.clear();
1012 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1013 // attributes should be translated correctly.
1014 address_map.clear();
1015 msg.ifa_flags = IFA_F_TEMPORARY;
1016 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
1017 EXPECT_TRUE(internal::GetNetworkListImpl(
1018 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
1019 address_map, GetInterfaceName));
1020 EXPECT_EQ(results.size(), 1ul);
1021 EXPECT_EQ(results[0].name, ifname_em1);
1022 EXPECT_EQ(results[0].prefix_length, 1ul);
1023 EXPECT_EQ(results[0].address, ipv6_address);
1024 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
1025 results.clear();
1027 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1028 // attributes should be translated correctly.
1029 address_map.clear();
1030 msg.ifa_flags = IFA_F_DEPRECATED;
1031 ASSERT_TRUE(address_map.insert(std::make_pair(ipv6_address, msg)).second);
1032 EXPECT_TRUE(internal::GetNetworkListImpl(
1033 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, online_links,
1034 address_map, GetInterfaceName));
1035 EXPECT_EQ(results.size(), 1ul);
1036 EXPECT_EQ(results[0].name, ifname_em1);
1037 EXPECT_EQ(results[0].prefix_length, 1ul);
1038 EXPECT_EQ(results[0].address, ipv6_address);
1039 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
1040 results.clear();
1043 #elif defined(OS_MACOSX)
1045 TEST(NetUtilTest, GetNetworkListTrimming) {
1046 IPAddressNumber ipv6_local_address(
1047 kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
1048 IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
1049 IPAddressNumber ipv6_netmask(kIPv6Netmask,
1050 kIPv6Netmask + arraysize(kIPv6Netmask));
1052 NetworkInterfaceList results;
1053 IPAttributesGetterTest ip_attributes_getter;
1054 sockaddr_storage addresses[2];
1055 ifaddrs interface;
1057 // Address of offline links should be ignored.
1058 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_UP, ipv6_address,
1059 ipv6_netmask, addresses));
1060 EXPECT_TRUE(internal::GetNetworkListImpl(
1061 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1062 &ip_attributes_getter));
1063 EXPECT_EQ(results.size(), 0ul);
1065 // Local address should be trimmed out.
1066 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING,
1067 ipv6_local_address, ipv6_netmask, addresses));
1068 EXPECT_TRUE(internal::GetNetworkListImpl(
1069 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1070 &ip_attributes_getter));
1071 EXPECT_EQ(results.size(), 0ul);
1073 // vmware address should return by default.
1074 ASSERT_TRUE(FillIfaddrs(&interface, ifname_vm, IFF_RUNNING, ipv6_address,
1075 ipv6_netmask, addresses));
1076 EXPECT_TRUE(internal::GetNetworkListImpl(
1077 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1078 &ip_attributes_getter));
1079 EXPECT_EQ(results.size(), 1ul);
1080 EXPECT_EQ(results[0].name, ifname_vm);
1081 EXPECT_EQ(results[0].prefix_length, 1ul);
1082 EXPECT_EQ(results[0].address, ipv6_address);
1083 results.clear();
1085 // vmware address should be trimmed out if policy specified so.
1086 ASSERT_TRUE(FillIfaddrs(&interface, ifname_vm, IFF_RUNNING, ipv6_address,
1087 ipv6_netmask, addresses));
1088 EXPECT_TRUE(internal::GetNetworkListImpl(
1089 &results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1090 &ip_attributes_getter));
1091 EXPECT_EQ(results.size(), 0ul);
1092 results.clear();
1094 #if !defined(OS_IOS)
1095 // Addresses with banned attributes should be ignored.
1096 ip_attributes_getter.set_native_attributes(IN6_IFF_ANYCAST);
1097 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
1098 ipv6_netmask, addresses));
1099 EXPECT_TRUE(internal::GetNetworkListImpl(
1100 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1101 &ip_attributes_getter));
1102 EXPECT_EQ(results.size(), 0ul);
1103 results.clear();
1105 // Addresses with allowed attribute IFA_F_TEMPORARY should be returned and
1106 // attributes should be translated correctly.
1107 ip_attributes_getter.set_native_attributes(IN6_IFF_TEMPORARY);
1108 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
1109 ipv6_netmask, addresses));
1110 EXPECT_TRUE(internal::GetNetworkListImpl(
1111 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1112 &ip_attributes_getter));
1113 EXPECT_EQ(results.size(), 1ul);
1114 EXPECT_EQ(results[0].name, ifname_em1);
1115 EXPECT_EQ(results[0].prefix_length, 1ul);
1116 EXPECT_EQ(results[0].address, ipv6_address);
1117 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
1118 results.clear();
1120 // Addresses with allowed attribute IFA_F_DEPRECATED should be returned and
1121 // attributes should be translated correctly.
1122 ip_attributes_getter.set_native_attributes(IN6_IFF_DEPRECATED);
1123 ASSERT_TRUE(FillIfaddrs(&interface, ifname_em1, IFF_RUNNING, ipv6_address,
1124 ipv6_netmask, addresses));
1125 EXPECT_TRUE(internal::GetNetworkListImpl(
1126 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, &interface,
1127 &ip_attributes_getter));
1128 EXPECT_EQ(results.size(), 1ul);
1129 EXPECT_EQ(results[0].name, ifname_em1);
1130 EXPECT_EQ(results[0].prefix_length, 1ul);
1131 EXPECT_EQ(results[0].address, ipv6_address);
1132 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
1133 results.clear();
1134 #endif // !OS_IOS
1136 #elif defined(OS_WIN) // !OS_MACOSX && !OS_WIN && !OS_NACL
1138 // Helper function to create a valid IP_ADAPTER_ADDRESSES with reasonable
1139 // default value. The output is the |adapter_address|. All the rests are input
1140 // to fill the |adapter_address|. |sock_addrs| are temporary storage used by
1141 // |adapter_address| once the function is returned.
1142 bool FillAdapterAddress(IP_ADAPTER_ADDRESSES* adapter_address,
1143 const char* ifname,
1144 const IPAddressNumber& ip_address,
1145 const IPAddressNumber& ip_netmask,
1146 sockaddr_storage sock_addrs[2]) {
1147 adapter_address->AdapterName = const_cast<char*>(ifname);
1148 adapter_address->FriendlyName = const_cast<PWCHAR>(L"interface");
1149 adapter_address->IfType = IF_TYPE_ETHERNET_CSMACD;
1150 adapter_address->OperStatus = IfOperStatusUp;
1151 adapter_address->FirstUnicastAddress->DadState = IpDadStatePreferred;
1152 adapter_address->FirstUnicastAddress->PrefixOrigin = IpPrefixOriginOther;
1153 adapter_address->FirstUnicastAddress->SuffixOrigin = IpSuffixOriginOther;
1154 adapter_address->FirstUnicastAddress->PreferredLifetime = 100;
1155 adapter_address->FirstUnicastAddress->ValidLifetime = 1000;
1157 socklen_t sock_len = sizeof(sockaddr_storage);
1159 // Convert to sockaddr for next check.
1160 if (!IPEndPoint(ip_address, 0)
1161 .ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[0]),
1162 &sock_len)) {
1163 return false;
1165 adapter_address->FirstUnicastAddress->Address.lpSockaddr =
1166 reinterpret_cast<sockaddr*>(&sock_addrs[0]);
1167 adapter_address->FirstUnicastAddress->Address.iSockaddrLength = sock_len;
1168 adapter_address->FirstUnicastAddress->OnLinkPrefixLength = 1;
1170 sock_len = sizeof(sockaddr_storage);
1171 if (!IPEndPoint(ip_netmask, 0)
1172 .ToSockAddr(reinterpret_cast<sockaddr*>(&sock_addrs[1]),
1173 &sock_len)) {
1174 return false;
1176 adapter_address->FirstPrefix->Address.lpSockaddr =
1177 reinterpret_cast<sockaddr*>(&sock_addrs[1]);
1178 adapter_address->FirstPrefix->Address.iSockaddrLength = sock_len;
1179 adapter_address->FirstPrefix->PrefixLength = 1;
1181 DCHECK_EQ(sock_addrs[0].ss_family, sock_addrs[1].ss_family);
1182 if (sock_addrs[0].ss_family == AF_INET6) {
1183 adapter_address->Ipv6IfIndex = 0;
1184 } else {
1185 DCHECK_EQ(sock_addrs[0].ss_family, AF_INET);
1186 adapter_address->IfIndex = 0;
1189 return true;
1192 TEST(NetUtilTest, GetNetworkListTrimming) {
1193 IPAddressNumber ipv6_local_address(
1194 kIPv6LocalAddr, kIPv6LocalAddr + arraysize(kIPv6LocalAddr));
1195 IPAddressNumber ipv6_address(kIPv6Addr, kIPv6Addr + arraysize(kIPv6Addr));
1196 IPAddressNumber ipv6_prefix(kIPv6AddrPrefix,
1197 kIPv6AddrPrefix + arraysize(kIPv6AddrPrefix));
1199 NetworkInterfaceList results;
1200 sockaddr_storage addresses[2];
1201 IP_ADAPTER_ADDRESSES adapter_address = {0};
1202 IP_ADAPTER_UNICAST_ADDRESS address = {0};
1203 IP_ADAPTER_PREFIX adapter_prefix = {0};
1204 adapter_address.FirstUnicastAddress = &address;
1205 adapter_address.FirstPrefix = &adapter_prefix;
1207 // Address of offline links should be ignored.
1208 ASSERT_TRUE(FillAdapterAddress(
1209 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1210 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1211 addresses /* sock_addrs */));
1212 adapter_address.OperStatus = IfOperStatusDown;
1214 EXPECT_TRUE(internal::GetNetworkListImpl(
1215 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1217 EXPECT_EQ(results.size(), 0ul);
1219 // Address on loopback interface should be trimmed out.
1220 ASSERT_TRUE(FillAdapterAddress(
1221 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1222 ipv6_local_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1223 addresses /* sock_addrs */));
1224 adapter_address.IfType = IF_TYPE_SOFTWARE_LOOPBACK;
1226 EXPECT_TRUE(internal::GetNetworkListImpl(
1227 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1228 EXPECT_EQ(results.size(), 0ul);
1230 // vmware address should return by default.
1231 ASSERT_TRUE(FillAdapterAddress(
1232 &adapter_address /* adapter_address */, ifname_vm /* ifname */,
1233 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1234 addresses /* sock_addrs */));
1235 EXPECT_TRUE(internal::GetNetworkListImpl(
1236 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1237 EXPECT_EQ(results.size(), 1ul);
1238 EXPECT_EQ(results[0].name, ifname_vm);
1239 EXPECT_EQ(results[0].prefix_length, 1ul);
1240 EXPECT_EQ(results[0].address, ipv6_address);
1241 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_NONE);
1242 results.clear();
1244 // vmware address should be trimmed out if policy specified so.
1245 ASSERT_TRUE(FillAdapterAddress(
1246 &adapter_address /* adapter_address */, ifname_vm /* ifname */,
1247 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1248 addresses /* sock_addrs */));
1249 EXPECT_TRUE(internal::GetNetworkListImpl(
1250 &results, EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1251 EXPECT_EQ(results.size(), 0ul);
1252 results.clear();
1254 // Addresses with incompleted DAD should be ignored.
1255 ASSERT_TRUE(FillAdapterAddress(
1256 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1257 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1258 addresses /* sock_addrs */));
1259 adapter_address.FirstUnicastAddress->DadState = IpDadStateTentative;
1261 EXPECT_TRUE(internal::GetNetworkListImpl(
1262 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1263 EXPECT_EQ(results.size(), 0ul);
1264 results.clear();
1266 // Addresses with allowed attribute IpSuffixOriginRandom should be returned
1267 // and attributes should be translated correctly to
1268 // IP_ADDRESS_ATTRIBUTE_TEMPORARY.
1269 ASSERT_TRUE(FillAdapterAddress(
1270 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1271 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1272 addresses /* sock_addrs */));
1273 adapter_address.FirstUnicastAddress->PrefixOrigin =
1274 IpPrefixOriginRouterAdvertisement;
1275 adapter_address.FirstUnicastAddress->SuffixOrigin = IpSuffixOriginRandom;
1277 EXPECT_TRUE(internal::GetNetworkListImpl(
1278 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1279 EXPECT_EQ(results.size(), 1ul);
1280 EXPECT_EQ(results[0].name, ifname_em1);
1281 EXPECT_EQ(results[0].prefix_length, 1ul);
1282 EXPECT_EQ(results[0].address, ipv6_address);
1283 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_TEMPORARY);
1284 results.clear();
1286 // Addresses with preferred lifetime 0 should be returned and
1287 // attributes should be translated correctly to
1288 // IP_ADDRESS_ATTRIBUTE_DEPRECATED.
1289 ASSERT_TRUE(FillAdapterAddress(
1290 &adapter_address /* adapter_address */, ifname_em1 /* ifname */,
1291 ipv6_address /* ip_address */, ipv6_prefix /* ip_netmask */,
1292 addresses /* sock_addrs */));
1293 adapter_address.FirstUnicastAddress->PreferredLifetime = 0;
1294 adapter_address.FriendlyName = const_cast<PWCHAR>(L"FriendlyInterfaceName");
1295 EXPECT_TRUE(internal::GetNetworkListImpl(
1296 &results, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, true, &adapter_address));
1297 EXPECT_EQ(results.size(), 1ul);
1298 EXPECT_EQ(results[0].friendly_name, "FriendlyInterfaceName");
1299 EXPECT_EQ(results[0].name, ifname_em1);
1300 EXPECT_EQ(results[0].prefix_length, 1ul);
1301 EXPECT_EQ(results[0].address, ipv6_address);
1302 EXPECT_EQ(results[0].ip_address_attributes, IP_ADDRESS_ATTRIBUTE_DEPRECATED);
1303 results.clear();
1306 #endif // !OS_MACOSX && !OS_WIN && !OS_NACL
1308 TEST(NetUtilTest, GetWifiSSID) {
1309 // We can't check the result of GetWifiSSID() directly, since the result
1310 // will differ across machines. Simply exercise the code path and hope that it
1311 // doesn't crash.
1312 EXPECT_NE((const char*)NULL, GetWifiSSID().c_str());
1315 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_CHROMEOS)
1316 TEST(NetUtilTest, GetWifiSSIDFromInterfaceList) {
1317 NetworkInterfaceList list;
1318 EXPECT_EQ(std::string(), internal::GetWifiSSIDFromInterfaceListInternal(
1319 list, TestGetInterfaceSSID));
1321 NetworkInterface interface1;
1322 interface1.name = "wlan0";
1323 interface1.type = NetworkChangeNotifier::CONNECTION_WIFI;
1324 list.push_back(interface1);
1325 ASSERT_EQ(1u, list.size());
1326 EXPECT_EQ(std::string(kWiFiSSID),
1327 internal::GetWifiSSIDFromInterfaceListInternal(
1328 list, TestGetInterfaceSSID));
1330 NetworkInterface interface2;
1331 interface2.name = "wlan1";
1332 interface2.type = NetworkChangeNotifier::CONNECTION_WIFI;
1333 list.push_back(interface2);
1334 ASSERT_EQ(2u, list.size());
1335 EXPECT_EQ(std::string(kWiFiSSID),
1336 internal::GetWifiSSIDFromInterfaceListInternal(
1337 list, TestGetInterfaceSSID));
1339 NetworkInterface interface3;
1340 interface3.name = kInterfaceWithDifferentSSID;
1341 interface3.type = NetworkChangeNotifier::CONNECTION_WIFI;
1342 list.push_back(interface3);
1343 ASSERT_EQ(3u, list.size());
1344 EXPECT_EQ(std::string(), internal::GetWifiSSIDFromInterfaceListInternal(
1345 list, TestGetInterfaceSSID));
1347 list.pop_back();
1348 NetworkInterface interface4;
1349 interface4.name = "eth0";
1350 interface4.type = NetworkChangeNotifier::CONNECTION_ETHERNET;
1351 list.push_back(interface4);
1352 ASSERT_EQ(3u, list.size());
1353 EXPECT_EQ(std::string(), internal::GetWifiSSIDFromInterfaceListInternal(
1354 list, TestGetInterfaceSSID));
1356 #endif // OS_LINUX
1358 namespace {
1360 #if defined(OS_WIN)
1361 bool read_int_or_bool(DWORD data_size,
1362 PVOID data) {
1363 switch (data_size) {
1364 case 1:
1365 return !!*reinterpret_cast<uint8*>(data);
1366 case 4:
1367 return !!*reinterpret_cast<uint32*>(data);
1368 default:
1369 LOG(FATAL) << "That is not a type I know!";
1370 return false;
1374 int GetWifiOptions() {
1375 const internal::WlanApi& wlanapi = internal::WlanApi::GetInstance();
1376 if (!wlanapi.initialized)
1377 return -1;
1379 internal::WlanHandle client;
1380 DWORD cur_version = 0;
1381 const DWORD kMaxClientVersion = 2;
1382 DWORD result = wlanapi.OpenHandle(
1383 kMaxClientVersion, &cur_version, &client);
1384 if (result != ERROR_SUCCESS)
1385 return -1;
1387 WLAN_INTERFACE_INFO_LIST* interface_list_ptr = NULL;
1388 result = wlanapi.enum_interfaces_func(client.Get(), NULL,
1389 &interface_list_ptr);
1390 if (result != ERROR_SUCCESS)
1391 return -1;
1392 scoped_ptr<WLAN_INTERFACE_INFO_LIST, internal::WlanApiDeleter> interface_list(
1393 interface_list_ptr);
1395 for (unsigned i = 0; i < interface_list->dwNumberOfItems; ++i) {
1396 WLAN_INTERFACE_INFO* info = &interface_list->InterfaceInfo[i];
1397 DWORD data_size;
1398 PVOID data;
1399 int options = 0;
1400 result = wlanapi.query_interface_func(
1401 client.Get(),
1402 &info->InterfaceGuid,
1403 wlan_intf_opcode_background_scan_enabled,
1404 NULL,
1405 &data_size,
1406 &data,
1407 NULL);
1408 if (result != ERROR_SUCCESS)
1409 continue;
1410 if (!read_int_or_bool(data_size, data)) {
1411 options |= WIFI_OPTIONS_DISABLE_SCAN;
1413 internal::WlanApi::GetInstance().free_memory_func(data);
1415 result = wlanapi.query_interface_func(
1416 client.Get(),
1417 &info->InterfaceGuid,
1418 wlan_intf_opcode_media_streaming_mode,
1419 NULL,
1420 &data_size,
1421 &data,
1422 NULL);
1423 if (result != ERROR_SUCCESS)
1424 continue;
1425 if (read_int_or_bool(data_size, data)) {
1426 options |= WIFI_OPTIONS_MEDIA_STREAMING_MODE;
1428 internal::WlanApi::GetInstance().free_memory_func(data);
1430 // Just the the options from the first succesful
1431 // interface.
1432 return options;
1435 // No wifi interface found.
1436 return -1;
1439 #else // OS_WIN
1441 int GetWifiOptions() {
1442 // Not supported.
1443 return -1;
1446 #endif // OS_WIN
1448 void TryChangeWifiOptions(int options) {
1449 int previous_options = GetWifiOptions();
1450 scoped_ptr<ScopedWifiOptions> scoped_options = SetWifiOptions(options);
1451 EXPECT_EQ(previous_options | options, GetWifiOptions());
1452 scoped_options.reset();
1453 EXPECT_EQ(previous_options, GetWifiOptions());
1456 }; // namespace
1458 // Test SetWifiOptions().
1459 TEST(NetUtilTest, SetWifiOptionsTest) {
1460 TryChangeWifiOptions(0);
1461 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN);
1462 TryChangeWifiOptions(WIFI_OPTIONS_MEDIA_STREAMING_MODE);
1463 TryChangeWifiOptions(WIFI_OPTIONS_DISABLE_SCAN |
1464 WIFI_OPTIONS_MEDIA_STREAMING_MODE);
1467 struct NonUniqueNameTestData {
1468 bool is_unique;
1469 const char* const hostname;
1472 // Google Test pretty-printer.
1473 void PrintTo(const NonUniqueNameTestData& data, std::ostream* os) {
1474 ASSERT_TRUE(data.hostname);
1475 *os << " hostname: " << testing::PrintToString(data.hostname)
1476 << "; is_unique: " << testing::PrintToString(data.is_unique);
1479 const NonUniqueNameTestData kNonUniqueNameTestData[] = {
1480 // Domains under ICANN-assigned domains.
1481 { true, "google.com" },
1482 { true, "google.co.uk" },
1483 // Domains under private registries.
1484 { true, "appspot.com" },
1485 { true, "test.appspot.com" },
1486 // Unreserved IPv4 addresses (in various forms).
1487 { true, "8.8.8.8" },
1488 { true, "99.64.0.0" },
1489 { true, "212.15.0.0" },
1490 { true, "212.15" },
1491 { true, "212.15.0" },
1492 { true, "3557752832" },
1493 // Reserved IPv4 addresses (in various forms).
1494 { false, "192.168.0.0" },
1495 { false, "192.168.0.6" },
1496 { false, "10.0.0.5" },
1497 { false, "10.0" },
1498 { false, "10.0.0" },
1499 { false, "3232235526" },
1500 // Unreserved IPv6 addresses.
1501 { true, "FFC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1502 { true, "2000:ba98:7654:2301:EFCD:BA98:7654:3210" },
1503 // Reserved IPv6 addresses.
1504 { false, "::192.9.5.5" },
1505 { false, "FEED::BEEF" },
1506 { false, "FEC0:ba98:7654:3210:FEDC:BA98:7654:3210" },
1507 // 'internal'/non-IANA assigned domains.
1508 { false, "intranet" },
1509 { false, "intranet." },
1510 { false, "intranet.example" },
1511 { false, "host.intranet.example" },
1512 // gTLDs under discussion, but not yet assigned.
1513 { false, "intranet.corp" },
1514 { false, "intranet.internal" },
1515 // Invalid host names are treated as unique - but expected to be
1516 // filtered out before then.
1517 { true, "junk)(£)$*!@~#" },
1518 { true, "w$w.example.com" },
1519 { true, "nocolonsallowed:example" },
1520 { true, "[::4.5.6.9]" },
1523 class NetUtilNonUniqueNameTest
1524 : public testing::TestWithParam<NonUniqueNameTestData> {
1525 public:
1526 virtual ~NetUtilNonUniqueNameTest() {}
1528 protected:
1529 bool IsUnique(const std::string& hostname) {
1530 return !IsHostnameNonUnique(hostname);
1534 // Test that internal/non-unique names are properly identified as such, but
1535 // that IP addresses and hosts beneath registry-controlled domains are flagged
1536 // as unique names.
1537 TEST_P(NetUtilNonUniqueNameTest, IsHostnameNonUnique) {
1538 const NonUniqueNameTestData& test_data = GetParam();
1540 EXPECT_EQ(test_data.is_unique, IsUnique(test_data.hostname));
1543 INSTANTIATE_TEST_CASE_P(, NetUtilNonUniqueNameTest,
1544 testing::ValuesIn(kNonUniqueNameTestData));
1546 } // namespace net