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. 4 5 #include "net/base/net_util.h" 6 7 #include <string.h> 8 9 #include <ostream> 10 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 "testing/gtest/include/gtest/gtest.h" 21 #include "url/gurl.h" 22 23 #if defined(OS_WIN) 24 #include <iphlpapi.h> 25 #include <objbase.h> 26 #include "base/win/windows_version.h" 27 #elif !defined(OS_ANDROID) 28 #include <net/if.h> 29 #endif // OS_WIN 30 31 using base::ASCIIToUTF16; 32 using base::WideToUTF16; 33 34 namespace net { 35 36 namespace { 37 38 struct HeaderCase { 39 const char* header_name; 40 const char* expected; 41 }; 42 43 struct CompliantHostCase { 44 const char* host; 45 const char* desired_tld; 46 bool expected_output; 47 }; 48 49 // Fills in sockaddr for the given 32-bit address (IPv4.) 50 // |bytes| should be an array of length 4. 51 void MakeIPv4Address(const uint8* bytes, int port, SockaddrStorage* storage) { 52 memset(&storage->addr_storage, 0, sizeof(storage->addr_storage)); 53 storage->addr_len = sizeof(struct sockaddr_in); 54 struct sockaddr_in* addr4 = reinterpret_cast<sockaddr_in*>(storage->addr); 55 addr4->sin_port = base::HostToNet16(port); 56 addr4->sin_family = AF_INET; 57 memcpy(&addr4->sin_addr, bytes, 4); 58 } 59 60 // Fills in sockaddr for the given 128-bit address (IPv6.) 61 // |bytes| should be an array of length 16. 62 void MakeIPv6Address(const uint8* bytes, int port, SockaddrStorage* storage) { 63 memset(&storage->addr_storage, 0, sizeof(storage->addr_storage)); 64 storage->addr_len = sizeof(struct sockaddr_in6); 65 struct sockaddr_in6* addr6 = reinterpret_cast<sockaddr_in6*>(storage->addr); 66 addr6->sin6_port = base::HostToNet16(port); 67 addr6->sin6_family = AF_INET6; 68 memcpy(&addr6->sin6_addr, bytes, 16); 69 } 70 71 // Helper to strignize an IP number (used to define expectations). 72 std::string DumpIPNumber(const IPAddressNumber& v) { 73 std::string out; 74 for (size_t i = 0; i < v.size(); ++i) { 75 if (i != 0) 76 out.append(","); 77 out.append(base::IntToString(static_cast<int>(v[i]))); 78 } 79 return out; 80 } 81 82 } // anonymous namespace 83 84 TEST(NetUtilTest, GetIdentityFromURL) { 85 struct { 86 const char* input_url; 87 const char* expected_username; 88 const char* expected_password; 89 } tests[] = { 90 { 91 "http://username:password@google.com", 92 "username", 93 "password", 94 }, 95 { // Test for http://crbug.com/19200 96 "http://username:p@ssword@google.com", 97 "username", 98 "p@ssword", 99 }, 100 { // Special URL characters should be unescaped. 101 "http://username:p%3fa%26s%2fs%23@google.com", 102 "username", 103 "p?a&s/s#", 104 }, 105 { // Username contains %20. 106 "http://use rname:password (at) google.com", 107 "use rname", 108 "password", 109 }, 110 { // Keep %00 as is. 111 "http://use%00rname:password@google.com", 112 "use%00rname", 113 "password", 114 }, 115 { // Use a '+' in the username. 116 "http://use+rname:password@google.com", 117 "use+rname", 118 "password", 119 }, 120 { // Use a '&' in the password. 121 "http://username:p&ssword@google.com", 122 "username", 123 "p&ssword", 124 }, 125 }; 126 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 127 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, 128 tests[i].input_url)); 129 GURL url(tests[i].input_url); 130 131 base::string16 username, password; 132 GetIdentityFromURL(url, &username, &password); 133 134 EXPECT_EQ(ASCIIToUTF16(tests[i].expected_username), username); 135 EXPECT_EQ(ASCIIToUTF16(tests[i].expected_password), password); 136 } 137 } 138 139 // Try extracting a username which was encoded with UTF8. 140 TEST(NetUtilTest, GetIdentityFromURL_UTF8) { 141 GURL url(WideToUTF16(L"http://foo:\x4f60\x597d@blah.com")); 142 143 EXPECT_EQ("foo", url.username()); 144 EXPECT_EQ("%E4%BD%A0%E5%A5%BD", url.password()); 145 146 // Extract the unescaped identity. 147 base::string16 username, password; 148 GetIdentityFromURL(url, &username, &password); 149 150 // Verify that it was decoded as UTF8. 151 EXPECT_EQ(ASCIIToUTF16("foo"), username); 152 EXPECT_EQ(WideToUTF16(L"\x4f60\x597d"), password); 153 } 154 155 // Just a bunch of fake headers. 156 const char* google_headers = 157 "HTTP/1.1 200 OK\n" 158 "Content-TYPE: text/html; charset=utf-8\n" 159 "Content-disposition: attachment; filename=\"download.pdf\"\n" 160 "Content-Length: 378557\n" 161 "X-Google-Google1: 314159265\n" 162 "X-Google-Google2: aaaa2:7783,bbb21:9441\n" 163 "X-Google-Google4: home\n" 164 "Transfer-Encoding: chunked\n" 165 "Set-Cookie: HEHE_AT=6666x66beef666x6-66xx6666x66; Path=/mail\n" 166 "Set-Cookie: HEHE_HELP=owned:0;Path=/\n" 167 "Set-Cookie: S=gmail=Xxx-beefbeefbeef_beefb:gmail_yj=beefbeef000beefbee" 168 "fbee:gmproxy=bee-fbeefbe; Domain=.google.com; Path=/\n" 169 "X-Google-Google2: /one/two/three/four/five/six/seven-height/nine:9411\n" 170 "Server: GFE/1.3\n" 171 "Transfer-Encoding: chunked\n" 172 "Date: Mon, 13 Nov 2006 21:38:09 GMT\n" 173 "Expires: Tue, 14 Nov 2006 19:23:58 GMT\n" 174 "X-Malformed: bla; arg=test\"\n" 175 "X-Malformed2: bla; arg=\n" 176 "X-Test: bla; arg1=val1; arg2=val2"; 177 178 TEST(NetUtilTest, GetSpecificHeader) { 179 const HeaderCase tests[] = { 180 {"content-type", "text/html; charset=utf-8"}, 181 {"CONTENT-LENGTH", "378557"}, 182 {"Date", "Mon, 13 Nov 2006 21:38:09 GMT"}, 183 {"Bad-Header", ""}, 184 {"", ""}, 185 }; 186 187 // Test first with google_headers. 188 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 189 std::string result = 190 GetSpecificHeader(google_headers, tests[i].header_name); 191 EXPECT_EQ(result, tests[i].expected); 192 } 193 194 // Test again with empty headers. 195 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 196 std::string result = GetSpecificHeader(std::string(), tests[i].header_name); 197 EXPECT_EQ(result, std::string()); 198 } 199 } 200 201 TEST(NetUtilTest, CompliantHost) { 202 const CompliantHostCase compliant_host_cases[] = { 203 {"", "", false}, 204 {"a", "", true}, 205 {"-", "", false}, 206 {".", "", false}, 207 {"9", "", true}, 208 {"9a", "", true}, 209 {"a.", "", true}, 210 {"a.a", "", true}, 211 {"9.a", "", true}, 212 {"a.9", "", true}, 213 {"_9a", "", false}, 214 {"-9a", "", false}, 215 {"-9a", "a", true}, 216 {"a.a9", "", true}, 217 {"a.-a9", "", false}, 218 {"a+9a", "", false}, 219 {"-a.a9", "", true}, 220 {"1-.a-b", "", true}, 221 {"1_.a-b", "", false}, 222 {"1-2.a_b", "", true}, 223 {"a.b.c.d.e", "", true}, 224 {"1.2.3.4.5", "", true}, 225 {"1.2.3.4.5.", "", true}, 226 }; 227 228 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(compliant_host_cases); ++i) { 229 EXPECT_EQ(compliant_host_cases[i].expected_output, 230 IsCanonicalizedHostCompliant(compliant_host_cases[i].host, 231 compliant_host_cases[i].desired_tld)); 232 } 233 } 234 235 TEST(NetUtilTest, ParseHostAndPort) { 236 const struct { 237 const char* input; 238 bool success; 239 const char* expected_host; 240 int expected_port; 241 } tests[] = { 242 // Valid inputs: 243 {"foo:10", true, "foo", 10}, 244 {"foo", true, "foo", -1}, 245 { 246 "[1080:0:0:0:8:800:200C:4171]:11", 247 true, 248 "[1080:0:0:0:8:800:200C:4171]", 249 11, 250 }, 251 // Invalid inputs: 252 {"foo:bar", false, "", -1}, 253 {"foo:", false, "", -1}, 254 {":", false, "", -1}, 255 {":80", false, "", -1}, 256 {"", false, "", -1}, 257 {"porttoolong:300000", false, "", -1}, 258 {"usrname@host", false, "", -1}, 259 {"usrname:password@host", false, "", -1}, 260 {":password@host", false, "", -1}, 261 {":password@host:80", false, "", -1}, 262 {":password@host", false, "", -1}, 263 {"@host", false, "", -1}, 264 }; 265 266 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 267 std::string host; 268 int port; 269 bool ok = ParseHostAndPort(tests[i].input, &host, &port); 270 271 EXPECT_EQ(tests[i].success, ok); 272 273 if (tests[i].success) { 274 EXPECT_EQ(tests[i].expected_host, host); 275 EXPECT_EQ(tests[i].expected_port, port); 276 } 277 } 278 } 279 280 TEST(NetUtilTest, GetHostAndPort) { 281 const struct { 282 GURL url; 283 const char* expected_host_and_port; 284 } tests[] = { 285 { GURL("http://www.foo.com/x"), "www.foo.com:80"}, 286 { GURL("http://www.foo.com:21/x"), "www.foo.com:21"}, 287 288 // For IPv6 literals should always include the brackets. 289 { GURL("http://[1::2]/x"), "[1::2]:80"}, 290 { GURL("http://[::a]:33/x"), "[::a]:33"}, 291 }; 292 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 293 std::string host_and_port = GetHostAndPort(tests[i].url); 294 EXPECT_EQ(std::string(tests[i].expected_host_and_port), host_and_port); 295 } 296 } 297 298 TEST(NetUtilTest, GetHostAndOptionalPort) { 299 const struct { 300 GURL url; 301 const char* expected_host_and_port; 302 } tests[] = { 303 { GURL("http://www.foo.com/x"), "www.foo.com"}, 304 { GURL("http://www.foo.com:21/x"), "www.foo.com:21"}, 305 306 // For IPv6 literals should always include the brackets. 307 { GURL("http://[1::2]/x"), "[1::2]"}, 308 { GURL("http://[::a]:33/x"), "[::a]:33"}, 309 }; 310 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 311 std::string host_and_port = GetHostAndOptionalPort(tests[i].url); 312 EXPECT_EQ(std::string(tests[i].expected_host_and_port), host_and_port); 313 } 314 } 315 316 TEST(NetUtilTest, IPAddressToString) { 317 uint8 addr1[4] = {0, 0, 0, 0}; 318 EXPECT_EQ("0.0.0.0", IPAddressToString(addr1, sizeof(addr1))); 319 320 uint8 addr2[4] = {192, 168, 0, 1}; 321 EXPECT_EQ("192.168.0.1", IPAddressToString(addr2, sizeof(addr2))); 322 323 uint8 addr3[16] = {0xFE, 0xDC, 0xBA, 0x98}; 324 EXPECT_EQ("fedc:ba98::", IPAddressToString(addr3, sizeof(addr3))); 325 } 326 327 TEST(NetUtilTest, IPAddressToStringWithPort) { 328 uint8 addr1[4] = {0, 0, 0, 0}; 329 EXPECT_EQ("0.0.0.0:3", IPAddressToStringWithPort(addr1, sizeof(addr1), 3)); 330 331 uint8 addr2[4] = {192, 168, 0, 1}; 332 EXPECT_EQ("192.168.0.1:99", 333 IPAddressToStringWithPort(addr2, sizeof(addr2), 99)); 334 335 uint8 addr3[16] = {0xFE, 0xDC, 0xBA, 0x98}; 336 EXPECT_EQ("[fedc:ba98::]:8080", 337 IPAddressToStringWithPort(addr3, sizeof(addr3), 8080)); 338 } 339 340 TEST(NetUtilTest, NetAddressToString_IPv4) { 341 const struct { 342 uint8 addr[4]; 343 const char* result; 344 } tests[] = { 345 {{0, 0, 0, 0}, "0.0.0.0"}, 346 {{127, 0, 0, 1}, "127.0.0.1"}, 347 {{192, 168, 0, 1}, "192.168.0.1"}, 348 }; 349 350 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 351 SockaddrStorage storage; 352 MakeIPv4Address(tests[i].addr, 80, &storage); 353 std::string result = NetAddressToString(storage.addr, storage.addr_len); 354 EXPECT_EQ(std::string(tests[i].result), result); 355 } 356 } 357 358 TEST(NetUtilTest, NetAddressToString_IPv6) { 359 const struct { 360 uint8 addr[16]; 361 const char* result; 362 } tests[] = { 363 {{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA, 364 0x98, 0x76, 0x54, 0x32, 0x10}, 365 "fedc:ba98:7654:3210:fedc:ba98:7654:3210"}, 366 }; 367 368 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 369 SockaddrStorage storage; 370 MakeIPv6Address(tests[i].addr, 80, &storage); 371 EXPECT_EQ(std::string(tests[i].result), 372 NetAddressToString(storage.addr, storage.addr_len)); 373 } 374 } 375 376 TEST(NetUtilTest, NetAddressToStringWithPort_IPv4) { 377 uint8 addr[] = {127, 0, 0, 1}; 378 SockaddrStorage storage; 379 MakeIPv4Address(addr, 166, &storage); 380 std::string result = NetAddressToStringWithPort(storage.addr, 381 storage.addr_len); 382 EXPECT_EQ("127.0.0.1:166", result); 383 } 384 385 TEST(NetUtilTest, NetAddressToStringWithPort_IPv6) { 386 uint8 addr[] = { 387 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA, 388 0x98, 0x76, 0x54, 0x32, 0x10 389 }; 390 SockaddrStorage storage; 391 MakeIPv6Address(addr, 361, &storage); 392 std::string result = NetAddressToStringWithPort(storage.addr, 393 storage.addr_len); 394 395 // May fail on systems that don't support IPv6. 396 if (!result.empty()) 397 EXPECT_EQ("[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:361", result); 398 } 399 400 TEST(NetUtilTest, GetHostName) { 401 // We can't check the result of GetHostName() directly, since the result 402 // will differ across machines. Our goal here is to simply exercise the 403 // code path, and check that things "look about right". 404 std::string hostname = GetHostName(); 405 EXPECT_FALSE(hostname.empty()); 406 } 407 408 TEST(NetUtilTest, SimplifyUrlForRequest) { 409 struct { 410 const char* input_url; 411 const char* expected_simplified_url; 412 } tests[] = { 413 { 414 // Reference section should be stripped. 415 "http://www.google.com:78/foobar?query=1#hash", 416 "http://www.google.com:78/foobar?query=1", 417 }, 418 { 419 // Reference section can itself contain #. 420 "http://192.168.0.1?query=1#hash#10#11#13#14", 421 "http://192.168.0.1?query=1", 422 }, 423 { // Strip username/password. 424 "http://user:pass@google.com", 425 "http://google.com/", 426 }, 427 { // Strip both the reference and the username/password. 428 "http://user:pass@google.com:80/sup?yo#X#X", 429 "http://google.com/sup?yo", 430 }, 431 { // Try an HTTPS URL -- strip both the reference and the username/password. 432 "https://user:pass@google.com:80/sup?yo#X#X", 433 "https://google.com:80/sup?yo", 434 }, 435 { // Try an FTP URL -- strip both the reference and the username/password. 436 "ftp://user:pass@google.com:80/sup?yo#X#X", 437 "ftp://google.com:80/sup?yo", 438 }, 439 { // Try a nonstandard URL 440 "foobar://user:pass (at) google.com:80/sup?yo#X#X", 441 "foobar://user:pass (at) google.com:80/sup?yo", 442 }, 443 }; 444 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 445 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i, 446 tests[i].input_url)); 447 GURL input_url(GURL(tests[i].input_url)); 448 GURL expected_url(GURL(tests[i].expected_simplified_url)); 449 EXPECT_EQ(expected_url, SimplifyUrlForRequest(input_url)); 450 } 451 } 452 453 TEST(NetUtilTest, SetExplicitlyAllowedPortsTest) { 454 std::string invalid[] = { "1,2,a", "'1','2'", "1, 2, 3", "1 0,11,12" }; 455 std::string valid[] = { "", "1", "1,2", "1,2,3", "10,11,12,13" }; 456 457 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(invalid); ++i) { 458 SetExplicitlyAllowedPorts(invalid[i]); 459 EXPECT_EQ(0, static_cast<int>(GetCountOfExplicitlyAllowedPorts())); 460 } 461 462 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(valid); ++i) { 463 SetExplicitlyAllowedPorts(valid[i]); 464 EXPECT_EQ(i, GetCountOfExplicitlyAllowedPorts()); 465 } 466 } 467 468 TEST(NetUtilTest, GetHostOrSpecFromURL) { 469 EXPECT_EQ("example.com", 470 GetHostOrSpecFromURL(GURL("http://example.com/test"))); 471 EXPECT_EQ("example.com", 472 GetHostOrSpecFromURL(GURL("http://example.com./test"))); 473 EXPECT_EQ("file:///tmp/test.html", 474 GetHostOrSpecFromURL(GURL("file:///tmp/test.html"))); 475 } 476 477 TEST(NetUtilTest, GetAddressFamily) { 478 IPAddressNumber number; 479 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &number)); 480 EXPECT_EQ(ADDRESS_FAMILY_IPV4, GetAddressFamily(number)); 481 EXPECT_TRUE(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number)); 482 EXPECT_EQ(ADDRESS_FAMILY_IPV6, GetAddressFamily(number)); 483 } 484 485 // Test that invalid IP literals fail to parse. 486 TEST(NetUtilTest, ParseIPLiteralToNumber_FailParse) { 487 IPAddressNumber number; 488 489 EXPECT_FALSE(ParseIPLiteralToNumber("bad value", &number)); 490 EXPECT_FALSE(ParseIPLiteralToNumber("bad:value", &number)); 491 EXPECT_FALSE(ParseIPLiteralToNumber(std::string(), &number)); 492 EXPECT_FALSE(ParseIPLiteralToNumber("192.168.0.1:30", &number)); 493 EXPECT_FALSE(ParseIPLiteralToNumber(" 192.168.0.1 ", &number)); 494 EXPECT_FALSE(ParseIPLiteralToNumber("[::1]", &number)); 495 } 496 497 // Test parsing an IPv4 literal. 498 TEST(NetUtilTest, ParseIPLiteralToNumber_IPv4) { 499 IPAddressNumber number; 500 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &number)); 501 EXPECT_EQ("192,168,0,1", DumpIPNumber(number)); 502 EXPECT_EQ("192.168.0.1", IPAddressToString(number)); 503 } 504 505 // Test parsing an IPv6 literal. 506 TEST(NetUtilTest, ParseIPLiteralToNumber_IPv6) { 507 IPAddressNumber number; 508 EXPECT_TRUE(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number)); 509 EXPECT_EQ("0,1,171,205,0,0,0,0,0,0,0,3,0,4,0,255", DumpIPNumber(number)); 510 EXPECT_EQ("1:abcd::3:4:ff", IPAddressToString(number)); 511 } 512 513 // Test mapping an IPv4 address to an IPv6 address. 514 TEST(NetUtilTest, ConvertIPv4NumberToIPv6Number) { 515 IPAddressNumber ipv4_number; 516 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number)); 517 518 IPAddressNumber ipv6_number = 519 ConvertIPv4NumberToIPv6Number(ipv4_number); 520 521 // ::ffff:192.168.0.1 522 EXPECT_EQ("0,0,0,0,0,0,0,0,0,0,255,255,192,168,0,1", 523 DumpIPNumber(ipv6_number)); 524 EXPECT_EQ("::ffff:c0a8:1", IPAddressToString(ipv6_number)); 525 } 526 527 TEST(NetUtilTest, IsIPv4Mapped) { 528 IPAddressNumber ipv4_number; 529 EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number)); 530 EXPECT_FALSE(IsIPv4Mapped(ipv4_number)); 531 532 IPAddressNumber ipv6_number; 533 EXPECT_TRUE(ParseIPLiteralToNumber("::1", &ipv4_number)); 534 EXPECT_FALSE(IsIPv4Mapped(ipv6_number)); 535 536 IPAddressNumber ipv4mapped_number; 537 EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number)); 538 EXPECT_TRUE(IsIPv4Mapped(ipv4mapped_number)); 539 } 540 541 TEST(NetUtilTest, ConvertIPv4MappedToIPv4) { 542 IPAddressNumber ipv4mapped_number; 543 EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number)); 544 IPAddressNumber expected; 545 EXPECT_TRUE(ParseIPLiteralToNumber("1.1.0.1", &expected)); 546 IPAddressNumber result = ConvertIPv4MappedToIPv4(ipv4mapped_number); 547 EXPECT_EQ(expected, result); 548 } 549 550 // Test parsing invalid CIDR notation literals. 551 TEST(NetUtilTest, ParseCIDRBlock_Invalid) { 552 const char* bad_literals[] = { 553 "foobar", 554 "", 555 "192.168.0.1", 556 "::1", 557 "/", 558 "/1", 559 "1", 560 "192.168.1.1/-1", 561 "192.168.1.1/33", 562 "::1/-3", 563 "a::3/129", 564 "::1/x", 565 "192.168.0.1//11" 566 }; 567 568 for (size_t i = 0; i < arraysize(bad_literals); ++i) { 569 IPAddressNumber ip_number; 570 size_t prefix_length_in_bits; 571 572 EXPECT_FALSE(ParseCIDRBlock(bad_literals[i], 573 &ip_number, 574 &prefix_length_in_bits)); 575 } 576 } 577 578 // Test parsing a valid CIDR notation literal. 579 TEST(NetUtilTest, ParseCIDRBlock_Valid) { 580 IPAddressNumber ip_number; 581 size_t prefix_length_in_bits; 582 583 EXPECT_TRUE(ParseCIDRBlock("192.168.0.1/11", 584 &ip_number, 585 &prefix_length_in_bits)); 586 587 EXPECT_EQ("192,168,0,1", DumpIPNumber(ip_number)); 588 EXPECT_EQ(11u, prefix_length_in_bits); 589 } 590 591 TEST(NetUtilTest, IPNumberMatchesPrefix) { 592 struct { 593 const char* cidr_literal; 594 const char* ip_literal; 595 bool expected_to_match; 596 } tests[] = { 597 // IPv4 prefix with IPv4 inputs. 598 { 599 "10.10.1.32/27", 600 "10.10.1.44", 601 true 602 }, 603 { 604 "10.10.1.32/27", 605 "10.10.1.90", 606 false 607 }, 608 { 609 "10.10.1.32/27", 610 "10.10.1.90", 611 false 612 }, 613 614 // IPv6 prefix with IPv6 inputs. 615 { 616 "2001:db8::/32", 617 "2001:DB8:3:4::5", 618 true 619 }, 620 { 621 "2001:db8::/32", 622 "2001:c8::", 623 false 624 }, 625 626 // IPv6 prefix with IPv4 inputs. 627 { 628 "2001:db8::/33", 629 "192.168.0.1", 630 false 631 }, 632 { 633 "::ffff:192.168.0.1/112", 634 "192.168.33.77", 635 true 636 }, 637 638 // IPv4 prefix with IPv6 inputs. 639 { 640 "10.11.33.44/16", 641 "::ffff:0a0b:89", 642 true 643 }, 644 { 645 "10.11.33.44/16", 646 "::ffff:10.12.33.44", 647 false 648 }, 649 }; 650 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { 651 SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s, %s", i, 652 tests[i].cidr_literal, 653 tests[i].ip_literal)); 654 655 IPAddressNumber ip_number; 656 EXPECT_TRUE(ParseIPLiteralToNumber(tests[i].ip_literal, &ip_number)); 657 658 IPAddressNumber ip_prefix; 659 size_t prefix_length_in_bits; 660 661 EXPECT_TRUE(ParseCIDRBlock(tests[i].cidr_literal, 662 &ip_prefix, 663 &prefix_length_in_bits)); 664 665 EXPECT_EQ(tests[i].expected_to_match, 666 IPNumberMatchesPrefix(ip_number, 667 ip_prefix, 668 prefix_length_in_bits)); 669 } 670 } 671 672 TEST(NetUtilTest, IsLocalhost) { 673 EXPECT_TRUE(net::IsLocalhost("localhost")); 674 EXPECT_TRUE(net::IsLocalhost("localhost.localdomain")); 675 EXPECT_TRUE(net::IsLocalhost("localhost6")); 676 EXPECT_TRUE(net::IsLocalhost("localhost6.localdomain6")); 677 EXPECT_TRUE(net::IsLocalhost("127.0.0.1")); 678 EXPECT_TRUE(net::IsLocalhost("127.0.1.0")); 679 EXPECT_TRUE(net::IsLocalhost("127.1.0.0")); 680 EXPECT_TRUE(net::IsLocalhost("127.0.0.255")); 681 EXPECT_TRUE(net::IsLocalhost("127.0.255.0")); 682 EXPECT_TRUE(net::IsLocalhost("127.255.0.0")); 683 EXPECT_TRUE(net::IsLocalhost("::1")); 684 EXPECT_TRUE(net::IsLocalhost("0:0:0:0:0:0:0:1")); 685 686 EXPECT_FALSE(net::IsLocalhost("localhostx")); 687 EXPECT_FALSE(net::IsLocalhost("foo.localdomain")); 688 EXPECT_FALSE(net::IsLocalhost("localhost6x")); 689 EXPECT_FALSE(net::IsLocalhost("localhost.localdomain6")); 690 EXPECT_FALSE(net::IsLocalhost("localhost6.localdomain")); 691 EXPECT_FALSE(net::IsLocalhost("127.0.0.1.1")); 692 EXPECT_FALSE(net::IsLocalhost(".127.0.0.255")); 693 EXPECT_FALSE(net::IsLocalhost("::2")); 694 EXPECT_FALSE(net::IsLocalhost("::1:1")); 695 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:1:0:0:1")); 696 EXPECT_FALSE(net::IsLocalhost("::1:1")); 697 EXPECT_FALSE(net::IsLocalhost("0:0:0:0:0:0:0:0:1")); 698 } 699 700 // Verify GetNetworkList(). 701 TEST(NetUtilTest, GetNetworkList) { 702 NetworkInterfaceList list; 703 ASSERT_TRUE(GetNetworkList(&list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES)); 704 for (NetworkInterfaceList::iterator it = list.begin(); 705 it != list.end(); ++it) { 706 // Verify that the names are not empty. 707 EXPECT_FALSE(it->name.empty()); 708 EXPECT_FALSE(it->friendly_name.empty()); 709 710 // Verify that the address is correct. 711 EXPECT_TRUE(it->address.size() == kIPv4AddressSize || 712 it->address.size() == kIPv6AddressSize) 713 << "Invalid address of size " << it->address.size(); 714 bool all_zeroes = true; 715 for (size_t i = 0; i < it->address.size(); ++i) { 716 if (it->address[i] != 0) { 717 all_zeroes = false; 718 break; 719 } 720 } 721 EXPECT_FALSE(all_zeroes); 722 EXPECT_GT(it->network_prefix, 1u); 723 EXPECT_LE(it->network_prefix, it->address.size() * 8); 724 725 #if defined(OS_WIN) 726 // On Windows |name| is NET_LUID. 727 base::ScopedNativeLibrary phlpapi_lib( 728 base::FilePath(FILE_PATH_LITERAL("iphlpapi.dll"))); 729 ASSERT_TRUE(phlpapi_lib.is_valid()); 730 typedef NETIO_STATUS (WINAPI* ConvertInterfaceIndexToLuid)(NET_IFINDEX, 731 PNET_LUID); 732 ConvertInterfaceIndexToLuid interface_to_luid = 733 reinterpret_cast<ConvertInterfaceIndexToLuid>( 734 phlpapi_lib.GetFunctionPointer("ConvertInterfaceIndexToLuid")); 735 736 typedef NETIO_STATUS (WINAPI* ConvertInterfaceLuidToGuid)(NET_LUID*, 737 GUID*); 738 ConvertInterfaceLuidToGuid luid_to_guid = 739 reinterpret_cast<ConvertInterfaceLuidToGuid>( 740 phlpapi_lib.GetFunctionPointer("ConvertInterfaceLuidToGuid")); 741 742 if (interface_to_luid && luid_to_guid) { 743 NET_LUID luid; 744 EXPECT_EQ(interface_to_luid(it->interface_index, &luid), NO_ERROR); 745 GUID guid; 746 EXPECT_EQ(luid_to_guid(&luid, &guid), NO_ERROR); 747 LPOLESTR name; 748 StringFromCLSID(guid, &name); 749 EXPECT_STREQ(base::UTF8ToWide(it->name).c_str(), name); 750 CoTaskMemFree(name); 751 continue; 752 } else { 753 EXPECT_LT(base::win::GetVersion(), base::win::VERSION_VISTA); 754 EXPECT_LT(it->interface_index, 1u << 24u); // Must fit 0.x.x.x. 755 EXPECT_NE(it->interface_index, 0u); // 0 means to use default. 756 } 757 if (it->type == NetworkChangeNotifier::CONNECTION_WIFI) { 758 EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE, GetWifiPHYLayerProtocol()); 759 } 760 #elif !defined(OS_ANDROID) 761 char name[IF_NAMESIZE]; 762 EXPECT_TRUE(if_indextoname(it->interface_index, name)); 763 EXPECT_STREQ(it->name.c_str(), name); 764 #endif 765 } 766 } 767 768 struct NonUniqueNameTestData { 769 bool is_unique; 770 const char* hostname; 771 }; 772 773 // Google Test pretty-printer. 774 void PrintTo(const NonUniqueNameTestData& data, std::ostream* os) { 775 ASSERT_TRUE(data.hostname); 776 *os << " hostname: " << testing::PrintToString(data.hostname) 777 << "; is_unique: " << testing::PrintToString(data.is_unique); 778 } 779 780 const NonUniqueNameTestData kNonUniqueNameTestData[] = { 781 // Domains under ICANN-assigned domains. 782 { true, "google.com" }, 783 { true, "google.co.uk" }, 784 // Domains under private registries. 785 { true, "appspot.com" }, 786 { true, "test.appspot.com" }, 787 // Unreserved IPv4 addresses (in various forms). 788 { true, "8.8.8.8" }, 789 { true, "99.64.0.0" }, 790 { true, "212.15.0.0" }, 791 { true, "212.15" }, 792 { true, "212.15.0" }, 793 { true, "3557752832" }, 794 // Reserved IPv4 addresses (in various forms). 795 { false, "192.168.0.0" }, 796 { false, "192.168.0.6" }, 797 { false, "10.0.0.5" }, 798 { false, "10.0" }, 799 { false, "10.0.0" }, 800 { false, "3232235526" }, 801 // Unreserved IPv6 addresses. 802 { true, "FFC0:ba98:7654:3210:FEDC:BA98:7654:3210" }, 803 { true, "2000:ba98:7654:2301:EFCD:BA98:7654:3210" }, 804 // Reserved IPv6 addresses. 805 { false, "::192.9.5.5" }, 806 { false, "FEED::BEEF" }, 807 { false, "FEC0:ba98:7654:3210:FEDC:BA98:7654:3210" }, 808 // 'internal'/non-IANA assigned domains. 809 { false, "intranet" }, 810 { false, "intranet." }, 811 { false, "intranet.example" }, 812 { false, "host.intranet.example" }, 813 // gTLDs under discussion, but not yet assigned. 814 { false, "intranet.corp" }, 815 { false, "example.tech" }, 816 { false, "intranet.internal" }, 817 // Invalid host names are treated as unique - but expected to be 818 // filtered out before then. 819 { true, "junk)()$*!@~#" }, 820 { true, "w$w.example.com" }, 821 { true, "nocolonsallowed:example" }, 822 { true, "[::4.5.6.9]" }, 823 }; 824 825 class NetUtilNonUniqueNameTest 826 : public testing::TestWithParam<NonUniqueNameTestData> { 827 public: 828 virtual ~NetUtilNonUniqueNameTest() {} 829 830 protected: 831 bool IsUnique(const std::string& hostname) { 832 return !IsHostnameNonUnique(hostname); 833 } 834 }; 835 836 // Test that internal/non-unique names are properly identified as such, but 837 // that IP addresses and hosts beneath registry-controlled domains are flagged 838 // as unique names. 839 TEST_P(NetUtilNonUniqueNameTest, IsHostnameNonUnique) { 840 const NonUniqueNameTestData& test_data = GetParam(); 841 842 EXPECT_EQ(test_data.is_unique, IsUnique(test_data.hostname)); 843 } 844 845 INSTANTIATE_TEST_CASE_P(, NetUtilNonUniqueNameTest, 846 testing::ValuesIn(kNonUniqueNameTestData)); 847 848 } // namespace net 849