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 #ifndef NET_BASE_NET_UTIL_H_
6 #define NET_BASE_NET_UTIL_H_
8 #include "build/build_config.h"
13 #elif defined(OS_POSIX)
14 #include <sys/types.h>
15 #include <sys/socket.h>
21 #include "base/basictypes.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/utf_offset_string_conversions.h"
24 #include "net/base/address_family.h"
25 #include "net/base/escape.h"
26 #include "net/base/net_export.h"
27 #include "net/base/network_change_notifier.h"
28 // TODO(eroman): Remove this header and require consumers to include it
30 #include "net/base/network_interfaces.h"
47 // This is a "forward declaration" to avoid including ip_address_number.h
49 typedef std::vector
<unsigned char> IPAddressNumber
;
51 // Used by FormatUrl to specify handling of certain parts of the url.
52 typedef uint32_t FormatUrlType
;
53 typedef uint32_t FormatUrlTypes
;
56 // Bluetooth address size. Windows Bluetooth is supported via winsock.
57 static const size_t kBluetoothAddressSize
= 6;
60 // Nothing is ommitted.
61 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitNothing
;
63 // If set, any username and password are removed.
64 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitUsernamePassword
;
66 // If the scheme is 'http://', it's removed.
67 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitHTTP
;
69 // Omits the path if it is just a slash and there is no query or ref. This is
70 // meaningful for non-file "standard" URLs.
71 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitTrailingSlashOnBareHostname
;
73 // Convenience for omitting all unecessary types.
74 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitAll
;
76 // Splits an input of the form <host>[":"<port>] into its consitituent parts.
77 // Saves the result into |*host| and |*port|. If the input did not have
78 // the optional port, sets |*port| to -1.
79 // Returns true if the parsing was successful, false otherwise.
80 // The returned host is NOT canonicalized, and may be invalid.
82 // IPv6 literals must be specified in a bracketed form, for instance:
85 // The resultant |*host| in both cases will be "::1" (not bracketed).
86 NET_EXPORT
bool ParseHostAndPort(
87 std::string::const_iterator host_and_port_begin
,
88 std::string::const_iterator host_and_port_end
,
91 NET_EXPORT
bool ParseHostAndPort(
92 const std::string
& host_and_port
,
96 // Returns a host:port string for the given URL.
97 NET_EXPORT
std::string
GetHostAndPort(const GURL
& url
);
99 // Returns a host[:port] string for the given URL, where the port is omitted
100 // if it is the default for the URL's scheme.
101 NET_EXPORT_PRIVATE
std::string
GetHostAndOptionalPort(const GURL
& url
);
103 // Returns true if |hostname| contains a non-registerable or non-assignable
104 // domain name (eg: a gTLD that has not been assigned by IANA) or an IP address
105 // that falls in an IANA-reserved range.
106 NET_EXPORT
bool IsHostnameNonUnique(const std::string
& hostname
);
108 // Convenience struct for when you need a |struct sockaddr|.
109 struct SockaddrStorage
{
110 SockaddrStorage() : addr_len(sizeof(addr_storage
)),
111 addr(reinterpret_cast<struct sockaddr
*>(&addr_storage
)) {}
112 SockaddrStorage(const SockaddrStorage
& other
);
113 void operator=(const SockaddrStorage
& other
);
115 struct sockaddr_storage addr_storage
;
117 struct sockaddr
* const addr
;
120 // Extracts the IP address and port portions of a sockaddr. |port| is optional,
121 // and will not be filled in if NULL.
122 bool GetIPAddressFromSockAddr(const struct sockaddr
* sock_addr
,
123 socklen_t sock_addr_len
,
124 const unsigned char** address
,
128 // Same as IPAddressToString() but for a sockaddr. This output will not include
129 // the IPv6 scope ID.
130 NET_EXPORT
std::string
NetAddressToString(const struct sockaddr
* sa
,
131 socklen_t sock_addr_len
);
133 // Same as IPAddressToStringWithPort() but for a sockaddr. This output will not
134 // include the IPv6 scope ID.
135 NET_EXPORT
std::string
NetAddressToStringWithPort(const struct sockaddr
* sa
,
136 socklen_t sock_addr_len
);
138 // Returns the hostname of the current system. Returns empty string on failure.
139 NET_EXPORT
std::string
GetHostName();
141 // Extracts the unescaped username/password from |url|, saving the results
142 // into |*username| and |*password|.
143 NET_EXPORT_PRIVATE
void GetIdentityFromURL(const GURL
& url
,
144 base::string16
* username
,
145 base::string16
* password
);
147 // Returns either the host from |url|, or, if the host is empty, the full spec.
148 NET_EXPORT
std::string
GetHostOrSpecFromURL(const GURL
& url
);
150 // Converts the given host name to unicode characters. This can be called for
151 // any host name, if the input is not IDN or is invalid in some way, we'll just
152 // return the ASCII source so it is still usable.
154 // The input should be the canonicalized ASCII host name from GURL. This
155 // function does NOT accept UTF-8!
157 // |languages| is a comma separated list of ISO 639 language codes. It
158 // is used to determine whether a hostname is 'comprehensible' to a user
159 // who understands languages listed. |host| will be converted to a
160 // human-readable form (Unicode) ONLY when each component of |host| is
161 // regarded as 'comprehensible'. Scipt-mixing is not allowed except that
162 // Latin letters in the ASCII range can be mixed with a limited set of
163 // script-language pairs (currently Han, Kana and Hangul for zh,ja and ko).
164 // When |languages| is empty, even that mixing is not allowed.
165 NET_EXPORT
base::string16
IDNToUnicode(const std::string
& host
,
166 const std::string
& languages
);
168 // Canonicalizes |host| and returns it. Also fills |host_info| with
169 // IP address information. |host_info| must not be NULL.
170 NET_EXPORT
std::string
CanonicalizeHost(const std::string
& host
,
171 url::CanonHostInfo
* host_info
);
173 // Returns true if |host| is not an IP address and is compliant with a set of
174 // rules based on RFC 1738 and tweaked to be compatible with the real world.
176 // * One or more components separated by '.'
177 // * Each component contains only alphanumeric characters and '-' or '_'
178 // * The last component begins with an alphanumeric character
179 // * Optional trailing dot after last component (means "treat as FQDN")
181 // NOTE: You should only pass in hosts that have been returned from
182 // CanonicalizeHost(), or you may not get accurate results.
183 NET_EXPORT
bool IsCanonicalizedHostCompliant(const std::string
& host
);
185 // Call these functions to get the html snippet for a directory listing.
186 // The return values of both functions are in UTF-8.
187 NET_EXPORT
std::string
GetDirectoryListingHeader(const base::string16
& title
);
189 // Given the name of a file in a directory (ftp or local) and
190 // other information (is_dir, size, modification time), it returns
191 // the html snippet to add the entry for the file to the directory listing.
192 // Currently, it's a script tag containing a call to a Javascript function
195 // |name| is the file name to be displayed. |raw_bytes| will be used
196 // as the actual target of the link (so for example, ftp links should use
197 // server's encoding). If |raw_bytes| is an empty string, UTF-8 encoded |name|
200 // Both |name| and |raw_bytes| are escaped internally.
201 NET_EXPORT
std::string
GetDirectoryListingEntry(const base::string16
& name
,
202 const std::string
& raw_bytes
,
205 base::Time modified
);
207 // If text starts with "www." it is removed, otherwise text is returned
209 NET_EXPORT
base::string16
StripWWW(const base::string16
& text
);
211 // Runs |url|'s host through StripWWW(). |url| must be valid.
212 NET_EXPORT
base::string16
StripWWWFromHost(const GURL
& url
);
214 // Set socket to non-blocking mode
215 NET_EXPORT
int SetNonBlocking(int fd
);
217 // Formats the host in |url| and appends it to |output|. The host formatter
218 // takes the same accept languages component as ElideURL().
219 NET_EXPORT
void AppendFormattedHost(const GURL
& url
,
220 const std::string
& languages
,
221 base::string16
* output
);
223 // Creates a string representation of |url|. The IDN host name may be in Unicode
224 // if |languages| accepts the Unicode representation. |format_type| is a bitmask
225 // of FormatUrlTypes, see it for details. |unescape_rules| defines how to clean
226 // the URL for human readability. You will generally want |UnescapeRule::SPACES|
227 // for display to the user if you can handle spaces, or |UnescapeRule::NORMAL|
228 // if not. If the path part and the query part seem to be encoded in %-encoded
229 // UTF-8, decodes %-encoding and UTF-8.
231 // The last three parameters may be NULL.
233 // |new_parsed| will be set to the parsing parameters of the resultant URL.
235 // |prefix_end| will be the length before the hostname of the resultant URL.
237 // |offset[s]_for_adjustment| specifies one or more offsets into the original
238 // URL, representing insertion or selection points between characters: if the
239 // input is "http://foo.com/", offset 0 is before the entire URL, offset 7 is
240 // between the scheme and the host, and offset 15 is after the end of the URL.
241 // Valid input offsets range from 0 to the length of the input URL string. On
242 // exit, each offset will have been modified to reflect any changes made to the
243 // output string. For example, if |url| is "http://a:b@c.com/",
244 // |omit_username_password| is true, and an offset is 12 (pointing between 'c'
245 // and '.'), then on return the output string will be "http://c.com/" and the
246 // offset will be 8. If an offset cannot be successfully adjusted (e.g. because
247 // it points into the middle of a component that was entirely removed or into
248 // the middle of an encoding sequence), it will be set to base::string16::npos.
249 // For consistency, if an input offset points between the scheme and the
250 // username/password, and both are removed, on output this offset will be 0
251 // rather than npos; this means that offsets at the starts and ends of removed
252 // components are always transformed the same way regardless of what other
253 // components are adjacent.
254 NET_EXPORT
base::string16
FormatUrl(const GURL
& url
,
255 const std::string
& languages
,
256 FormatUrlTypes format_types
,
257 UnescapeRule::Type unescape_rules
,
258 url::Parsed
* new_parsed
,
260 size_t* offset_for_adjustment
);
261 NET_EXPORT
base::string16
FormatUrlWithOffsets(
263 const std::string
& languages
,
264 FormatUrlTypes format_types
,
265 UnescapeRule::Type unescape_rules
,
266 url::Parsed
* new_parsed
,
268 std::vector
<size_t>* offsets_for_adjustment
);
269 // This function is like those above except it takes |adjustments| rather
270 // than |offset[s]_for_adjustment|. |adjustments| will be set to reflect all
271 // the transformations that happened to |url| to convert it into the returned
273 NET_EXPORT
base::string16
FormatUrlWithAdjustments(
275 const std::string
& languages
,
276 FormatUrlTypes format_types
,
277 UnescapeRule::Type unescape_rules
,
278 url::Parsed
* new_parsed
,
280 base::OffsetAdjuster::Adjustments
* adjustments
);
282 // This is a convenience function for FormatUrl() with
283 // format_types = kFormatUrlOmitAll and unescape = SPACES. This is the typical
284 // set of flags for "URLs to display to the user". You should be cautious about
285 // using this for URLs which will be parsed or sent to other applications.
286 inline base::string16
FormatUrl(const GURL
& url
, const std::string
& languages
) {
287 return FormatUrl(url
, languages
, kFormatUrlOmitAll
, UnescapeRule::SPACES
,
291 // Returns whether FormatUrl() would strip a trailing slash from |url|, given a
292 // format flag including kFormatUrlOmitTrailingSlashOnBareHostname.
293 NET_EXPORT
bool CanStripTrailingSlash(const GURL
& url
);
295 // Strip the portions of |url| that aren't core to the network request.
296 // - user name / password
297 // - reference section
298 NET_EXPORT_PRIVATE GURL
SimplifyUrlForRequest(const GURL
& url
);
300 // Returns true if it can determine that only loopback addresses are configured.
301 // i.e. if only 127.0.0.1 and ::1 are routable.
302 // Also returns false if it cannot determine this.
303 bool HaveOnlyLoopbackAddresses();
305 // Returns AddressFamily of the address.
306 NET_EXPORT_PRIVATE AddressFamily
GetAddressFamily(
307 const IPAddressNumber
& address
);
309 // Maps the given AddressFamily to either AF_INET, AF_INET6 or AF_UNSPEC.
310 NET_EXPORT_PRIVATE
int ConvertAddressFamily(AddressFamily address_family
);
312 // Retuns the port field of the |sockaddr|.
313 const uint16_t* GetPortFieldFromSockaddr(const struct sockaddr
* address
,
314 socklen_t address_len
);
315 // Returns the value of port in |sockaddr| (in host byte ordering).
316 NET_EXPORT_PRIVATE
int GetPortFromSockaddr(const struct sockaddr
* address
,
317 socklen_t address_len
);
319 // Resolves a local hostname (such as "localhost" or "localhost6") into
320 // IP endpoints with the given port. Returns true if |host| is a local
321 // hostname and false otherwise. Special IPv6 names (e.g. "localhost6")
322 // will resolve to an IPv6 address only, whereas other names will
323 // resolve to both IPv4 and IPv6.
324 NET_EXPORT_PRIVATE
bool ResolveLocalHostname(const std::string
& host
,
326 AddressList
* address_list
);
328 // Returns true if |host| is one of the local hostnames
329 // (e.g. "localhost") or IP addresses (IPv4 127.0.0.0/8 or IPv6 ::1).
331 // Note that this function does not check for IP addresses other than
332 // the above, although other IP addresses may point to the local
334 NET_EXPORT_PRIVATE
bool IsLocalhost(const std::string
& host
);
336 NET_EXPORT_PRIVATE
bool IsLocalhostTLD(const std::string
& host
);
338 // Returns true if the url's host is a Google server. This should only be used
339 // for histograms and shouldn't be used to affect behavior.
340 NET_EXPORT_PRIVATE
bool HasGoogleHost(const GURL
& url
);
342 // A subset of IP address attributes which are actionable by the
343 // application layer. Currently unimplemented for all hosts;
344 // IP_ADDRESS_ATTRIBUTE_NONE is always returned.
345 enum IPAddressAttributes
{
346 IP_ADDRESS_ATTRIBUTE_NONE
= 0,
348 // A temporary address is dynamic by nature and will not contain MAC
349 // address. Presence of MAC address in IPv6 addresses can be used to
350 // track an endpoint and cause privacy concern. Please refer to
352 IP_ADDRESS_ATTRIBUTE_TEMPORARY
= 1 << 0,
354 // A temporary address could become deprecated once the preferred
355 // lifetime is reached. It is still valid but shouldn't be used to
356 // create new connections.
357 IP_ADDRESS_ATTRIBUTE_DEPRECATED
= 1 << 1,
360 // Differentiated Services Code Point.
361 // See http://tools.ietf.org/html/rfc2474 for details.
362 enum DiffServCodePoint
{
364 DSCP_FIRST
= DSCP_NO_CHANGE
,
365 DSCP_DEFAULT
= 0, // Same as DSCP_CS0
366 DSCP_CS0
= 0, // The default
367 DSCP_CS1
= 8, // Bulk/background traffic
380 DSCP_AF41
= 34, // Video
381 DSCP_AF42
= 36, // Video
382 DSCP_AF43
= 38, // Video
383 DSCP_CS5
= 40, // Video
384 DSCP_EF
= 46, // Voice
385 DSCP_CS6
= 48, // Voice
386 DSCP_CS7
= 56, // Control messages
392 #endif // NET_BASE_NET_UTIL_H_