• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef URL_GURL_H_
6 #define URL_GURL_H_
7 
8 #include <stddef.h>
9 
10 #include <iosfwd>
11 #include <memory>
12 #include <string>
13 #include <string_view>
14 
15 #include "base/component_export.h"
16 #include "base/debug/alias.h"
17 #include "base/debug/crash_logging.h"
18 #include "base/trace_event/base_tracing_forward.h"
19 #include "url/third_party/mozilla/url_parse.h"
20 #include "url/url_canon.h"
21 #include "url/url_canon_stdstring.h"
22 #include "url/url_constants.h"
23 
24 // Represents a URL. GURL is Google's URL parsing library.
25 //
26 // A parsed canonicalized URL is guaranteed to be UTF-8. Any non-ASCII input
27 // characters are UTF-8 encoded and % escaped to ASCII.
28 //
29 // The string representation of a URL is called the spec(). Getting the
30 // spec will assert if the URL is invalid to help protect against malicious
31 // URLs. If you want the "best effort" canonicalization of an invalid URL, you
32 // can use possibly_invalid_spec(). Test validity with is_valid(). Data and
33 // javascript URLs use GetContent() to extract the data.
34 //
35 // This class has existence checkers and getters for the various components of
36 // a URL. Existence is different than being nonempty. "http://www.google.com/?"
37 // has a query that just happens to be empty, and has_query() will return true
38 // while the query getters will return the empty string.
39 //
40 // Prefer not to modify a URL using string operations (though sometimes this is
41 // unavoidable). Instead, use ReplaceComponents which can replace or delete
42 // multiple parts of a URL in one step, doesn't re-canonicalize unchanged
43 // sections, and avoids some screw-ups. An example is creating a URL with a
44 // path that contains a literal '#'. Using string concatenation will generate a
45 // URL with a truncated path and a reference fragment, while ReplaceComponents
46 // will know to escape this and produce the desired result.
47 //
48 // WARNING: While there is no length limit on GURLs, the Mojo serialization
49 // code will replace any very long URL with an invalid GURL.
50 // See url::mojom::kMaxURLChars for more details.
COMPONENT_EXPORT(URL)51 class COMPONENT_EXPORT(URL) GURL {
52  public:
53   using Replacements = url::StringViewReplacements<char>;
54   using ReplacementsW = url::StringViewReplacements<char16_t>;
55 
56   // Creates an empty, invalid URL.
57   GURL();
58 
59   // Copy construction is relatively inexpensive, with most of the time going
60   // to reallocating the string. It does not re-parse.
61   GURL(const GURL& other);
62   GURL(GURL&& other) noexcept;
63 
64   // The strings to this constructor should be UTF-8 / UTF-16. They will be
65   // parsed and canonicalized. For example, the host is lower cased, and
66   // characters may be percent-encoded or percent-decoded to normalize the URL.
67   explicit GURL(std::string_view url_string);
68   explicit GURL(std::u16string_view url_string);
69 
70   // Constructor for URLs that have already been parsed and canonicalized. This
71   // is used for conversions from KURL, for example. The caller must supply all
72   // information associated with the URL, which must be correct and consistent.
73   GURL(const char* canonical_spec,
74        size_t canonical_spec_len,
75        const url::Parsed& parsed,
76        bool is_valid);
77   // Notice that we take the canonical_spec by value so that we can convert
78   // from WebURL without copying the string. When we call this constructor
79   // we pass in a temporary std::string, which lets the compiler skip the
80   // copy and just move the std::string into the function argument. In the
81   // implementation, we use std::move to move the data into the GURL itself,
82   // which means we end up with zero copies.
83   GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid);
84 
85   ~GURL();
86 
87   GURL& operator=(const GURL& other);
88   GURL& operator=(GURL&& other) noexcept;
89 
90   // Returns true when this object represents a valid parsed URL. When not
91   // valid, other functions will still succeed, but you will not get canonical
92   // data out in the format you may be expecting. Instead, we keep something
93   // "reasonable looking" so that the user can see how it's busted if
94   // displayed to them.
95   bool is_valid() const {
96     return is_valid_;
97   }
98 
99   // Returns true if the URL is zero-length. Note that empty URLs are also
100   // invalid, and is_valid() will return false for them. This is provided
101   // because some users may want to treat the empty case differently.
102   bool is_empty() const {
103     return spec_.empty();
104   }
105 
106   // Returns the raw spec, i.e., the full text of the URL, in canonical UTF-8,
107   // if the URL is valid. If the URL is not valid, this will assert and return
108   // the empty string (for safety in release builds, to keep them from being
109   // misused which might be a security problem).
110   //
111   // The URL will be ASCII (non-ASCII characters will be %-escaped UTF-8).
112   //
113   // The exception is for empty() URLs (which are !is_valid()) but this will
114   // return the empty string without asserting.
115   //
116   // Use invalid_spec() below to get the unusable spec of an invalid URL. This
117   // separation is designed to prevent errors that may cause security problems
118   // that could result from the mistaken use of an invalid URL.
119   const std::string& spec() const;
120 
121   // Returns the potentially invalid spec for a the URL. This spec MUST NOT be
122   // modified or sent over the network. It is designed to be displayed in error
123   // messages to the user, as the appearance of the spec may explain the error.
124   // If the spec is valid, the valid spec will be returned.
125   //
126   // The returned string is guaranteed to be valid UTF-8.
127   const std::string& possibly_invalid_spec() const {
128     return spec_;
129   }
130 
131   // Getter for the raw parsed structure. This allows callers to locate parts
132   // of the URL within the spec themselves. Most callers should consider using
133   // the individual component getters below.
134   //
135   // The returned parsed structure will reference into the raw spec, which may
136   // or may not be valid. If you are using this to index into the spec, BE
137   // SURE YOU ARE USING possibly_invalid_spec() to get the spec, and that you
138   // don't do anything "important" with invalid specs.
139   const url::Parsed& parsed_for_possibly_invalid_spec() const {
140     return parsed_;
141   }
142 
143   // Allows GURL to used as a key in STL (for example, a std::set or std::map).
144   constexpr friend auto operator<=>(const GURL& lhs, const GURL& rhs) {
145     return lhs.spec_ <=> rhs.spec_;
146   }
147 
148   // Resolves a URL that's possibly relative to this object's URL, and returns
149   // it. Absolute URLs are also handled according to the rules of URLs on web
150   // pages.
151   //
152   // It may be impossible to resolve the URLs properly. If the input is not
153   // "standard" (IsStandard() == false) and the input looks relative, we can't
154   // resolve it. In these cases, the result will be an empty, invalid GURL.
155   //
156   // The result may also be a nonempty, invalid URL if the input has some kind
157   // of encoding error. In these cases, we will try to construct a "good" URL
158   // that may have meaning to the user, but it will be marked invalid.
159   //
160   // It is an error to resolve a URL relative to an invalid URL. The result
161   // will be the empty URL.
162   [[nodiscard]] GURL Resolve(std::string_view relative) const;
163   [[nodiscard]] GURL Resolve(std::u16string_view relative) const;
164 
165   // Creates a new GURL by replacing the current URL's components with the
166   // supplied versions. See the Replacements class in url_canon.h for more.
167   //
168   // These are not particularly quick, so avoid doing mutations when possible.
169   // Prefer the 8-bit version when possible.
170   //
171   // It is an error to replace components of an invalid URL. The result will
172   // be the empty URL.
173   //
174   // Note that this intentionally disallows direct use of url::Replacements,
175   // which is harder to use correctly.
176   [[nodiscard]] GURL ReplaceComponents(const Replacements& replacements) const;
177   [[nodiscard]] GURL ReplaceComponents(const ReplacementsW& replacements) const;
178 
179   // A helper function that is equivalent to replacing the path with a slash
180   // and clearing out everything after that. We sometimes need to know just the
181   // scheme and the authority. If this URL is not a standard URL (it doesn't
182   // have the regular authority and path sections), then the result will be
183   // an empty, invalid GURL. Note that this *does* work for file: URLs, which
184   // some callers may want to filter out before calling this.
185   //
186   // It is an error to get an empty path on an invalid URL. The result
187   // will be the empty URL.
188   [[nodiscard]] GURL GetWithEmptyPath() const;
189 
190   // A helper function to return a GURL without the filename, query values, and
191   // fragment. For example,
192   // GURL("https://www.foo.com/index.html?q=test").GetWithoutFilename().spec()
193   // will return "https://www.foo.com/".
194   // GURL("https://www.foo.com/bar/").GetWithoutFilename().spec()
195   // will return "https://www.foo.com/bar/". If the GURL is invalid or missing a
196   // scheme, authority or path, it will return an empty, invalid GURL.
197   [[nodiscard]] GURL GetWithoutFilename() const;
198 
199   // A helper function to return a GURL without the Ref (also named Fragment
200   // Identifier). For example,
201   // GURL("https://www.foo.com/index.html#test").GetWithoutRef().spec()
202   // will return "https://www.foo.com/index.html".
203   // If the GURL is invalid or missing a
204   // scheme, authority or path, it will return an empty, invalid GURL.
205   [[nodiscard]] GURL GetWithoutRef() const;
206 
207   // A helper function to return a GURL containing just the scheme, host,
208   // and port from a URL. Equivalent to clearing any username and password,
209   // replacing the path with a slash, and clearing everything after that. If
210   // this URL is not a standard URL, then the result will be an empty,
211   // invalid GURL. If the URL has neither username nor password, this
212   // degenerates to GetWithEmptyPath().
213   //
214   // It is an error to get the origin of an invalid URL. The result
215   // will be the empty URL.
216   //
217   // WARNING: Please avoid converting urls into origins if at all possible!
218   // //docs/security/origin-vs-url.md is a list of gotchas that can result. Such
219   // conversions will likely return a wrong result for about:blank and/or
220   // in the presence of iframe.sandbox attribute. Prefer to get origins directly
221   // from the source (e.g. RenderFrameHost::GetLastCommittedOrigin).
222   [[nodiscard]] GURL DeprecatedGetOriginAsURL() const;
223 
224   // A helper function to return a GURL stripped from the elements that are not
225   // supposed to be sent as HTTP referrer: username, password and ref fragment.
226   // For invalid URLs or URLs that no valid referrers, an empty URL will be
227   // returned.
228   [[nodiscard]] GURL GetAsReferrer() const;
229 
230   // Returns true if the scheme for the current URL is a known "standard-format"
231   // scheme. A standard-format scheme adheres to what RFC 3986 calls "generic
232   // URI syntax" (https://tools.ietf.org/html/rfc3986#section-3). This includes
233   // file: and filesystem:, which some callers may want to filter out explicitly
234   // by calling SchemeIsFile[System].
235   bool IsStandard() const;
236 
237   // Returns true when the url is of the form about:blank, about:blank?foo or
238   // about:blank/#foo.
239   bool IsAboutBlank() const;
240 
241   // Returns true when the url is of the form about:srcdoc, about:srcdoc?foo or
242   // about:srcdoc/#foo.
243   bool IsAboutSrcdoc() const;
244 
245   // Returns true if the given parameter (should be lower-case ASCII to match
246   // the canonicalized scheme) is the scheme for this URL. Do not include a
247   // colon.
248   bool SchemeIs(std::string_view lower_ascii_scheme) const;
249 
250   // Returns true if the scheme is "http" or "https".
251   bool SchemeIsHTTPOrHTTPS() const;
252 
253   // Returns true is the scheme is "ws" or "wss".
254   bool SchemeIsWSOrWSS() const;
255 
256   // We often need to know if this is a file URL. File URLs are "standard", but
257   // are often treated separately by some programs.
258   bool SchemeIsFile() const {
259     return SchemeIs(url::kFileScheme);
260   }
261 
262   // FileSystem URLs need to be treated differently in some cases.
263   bool SchemeIsFileSystem() const {
264     return SchemeIs(url::kFileSystemScheme);
265   }
266 
267   // Returns true if the scheme indicates a network connection that uses TLS or
268   // some other cryptographic protocol (e.g. QUIC) for security.
269   //
270   // This function is a not a complete test of whether or not an origin's code
271   // is minimally trustworthy. For that, see Chromium's |IsOriginSecure| for a
272   // higher-level and more complete semantics. See that function's documentation
273   // for more detail.
274   bool SchemeIsCryptographic() const;
275 
276   // As above, but static. Parameter should be lower-case ASCII.
277   static bool SchemeIsCryptographic(std::string_view lower_ascii_scheme);
278 
279   // Returns true if the scheme is "blob".
280   bool SchemeIsBlob() const {
281     return SchemeIs(url::kBlobScheme);
282   }
283 
284   // Returns true if the scheme is a local scheme, as defined in Fetch:
285   // https://fetch.spec.whatwg.org/#local-scheme
286   bool SchemeIsLocal() const;
287 
288   // For most URLs, the "content" is everything after the scheme (skipping the
289   // scheme delimiting colon) and before the fragment (skipping the fragment
290   // delimiting octothorpe). For javascript URLs the "content" also includes the
291   // fragment delimiter and fragment.
292   //
293   // It is an error to get the content of an invalid URL: the result will be an
294   // empty string.
295   //
296   // Important note: The feature flag,
297   // url::kStandardCompliantNonSpecialSchemeURLParsing, changes the behavior of
298   // GetContent() and GetContentPiece() for some non-special URLs. See
299   // GURLTest::ContentForNonStandardURLs for the differences.
300   //
301   // Until the flag becomes enabled by default, you'll need to manually check
302   // the flag when using GetContent() and GetContentPiece() for non-special
303   // URLs. See http://crbug.com/40063064 for more details.
304   std::string GetContent() const;
305   std::string_view GetContentPiece() const;
306 
307   // Returns true if the hostname is an IP address. Note: this function isn't
308   // as cheap as a simple getter because it re-parses the hostname to verify.
309   bool HostIsIPAddress() const;
310 
311   // Not including the colon. If you are comparing schemes, prefer SchemeIs.
312   bool has_scheme() const { return parsed_.scheme.is_valid(); }
313   std::string scheme() const {
314     return ComponentString(parsed_.scheme);
315   }
316   std::string_view scheme_piece() const {
317     return ComponentStringPiece(parsed_.scheme);
318   }
319 
320   bool has_username() const { return parsed_.username.is_valid(); }
321   std::string username() const {
322     return ComponentString(parsed_.username);
323   }
324   std::string_view username_piece() const {
325     return ComponentStringPiece(parsed_.username);
326   }
327 
328   bool has_password() const { return parsed_.password.is_valid(); }
329   std::string password() const {
330     return ComponentString(parsed_.password);
331   }
332   std::string_view password_piece() const {
333     return ComponentStringPiece(parsed_.password);
334   }
335 
336   // The host may be a hostname, an IPv4 address, or an IPv6 literal surrounded
337   // by square brackets, like "[2001:db8::1]". To exclude these brackets, use
338   // HostNoBrackets() below.
339   bool has_host() const {
340     // Note that hosts are special, absence of host means length 0.
341     return parsed_.host.is_nonempty();
342   }
343   std::string host() const {
344     return ComponentString(parsed_.host);
345   }
346   std::string_view host_piece() const {
347     return ComponentStringPiece(parsed_.host);
348   }
349 
350   // The port if one is explicitly specified. Most callers will want IntPort()
351   // or EffectiveIntPort() instead of these. The getters will not include the
352   // ':'.
353   bool has_port() const { return parsed_.port.is_valid(); }
354   std::string port() const {
355     return ComponentString(parsed_.port);
356   }
357   std::string_view port_piece() const {
358     return ComponentStringPiece(parsed_.port);
359   }
360 
361   // Including first slash following host, up to the query. The URL
362   // "http://www.google.com/" has a path of "/".
363   bool has_path() const { return parsed_.path.is_valid(); }
364   std::string path() const {
365     return ComponentString(parsed_.path);
366   }
367   std::string_view path_piece() const {
368     return ComponentStringPiece(parsed_.path);
369   }
370 
371   // Stuff following '?' up to the ref. The getters will not include the '?'.
372   bool has_query() const { return parsed_.query.is_valid(); }
373   std::string query() const {
374     return ComponentString(parsed_.query);
375   }
376   std::string_view query_piece() const {
377     return ComponentStringPiece(parsed_.query);
378   }
379 
380   // Stuff following '#' to the end of the string. This will be %-escaped UTF-8.
381   // The getters will not include the '#'.
382   bool has_ref() const { return parsed_.ref.is_valid(); }
383   std::string ref() const {
384     return ComponentString(parsed_.ref);
385   }
386   std::string_view ref_piece() const {
387     return ComponentStringPiece(parsed_.ref);
388   }
389 
390   // Returns a parsed version of the port. Can also be any of the special
391   // values defined in Parsed for ExtractPort.
392   int IntPort() const;
393 
394   // Returns the port number of the URL, or the default port number.
395   // If the scheme has no concept of port (or unknown default) returns
396   // PORT_UNSPECIFIED.
397   int EffectiveIntPort() const;
398 
399   // Extracts the filename portion of the path and returns it. The filename
400   // is everything after the last slash in the path. This may be empty.
401   std::string ExtractFileName() const;
402 
403   // Returns the path that should be sent to the server. This is the path,
404   // parameter, and query portions of the URL. It is guaranteed to be ASCII.
405   std::string PathForRequest() const;
406 
407   // Returns the same characters as PathForRequest(), avoiding a copy.
408   std::string_view PathForRequestPiece() const;
409 
410   // Returns the host, excluding the square brackets surrounding IPv6 address
411   // literals. This can be useful for passing to getaddrinfo().
412   std::string HostNoBrackets() const;
413 
414   // Returns the same characters as HostNoBrackets(), avoiding a copy.
415   std::string_view HostNoBracketsPiece() const;
416 
417   // Returns true if this URL's host matches or is in the same domain as
418   // the given input string. For example, if the hostname of the URL is
419   // "www.google.com", this will return true for "com", "google.com", and
420   // "www.google.com".
421   //
422   // The input domain should match host canonicalization rules. i.e. the input
423   // should be lowercase except for escape chars.
424   //
425   // This call is more efficient than getting the host and checking whether the
426   // host has the specific domain or not because no copies or object
427   // constructions are done.
428   bool DomainIs(std::string_view canonical_domain) const;
429 
430   // Checks whether or not two URLs differ only in the ref (the part after
431   // the # character).
432   bool EqualsIgnoringRef(const GURL& other) const;
433 
434   // Swaps the contents of this GURL object with |other|, without doing
435   // any memory allocations.
436   void Swap(GURL* other);
437 
438   // Returns a reference to a singleton empty GURL. This object is for callers
439   // who return references but don't have anything to return in some cases.
440   // If you just want an empty URL for normal use, prefer GURL(). This function
441   // may be called from any thread.
442   static const GURL& EmptyGURL();
443 
444   // Returns the inner URL of a nested URL (currently only non-null for
445   // filesystem URLs).
446   //
447   // TODO(mmenke): inner_url().spec() currently returns the same value as
448   // caling spec() on the GURL itself. This should be fixed.
449   // See https://crbug.com/619596
450   const GURL* inner_url() const {
451     return inner_url_.get();
452   }
453 
454   // Estimates dynamic memory usage.
455   // See base/trace_event/memory_usage_estimator.h for more info.
456   size_t EstimateMemoryUsage() const;
457 
458   // Helper used by GURL::IsAboutUrl and KURL::IsAboutURL.
459   static bool IsAboutPath(std::string_view actual_path,
460                           std::string_view allowed_path);
461 
462   void WriteIntoTrace(perfetto::TracedValue context) const;
463 
464  private:
465   // Variant of the string parsing constructor that allows the caller to elect
466   // retain trailing whitespace, if any, on the passed URL spec, but only if
467   // the scheme is one that allows trailing whitespace. The primary use-case is
468   // for data: URLs. In most cases, you want to use the single parameter
469   // constructor above.
470   enum RetainWhiteSpaceSelector { RETAIN_TRAILING_PATH_WHITEPACE };
471   GURL(const std::string& url_string, RetainWhiteSpaceSelector);
472 
473   template <typename T, typename CharT = typename T::value_type>
474   void InitCanonical(T input_spec, bool trim_path_end);
475 
476   void InitializeFromCanonicalSpec();
477 
478   // Helper used by IsAboutBlank and IsAboutSrcdoc.
479   bool IsAboutUrl(std::string_view allowed_path) const;
480 
481   // Returns the substring of the input identified by the given component.
482   std::string ComponentString(const url::Component& comp) const {
483     return std::string(ComponentStringPiece(comp));
484   }
485   std::string_view ComponentStringPiece(const url::Component& comp) const {
486     if (comp.is_empty())
487       return std::string_view();
488     return std::string_view(spec_).substr(static_cast<size_t>(comp.begin),
489                                           static_cast<size_t>(comp.len));
490   }
491 
492   void ProcessFileSystemURLAfterReplaceComponents();
493 
494   // The actual text of the URL, in canonical ASCII form.
495   std::string spec_;
496 
497   // Set when the given URL is valid. Otherwise, we may still have a spec and
498   // components, but they may not identify valid resources (for example, an
499   // invalid port number, invalid characters in the scheme, etc.).
500   bool is_valid_;
501 
502   // Identified components of the canonical spec.
503   url::Parsed parsed_;
504 
505   // Used for nested schemes [currently only filesystem:].
506   std::unique_ptr<GURL> inner_url_;
507 };
508 
509 // Stream operator so GURL can be used in assertion statements.
510 COMPONENT_EXPORT(URL)
511 std::ostream& operator<<(std::ostream& out, const GURL& url);
512 
513 COMPONENT_EXPORT(URL) bool operator==(const GURL& x, const GURL& y);
514 
515 // Equality operator for comparing raw spec_. This should be used in place of
516 // url == GURL(spec) where |spec| is known (i.e. constants). This is to prevent
517 // needlessly re-parsing |spec| into a temporary GURL.
518 COMPONENT_EXPORT(URL)
519 bool operator==(const GURL& x, std::string_view spec);
520 
521 // DEBUG_ALIAS_FOR_GURL(var_name, url) copies |url| into a new stack-allocated
522 // variable named |<var_name>|.  This helps ensure that the value of |url| gets
523 // preserved in crash dumps.
524 #define DEBUG_ALIAS_FOR_GURL(var_name, url) \
525   DEBUG_ALIAS_FOR_CSTR(var_name, (url).possibly_invalid_spec().c_str(), 128)
526 
527 namespace url::debug {
528 
COMPONENT_EXPORT(URL)529 class COMPONENT_EXPORT(URL) ScopedUrlCrashKey {
530  public:
531   ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key, const GURL& value);
532   ~ScopedUrlCrashKey();
533 
534   ScopedUrlCrashKey(const ScopedUrlCrashKey&) = delete;
535   ScopedUrlCrashKey& operator=(const ScopedUrlCrashKey&) = delete;
536 
537  private:
538   base::debug::ScopedCrashKeyString scoped_string_value_;
539 };
540 
541 }  // namespace url::debug
542 
543 #endif  // URL_GURL_H_
544