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>
23 #include "base/basictypes.h"
24 #include "base/strings/string16.h"
25 #include "net/base/address_family.h"
26 #include "net/base/escape.h"
27 #include "net/base/net_export.h"
28 #include "net/base/net_log.h"
47 // Used by FormatUrl to specify handling of certain parts of the url.
48 typedef uint32 FormatUrlType
;
49 typedef uint32 FormatUrlTypes
;
51 // IPAddressNumber is used to represent an IP address's numeric value as an
52 // array of bytes, from most significant to least significant. This is the
53 // network byte ordering.
55 // IPv4 addresses will have length 4, whereas IPv6 address will have length 16.
56 typedef std::vector
<unsigned char> IPAddressNumber
;
57 typedef std::vector
<IPAddressNumber
> IPAddressList
;
59 static const size_t kIPv4AddressSize
= 4;
60 static const size_t kIPv6AddressSize
= 16;
62 // Nothing is ommitted.
63 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitNothing
;
65 // If set, any username and password are removed.
66 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitUsernamePassword
;
68 // If the scheme is 'http://', it's removed.
69 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitHTTP
;
71 // Omits the path if it is just a slash and there is no query or ref. This is
72 // meaningful for non-file "standard" URLs.
73 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitTrailingSlashOnBareHostname
;
75 // Convenience for omitting all unecessary types.
76 NET_EXPORT
extern const FormatUrlType kFormatUrlOmitAll
;
78 // Returns the number of explicitly allowed ports; for testing.
79 NET_EXPORT_PRIVATE
extern size_t GetCountOfExplicitlyAllowedPorts();
81 // Given the full path to a file name, creates a file: URL. The returned URL
82 // may not be valid if the input is malformed.
83 NET_EXPORT GURL
FilePathToFileURL(const base::FilePath
& path
);
85 // Converts a file: URL back to a filename that can be passed to the OS. The
86 // file URL must be well-formed (GURL::is_valid() must return true); we don't
87 // handle degenerate cases here. Returns true on success, false if it isn't a
88 // valid file URL. On failure, *file_path will be empty.
89 NET_EXPORT
bool FileURLToFilePath(const GURL
& url
, base::FilePath
* file_path
);
91 // Splits an input of the form <host>[":"<port>] into its consitituent parts.
92 // Saves the result into |*host| and |*port|. If the input did not have
93 // the optional port, sets |*port| to -1.
94 // Returns true if the parsing was successful, false otherwise.
95 // The returned host is NOT canonicalized, and may be invalid. If <host> is
96 // an IPv6 literal address, the returned host includes the square brackets.
97 NET_EXPORT
bool ParseHostAndPort(
98 std::string::const_iterator host_and_port_begin
,
99 std::string::const_iterator host_and_port_end
,
102 NET_EXPORT
bool ParseHostAndPort(
103 const std::string
& host_and_port
,
107 // Returns a host:port string for the given URL.
108 NET_EXPORT
std::string
GetHostAndPort(const GURL
& url
);
110 // Returns a host[:port] string for the given URL, where the port is omitted
111 // if it is the default for the URL's scheme.
112 NET_EXPORT_PRIVATE
std::string
GetHostAndOptionalPort(const GURL
& url
);
114 // Returns true if |hostname| contains a non-registerable or non-assignable
115 // domain name (eg: a gTLD that has not been assigned by IANA) or an IP address
116 // that falls in an IANA-reserved range.
117 NET_EXPORT
bool IsHostnameNonUnique(const std::string
& hostname
);
119 // Returns true if an IP address hostname is in a range reserved by the IANA.
120 // Works with both IPv4 and IPv6 addresses, and only compares against a given
121 // protocols's reserved ranges.
122 NET_EXPORT
bool IsIPAddressReserved(const IPAddressNumber
& address
);
124 // Convenience struct for when you need a |struct sockaddr|.
125 struct SockaddrStorage
{
126 SockaddrStorage() : addr_len(sizeof(addr_storage
)),
127 addr(reinterpret_cast<struct sockaddr
*>(&addr_storage
)) {}
128 struct sockaddr_storage addr_storage
;
130 struct sockaddr
* const addr
;
133 // Extracts the IP address and port portions of a sockaddr. |port| is optional,
134 // and will not be filled in if NULL.
135 bool GetIPAddressFromSockAddr(const struct sockaddr
* sock_addr
,
136 socklen_t sock_addr_len
,
137 const unsigned char** address
,
141 // Returns the string representation of an IP address.
142 // For example: "192.168.0.1" or "::1".
143 NET_EXPORT
std::string
IPAddressToString(const uint8
* address
,
146 // Returns the string representation of an IP address along with its port.
147 // For example: "192.168.0.1:99" or "[::1]:80".
148 NET_EXPORT
std::string
IPAddressToStringWithPort(const uint8
* address
,
152 // Same as IPAddressToString() but for a sockaddr. This output will not include
153 // the IPv6 scope ID.
154 NET_EXPORT
std::string
NetAddressToString(const struct sockaddr
* sa
,
155 socklen_t sock_addr_len
);
157 // Same as IPAddressToStringWithPort() but for a sockaddr. This output will not
158 // include the IPv6 scope ID.
159 NET_EXPORT
std::string
NetAddressToStringWithPort(const struct sockaddr
* sa
,
160 socklen_t sock_addr_len
);
162 // Same as IPAddressToString() but for an IPAddressNumber.
163 NET_EXPORT
std::string
IPAddressToString(const IPAddressNumber
& addr
);
165 // Same as IPAddressToStringWithPort() but for an IPAddressNumber.
166 NET_EXPORT
std::string
IPAddressToStringWithPort(
167 const IPAddressNumber
& addr
, uint16 port
);
169 // Returns the hostname of the current system. Returns empty string on failure.
170 NET_EXPORT
std::string
GetHostName();
172 // Extracts the unescaped username/password from |url|, saving the results
173 // into |*username| and |*password|.
174 NET_EXPORT_PRIVATE
void GetIdentityFromURL(const GURL
& url
,
175 base::string16
* username
,
176 base::string16
* password
);
178 // Returns either the host from |url|, or, if the host is empty, the full spec.
179 NET_EXPORT
std::string
GetHostOrSpecFromURL(const GURL
& url
);
181 // Return the value of the HTTP response header with name 'name'. 'headers'
182 // should be in the format that URLRequest::GetResponseHeaders() returns.
183 // Returns the empty string if the header is not found.
184 NET_EXPORT
std::string
GetSpecificHeader(const std::string
& headers
,
185 const std::string
& name
);
187 // Converts the given host name to unicode characters. This can be called for
188 // any host name, if the input is not IDN or is invalid in some way, we'll just
189 // return the ASCII source so it is still usable.
191 // The input should be the canonicalized ASCII host name from GURL. This
192 // function does NOT accept UTF-8!
194 // |languages| is a comma separated list of ISO 639 language codes. It
195 // is used to determine whether a hostname is 'comprehensible' to a user
196 // who understands languages listed. |host| will be converted to a
197 // human-readable form (Unicode) ONLY when each component of |host| is
198 // regarded as 'comprehensible'. Scipt-mixing is not allowed except that
199 // Latin letters in the ASCII range can be mixed with a limited set of
200 // script-language pairs (currently Han, Kana and Hangul for zh,ja and ko).
201 // When |languages| is empty, even that mixing is not allowed.
202 NET_EXPORT
base::string16
IDNToUnicode(const std::string
& host
,
203 const std::string
& languages
);
205 // Canonicalizes |host| and returns it. Also fills |host_info| with
206 // IP address information. |host_info| must not be NULL.
207 NET_EXPORT
std::string
CanonicalizeHost(const std::string
& host
,
208 url_canon::CanonHostInfo
* host_info
);
210 // Returns true if |host| is not an IP address and is compliant with a set of
211 // rules based on RFC 1738 and tweaked to be compatible with the real world.
213 // * One or more components separated by '.'
214 // * Each component begins with an alphanumeric character or '-'
215 // * Each component contains only alphanumeric characters and '-' or '_'
216 // * Each component ends with an alphanumeric character or '-'
217 // * The last component begins with an alphanumeric character
218 // * Optional trailing dot after last component (means "treat as FQDN")
219 // If |desired_tld| is non-NULL, the host will only be considered invalid if
220 // appending it as a trailing component still results in an invalid host. This
221 // helps us avoid marking as "invalid" user attempts to open, say, "www.-9.com"
222 // by typing -, 9, <ctrl>+<enter>.
224 // NOTE: You should only pass in hosts that have been returned from
225 // CanonicalizeHost(), or you may not get accurate results.
226 NET_EXPORT
bool IsCanonicalizedHostCompliant(const std::string
& host
,
227 const std::string
& desired_tld
);
229 // Call these functions to get the html snippet for a directory listing.
230 // The return values of both functions are in UTF-8.
231 NET_EXPORT
std::string
GetDirectoryListingHeader(const base::string16
& title
);
233 // Given the name of a file in a directory (ftp or local) and
234 // other information (is_dir, size, modification time), it returns
235 // the html snippet to add the entry for the file to the directory listing.
236 // Currently, it's a script tag containing a call to a Javascript function
239 // |name| is the file name to be displayed. |raw_bytes| will be used
240 // as the actual target of the link (so for example, ftp links should use
241 // server's encoding). If |raw_bytes| is an empty string, UTF-8 encoded |name|
244 // Both |name| and |raw_bytes| are escaped internally.
245 NET_EXPORT
std::string
GetDirectoryListingEntry(const base::string16
& name
,
246 const std::string
& raw_bytes
,
247 bool is_dir
, int64 size
,
248 base::Time modified
);
250 // If text starts with "www." it is removed, otherwise text is returned
252 NET_EXPORT
base::string16
StripWWW(const base::string16
& text
);
254 // Runs |url|'s host through StripWWW(). |url| must be valid.
255 NET_EXPORT
base::string16
StripWWWFromHost(const GURL
& url
);
257 // Generates a filename using the first successful method from the following (in
260 // 1) The raw Content-Disposition header in |content_disposition| as read from
261 // the network. |referrer_charset| is used to decode non-ASCII strings.
262 // 2) |suggested_name| if specified. |suggested_name| is assumed to be in
264 // 3) The filename extracted from the |url|. |referrer_charset| will be used to
265 // interpret the URL if there are non-ascii characters.
266 // 4) |default_name|. If non-empty, |default_name| is assumed to be a filename
267 // and shouldn't contain a path. |default_name| is not subject to validation
268 // or sanitization, and therefore shouldn't be a user supplied string.
269 // 5) The hostname portion from the |url|
271 // Then, leading and trailing '.'s will be removed. On Windows, trailing spaces
272 // are also removed. The string "download" is the final fallback if no filename
273 // is found or the filename is empty.
275 // Any illegal characters in the filename will be replaced by '-'. If the
276 // filename doesn't contain an extension, and a |mime_type| is specified, the
277 // preferred extension for the |mime_type| will be appended to the filename.
278 // The resulting filename is then checked against a list of reserved names on
279 // Windows. If the name is reserved, an underscore will be prepended to the
282 // Note: |mime_type| should only be specified if this function is called from a
283 // thread that allows IO.
284 NET_EXPORT
base::string16
GetSuggestedFilename(
286 const std::string
& content_disposition
,
287 const std::string
& referrer_charset
,
288 const std::string
& suggested_name
,
289 const std::string
& mime_type
,
290 const std::string
& default_name
);
292 // Similar to GetSuggestedFilename(), but returns a FilePath.
293 NET_EXPORT
base::FilePath
GenerateFileName(
295 const std::string
& content_disposition
,
296 const std::string
& referrer_charset
,
297 const std::string
& suggested_name
,
298 const std::string
& mime_type
,
299 const std::string
& default_name
);
303 // * are not Windows reserved names (CON, NUL.zip, etc.)
304 // * are just basenames
305 // * do not have trailing separators
306 // * do not equal kCurrentDirectory
307 // * do not reference the parent directory
308 // * are valid path components, which:
309 // - * are not the empty string
310 // - * do not contain illegal characters
311 // - * do not end with Windows shell-integrated extensions (even on posix)
312 // - * do not begin with '.' (which would hide them in most file managers)
313 // - * do not end with ' ' or '.'
314 NET_EXPORT
bool IsSafePortableBasename(const base::FilePath
& path
);
316 // Basenames of valid relative paths are IsSafePortableBasename(), and internal
317 // path components of valid relative paths are valid path components as
318 // described above IsSafePortableBasename(). Valid relative paths are not
320 NET_EXPORT
bool IsSafePortableRelativePath(const base::FilePath
& path
);
322 // Ensures that the filename and extension is safe to use in the filesystem.
324 // Assumes that |file_path| already contains a valid path or file name. On
325 // Windows if the extension causes the file to have an unsafe interaction with
326 // the shell (see net_util::IsShellIntegratedExtension()), then it will be
327 // replaced by the string 'download'. If |file_path| doesn't contain an
328 // extension or |ignore_extension| is true then the preferred extension, if one
329 // exists, for |mime_type| will be used as the extension.
331 // On Windows, the filename will be checked against a set of reserved names, and
332 // if so, an underscore will be prepended to the name.
334 // |file_name| can either be just the file name or it can be a full path to a
337 // Note: |mime_type| should only be non-empty if this function is called from a
338 // thread that allows IO.
339 NET_EXPORT
void GenerateSafeFileName(const std::string
& mime_type
,
340 bool ignore_extension
,
341 base::FilePath
* file_path
);
343 // Checks |port| against a list of ports which are restricted by default.
344 // Returns true if |port| is allowed, false if it is restricted.
345 NET_EXPORT
bool IsPortAllowedByDefault(int port
);
347 // Checks |port| against a list of ports which are restricted by the FTP
348 // protocol. Returns true if |port| is allowed, false if it is restricted.
349 NET_EXPORT_PRIVATE
bool IsPortAllowedByFtp(int port
);
351 // Check if banned |port| has been overriden by an entry in
352 // |explicitly_allowed_ports_|.
353 NET_EXPORT_PRIVATE
bool IsPortAllowedByOverride(int port
);
355 // Set socket to non-blocking mode
356 NET_EXPORT
int SetNonBlocking(int fd
);
358 // Formats the host in |url| and appends it to |output|. The host formatter
359 // takes the same accept languages component as ElideURL().
360 NET_EXPORT
void AppendFormattedHost(const GURL
& url
,
361 const std::string
& languages
,
362 base::string16
* output
);
364 // Creates a string representation of |url|. The IDN host name may be in Unicode
365 // if |languages| accepts the Unicode representation. |format_type| is a bitmask
366 // of FormatUrlTypes, see it for details. |unescape_rules| defines how to clean
367 // the URL for human readability. You will generally want |UnescapeRule::SPACES|
368 // for display to the user if you can handle spaces, or |UnescapeRule::NORMAL|
369 // if not. If the path part and the query part seem to be encoded in %-encoded
370 // UTF-8, decodes %-encoding and UTF-8.
372 // The last three parameters may be NULL.
373 // |new_parsed| will be set to the parsing parameters of the resultant URL.
374 // |prefix_end| will be the length before the hostname of the resultant URL.
376 // (|offset[s]_for_adjustment|) specifies one or more offsets into the original
377 // |url|'s spec(); each offset will be modified to reflect changes this function
378 // makes to the output string. For example, if |url| is "http://a:b@c.com/",
379 // |omit_username_password| is true, and an offset is 12 (the offset of '.'),
380 // then on return the output string will be "http://c.com/" and the offset will
381 // be 8. If an offset cannot be successfully adjusted (e.g. because it points
382 // into the middle of a component that was entirely removed, past the end of the
383 // string, or into the middle of an encoding sequence), it will be set to
384 // base::string16::npos.
385 NET_EXPORT
base::string16
FormatUrl(const GURL
& url
,
386 const std::string
& languages
,
387 FormatUrlTypes format_types
,
388 UnescapeRule::Type unescape_rules
,
389 url_parse::Parsed
* new_parsed
,
391 size_t* offset_for_adjustment
);
392 NET_EXPORT
base::string16
FormatUrlWithOffsets(
394 const std::string
& languages
,
395 FormatUrlTypes format_types
,
396 UnescapeRule::Type unescape_rules
,
397 url_parse::Parsed
* new_parsed
,
399 std::vector
<size_t>* offsets_for_adjustment
);
401 // This is a convenience function for FormatUrl() with
402 // format_types = kFormatUrlOmitAll and unescape = SPACES. This is the typical
403 // set of flags for "URLs to display to the user". You should be cautious about
404 // using this for URLs which will be parsed or sent to other applications.
405 inline base::string16
FormatUrl(const GURL
& url
, const std::string
& languages
) {
406 return FormatUrl(url
, languages
, kFormatUrlOmitAll
, UnescapeRule::SPACES
,
410 // Returns whether FormatUrl() would strip a trailing slash from |url|, given a
411 // format flag including kFormatUrlOmitTrailingSlashOnBareHostname.
412 NET_EXPORT
bool CanStripTrailingSlash(const GURL
& url
);
414 // Strip the portions of |url| that aren't core to the network request.
415 // - user name / password
416 // - reference section
417 NET_EXPORT_PRIVATE GURL
SimplifyUrlForRequest(const GURL
& url
);
419 NET_EXPORT
void SetExplicitlyAllowedPorts(const std::string
& allowed_ports
);
421 class NET_EXPORT ScopedPortException
{
423 ScopedPortException(int port
);
424 ~ScopedPortException();
429 DISALLOW_COPY_AND_ASSIGN(ScopedPortException
);
432 // Returns true if it can determine that only loopback addresses are configured.
433 // i.e. if only 127.0.0.1 and ::1 are routable.
434 // Also returns false if it cannot determine this.
435 bool HaveOnlyLoopbackAddresses();
437 // Returns AddressFamily of the address.
438 NET_EXPORT_PRIVATE AddressFamily
GetAddressFamily(
439 const IPAddressNumber
& address
);
441 // Parses an IP address literal (either IPv4 or IPv6) to its numeric value.
442 // Returns true on success and fills |ip_number| with the numeric value.
443 NET_EXPORT_PRIVATE
bool ParseIPLiteralToNumber(const std::string
& ip_literal
,
444 IPAddressNumber
* ip_number
);
446 // Converts an IPv4 address to an IPv4-mapped IPv6 address.
447 // For example 192.168.0.1 would be converted to ::ffff:192.168.0.1.
448 NET_EXPORT_PRIVATE IPAddressNumber
ConvertIPv4NumberToIPv6Number(
449 const IPAddressNumber
& ipv4_number
);
451 // Returns true iff |address| is an IPv4-mapped IPv6 address.
452 NET_EXPORT_PRIVATE
bool IsIPv4Mapped(const IPAddressNumber
& address
);
454 // Converts an IPv4-mapped IPv6 address to IPv4 address. Should only be called
455 // on IPv4-mapped IPv6 addresses.
456 NET_EXPORT_PRIVATE IPAddressNumber
ConvertIPv4MappedToIPv4(
457 const IPAddressNumber
& address
);
459 // Parses an IP block specifier from CIDR notation to an
460 // (IP address, prefix length) pair. Returns true on success and fills
461 // |*ip_number| with the numeric value of the IP address and sets
462 // |*prefix_length_in_bits| with the length of the prefix.
464 // CIDR notation literals can use either IPv4 or IPv6 literals. Some examples:
469 NET_EXPORT
bool ParseCIDRBlock(const std::string
& cidr_literal
,
470 IPAddressNumber
* ip_number
,
471 size_t* prefix_length_in_bits
);
473 // Compares an IP address to see if it falls within the specified IP block.
474 // Returns true if it does, false otherwise.
476 // The IP block is given by (|ip_prefix|, |prefix_length_in_bits|) -- any
477 // IP address whose |prefix_length_in_bits| most significant bits match
478 // |ip_prefix| will be matched.
480 // In cases when an IPv4 address is being compared to an IPv6 address prefix
481 // and vice versa, the IPv4 addresses will be converted to IPv4-mapped
483 NET_EXPORT_PRIVATE
bool IPNumberMatchesPrefix(const IPAddressNumber
& ip_number
,
484 const IPAddressNumber
& ip_prefix
,
485 size_t prefix_length_in_bits
);
487 // Retuns the port field of the |sockaddr|.
488 const uint16
* GetPortFieldFromSockaddr(const struct sockaddr
* address
,
489 socklen_t address_len
);
490 // Returns the value of port in |sockaddr| (in host byte ordering).
491 NET_EXPORT_PRIVATE
int GetPortFromSockaddr(const struct sockaddr
* address
,
492 socklen_t address_len
);
494 // Returns true if |host| is one of the names (e.g. "localhost") or IP
495 // addresses (IPv4 127.0.0.0/8 or IPv6 ::1) that indicate a loopback.
497 // Note that this function does not check for IP addresses other than
498 // the above, although other IP addresses may point to the local
500 NET_EXPORT_PRIVATE
bool IsLocalhost(const std::string
& host
);
502 // struct that is used by GetNetworkList() to represent a network
504 struct NET_EXPORT NetworkInterface
{
506 NetworkInterface(const std::string
& name
, const IPAddressNumber
& address
);
510 IPAddressNumber address
;
513 typedef std::vector
<NetworkInterface
> NetworkInterfaceList
;
515 // Returns list of network interfaces except loopback interface. If an
516 // interface has more than one address, a separate entry is added to
517 // the list for each address.
518 // Can be called only on a thread that allows IO.
519 NET_EXPORT
bool GetNetworkList(NetworkInterfaceList
* networks
);
521 // General category of the IEEE 802.11 (wifi) physical layer operating mode.
522 enum WifiPHYLayerProtocol
{
523 // No wifi support or no associated AP.
524 WIFI_PHY_LAYER_PROTOCOL_NONE
,
525 // An obsolete modes introduced by the original 802.11, e.g. IR, FHSS,
526 WIFI_PHY_LAYER_PROTOCOL_ANCIENT
,
527 // 802.11a, OFDM-based rates.
528 WIFI_PHY_LAYER_PROTOCOL_A
,
529 // 802.11b, DSSS or HR DSSS.
530 WIFI_PHY_LAYER_PROTOCOL_B
,
531 // 802.11g, same rates as 802.11a but compatible with 802.11b.
532 WIFI_PHY_LAYER_PROTOCOL_G
,
533 // 802.11n, HT rates.
534 WIFI_PHY_LAYER_PROTOCOL_N
,
535 // Unclassified mode or failure to identify.
536 WIFI_PHY_LAYER_PROTOCOL_UNKNOWN
539 // Characterize the PHY mode of the currently associated access point.
540 // Currently only available on OS_WIN.
541 NET_EXPORT WifiPHYLayerProtocol
GetWifiPHYLayerProtocol();
545 #endif // NET_BASE_NET_UTIL_H_