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.
14 #include "base/check_op.h"
15 #include "base/no_destructor.h"
16 #include "base/strings/string_piece.h"
17 #include "base/strings/string_util.h"
18 #include "base/trace_event/memory_usage_estimator.h"
19 #include "third_party/perfetto/include/perfetto/tracing/traced_value.h"
20 #include "url/url_canon_stdstring.h"
21 #include "url/url_util.h"
23 GURL::GURL() : is_valid_(false) {
26 GURL::GURL(const GURL& other)
28 is_valid_(other.is_valid_),
29 parsed_(other.parsed_) {
31 inner_url_ = std::make_unique<GURL>(*other.inner_url_);
32 // Valid filesystem urls should always have an inner_url_.
33 DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_);
36 GURL::GURL(GURL&& other) noexcept
37 : spec_(std::move(other.spec_)),
38 is_valid_(other.is_valid_),
39 parsed_(other.parsed_),
40 inner_url_(std::move(other.inner_url_)) {
41 other.is_valid_ = false;
42 other.parsed_ = url::Parsed();
45 GURL::GURL(base::StringPiece url_string) {
46 InitCanonical(url_string, true);
49 GURL::GURL(base::StringPiece16 url_string) {
50 InitCanonical(url_string, true);
53 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
54 InitCanonical(url_string, false);
57 GURL::GURL(const char* canonical_spec,
58 size_t canonical_spec_len,
59 const url::Parsed& parsed,
61 : spec_(canonical_spec, canonical_spec_len),
64 InitializeFromCanonicalSpec();
67 GURL::GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid)
68 : spec_(std::move(canonical_spec)), is_valid_(is_valid), parsed_(parsed) {
69 InitializeFromCanonicalSpec();
72 template <typename T, typename CharT>
73 void GURL::InitCanonical(T input_spec, bool trim_path_end) {
74 url::StdStringCanonOutput output(&spec_);
75 is_valid_ = url::Canonicalize(
76 input_spec.data(), static_cast<int>(input_spec.length()), trim_path_end,
77 NULL, &output, &parsed_);
79 output.Complete(); // Must be done before using string.
80 if (is_valid_ && SchemeIsFileSystem()) {
81 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
82 *parsed_.inner_parsed(), true);
84 // Valid URLs always have non-empty specs.
85 DCHECK(!is_valid_ || !spec_.empty());
88 void GURL::InitializeFromCanonicalSpec() {
89 if (is_valid_ && SchemeIsFileSystem()) {
90 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
91 *parsed_.inner_parsed(), true);
95 // For testing purposes, check that the parsed canonical URL is identical to
96 // what we would have produced. Skip checking for invalid URLs have no meaning
97 // and we can't always canonicalize then reproducibly.
99 DCHECK(!spec_.empty());
100 url::Component scheme;
101 // We can't do this check on the inner_url of a filesystem URL, as
102 // canonical_spec actually points to the start of the outer URL, so we'd
103 // end up with infinite recursion in this constructor.
104 if (!url::FindAndCompareScheme(spec_.data(), spec_.length(),
105 url::kFileSystemScheme, &scheme) ||
106 scheme.begin == parsed_.scheme.begin) {
107 // We need to retain trailing whitespace on path URLs, as the |parsed_|
108 // spec we originally received may legitimately contain trailing white-
109 // space on the path or components e.g. if the #ref has been
110 // removed from a "foo:hello #ref" URL (see http://crbug.com/291747).
111 GURL test_url(spec_, RETAIN_TRAILING_PATH_WHITEPACE);
113 DCHECK_EQ(test_url.is_valid_, is_valid_);
114 DCHECK_EQ(test_url.spec_, spec_);
116 DCHECK_EQ(test_url.parsed_.scheme, parsed_.scheme);
117 DCHECK_EQ(test_url.parsed_.username, parsed_.username);
118 DCHECK_EQ(test_url.parsed_.password, parsed_.password);
119 DCHECK_EQ(test_url.parsed_.host, parsed_.host);
120 DCHECK_EQ(test_url.parsed_.port, parsed_.port);
121 DCHECK_EQ(test_url.parsed_.path, parsed_.path);
122 DCHECK_EQ(test_url.parsed_.query, parsed_.query);
123 DCHECK_EQ(test_url.parsed_.ref, parsed_.ref);
129 GURL::~GURL() = default;
131 GURL& GURL::operator=(const GURL& other) {
133 is_valid_ = other.is_valid_;
134 parsed_ = other.parsed_;
136 if (!other.inner_url_)
139 *inner_url_ = *other.inner_url_;
141 inner_url_ = std::make_unique<GURL>(*other.inner_url_);
146 GURL& GURL::operator=(GURL&& other) noexcept {
147 spec_ = std::move(other.spec_);
148 is_valid_ = other.is_valid_;
149 parsed_ = other.parsed_;
150 inner_url_ = std::move(other.inner_url_);
152 other.is_valid_ = false;
153 other.parsed_ = url::Parsed();
157 const std::string& GURL::spec() const {
158 if (is_valid_ || spec_.empty())
161 DCHECK(false) << "Trying to get the spec of an invalid URL!";
162 return base::EmptyString();
165 bool GURL::operator<(const GURL& other) const {
166 return spec_ < other.spec_;
169 bool GURL::operator>(const GURL& other) const {
170 return spec_ > other.spec_;
173 // Note: code duplicated below (it's inconvenient to use a template here).
174 GURL GURL::Resolve(base::StringPiece relative) const {
175 // Not allowed for invalid URLs.
180 url::StdStringCanonOutput output(&result.spec_);
181 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
182 parsed_, relative.data(),
183 static_cast<int>(relative.length()),
184 nullptr, &output, &result.parsed_)) {
185 // Error resolving, return an empty URL.
190 result.is_valid_ = true;
191 if (result.SchemeIsFileSystem()) {
193 std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
194 *result.parsed_.inner_parsed(), true);
199 // Note: code duplicated above (it's inconvenient to use a template here).
200 GURL GURL::Resolve(base::StringPiece16 relative) const {
201 // Not allowed for invalid URLs.
206 url::StdStringCanonOutput output(&result.spec_);
207 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
208 parsed_, relative.data(),
209 static_cast<int>(relative.length()),
210 nullptr, &output, &result.parsed_)) {
211 // Error resolving, return an empty URL.
216 result.is_valid_ = true;
217 if (result.SchemeIsFileSystem()) {
219 std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
220 *result.parsed_.inner_parsed(), true);
225 // Note: code duplicated below (it's inconvenient to use a template here).
226 GURL GURL::ReplaceComponents(const Replacements& replacements) const {
229 // Not allowed for invalid URLs.
233 url::StdStringCanonOutput output(&result.spec_);
234 result.is_valid_ = url::ReplaceComponents(
235 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
236 NULL, &output, &result.parsed_);
240 result.ProcessFileSystemURLAfterReplaceComponents();
244 // Note: code duplicated above (it's inconvenient to use a template here).
245 GURL GURL::ReplaceComponents(const ReplacementsW& replacements) const {
248 // Not allowed for invalid URLs.
252 url::StdStringCanonOutput output(&result.spec_);
253 result.is_valid_ = url::ReplaceComponents(
254 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
255 NULL, &output, &result.parsed_);
259 result.ProcessFileSystemURLAfterReplaceComponents();
264 void GURL::ProcessFileSystemURLAfterReplaceComponents() {
267 if (SchemeIsFileSystem()) {
268 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
269 *parsed_.inner_parsed(), true);
273 GURL GURL::DeprecatedGetOriginAsURL() const {
274 // This doesn't make sense for invalid or nonstandard URLs, so return
276 if (!is_valid_ || !IsStandard())
279 if (SchemeIsFileSystem())
280 return inner_url_->DeprecatedGetOriginAsURL();
282 Replacements replacements;
283 replacements.ClearUsername();
284 replacements.ClearPassword();
285 replacements.ClearPath();
286 replacements.ClearQuery();
287 replacements.ClearRef();
289 return ReplaceComponents(replacements);
292 GURL GURL::GetAsReferrer() const {
293 if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme))
296 if (!has_ref() && !has_username() && !has_password())
299 Replacements replacements;
300 replacements.ClearRef();
301 replacements.ClearUsername();
302 replacements.ClearPassword();
303 return ReplaceComponents(replacements);
306 GURL GURL::GetWithEmptyPath() const {
307 // This doesn't make sense for invalid or nonstandard URLs, so return
309 if (!is_valid_ || !IsStandard())
312 // We could optimize this since we know that the URL is canonical, and we are
313 // appending a canonical path, so avoiding re-parsing.
315 if (parsed_.path.len == 0)
318 // Clear everything after the path.
319 other.parsed_.query.reset();
320 other.parsed_.ref.reset();
322 // Set the path, since the path is longer than one, we can just set the
323 // first character and resize.
324 other.spec_[other.parsed_.path.begin] = '/';
325 other.parsed_.path.len = 1;
326 other.spec_.resize(other.parsed_.path.begin + 1);
330 GURL GURL::GetWithoutFilename() const {
334 bool GURL::IsStandard() const {
335 return url::IsStandard(spec_.data(), parsed_.scheme);
338 bool GURL::IsAboutBlank() const {
339 return IsAboutUrl(url::kAboutBlankPath);
342 bool GURL::IsAboutSrcdoc() const {
343 return IsAboutUrl(url::kAboutSrcdocPath);
346 bool GURL::SchemeIs(base::StringPiece lower_ascii_scheme) const {
347 DCHECK(base::IsStringASCII(lower_ascii_scheme));
348 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
351 return lower_ascii_scheme.empty();
352 return scheme_piece() == lower_ascii_scheme;
355 bool GURL::SchemeIsHTTPOrHTTPS() const {
356 return SchemeIs(url::kHttpScheme) || SchemeIs(url::kHttpsScheme);
359 bool GURL::SchemeIsWSOrWSS() const {
360 return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
363 bool GURL::SchemeIsCryptographic() const {
366 return SchemeIsCryptographic(scheme_piece());
369 bool GURL::SchemeIsCryptographic(base::StringPiece lower_ascii_scheme) {
370 DCHECK(base::IsStringASCII(lower_ascii_scheme));
371 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
373 return lower_ascii_scheme == url::kHttpsScheme ||
374 lower_ascii_scheme == url::kWssScheme;
377 bool GURL::SchemeIsLocal() const {
378 // The `filesystem:` scheme is not in the Fetch spec, but Chromium still
379 // supports it in large part. It should be treated as a local scheme too.
380 return SchemeIs(url::kAboutScheme) || SchemeIs(url::kBlobScheme) ||
381 SchemeIs(url::kDataScheme) || SchemeIs(url::kFileSystemScheme);
384 int GURL::IntPort() const {
385 if (parsed_.port.is_nonempty())
386 return url::ParsePort(spec_.data(), parsed_.port);
387 return url::PORT_UNSPECIFIED;
390 int GURL::EffectiveIntPort() const {
391 int int_port = IntPort();
392 if (int_port == url::PORT_UNSPECIFIED && IsStandard())
393 return url::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin,
398 std::string GURL::ExtractFileName() const {
399 url::Component file_component;
400 url::ExtractFileName(spec_.data(), parsed_.path, &file_component);
401 return ComponentString(file_component);
404 base::StringPiece GURL::PathForRequestPiece() const {
405 DCHECK(parsed_.path.len > 0)
406 << "Canonical path for requests should be non-empty";
407 if (parsed_.ref.len >= 0) {
408 // Clip off the reference when it exists. The reference starts after the
409 // #-sign, so we have to subtract one to also remove it.
410 return base::StringPiece(&spec_[parsed_.path.begin],
411 parsed_.ref.begin - parsed_.path.begin - 1);
413 // Compute the actual path length, rather than depending on the spec's
414 // terminator. If we're an inner_url, our spec continues on into our outer
415 // URL's path/query/ref.
416 int path_len = parsed_.path.len;
417 if (parsed_.query.is_valid())
418 path_len = parsed_.query.end() - parsed_.path.begin;
420 return base::StringPiece(&spec_[parsed_.path.begin], path_len);
423 std::string GURL::PathForRequest() const {
424 return std::string(PathForRequestPiece());
427 std::string GURL::HostNoBrackets() const {
428 return std::string(HostNoBracketsPiece());
431 base::StringPiece GURL::HostNoBracketsPiece() const {
432 // If host looks like an IPv6 literal, strip the square brackets.
433 url::Component h(parsed_.host);
434 if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') {
438 return ComponentStringPiece(h);
441 std::string GURL::GetContent() const {
442 return std::string(GetContentPiece());
445 base::StringPiece GURL::GetContentPiece() const {
447 return base::StringPiece();
448 url::Component content_component = parsed_.GetContent();
449 if (!SchemeIs(url::kJavaScriptScheme) && parsed_.ref.len >= 0)
450 content_component.len -= parsed_.ref.len + 1;
451 return ComponentStringPiece(content_component);
454 bool GURL::HostIsIPAddress() const {
455 return is_valid_ && url::HostIsIPAddress(host_piece());
458 const GURL& GURL::EmptyGURL() {
459 static base::NoDestructor<GURL> empty_gurl;
463 bool GURL::DomainIs(base::StringPiece canonical_domain) const {
467 // FileSystem URLs have empty host_piece, so check this first.
468 if (inner_url_ && SchemeIsFileSystem())
469 return inner_url_->DomainIs(canonical_domain);
470 return url::DomainIs(host_piece(), canonical_domain);
473 bool GURL::EqualsIgnoringRef(const GURL& other) const {
474 int ref_position = parsed_.CountCharactersBefore(url::Parsed::REF, true);
475 int ref_position_other =
476 other.parsed_.CountCharactersBefore(url::Parsed::REF, true);
477 return base::StringPiece(spec_).substr(0, ref_position) ==
478 base::StringPiece(other.spec_).substr(0, ref_position_other);
481 void GURL::Swap(GURL* other) {
482 spec_.swap(other->spec_);
483 std::swap(is_valid_, other->is_valid_);
484 std::swap(parsed_, other->parsed_);
485 inner_url_.swap(other->inner_url_);
488 size_t GURL::EstimateMemoryUsage() const {
489 return base::trace_event::EstimateMemoryUsage(spec_) +
490 base::trace_event::EstimateMemoryUsage(inner_url_) +
491 (parsed_.inner_parsed() ? sizeof(url::Parsed) : 0);
494 bool GURL::IsAboutUrl(base::StringPiece allowed_path) const {
495 if (!SchemeIs(url::kAboutScheme))
498 if (has_host() || has_username() || has_password() || has_port())
501 return IsAboutPath(path_piece(), allowed_path);
505 bool GURL::IsAboutPath(base::StringPiece actual_path,
506 base::StringPiece allowed_path) {
507 if (!base::StartsWith(actual_path, allowed_path))
510 if (actual_path.size() == allowed_path.size()) {
511 DCHECK_EQ(actual_path, allowed_path);
515 if ((actual_path.size() == allowed_path.size() + 1) &&
516 actual_path.back() == '/') {
517 DCHECK_EQ(actual_path, std::string(allowed_path) + '/');
524 void GURL::WriteIntoTrace(perfetto::TracedValue context) const {
525 std::move(context).WriteString(possibly_invalid_spec());
528 std::ostream& operator<<(std::ostream& out, const GURL& url) {
529 return out << url.possibly_invalid_spec();
532 bool operator==(const GURL& x, const GURL& y) {
533 return x.possibly_invalid_spec() == y.possibly_invalid_spec();
536 bool operator!=(const GURL& x, const GURL& y) {
540 bool operator==(const GURL& x, const base::StringPiece& spec) {
541 DCHECK_EQ(GURL(spec).possibly_invalid_spec(), spec)
542 << "Comparisons of GURLs and strings must ensure as a precondition that "
543 "the string is fully canonicalized.";
544 return x.possibly_invalid_spec() == spec;
547 bool operator==(const base::StringPiece& spec, const GURL& x) {
551 bool operator!=(const GURL& x, const base::StringPiece& spec) {
555 bool operator!=(const base::StringPiece& spec, const GURL& x) {
559 namespace url::debug {
561 ScopedUrlCrashKey::ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key,
563 : scoped_string_value_(
565 url.is_empty() ? "<empty url>" : url.possibly_invalid_spec()) {}
567 ScopedUrlCrashKey::~ScopedUrlCrashKey() = default;
569 } // namespace url::debug