Add ICU message format support
[chromium-blink-merge.git] / url / gurl.h
blob908a649db5280c8fb6803cf3bc5277b72b011ad7
1 // Copyright 2013 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 URL_GURL_H_
6 #define URL_GURL_H_
8 #include <iosfwd>
9 #include <string>
11 #include "base/memory/scoped_ptr.h"
12 #include "base/strings/string16.h"
13 #include "base/strings/string_piece.h"
14 #include "url/third_party/mozilla/url_parse.h"
15 #include "url/url_canon.h"
16 #include "url/url_canon_stdstring.h"
17 #include "url/url_constants.h"
18 #include "url/url_export.h"
20 class URL_EXPORT GURL {
21 public:
22 typedef url::StringPieceReplacements<std::string> Replacements;
23 typedef url::StringPieceReplacements<base::string16> ReplacementsW;
25 // Creates an empty, invalid URL.
26 GURL();
28 // Copy construction is relatively inexpensive, with most of the time going
29 // to reallocating the string. It does not re-parse.
30 GURL(const GURL& other);
32 // The narrow version requires the input be UTF-8. Invalid UTF-8 input will
33 // result in an invalid URL.
35 // The wide version should also take an encoding parameter so we know how to
36 // encode the query parameters. It is probably sufficient for the narrow
37 // version to assume the query parameter encoding should be the same as the
38 // input encoding.
39 explicit GURL(const std::string& url_string /*, output_param_encoding*/);
40 explicit GURL(const base::string16& url_string /*, output_param_encoding*/);
42 // Constructor for URLs that have already been parsed and canonicalized. This
43 // is used for conversions from KURL, for example. The caller must supply all
44 // information associated with the URL, which must be correct and consistent.
45 GURL(const char* canonical_spec,
46 size_t canonical_spec_len,
47 const url::Parsed& parsed,
48 bool is_valid);
49 // Notice that we take the canonical_spec by value so that we can convert
50 // from WebURL without copying the string. When we call this constructor
51 // we pass in a temporary std::string, which lets the compiler skip the
52 // copy and just move the std::string into the function argument. In the
53 // implementation, we use swap to move the data into the GURL itself,
54 // which means we end up with zero copies.
55 GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid);
57 ~GURL();
59 GURL& operator=(GURL other);
61 // Returns true when this object represents a valid parsed URL. When not
62 // valid, other functions will still succeed, but you will not get canonical
63 // data out in the format you may be expecting. Instead, we keep something
64 // "reasonable looking" so that the user can see how it's busted if
65 // displayed to them.
66 bool is_valid() const {
67 return is_valid_;
70 // Returns true if the URL is zero-length. Note that empty URLs are also
71 // invalid, and is_valid() will return false for them. This is provided
72 // because some users may want to treat the empty case differently.
73 bool is_empty() const {
74 return spec_.empty();
77 // Returns the raw spec, i.e., the full text of the URL, in canonical UTF-8,
78 // if the URL is valid. If the URL is not valid, this will assert and return
79 // the empty string (for safety in release builds, to keep them from being
80 // misused which might be a security problem).
82 // The URL will be ASCII except the reference fragment, which may be UTF-8.
83 // It is guaranteed to be valid UTF-8.
85 // The exception is for empty() URLs (which are !is_valid()) but this will
86 // return the empty string without asserting.
88 // Used invalid_spec() below to get the unusable spec of an invalid URL. This
89 // separation is designed to prevent errors that may cause security problems
90 // that could result from the mistaken use of an invalid URL.
91 const std::string& spec() const;
93 // Returns the potentially invalid spec for a the URL. This spec MUST NOT be
94 // modified or sent over the network. It is designed to be displayed in error
95 // messages to the user, as the apperance of the spec may explain the error.
96 // If the spec is valid, the valid spec will be returned.
98 // The returned string is guaranteed to be valid UTF-8.
99 const std::string& possibly_invalid_spec() const {
100 return spec_;
103 // Getter for the raw parsed structure. This allows callers to locate parts
104 // of the URL within the spec themselves. Most callers should consider using
105 // the individual component getters below.
107 // The returned parsed structure will reference into the raw spec, which may
108 // or may not be valid. If you are using this to index into the spec, BE
109 // SURE YOU ARE USING possibly_invalid_spec() to get the spec, and that you
110 // don't do anything "important" with invalid specs.
111 const url::Parsed& parsed_for_possibly_invalid_spec() const {
112 return parsed_;
115 // Defiant equality operator!
116 bool operator==(const GURL& other) const;
117 bool operator!=(const GURL& other) const;
119 // Allows GURL to used as a key in STL (for example, a std::set or std::map).
120 bool operator<(const GURL& other) const;
121 bool operator>(const GURL& other) const;
123 // Resolves a URL that's possibly relative to this object's URL, and returns
124 // it. Absolute URLs are also handled according to the rules of URLs on web
125 // pages.
127 // It may be impossible to resolve the URLs properly. If the input is not
128 // "standard" (SchemeIsStandard() == false) and the input looks relative, we
129 // can't resolve it. In these cases, the result will be an empty, invalid
130 // GURL.
132 // The result may also be a nonempty, invalid URL if the input has some kind
133 // of encoding error. In these cases, we will try to construct a "good" URL
134 // that may have meaning to the user, but it will be marked invalid.
136 // It is an error to resolve a URL relative to an invalid URL. The result
137 // will be the empty URL.
138 GURL Resolve(const std::string& relative) const;
139 GURL Resolve(const base::string16& relative) const;
141 // Creates a new GURL by replacing the current URL's components with the
142 // supplied versions. See the Replacements class in url_canon.h for more.
144 // These are not particularly quick, so avoid doing mutations when possible.
145 // Prefer the 8-bit version when possible.
147 // It is an error to replace components of an invalid URL. The result will
148 // be the empty URL.
150 // Note that we use the more general url::Replacements type to give
151 // callers extra flexibility rather than our override.
152 GURL ReplaceComponents(const url::Replacements<char>& replacements) const;
153 GURL ReplaceComponents(
154 const url::Replacements<base::char16>& replacements) const;
156 // A helper function that is equivalent to replacing the path with a slash
157 // and clearing out everything after that. We sometimes need to know just the
158 // scheme and the authority. If this URL is not a standard URL (it doesn't
159 // have the regular authority and path sections), then the result will be
160 // an empty, invalid GURL. Note that this *does* work for file: URLs, which
161 // some callers may want to filter out before calling this.
163 // It is an error to get an empty path on an invalid URL. The result
164 // will be the empty URL.
165 GURL GetWithEmptyPath() const;
167 // A helper function to return a GURL containing just the scheme, host,
168 // and port from a URL. Equivalent to clearing any username and password,
169 // replacing the path with a slash, and clearing everything after that. If
170 // this URL is not a standard URL, then the result will be an empty,
171 // invalid GURL. If the URL has neither username nor password, this
172 // degenerates to GetWithEmptyPath().
174 // It is an error to get the origin of an invalid URL. The result
175 // will be the empty URL.
176 GURL GetOrigin() const;
178 // A helper function to return a GURL stripped from the elements that are not
179 // supposed to be sent as HTTP referrer: username, password and ref fragment.
180 // For invalid URLs or URLs that no valid referrers, an empty URL will be
181 // returned.
182 GURL GetAsReferrer() const;
184 // Returns true if the scheme for the current URL is a known "standard-format"
185 // scheme. A standard-format scheme adheres to what RFC 3986 calls "generic
186 // URI syntax" (https://tools.ietf.org/html/rfc3986#section-3). This includes
187 // file: and filesystem:, which some callers may want to filter out explicitly
188 // by calling SchemeIsFile[System].
189 bool IsStandard() const;
191 // Returns true if the given parameter (should be lower-case ASCII to match
192 // the canonicalized scheme) is the scheme for this URL. This call is more
193 // efficient than getting the scheme and comparing it because no copies or
194 // object constructions are done.
195 bool SchemeIs(const char* lower_ascii_scheme) const;
197 // Returns true if the scheme is "http" or "https".
198 bool SchemeIsHTTPOrHTTPS() const;
200 // Returns true is the scheme is "ws" or "wss".
201 bool SchemeIsWSOrWSS() const;
203 // We often need to know if this is a file URL. File URLs are "standard", but
204 // are often treated separately by some programs.
205 bool SchemeIsFile() const {
206 return SchemeIs(url::kFileScheme);
209 // FileSystem URLs need to be treated differently in some cases.
210 bool SchemeIsFileSystem() const {
211 return SchemeIs(url::kFileSystemScheme);
214 // Returns true if the scheme indicates a secure connection.
216 // NOTE: This function is deprecated. You probably want
217 // |SchemeIsCryptographic| (if you just want to know if a scheme uses TLS for
218 // network transport) or Chromium's |IsOriginSecure| for a higher-level test
219 // about an origin's security. See those functions' documentation for more
220 // detail.
222 // TODO(palmer): Audit callers and change them to |SchemeIsCryptographic| or
223 // |IsOriginSecure|, as appropriate. Then remove |SchemeIsSecure|.
224 // crbug.com/362214
225 bool SchemeIsSecure() const {
226 return SchemeIs(url::kHttpsScheme) || SchemeIs(url::kWssScheme) ||
227 (SchemeIsFileSystem() && inner_url() &&
228 inner_url()->SchemeIsSecure());
231 // Returns true if the scheme indicates a network connection that uses TLS or
232 // some other cryptographic protocol (e.g. QUIC) for security.
234 // This function is a not a complete test of whether or not an origin's code
235 // is minimally trustworthy. For that, see Chromium's |IsOriginSecure| for a
236 // higher-level and more complete semantics. See that function's documentation
237 // for more detail.
238 bool SchemeIsCryptographic() const {
239 return SchemeIs(url::kHttpsScheme) || SchemeIs(url::kWssScheme);
242 // Returns true if the scheme is "blob".
243 bool SchemeIsBlob() const {
244 return SchemeIs(url::kBlobScheme);
247 // The "content" of the URL is everything after the scheme (skipping the
248 // scheme delimiting colon). It is an error to get the content of an invalid
249 // URL: the result will be an empty string.
250 std::string GetContent() const;
252 // Returns true if the hostname is an IP address. Note: this function isn't
253 // as cheap as a simple getter because it re-parses the hostname to verify.
254 bool HostIsIPAddress() const;
256 // Getters for various components of the URL. The returned string will be
257 // empty if the component is empty or is not present.
258 std::string scheme() const { // Not including the colon. See also SchemeIs.
259 return ComponentString(parsed_.scheme);
261 std::string username() const {
262 return ComponentString(parsed_.username);
264 std::string password() const {
265 return ComponentString(parsed_.password);
267 // Note that this may be a hostname, an IPv4 address, or an IPv6 literal
268 // surrounded by square brackets, like "[2001:db8::1]". To exclude these
269 // brackets, use HostNoBrackets() below.
270 std::string host() const {
271 return ComponentString(parsed_.host);
273 std::string port() const { // Returns -1 if "default"
274 return ComponentString(parsed_.port);
276 std::string path() const { // Including first slash following host
277 return ComponentString(parsed_.path);
279 std::string query() const { // Stuff following '?'
280 return ComponentString(parsed_.query);
282 std::string ref() const { // Stuff following '#'
283 return ComponentString(parsed_.ref);
286 // Existance querying. These functions will return true if the corresponding
287 // URL component exists in this URL. Note that existance is different than
288 // being nonempty. http://www.google.com/? has a query that just happens to
289 // be empty, and has_query() will return true.
290 bool has_scheme() const {
291 return parsed_.scheme.len >= 0;
293 bool has_username() const {
294 return parsed_.username.len >= 0;
296 bool has_password() const {
297 return parsed_.password.len >= 0;
299 bool has_host() const {
300 // Note that hosts are special, absense of host means length 0.
301 return parsed_.host.len > 0;
303 bool has_port() const {
304 return parsed_.port.len >= 0;
306 bool has_path() const {
307 // Note that http://www.google.com/" has a path, the path is "/". This can
308 // return false only for invalid or nonstandard URLs.
309 return parsed_.path.len >= 0;
311 bool has_query() const {
312 return parsed_.query.len >= 0;
314 bool has_ref() const {
315 return parsed_.ref.len >= 0;
318 // Returns a parsed version of the port. Can also be any of the special
319 // values defined in Parsed for ExtractPort.
320 int IntPort() const;
322 // Returns the port number of the URL, or the default port number.
323 // If the scheme has no concept of port (or unknown default) returns
324 // PORT_UNSPECIFIED.
325 int EffectiveIntPort() const;
327 // Extracts the filename portion of the path and returns it. The filename
328 // is everything after the last slash in the path. This may be empty.
329 std::string ExtractFileName() const;
331 // Returns the path that should be sent to the server. This is the path,
332 // parameter, and query portions of the URL. It is guaranteed to be ASCII.
333 std::string PathForRequest() const;
335 // Returns the host, excluding the square brackets surrounding IPv6 address
336 // literals. This can be useful for passing to getaddrinfo().
337 std::string HostNoBrackets() const;
339 // Returns true if this URL's host matches or is in the same domain as
340 // the given input string. For example, if the hostname of the URL is
341 // "www.google.com", this will return true for "com", "google.com", and
342 // "www.google.com".
344 // The input domain should be lower-case ASCII to match the canonicalized
345 // scheme. This call is more efficient than getting the host and check
346 // whether host has the specific domain or not because no copies or
347 // object constructions are done.
348 bool DomainIs(base::StringPiece lower_ascii_domain) const;
350 // Swaps the contents of this GURL object with the argument without doing
351 // any memory allocations.
352 void Swap(GURL* other);
354 // Returns a reference to a singleton empty GURL. This object is for callers
355 // who return references but don't have anything to return in some cases.
356 // This function may be called from any thread.
357 static const GURL& EmptyGURL();
359 // Returns the inner URL of a nested URL [currently only non-null for
360 // filesystem: URLs].
361 const GURL* inner_url() const {
362 return inner_url_.get();
365 private:
366 // Variant of the string parsing constructor that allows the caller to elect
367 // retain trailing whitespace, if any, on the passed URL spec but only if the
368 // scheme is one that allows trailing whitespace. The primary use-case is
369 // for data: URLs. In most cases, you want to use the single parameter
370 // constructor above.
371 enum RetainWhiteSpaceSelector { RETAIN_TRAILING_PATH_WHITEPACE };
372 GURL(const std::string& url_string, RetainWhiteSpaceSelector);
374 template<typename STR>
375 void InitCanonical(const STR& input_spec, bool trim_path_end);
377 void InitializeFromCanonicalSpec();
379 // Returns the substring of the input identified by the given component.
380 std::string ComponentString(const url::Component& comp) const {
381 if (comp.len <= 0)
382 return std::string();
383 return std::string(spec_, comp.begin, comp.len);
386 // The actual text of the URL, in canonical ASCII form.
387 std::string spec_;
389 // Set when the given URL is valid. Otherwise, we may still have a spec and
390 // components, but they may not identify valid resources (for example, an
391 // invalid port number, invalid characters in the scheme, etc.).
392 bool is_valid_;
394 // Identified components of the canonical spec.
395 url::Parsed parsed_;
397 // Used for nested schemes [currently only filesystem:].
398 scoped_ptr<GURL> inner_url_;
400 // TODO bug 684583: Add encoding for query params.
403 // Stream operator so GURL can be used in assertion statements.
404 URL_EXPORT std::ostream& operator<<(std::ostream& out, const GURL& url);
406 #endif // URL_GURL_H_