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.
12 #include <string_view>
15 #include "base/check_op.h"
16 #include "base/no_destructor.h"
17 #include "base/notreached.h"
18 #include "base/strings/string_util.h"
19 #include "base/trace_event/base_tracing.h"
20 #include "base/trace_event/memory_usage_estimator.h"
21 #include "url/url_canon_stdstring.h"
22 #include "url/url_util.h"
24 GURL::GURL() : is_valid_(false) {
27 GURL::GURL(const GURL& other)
29 is_valid_(other.is_valid_),
30 parsed_(other.parsed_) {
32 inner_url_ = std::make_unique<GURL>(*other.inner_url_);
33 // Valid filesystem urls should always have an inner_url_.
34 DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_);
37 GURL::GURL(GURL&& other) noexcept
38 : spec_(std::move(other.spec_)),
39 is_valid_(other.is_valid_),
40 parsed_(other.parsed_),
41 inner_url_(std::move(other.inner_url_)) {
42 other.is_valid_ = false;
43 other.parsed_ = url::Parsed();
46 GURL::GURL(std::string_view url_string) {
47 InitCanonical(url_string, true);
50 GURL::GURL(std::u16string_view url_string) {
51 InitCanonical(url_string, true);
54 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
55 InitCanonical(url_string, false);
58 GURL::GURL(const char* canonical_spec,
59 size_t canonical_spec_len,
60 const url::Parsed& parsed,
62 : spec_(canonical_spec, canonical_spec_len),
65 InitializeFromCanonicalSpec();
68 GURL::GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid)
69 : spec_(std::move(canonical_spec)), is_valid_(is_valid), parsed_(parsed) {
70 InitializeFromCanonicalSpec();
73 template <typename T, typename CharT>
74 void GURL::InitCanonical(T input_spec, bool trim_path_end) {
75 url::StdStringCanonOutput output(&spec_);
76 is_valid_ = url::Canonicalize(
77 input_spec.data(), static_cast<int>(input_spec.length()), trim_path_end,
78 NULL, &output, &parsed_);
80 output.Complete(); // Must be done before using string.
81 if (is_valid_ && SchemeIsFileSystem()) {
82 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
83 *parsed_.inner_parsed(), true);
85 // Valid URLs always have non-empty specs.
86 DCHECK(!is_valid_ || !spec_.empty());
89 void GURL::InitializeFromCanonicalSpec() {
90 if (is_valid_ && SchemeIsFileSystem()) {
91 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
92 *parsed_.inner_parsed(), true);
96 // For testing purposes, check that the parsed canonical URL is identical to
97 // what we would have produced. Skip checking for invalid URLs have no meaning
98 // and we can't always canonicalize then reproducibly.
100 DCHECK(!spec_.empty());
101 url::Component scheme;
102 // We can't do this check on the inner_url of a filesystem URL, as
103 // canonical_spec actually points to the start of the outer URL, so we'd
104 // end up with infinite recursion in this constructor.
105 if (!url::FindAndCompareScheme(spec_.data(), spec_.length(),
106 url::kFileSystemScheme, &scheme) ||
107 scheme.begin == parsed_.scheme.begin) {
108 // We need to retain trailing whitespace on path URLs, as the |parsed_|
109 // spec we originally received may legitimately contain trailing white-
110 // space on the path or components e.g. if the #ref has been
111 // removed from a "foo:hello #ref" URL (see http://crbug.com/291747).
112 GURL test_url(spec_, RETAIN_TRAILING_PATH_WHITEPACE);
114 DCHECK_EQ(test_url.is_valid_, is_valid_);
115 DCHECK_EQ(test_url.spec_, spec_);
117 DCHECK_EQ(test_url.parsed_.scheme, parsed_.scheme);
118 DCHECK_EQ(test_url.parsed_.username, parsed_.username);
119 DCHECK_EQ(test_url.parsed_.password, parsed_.password);
120 DCHECK_EQ(test_url.parsed_.host, parsed_.host);
121 DCHECK_EQ(test_url.parsed_.port, parsed_.port);
122 DCHECK_EQ(test_url.parsed_.path, parsed_.path);
123 DCHECK_EQ(test_url.parsed_.query, parsed_.query);
124 DCHECK_EQ(test_url.parsed_.ref, parsed_.ref);
130 GURL::~GURL() = default;
132 GURL& GURL::operator=(const GURL& other) {
134 is_valid_ = other.is_valid_;
135 parsed_ = other.parsed_;
137 if (!other.inner_url_)
140 *inner_url_ = *other.inner_url_;
142 inner_url_ = std::make_unique<GURL>(*other.inner_url_);
147 GURL& GURL::operator=(GURL&& other) noexcept {
148 spec_ = std::move(other.spec_);
149 is_valid_ = other.is_valid_;
150 parsed_ = other.parsed_;
151 inner_url_ = std::move(other.inner_url_);
153 other.is_valid_ = false;
154 other.parsed_ = url::Parsed();
158 const std::string& GURL::spec() const {
159 if (is_valid_ || spec_.empty())
162 // TODO(crbug.com/851128): Make sure this no longer hits before making
163 // NOTREACHED_NORETURN();
164 NOTREACHED() << "Trying to get the spec of an invalid URL!";
165 return base::EmptyString();
168 bool GURL::operator<(const GURL& other) const {
169 return spec_ < other.spec_;
172 bool GURL::operator>(const GURL& other) const {
173 return spec_ > other.spec_;
176 // Note: code duplicated below (it's inconvenient to use a template here).
177 GURL GURL::Resolve(std::string_view relative) const {
178 // Not allowed for invalid URLs.
183 url::StdStringCanonOutput output(&result.spec_);
184 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
185 parsed_, relative.data(),
186 static_cast<int>(relative.length()),
187 nullptr, &output, &result.parsed_)) {
188 // Error resolving, return an empty URL.
193 result.is_valid_ = true;
194 if (result.SchemeIsFileSystem()) {
196 std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
197 *result.parsed_.inner_parsed(), true);
202 // Note: code duplicated above (it's inconvenient to use a template here).
203 GURL GURL::Resolve(std::u16string_view relative) const {
204 // Not allowed for invalid URLs.
209 url::StdStringCanonOutput output(&result.spec_);
210 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
211 parsed_, relative.data(),
212 static_cast<int>(relative.length()),
213 nullptr, &output, &result.parsed_)) {
214 // Error resolving, return an empty URL.
219 result.is_valid_ = true;
220 if (result.SchemeIsFileSystem()) {
222 std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
223 *result.parsed_.inner_parsed(), true);
228 // Note: code duplicated below (it's inconvenient to use a template here).
229 GURL GURL::ReplaceComponents(const Replacements& replacements) const {
232 // Not allowed for invalid URLs.
236 url::StdStringCanonOutput output(&result.spec_);
237 result.is_valid_ = url::ReplaceComponents(
238 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
239 NULL, &output, &result.parsed_);
243 result.ProcessFileSystemURLAfterReplaceComponents();
247 // Note: code duplicated above (it's inconvenient to use a template here).
248 GURL GURL::ReplaceComponents(const ReplacementsW& replacements) const {
251 // Not allowed for invalid URLs.
255 url::StdStringCanonOutput output(&result.spec_);
256 result.is_valid_ = url::ReplaceComponents(
257 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
258 NULL, &output, &result.parsed_);
262 result.ProcessFileSystemURLAfterReplaceComponents();
267 void GURL::ProcessFileSystemURLAfterReplaceComponents() {
270 if (SchemeIsFileSystem()) {
271 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
272 *parsed_.inner_parsed(), true);
276 GURL GURL::DeprecatedGetOriginAsURL() const {
277 // This doesn't make sense for invalid or nonstandard URLs, so return
279 if (!is_valid_ || !IsStandard())
282 if (SchemeIsFileSystem())
283 return inner_url_->DeprecatedGetOriginAsURL();
285 Replacements replacements;
286 replacements.ClearUsername();
287 replacements.ClearPassword();
288 replacements.ClearPath();
289 replacements.ClearQuery();
290 replacements.ClearRef();
292 return ReplaceComponents(replacements);
295 GURL GURL::GetAsReferrer() const {
296 if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme))
299 if (!has_ref() && !has_username() && !has_password())
302 Replacements replacements;
303 replacements.ClearRef();
304 replacements.ClearUsername();
305 replacements.ClearPassword();
306 return ReplaceComponents(replacements);
309 GURL GURL::GetWithEmptyPath() const {
310 // This doesn't make sense for invalid or nonstandard URLs, so return
312 if (!is_valid_ || !IsStandard())
315 // We could optimize this since we know that the URL is canonical, and we are
316 // appending a canonical path, so avoiding re-parsing.
318 if (parsed_.path.len == 0)
321 // Clear everything after the path.
322 other.parsed_.query.reset();
323 other.parsed_.ref.reset();
325 // Set the path, since the path is longer than one, we can just set the
326 // first character and resize.
327 other.spec_[other.parsed_.path.begin] = '/';
328 other.parsed_.path.len = 1;
329 other.spec_.resize(other.parsed_.path.begin + 1);
333 GURL GURL::GetWithoutFilename() const {
337 GURL GURL::GetWithoutRef() const {
341 Replacements replacements;
342 replacements.ClearRef();
343 return ReplaceComponents(replacements);
346 bool GURL::IsStandard() const {
347 return url::IsStandard(spec_.data(), parsed_.scheme);
350 bool GURL::IsAboutBlank() const {
351 return IsAboutUrl(url::kAboutBlankPath);
354 bool GURL::IsAboutSrcdoc() const {
355 return IsAboutUrl(url::kAboutSrcdocPath);
358 bool GURL::SchemeIs(std::string_view lower_ascii_scheme) const {
359 DCHECK(base::IsStringASCII(lower_ascii_scheme));
360 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
363 return lower_ascii_scheme.empty();
364 return scheme_piece() == lower_ascii_scheme;
367 bool GURL::SchemeIsHTTPOrHTTPS() const {
368 return SchemeIs(url::kHttpsScheme) || SchemeIs(url::kHttpScheme);
371 bool GURL::SchemeIsWSOrWSS() const {
372 return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
375 bool GURL::SchemeIsCryptographic() const {
378 return SchemeIsCryptographic(scheme_piece());
381 bool GURL::SchemeIsCryptographic(std::string_view lower_ascii_scheme) {
382 DCHECK(base::IsStringASCII(lower_ascii_scheme));
383 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
385 return lower_ascii_scheme == url::kHttpsScheme ||
386 lower_ascii_scheme == url::kWssScheme;
389 bool GURL::SchemeIsLocal() const {
390 // The `filesystem:` scheme is not in the Fetch spec, but Chromium still
391 // supports it in large part. It should be treated as a local scheme too.
392 return SchemeIs(url::kAboutScheme) || SchemeIs(url::kBlobScheme) ||
393 SchemeIs(url::kDataScheme) || SchemeIs(url::kFileSystemScheme);
396 int GURL::IntPort() const {
397 if (parsed_.port.is_nonempty())
398 return url::ParsePort(spec_.data(), parsed_.port);
399 return url::PORT_UNSPECIFIED;
402 int GURL::EffectiveIntPort() const {
403 int int_port = IntPort();
404 if (int_port == url::PORT_UNSPECIFIED && IsStandard())
405 return url::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin,
410 std::string GURL::ExtractFileName() const {
411 url::Component file_component;
412 url::ExtractFileName(spec_.data(), parsed_.path, &file_component);
413 return ComponentString(file_component);
416 std::string_view GURL::PathForRequestPiece() const {
417 DCHECK(parsed_.path.is_nonempty())
418 << "Canonical path for requests should be non-empty";
419 if (parsed_.ref.is_valid()) {
420 // Clip off the reference when it exists. The reference starts after the
421 // #-sign, so we have to subtract one to also remove it.
422 return std::string_view(spec_).substr(
423 parsed_.path.begin, parsed_.ref.begin - parsed_.path.begin - 1);
425 // Compute the actual path length, rather than depending on the spec's
426 // terminator. If we're an inner_url, our spec continues on into our outer
427 // URL's path/query/ref.
428 int path_len = parsed_.path.len;
429 if (parsed_.query.is_valid())
430 path_len = parsed_.query.end() - parsed_.path.begin;
432 return std::string_view(spec_).substr(parsed_.path.begin, path_len);
435 std::string GURL::PathForRequest() const {
436 return std::string(PathForRequestPiece());
439 std::string GURL::HostNoBrackets() const {
440 return std::string(HostNoBracketsPiece());
443 std::string_view GURL::HostNoBracketsPiece() const {
444 // If host looks like an IPv6 literal, strip the square brackets.
445 url::Component h(parsed_.host);
446 if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') {
450 return ComponentStringPiece(h);
453 std::string GURL::GetContent() const {
454 return std::string(GetContentPiece());
457 std::string_view GURL::GetContentPiece() const {
459 return std::string_view();
460 url::Component content_component = parsed_.GetContent();
461 if (!SchemeIs(url::kJavaScriptScheme) && parsed_.ref.is_valid())
462 content_component.len -= parsed_.ref.len + 1;
463 return ComponentStringPiece(content_component);
466 bool GURL::HostIsIPAddress() const {
467 return is_valid_ && url::HostIsIPAddress(host_piece());
470 const GURL& GURL::EmptyGURL() {
471 static base::NoDestructor<GURL> empty_gurl;
475 bool GURL::DomainIs(std::string_view canonical_domain) const {
479 // FileSystem URLs have empty host_piece, so check this first.
480 if (inner_url_ && SchemeIsFileSystem())
481 return inner_url_->DomainIs(canonical_domain);
482 return url::DomainIs(host_piece(), canonical_domain);
485 bool GURL::EqualsIgnoringRef(const GURL& other) const {
486 int ref_position = parsed_.CountCharactersBefore(url::Parsed::REF, true);
487 int ref_position_other =
488 other.parsed_.CountCharactersBefore(url::Parsed::REF, true);
489 return std::string_view(spec_).substr(0, ref_position) ==
490 std::string_view(other.spec_).substr(0, ref_position_other);
493 void GURL::Swap(GURL* other) {
494 spec_.swap(other->spec_);
495 std::swap(is_valid_, other->is_valid_);
496 std::swap(parsed_, other->parsed_);
497 inner_url_.swap(other->inner_url_);
500 size_t GURL::EstimateMemoryUsage() const {
501 return base::trace_event::EstimateMemoryUsage(spec_) +
502 base::trace_event::EstimateMemoryUsage(inner_url_) +
503 (parsed_.inner_parsed() ? sizeof(url::Parsed) : 0);
506 bool GURL::IsAboutUrl(std::string_view allowed_path) const {
507 if (!SchemeIs(url::kAboutScheme))
510 if (has_host() || has_username() || has_password() || has_port())
513 return IsAboutPath(path_piece(), allowed_path);
517 bool GURL::IsAboutPath(std::string_view actual_path,
518 std::string_view allowed_path) {
519 if (!base::StartsWith(actual_path, allowed_path))
522 if (actual_path.size() == allowed_path.size()) {
523 DCHECK_EQ(actual_path, allowed_path);
527 if ((actual_path.size() == allowed_path.size() + 1) &&
528 actual_path.back() == '/') {
529 DCHECK_EQ(actual_path, std::string(allowed_path) + '/');
536 void GURL::WriteIntoTrace(perfetto::TracedValue context) const {
537 std::move(context).WriteString(possibly_invalid_spec());
540 std::ostream& operator<<(std::ostream& out, const GURL& url) {
541 return out << url.possibly_invalid_spec();
544 bool operator==(const GURL& x, const GURL& y) {
545 return x.possibly_invalid_spec() == y.possibly_invalid_spec();
548 bool operator!=(const GURL& x, const GURL& y) {
552 bool operator==(const GURL& x, std::string_view spec) {
553 DCHECK_EQ(GURL(spec).possibly_invalid_spec(), spec)
554 << "Comparisons of GURLs and strings must ensure as a precondition that "
555 "the string is fully canonicalized.";
556 return x.possibly_invalid_spec() == spec;
559 bool operator==(std::string_view spec, const GURL& x) {
563 bool operator!=(const GURL& x, std::string_view spec) {
567 bool operator!=(std::string_view spec, const GURL& x) {
571 namespace url::debug {
573 ScopedUrlCrashKey::ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key,
575 : scoped_string_value_(
577 url.is_empty() ? "<empty url>" : url.possibly_invalid_spec()) {}
579 ScopedUrlCrashKey::~ScopedUrlCrashKey() = default;
581 } // namespace url::debug