Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / net / base / net_util.cc
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 <errno.h>
8
9 #include <algorithm>
10 #include <iterator>
11 #include <set>
12
13 #include "build/build_config.h"
14
15 #if defined(OS_WIN)
16 #include <windows.h>
17 #include <iphlpapi.h>
18 #include <winsock2.h>
19 #include <ws2bth.h>
20 #pragma comment(lib, "iphlpapi.lib")
21 #elif defined(OS_POSIX)
22 #include <fcntl.h>
23 #include <netdb.h>
24 #include <netinet/in.h>
25 #include <unistd.h>
26 #if !defined(OS_NACL)
27 #include <net/if.h>
28 #if !defined(OS_ANDROID)
29 #include <ifaddrs.h>
30 #endif  // !defined(OS_NACL)
31 #endif  // !defined(OS_ANDROID)
32 #endif  // defined(OS_POSIX)
33
34 #include "base/basictypes.h"
35 #include "base/json/string_escape.h"
36 #include "base/lazy_instance.h"
37 #include "base/logging.h"
38 #include "base/strings/string_number_conversions.h"
39 #include "base/strings/string_piece.h"
40 #include "base/strings/string_split.h"
41 #include "base/strings/string_util.h"
42 #include "base/strings/stringprintf.h"
43 #include "base/strings/utf_string_conversions.h"
44 #include "base/sys_byteorder.h"
45 #include "base/values.h"
46 #include "grit/net_resources.h"
47 #include "url/gurl.h"
48 #include "url/url_canon.h"
49 #include "url/url_canon_ip.h"
50 #include "url/url_parse.h"
51 #include "net/base/dns_util.h"
52 #include "net/base/net_module.h"
53 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
54 #include "net/http/http_content_disposition.h"
55
56 #if defined(OS_ANDROID)
57 #include "net/android/network_library.h"
58 #endif
59 #if defined(OS_WIN)
60 #include "net/base/winsock_init.h"
61 #endif
62
63 namespace net {
64
65 namespace {
66
67 // The general list of blocked ports. Will be blocked unless a specific
68 // protocol overrides it. (Ex: ftp can use ports 20 and 21)
69 static const int kRestrictedPorts[] = {
70   1,    // tcpmux
71   7,    // echo
72   9,    // discard
73   11,   // systat
74   13,   // daytime
75   15,   // netstat
76   17,   // qotd
77   19,   // chargen
78   20,   // ftp data
79   21,   // ftp access
80   22,   // ssh
81   23,   // telnet
82   25,   // smtp
83   37,   // time
84   42,   // name
85   43,   // nicname
86   53,   // domain
87   77,   // priv-rjs
88   79,   // finger
89   87,   // ttylink
90   95,   // supdup
91   101,  // hostriame
92   102,  // iso-tsap
93   103,  // gppitnp
94   104,  // acr-nema
95   109,  // pop2
96   110,  // pop3
97   111,  // sunrpc
98   113,  // auth
99   115,  // sftp
100   117,  // uucp-path
101   119,  // nntp
102   123,  // NTP
103   135,  // loc-srv /epmap
104   139,  // netbios
105   143,  // imap2
106   179,  // BGP
107   389,  // ldap
108   465,  // smtp+ssl
109   512,  // print / exec
110   513,  // login
111   514,  // shell
112   515,  // printer
113   526,  // tempo
114   530,  // courier
115   531,  // chat
116   532,  // netnews
117   540,  // uucp
118   556,  // remotefs
119   563,  // nntp+ssl
120   587,  // stmp?
121   601,  // ??
122   636,  // ldap+ssl
123   993,  // ldap+ssl
124   995,  // pop3+ssl
125   2049, // nfs
126   3659, // apple-sasl / PasswordServer
127   4045, // lockd
128   6000, // X11
129   6665, // Alternate IRC [Apple addition]
130   6666, // Alternate IRC [Apple addition]
131   6667, // Standard IRC [Apple addition]
132   6668, // Alternate IRC [Apple addition]
133   6669, // Alternate IRC [Apple addition]
134   0xFFFF, // Used to block all invalid port numbers (see
135           // third_party/WebKit/Source/platform/weborigin/KURL.cpp,
136           // KURL::port())
137 };
138
139 // FTP overrides the following restricted ports.
140 static const int kAllowedFtpPorts[] = {
141   21,   // ftp data
142   22,   // ssh
143 };
144
145 bool IPNumberPrefixCheck(const IPAddressNumber& ip_number,
146                          const unsigned char* ip_prefix,
147                          size_t prefix_length_in_bits) {
148   // Compare all the bytes that fall entirely within the prefix.
149   int num_entire_bytes_in_prefix = prefix_length_in_bits / 8;
150   for (int i = 0; i < num_entire_bytes_in_prefix; ++i) {
151     if (ip_number[i] != ip_prefix[i])
152       return false;
153   }
154
155   // In case the prefix was not a multiple of 8, there will be 1 byte
156   // which is only partially masked.
157   int remaining_bits = prefix_length_in_bits % 8;
158   if (remaining_bits != 0) {
159     unsigned char mask = 0xFF << (8 - remaining_bits);
160     int i = num_entire_bytes_in_prefix;
161     if ((ip_number[i] & mask) != (ip_prefix[i] & mask))
162       return false;
163   }
164   return true;
165 }
166
167 }  // namespace
168
169 static base::LazyInstance<std::multiset<int> >::Leaky
170     g_explicitly_allowed_ports = LAZY_INSTANCE_INITIALIZER;
171
172 size_t GetCountOfExplicitlyAllowedPorts() {
173   return g_explicitly_allowed_ports.Get().size();
174 }
175
176 std::string GetSpecificHeader(const std::string& headers,
177                               const std::string& name) {
178   // We want to grab the Value from the "Key: Value" pairs in the headers,
179   // which should look like this (no leading spaces, \n-separated) (we format
180   // them this way in url_request_inet.cc):
181   //    HTTP/1.1 200 OK\n
182   //    ETag: "6d0b8-947-24f35ec0"\n
183   //    Content-Length: 2375\n
184   //    Content-Type: text/html; charset=UTF-8\n
185   //    Last-Modified: Sun, 03 Sep 2006 04:34:43 GMT\n
186   if (headers.empty())
187     return std::string();
188
189   std::string match('\n' + name + ':');
190
191   std::string::const_iterator begin =
192       std::search(headers.begin(), headers.end(), match.begin(), match.end(),
193              base::CaseInsensitiveCompareASCII<char>());
194
195   if (begin == headers.end())
196     return std::string();
197
198   begin += match.length();
199
200   std::string ret;
201   base::TrimWhitespace(std::string(begin,
202                                    std::find(begin, headers.end(), '\n')),
203                        base::TRIM_ALL, &ret);
204   return ret;
205 }
206
207 std::string CanonicalizeHost(const std::string& host,
208                              url::CanonHostInfo* host_info) {
209   // Try to canonicalize the host.
210   const url::Component raw_host_component(0, static_cast<int>(host.length()));
211   std::string canon_host;
212   url::StdStringCanonOutput canon_host_output(&canon_host);
213   url::CanonicalizeHostVerbose(host.c_str(), raw_host_component,
214                                &canon_host_output, host_info);
215
216   if (host_info->out_host.is_nonempty() &&
217       host_info->family != url::CanonHostInfo::BROKEN) {
218     // Success!  Assert that there's no extra garbage.
219     canon_host_output.Complete();
220     DCHECK_EQ(host_info->out_host.len, static_cast<int>(canon_host.length()));
221   } else {
222     // Empty host, or canonicalization failed.  We'll return empty.
223     canon_host.clear();
224   }
225
226   return canon_host;
227 }
228
229 std::string GetDirectoryListingHeader(const base::string16& title) {
230   static const base::StringPiece header(
231       NetModule::GetResource(IDR_DIR_HEADER_HTML));
232   // This can be null in unit tests.
233   DLOG_IF(WARNING, header.empty()) <<
234       "Missing resource: directory listing header";
235
236   std::string result;
237   if (!header.empty())
238     result.assign(header.data(), header.size());
239
240   result.append("<script>start(");
241   base::EscapeJSONString(title, true, &result);
242   result.append(");</script>\n");
243
244   return result;
245 }
246
247 inline bool IsHostCharAlphanumeric(char c) {
248   // We can just check lowercase because uppercase characters have already been
249   // normalized.
250   return ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'));
251 }
252
253 bool IsCanonicalizedHostCompliant(const std::string& host,
254                                   const std::string& desired_tld) {
255   if (host.empty())
256     return false;
257
258   bool in_component = false;
259   bool most_recent_component_started_alphanumeric = false;
260   bool last_char_was_underscore = false;
261
262   for (std::string::const_iterator i(host.begin()); i != host.end(); ++i) {
263     const char c = *i;
264     if (!in_component) {
265       most_recent_component_started_alphanumeric = IsHostCharAlphanumeric(c);
266       if (!most_recent_component_started_alphanumeric && (c != '-'))
267         return false;
268       in_component = true;
269     } else {
270       if (c == '.') {
271         if (last_char_was_underscore)
272           return false;
273         in_component = false;
274       } else if (IsHostCharAlphanumeric(c) || (c == '-')) {
275         last_char_was_underscore = false;
276       } else if (c == '_') {
277         last_char_was_underscore = true;
278       } else {
279         return false;
280       }
281     }
282   }
283
284   return most_recent_component_started_alphanumeric ||
285       (!desired_tld.empty() && IsHostCharAlphanumeric(desired_tld[0]));
286 }
287
288 base::string16 StripWWW(const base::string16& text) {
289   const base::string16 www(base::ASCIIToUTF16("www."));
290   return StartsWith(text, www, true) ? text.substr(www.length()) : text;
291 }
292
293 base::string16 StripWWWFromHost(const GURL& url) {
294   DCHECK(url.is_valid());
295   return StripWWW(base::ASCIIToUTF16(url.host()));
296 }
297
298 bool IsPortAllowedByDefault(int port) {
299   int array_size = arraysize(kRestrictedPorts);
300   for (int i = 0; i < array_size; i++) {
301     if (kRestrictedPorts[i] == port) {
302       return false;
303     }
304   }
305   return true;
306 }
307
308 bool IsPortAllowedByFtp(int port) {
309   int array_size = arraysize(kAllowedFtpPorts);
310   for (int i = 0; i < array_size; i++) {
311     if (kAllowedFtpPorts[i] == port) {
312         return true;
313     }
314   }
315   // Port not explicitly allowed by FTP, so return the default restrictions.
316   return IsPortAllowedByDefault(port);
317 }
318
319 bool IsPortAllowedByOverride(int port) {
320   if (g_explicitly_allowed_ports.Get().empty())
321     return false;
322
323   return g_explicitly_allowed_ports.Get().count(port) > 0;
324 }
325
326 int SetNonBlocking(int fd) {
327 #if defined(OS_WIN)
328   unsigned long no_block = 1;
329   return ioctlsocket(fd, FIONBIO, &no_block);
330 #elif defined(OS_POSIX)
331   int flags = fcntl(fd, F_GETFL, 0);
332   if (-1 == flags)
333     return flags;
334   return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
335 #endif
336 }
337
338 bool ParseHostAndPort(std::string::const_iterator host_and_port_begin,
339                       std::string::const_iterator host_and_port_end,
340                       std::string* host,
341                       int* port) {
342   if (host_and_port_begin >= host_and_port_end)
343     return false;
344
345   // When using url, we use char*.
346   const char* auth_begin = &(*host_and_port_begin);
347   int auth_len = host_and_port_end - host_and_port_begin;
348
349   url::Component auth_component(0, auth_len);
350   url::Component username_component;
351   url::Component password_component;
352   url::Component hostname_component;
353   url::Component port_component;
354
355   url::ParseAuthority(auth_begin, auth_component, &username_component,
356       &password_component, &hostname_component, &port_component);
357
358   // There shouldn't be a username/password.
359   if (username_component.is_valid() || password_component.is_valid())
360     return false;
361
362   if (!hostname_component.is_nonempty())
363     return false;  // Failed parsing.
364
365   int parsed_port_number = -1;
366   if (port_component.is_nonempty()) {
367     parsed_port_number = url::ParsePort(auth_begin, port_component);
368
369     // If parsing failed, port_number will be either PORT_INVALID or
370     // PORT_UNSPECIFIED, both of which are negative.
371     if (parsed_port_number < 0)
372       return false;  // Failed parsing the port number.
373   }
374
375   if (port_component.len == 0)
376     return false;  // Reject inputs like "foo:"
377
378   // Pass results back to caller.
379   host->assign(auth_begin + hostname_component.begin, hostname_component.len);
380   *port = parsed_port_number;
381
382   return true;  // Success.
383 }
384
385 bool ParseHostAndPort(const std::string& host_and_port,
386                       std::string* host,
387                       int* port) {
388   return ParseHostAndPort(
389       host_and_port.begin(), host_and_port.end(), host, port);
390 }
391
392 std::string GetHostAndPort(const GURL& url) {
393   // For IPv6 literals, GURL::host() already includes the brackets so it is
394   // safe to just append a colon.
395   return base::StringPrintf("%s:%d", url.host().c_str(),
396                             url.EffectiveIntPort());
397 }
398
399 std::string GetHostAndOptionalPort(const GURL& url) {
400   // For IPv6 literals, GURL::host() already includes the brackets
401   // so it is safe to just append a colon.
402   if (url.has_port())
403     return base::StringPrintf("%s:%s", url.host().c_str(), url.port().c_str());
404   return url.host();
405 }
406
407 bool IsHostnameNonUnique(const std::string& hostname) {
408   // CanonicalizeHost requires surrounding brackets to parse an IPv6 address.
409   const std::string host_or_ip = hostname.find(':') != std::string::npos ?
410       "[" + hostname + "]" : hostname;
411   url::CanonHostInfo host_info;
412   std::string canonical_name = CanonicalizeHost(host_or_ip, &host_info);
413
414   // If canonicalization fails, then the input is truly malformed. However,
415   // to avoid mis-reporting bad inputs as "non-unique", treat them as unique.
416   if (canonical_name.empty())
417     return false;
418
419   // If |hostname| is an IP address, check to see if it's in an IANA-reserved
420   // range.
421   if (host_info.IsIPAddress()) {
422     IPAddressNumber host_addr;
423     if (!ParseIPLiteralToNumber(hostname.substr(host_info.out_host.begin,
424                                                 host_info.out_host.len),
425                                 &host_addr)) {
426       return false;
427     }
428     switch (host_info.family) {
429       case url::CanonHostInfo::IPV4:
430       case url::CanonHostInfo::IPV6:
431         return IsIPAddressReserved(host_addr);
432       case url::CanonHostInfo::NEUTRAL:
433       case url::CanonHostInfo::BROKEN:
434         return false;
435     }
436   }
437
438   // Check for a registry controlled portion of |hostname|, ignoring private
439   // registries, as they already chain to ICANN-administered registries,
440   // and explicitly ignoring unknown registries.
441   //
442   // Note: This means that as new gTLDs are introduced on the Internet, they
443   // will be treated as non-unique until the registry controlled domain list
444   // is updated. However, because gTLDs are expected to provide significant
445   // advance notice to deprecate older versions of this code, this an
446   // acceptable tradeoff.
447   return 0 == registry_controlled_domains::GetRegistryLength(
448                   canonical_name,
449                   registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
450                   registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
451 }
452
453 // Don't compare IPv4 and IPv6 addresses (they have different range
454 // reservations). Keep separate reservation arrays for each IP type, and
455 // consolidate adjacent reserved ranges within a reservation array when
456 // possible.
457 // Sources for info:
458 // www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
459 // www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
460 // They're formatted here with the prefix as the last element. For example:
461 // 10.0.0.0/8 becomes 10,0,0,0,8 and fec0::/10 becomes 0xfe,0xc0,0,0,0...,10.
462 bool IsIPAddressReserved(const IPAddressNumber& host_addr) {
463   static const unsigned char kReservedIPv4[][5] = {
464       { 0,0,0,0,8 }, { 10,0,0,0,8 }, { 100,64,0,0,10 }, { 127,0,0,0,8 },
465       { 169,254,0,0,16 }, { 172,16,0,0,12 }, { 192,0,2,0,24 },
466       { 192,88,99,0,24 }, { 192,168,0,0,16 }, { 198,18,0,0,15 },
467       { 198,51,100,0,24 }, { 203,0,113,0,24 }, { 224,0,0,0,3 }
468   };
469   static const unsigned char kReservedIPv6[][17] = {
470       { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8 },
471       { 0x40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
472       { 0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2 },
473       { 0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3 },
474       { 0xe0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4 },
475       { 0xf0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5 },
476       { 0xf8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6 },
477       { 0xfc,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7 },
478       { 0xfe,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9 },
479       { 0xfe,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
480       { 0xfe,0xc0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10 },
481   };
482   size_t array_size = 0;
483   const unsigned char* array = NULL;
484   switch (host_addr.size()) {
485     case kIPv4AddressSize:
486       array_size = arraysize(kReservedIPv4);
487       array = kReservedIPv4[0];
488       break;
489     case kIPv6AddressSize:
490       array_size = arraysize(kReservedIPv6);
491       array = kReservedIPv6[0];
492       break;
493   }
494   if (!array)
495     return false;
496   size_t width = host_addr.size() + 1;
497   for (size_t i = 0; i < array_size; ++i, array += width) {
498     if (IPNumberPrefixCheck(host_addr, array, array[width-1]))
499       return true;
500   }
501   return false;
502 }
503
504 // Extracts the address and port portions of a sockaddr.
505 bool GetIPAddressFromSockAddr(const struct sockaddr* sock_addr,
506                               socklen_t sock_addr_len,
507                               const uint8** address,
508                               size_t* address_len,
509                               uint16* port) {
510   if (sock_addr->sa_family == AF_INET) {
511     if (sock_addr_len < static_cast<socklen_t>(sizeof(struct sockaddr_in)))
512       return false;
513     const struct sockaddr_in* addr =
514         reinterpret_cast<const struct sockaddr_in*>(sock_addr);
515     *address = reinterpret_cast<const uint8*>(&addr->sin_addr);
516     *address_len = kIPv4AddressSize;
517     if (port)
518       *port = base::NetToHost16(addr->sin_port);
519     return true;
520   }
521
522   if (sock_addr->sa_family == AF_INET6) {
523     if (sock_addr_len < static_cast<socklen_t>(sizeof(struct sockaddr_in6)))
524       return false;
525     const struct sockaddr_in6* addr =
526         reinterpret_cast<const struct sockaddr_in6*>(sock_addr);
527     *address = reinterpret_cast<const uint8*>(&addr->sin6_addr);
528     *address_len = kIPv6AddressSize;
529     if (port)
530       *port = base::NetToHost16(addr->sin6_port);
531     return true;
532   }
533
534 #if defined(OS_WIN)
535   if (sock_addr->sa_family == AF_BTH) {
536     if (sock_addr_len < static_cast<socklen_t>(sizeof(SOCKADDR_BTH)))
537       return false;
538     const SOCKADDR_BTH* addr =
539         reinterpret_cast<const SOCKADDR_BTH*>(sock_addr);
540     *address = reinterpret_cast<const uint8*>(&addr->btAddr);
541     *address_len = kBluetoothAddressSize;
542     if (port)
543       *port = addr->port;
544     return true;
545   }
546 #endif
547
548   return false;  // Unrecognized |sa_family|.
549 }
550
551 std::string IPAddressToString(const uint8* address,
552                               size_t address_len) {
553   std::string str;
554   url::StdStringCanonOutput output(&str);
555
556   if (address_len == kIPv4AddressSize) {
557     url::AppendIPv4Address(address, &output);
558   } else if (address_len == kIPv6AddressSize) {
559     url::AppendIPv6Address(address, &output);
560   } else {
561     CHECK(false) << "Invalid IP address with length: " << address_len;
562   }
563
564   output.Complete();
565   return str;
566 }
567
568 std::string IPAddressToStringWithPort(const uint8* address,
569                                       size_t address_len,
570                                       uint16 port) {
571   std::string address_str = IPAddressToString(address, address_len);
572
573   if (address_len == kIPv6AddressSize) {
574     // Need to bracket IPv6 addresses since they contain colons.
575     return base::StringPrintf("[%s]:%d", address_str.c_str(), port);
576   }
577   return base::StringPrintf("%s:%d", address_str.c_str(), port);
578 }
579
580 std::string NetAddressToString(const struct sockaddr* sa,
581                                socklen_t sock_addr_len) {
582   const uint8* address;
583   size_t address_len;
584   if (!GetIPAddressFromSockAddr(sa, sock_addr_len, &address,
585                                 &address_len, NULL)) {
586     NOTREACHED();
587     return std::string();
588   }
589   return IPAddressToString(address, address_len);
590 }
591
592 std::string NetAddressToStringWithPort(const struct sockaddr* sa,
593                                        socklen_t sock_addr_len) {
594   const uint8* address;
595   size_t address_len;
596   uint16 port;
597   if (!GetIPAddressFromSockAddr(sa, sock_addr_len, &address,
598                                 &address_len, &port)) {
599     NOTREACHED();
600     return std::string();
601   }
602   return IPAddressToStringWithPort(address, address_len, port);
603 }
604
605 std::string IPAddressToString(const IPAddressNumber& addr) {
606   return IPAddressToString(&addr.front(), addr.size());
607 }
608
609 std::string IPAddressToStringWithPort(const IPAddressNumber& addr,
610                                       uint16 port) {
611   return IPAddressToStringWithPort(&addr.front(), addr.size(), port);
612 }
613
614 std::string IPAddressToPackedString(const IPAddressNumber& addr) {
615   return std::string(reinterpret_cast<const char *>(&addr.front()),
616                      addr.size());
617 }
618
619 std::string GetHostName() {
620 #if defined(OS_NACL)
621   NOTIMPLEMENTED();
622   return std::string();
623 #else  // defined(OS_NACL)
624 #if defined(OS_WIN)
625   EnsureWinsockInit();
626 #endif
627
628   // Host names are limited to 255 bytes.
629   char buffer[256];
630   int result = gethostname(buffer, sizeof(buffer));
631   if (result != 0) {
632     DVLOG(1) << "gethostname() failed with " << result;
633     buffer[0] = '\0';
634   }
635   return std::string(buffer);
636 #endif  // !defined(OS_NACL)
637 }
638
639 void GetIdentityFromURL(const GURL& url,
640                         base::string16* username,
641                         base::string16* password) {
642   UnescapeRule::Type flags =
643       UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS;
644   *username = UnescapeAndDecodeUTF8URLComponent(url.username(), flags);
645   *password = UnescapeAndDecodeUTF8URLComponent(url.password(), flags);
646 }
647
648 std::string GetHostOrSpecFromURL(const GURL& url) {
649   return url.has_host() ? TrimEndingDot(url.host()) : url.spec();
650 }
651
652 bool CanStripTrailingSlash(const GURL& url) {
653   // Omit the path only for standard, non-file URLs with nothing but "/" after
654   // the hostname.
655   return url.IsStandard() && !url.SchemeIsFile() &&
656       !url.SchemeIsFileSystem() && !url.has_query() && !url.has_ref()
657       && url.path() == "/";
658 }
659
660 GURL SimplifyUrlForRequest(const GURL& url) {
661   DCHECK(url.is_valid());
662   GURL::Replacements replacements;
663   replacements.ClearUsername();
664   replacements.ClearPassword();
665   replacements.ClearRef();
666   return url.ReplaceComponents(replacements);
667 }
668
669 // Specifies a comma separated list of port numbers that should be accepted
670 // despite bans. If the string is invalid no allowed ports are stored.
671 void SetExplicitlyAllowedPorts(const std::string& allowed_ports) {
672   if (allowed_ports.empty())
673     return;
674
675   std::multiset<int> ports;
676   size_t last = 0;
677   size_t size = allowed_ports.size();
678   // The comma delimiter.
679   const std::string::value_type kComma = ',';
680
681   // Overflow is still possible for evil user inputs.
682   for (size_t i = 0; i <= size; ++i) {
683     // The string should be composed of only digits and commas.
684     if (i != size && !IsAsciiDigit(allowed_ports[i]) &&
685         (allowed_ports[i] != kComma))
686       return;
687     if (i == size || allowed_ports[i] == kComma) {
688       if (i > last) {
689         int port;
690         base::StringToInt(base::StringPiece(allowed_ports.begin() + last,
691                                             allowed_ports.begin() + i),
692                           &port);
693         ports.insert(port);
694       }
695       last = i + 1;
696     }
697   }
698   g_explicitly_allowed_ports.Get() = ports;
699 }
700
701 ScopedPortException::ScopedPortException(int port) : port_(port) {
702   g_explicitly_allowed_ports.Get().insert(port);
703 }
704
705 ScopedPortException::~ScopedPortException() {
706   std::multiset<int>::iterator it =
707       g_explicitly_allowed_ports.Get().find(port_);
708   if (it != g_explicitly_allowed_ports.Get().end())
709     g_explicitly_allowed_ports.Get().erase(it);
710   else
711     NOTREACHED();
712 }
713
714 bool HaveOnlyLoopbackAddresses() {
715 #if defined(OS_ANDROID)
716   return android::HaveOnlyLoopbackAddresses();
717 #elif defined(OS_NACL)
718   NOTIMPLEMENTED();
719   return false;
720 #elif defined(OS_POSIX)
721   struct ifaddrs* interface_addr = NULL;
722   int rv = getifaddrs(&interface_addr);
723   if (rv != 0) {
724     DVLOG(1) << "getifaddrs() failed with errno = " << errno;
725     return false;
726   }
727
728   bool result = true;
729   for (struct ifaddrs* interface = interface_addr;
730        interface != NULL;
731        interface = interface->ifa_next) {
732     if (!(IFF_UP & interface->ifa_flags))
733       continue;
734     if (IFF_LOOPBACK & interface->ifa_flags)
735       continue;
736     const struct sockaddr* addr = interface->ifa_addr;
737     if (!addr)
738       continue;
739     if (addr->sa_family == AF_INET6) {
740       // Safe cast since this is AF_INET6.
741       const struct sockaddr_in6* addr_in6 =
742           reinterpret_cast<const struct sockaddr_in6*>(addr);
743       const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
744       if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
745         continue;
746     }
747     if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
748       continue;
749
750     result = false;
751     break;
752   }
753   freeifaddrs(interface_addr);
754   return result;
755 #elif defined(OS_WIN)
756   // TODO(wtc): implement with the GetAdaptersAddresses function.
757   NOTIMPLEMENTED();
758   return false;
759 #else
760   NOTIMPLEMENTED();
761   return false;
762 #endif  // defined(various platforms)
763 }
764
765 AddressFamily GetAddressFamily(const IPAddressNumber& address) {
766   switch (address.size()) {
767     case kIPv4AddressSize:
768       return ADDRESS_FAMILY_IPV4;
769     case kIPv6AddressSize:
770       return ADDRESS_FAMILY_IPV6;
771     default:
772       return ADDRESS_FAMILY_UNSPECIFIED;
773   }
774 }
775
776 int ConvertAddressFamily(AddressFamily address_family) {
777   switch (address_family) {
778     case ADDRESS_FAMILY_UNSPECIFIED:
779       return AF_UNSPEC;
780     case ADDRESS_FAMILY_IPV4:
781       return AF_INET;
782     case ADDRESS_FAMILY_IPV6:
783       return AF_INET6;
784   }
785   NOTREACHED();
786   return AF_UNSPEC;
787 }
788
789 bool ParseIPLiteralToNumber(const std::string& ip_literal,
790                             IPAddressNumber* ip_number) {
791   // |ip_literal| could be either a IPv4 or an IPv6 literal. If it contains
792   // a colon however, it must be an IPv6 address.
793   if (ip_literal.find(':') != std::string::npos) {
794     // GURL expects IPv6 hostnames to be surrounded with brackets.
795     std::string host_brackets = "[" + ip_literal + "]";
796     url::Component host_comp(0, host_brackets.size());
797
798     // Try parsing the hostname as an IPv6 literal.
799     ip_number->resize(16);  // 128 bits.
800     return url::IPv6AddressToNumber(host_brackets.data(), host_comp,
801                                     &(*ip_number)[0]);
802   }
803
804   // Otherwise the string is an IPv4 address.
805   ip_number->resize(4);  // 32 bits.
806   url::Component host_comp(0, ip_literal.size());
807   int num_components;
808   url::CanonHostInfo::Family family = url::IPv4AddressToNumber(
809       ip_literal.data(), host_comp, &(*ip_number)[0], &num_components);
810   return family == url::CanonHostInfo::IPV4;
811 }
812
813 namespace {
814
815 const unsigned char kIPv4MappedPrefix[] =
816     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
817 }
818
819 IPAddressNumber ConvertIPv4NumberToIPv6Number(
820     const IPAddressNumber& ipv4_number) {
821   DCHECK(ipv4_number.size() == 4);
822
823   // IPv4-mapped addresses are formed by:
824   // <80 bits of zeros>  + <16 bits of ones> + <32-bit IPv4 address>.
825   IPAddressNumber ipv6_number;
826   ipv6_number.reserve(16);
827   ipv6_number.insert(ipv6_number.end(),
828                      kIPv4MappedPrefix,
829                      kIPv4MappedPrefix + arraysize(kIPv4MappedPrefix));
830   ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end());
831   return ipv6_number;
832 }
833
834 bool IsIPv4Mapped(const IPAddressNumber& address) {
835   if (address.size() != kIPv6AddressSize)
836     return false;
837   return std::equal(address.begin(),
838                     address.begin() + arraysize(kIPv4MappedPrefix),
839                     kIPv4MappedPrefix);
840 }
841
842 IPAddressNumber ConvertIPv4MappedToIPv4(const IPAddressNumber& address) {
843   DCHECK(IsIPv4Mapped(address));
844   return IPAddressNumber(address.begin() + arraysize(kIPv4MappedPrefix),
845                          address.end());
846 }
847
848 bool ParseCIDRBlock(const std::string& cidr_literal,
849                     IPAddressNumber* ip_number,
850                     size_t* prefix_length_in_bits) {
851   // We expect CIDR notation to match one of these two templates:
852   //   <IPv4-literal> "/" <number of bits>
853   //   <IPv6-literal> "/" <number of bits>
854
855   std::vector<std::string> parts;
856   base::SplitString(cidr_literal, '/', &parts);
857   if (parts.size() != 2)
858     return false;
859
860   // Parse the IP address.
861   if (!ParseIPLiteralToNumber(parts[0], ip_number))
862     return false;
863
864   // Parse the prefix length.
865   int number_of_bits = -1;
866   if (!base::StringToInt(parts[1], &number_of_bits))
867     return false;
868
869   // Make sure the prefix length is in a valid range.
870   if (number_of_bits < 0 ||
871       number_of_bits > static_cast<int>(ip_number->size() * 8))
872     return false;
873
874   *prefix_length_in_bits = static_cast<size_t>(number_of_bits);
875   return true;
876 }
877
878 bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number,
879                            const IPAddressNumber& ip_prefix,
880                            size_t prefix_length_in_bits) {
881   // Both the input IP address and the prefix IP address should be
882   // either IPv4 or IPv6.
883   DCHECK(ip_number.size() == 4 || ip_number.size() == 16);
884   DCHECK(ip_prefix.size() == 4 || ip_prefix.size() == 16);
885
886   DCHECK_LE(prefix_length_in_bits, ip_prefix.size() * 8);
887
888   // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to
889   // IPv6 addresses in order to do the comparison.
890   if (ip_number.size() != ip_prefix.size()) {
891     if (ip_number.size() == 4) {
892       return IPNumberMatchesPrefix(ConvertIPv4NumberToIPv6Number(ip_number),
893                                    ip_prefix, prefix_length_in_bits);
894     }
895     return IPNumberMatchesPrefix(ip_number,
896                                  ConvertIPv4NumberToIPv6Number(ip_prefix),
897                                  96 + prefix_length_in_bits);
898   }
899
900   return IPNumberPrefixCheck(ip_number, &ip_prefix[0], prefix_length_in_bits);
901 }
902
903 const uint16* GetPortFieldFromSockaddr(const struct sockaddr* address,
904                                        socklen_t address_len) {
905   if (address->sa_family == AF_INET) {
906     DCHECK_LE(sizeof(sockaddr_in), static_cast<size_t>(address_len));
907     const struct sockaddr_in* sockaddr =
908         reinterpret_cast<const struct sockaddr_in*>(address);
909     return &sockaddr->sin_port;
910   } else if (address->sa_family == AF_INET6) {
911     DCHECK_LE(sizeof(sockaddr_in6), static_cast<size_t>(address_len));
912     const struct sockaddr_in6* sockaddr =
913         reinterpret_cast<const struct sockaddr_in6*>(address);
914     return &sockaddr->sin6_port;
915   } else {
916     NOTREACHED();
917     return NULL;
918   }
919 }
920
921 int GetPortFromSockaddr(const struct sockaddr* address, socklen_t address_len) {
922   const uint16* port_field = GetPortFieldFromSockaddr(address, address_len);
923   if (!port_field)
924     return -1;
925   return base::NetToHost16(*port_field);
926 }
927
928 bool IsLocalhost(const std::string& host) {
929   if (host == "localhost" ||
930       host == "localhost.localdomain" ||
931       host == "localhost6" ||
932       host == "localhost6.localdomain6")
933     return true;
934
935   IPAddressNumber ip_number;
936   if (ParseIPLiteralToNumber(host, &ip_number)) {
937     size_t size = ip_number.size();
938     switch (size) {
939       case kIPv4AddressSize: {
940         IPAddressNumber localhost_prefix;
941         localhost_prefix.push_back(127);
942         for (int i = 0; i < 3; ++i) {
943           localhost_prefix.push_back(0);
944         }
945         return IPNumberMatchesPrefix(ip_number, localhost_prefix, 8);
946       }
947
948       case kIPv6AddressSize: {
949         struct in6_addr sin6_addr;
950         memcpy(&sin6_addr, &ip_number[0], kIPv6AddressSize);
951         return !!IN6_IS_ADDR_LOOPBACK(&sin6_addr);
952       }
953
954       default:
955         NOTREACHED();
956     }
957   }
958
959   return false;
960 }
961
962 NetworkInterface::NetworkInterface()
963     : type(NetworkChangeNotifier::CONNECTION_UNKNOWN),
964       network_prefix(0) {
965 }
966
967 NetworkInterface::NetworkInterface(const std::string& name,
968                                    const std::string& friendly_name,
969                                    uint32 interface_index,
970                                    NetworkChangeNotifier::ConnectionType type,
971                                    const IPAddressNumber& address,
972                                    size_t network_prefix)
973     : name(name),
974       friendly_name(friendly_name),
975       interface_index(interface_index),
976       type(type),
977       address(address),
978       network_prefix(network_prefix) {
979 }
980
981 NetworkInterface::~NetworkInterface() {
982 }
983
984 unsigned CommonPrefixLength(const IPAddressNumber& a1,
985                             const IPAddressNumber& a2) {
986   DCHECK_EQ(a1.size(), a2.size());
987   for (size_t i = 0; i < a1.size(); ++i) {
988     unsigned diff = a1[i] ^ a2[i];
989     if (!diff)
990       continue;
991     for (unsigned j = 0; j < CHAR_BIT; ++j) {
992       if (diff & (1 << (CHAR_BIT - 1)))
993         return i * CHAR_BIT + j;
994       diff <<= 1;
995     }
996     NOTREACHED();
997   }
998   return a1.size() * CHAR_BIT;
999 }
1000
1001 unsigned MaskPrefixLength(const IPAddressNumber& mask) {
1002   IPAddressNumber all_ones(mask.size(), 0xFF);
1003   return CommonPrefixLength(mask, all_ones);
1004 }
1005
1006 }  // namespace net