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.
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_util.h"
16 #include "base/trace_event/memory_usage_estimator.h"
17 #include "url/url_canon_stdstring.h"
18 #include "url/url_util.h"
22 static base::LazyInstance<std::string>::Leaky empty_string =
23 LAZY_INSTANCE_INITIALIZER;
24 static base::LazyInstance<GURL>::Leaky empty_gurl = LAZY_INSTANCE_INITIALIZER;
28 GURL::GURL() : is_valid_(false) {
31 GURL::GURL(const GURL& other)
33 is_valid_(other.is_valid_),
34 parsed_(other.parsed_) {
36 inner_url_.reset(new GURL(*other.inner_url_));
37 // Valid filesystem urls should always have an inner_url_.
38 DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_);
41 GURL::GURL(GURL&& other) noexcept
42 : spec_(std::move(other.spec_)),
43 is_valid_(other.is_valid_),
44 parsed_(other.parsed_),
45 inner_url_(std::move(other.inner_url_)) {
46 other.is_valid_ = false;
47 other.parsed_ = url::Parsed();
50 GURL::GURL(base::StringPiece url_string) {
51 InitCanonical(url_string, true);
54 GURL::GURL(base::StringPiece16 url_string) {
55 InitCanonical(url_string, true);
58 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
59 InitCanonical(base::StringPiece(url_string), false);
62 GURL::GURL(const char* canonical_spec,
63 size_t canonical_spec_len,
64 const url::Parsed& parsed,
66 : spec_(canonical_spec, canonical_spec_len),
69 InitializeFromCanonicalSpec();
72 GURL::GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid)
73 : spec_(std::move(canonical_spec)), is_valid_(is_valid), parsed_(parsed) {
74 InitializeFromCanonicalSpec();
77 template<typename STR>
78 void GURL::InitCanonical(base::BasicStringPiece<STR> input_spec,
80 url::StdStringCanonOutput output(&spec_);
81 is_valid_ = url::Canonicalize(
82 input_spec.data(), static_cast<int>(input_spec.length()), trim_path_end,
83 NULL, &output, &parsed_);
85 output.Complete(); // Must be done before using string.
86 if (is_valid_ && SchemeIsFileSystem()) {
87 inner_url_.reset(new GURL(spec_.data(), parsed_.Length(),
88 *parsed_.inner_parsed(), true));
90 // Valid URLs always have non-empty specs.
91 DCHECK(!is_valid_ || !spec_.empty());
94 void GURL::InitializeFromCanonicalSpec() {
95 if (is_valid_ && SchemeIsFileSystem()) {
97 new GURL(spec_.data(), parsed_.Length(),
98 *parsed_.inner_parsed(), true));
102 // For testing purposes, check that the parsed canonical URL is identical to
103 // what we would have produced. Skip checking for invalid URLs have no meaning
104 // and we can't always canonicalize then reproducibly.
106 DCHECK(!spec_.empty());
107 url::Component scheme;
108 // We can't do this check on the inner_url of a filesystem URL, as
109 // canonical_spec actually points to the start of the outer URL, so we'd
110 // end up with infinite recursion in this constructor.
111 if (!url::FindAndCompareScheme(spec_.data(), spec_.length(),
112 url::kFileSystemScheme, &scheme) ||
113 scheme.begin == parsed_.scheme.begin) {
114 // We need to retain trailing whitespace on path URLs, as the |parsed_|
115 // spec we originally received may legitimately contain trailing white-
116 // space on the path or components e.g. if the #ref has been
117 // removed from a "foo:hello #ref" URL (see http://crbug.com/291747).
118 GURL test_url(spec_, RETAIN_TRAILING_PATH_WHITEPACE);
120 DCHECK(test_url.is_valid_ == is_valid_);
121 DCHECK(test_url.spec_ == spec_);
123 DCHECK(test_url.parsed_.scheme == parsed_.scheme);
124 DCHECK(test_url.parsed_.username == parsed_.username);
125 DCHECK(test_url.parsed_.password == parsed_.password);
126 DCHECK(test_url.parsed_.host == parsed_.host);
127 DCHECK(test_url.parsed_.port == parsed_.port);
128 DCHECK(test_url.parsed_.path == parsed_.path);
129 DCHECK(test_url.parsed_.query == parsed_.query);
130 DCHECK(test_url.parsed_.ref == parsed_.ref);
136 GURL::~GURL() = default;
138 GURL& GURL::operator=(const GURL& other) {
140 is_valid_ = other.is_valid_;
141 parsed_ = other.parsed_;
143 if (!other.inner_url_)
146 *inner_url_ = *other.inner_url_;
148 inner_url_.reset(new GURL(*other.inner_url_));
153 GURL& GURL::operator=(GURL&& other) {
154 spec_ = std::move(other.spec_);
155 is_valid_ = other.is_valid_;
156 parsed_ = other.parsed_;
157 inner_url_ = std::move(other.inner_url_);
159 other.is_valid_ = false;
160 other.parsed_ = url::Parsed();
164 const std::string& GURL::spec() const {
165 if (is_valid_ || spec_.empty())
168 DCHECK(false) << "Trying to get the spec of an invalid URL!";
169 return empty_string.Get();
172 bool GURL::operator<(const GURL& other) const {
173 return spec_ < other.spec_;
176 bool GURL::operator>(const GURL& other) const {
177 return spec_ > other.spec_;
180 // Note: code duplicated below (it's inconvenient to use a template here).
181 GURL GURL::Resolve(const std::string& relative) const {
182 // Not allowed for invalid URLs.
187 url::StdStringCanonOutput output(&result.spec_);
188 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
189 parsed_, relative.data(),
190 static_cast<int>(relative.length()),
191 nullptr, &output, &result.parsed_)) {
192 // Error resolving, return an empty URL.
197 result.is_valid_ = true;
198 if (result.SchemeIsFileSystem()) {
199 result.inner_url_.reset(
200 new GURL(result.spec_.data(), result.parsed_.Length(),
201 *result.parsed_.inner_parsed(), true));
206 // Note: code duplicated above (it's inconvenient to use a template here).
207 GURL GURL::Resolve(const base::string16& relative) const {
208 // Not allowed for invalid URLs.
213 url::StdStringCanonOutput output(&result.spec_);
214 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
215 parsed_, relative.data(),
216 static_cast<int>(relative.length()),
217 nullptr, &output, &result.parsed_)) {
218 // Error resolving, return an empty URL.
223 result.is_valid_ = true;
224 if (result.SchemeIsFileSystem()) {
225 result.inner_url_.reset(
226 new GURL(result.spec_.data(), result.parsed_.Length(),
227 *result.parsed_.inner_parsed(), true));
232 // Note: code duplicated below (it's inconvenient to use a template here).
233 GURL GURL::ReplaceComponents(
234 const url::Replacements<char>& replacements) const {
237 // Not allowed for invalid URLs.
241 url::StdStringCanonOutput output(&result.spec_);
242 result.is_valid_ = url::ReplaceComponents(
243 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
244 NULL, &output, &result.parsed_);
247 if (result.is_valid_ && result.SchemeIsFileSystem()) {
248 result.inner_url_.reset(new GURL(result.spec_.data(),
249 result.parsed_.Length(),
250 *result.parsed_.inner_parsed(), true));
255 // Note: code duplicated above (it's inconvenient to use a template here).
256 GURL GURL::ReplaceComponents(
257 const url::Replacements<base::char16>& replacements) const {
260 // Not allowed for invalid URLs.
264 url::StdStringCanonOutput output(&result.spec_);
265 result.is_valid_ = url::ReplaceComponents(
266 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
267 NULL, &output, &result.parsed_);
270 if (result.is_valid_ && result.SchemeIsFileSystem()) {
271 result.inner_url_.reset(new GURL(result.spec_.data(),
272 result.parsed_.Length(),
273 *result.parsed_.inner_parsed(), true));
278 GURL GURL::GetOrigin() const {
279 // This doesn't make sense for invalid or nonstandard URLs, so return
281 if (!is_valid_ || !IsStandard())
284 if (SchemeIsFileSystem())
285 return inner_url_->GetOrigin();
287 url::Replacements<char> replacements;
288 replacements.ClearUsername();
289 replacements.ClearPassword();
290 replacements.ClearPath();
291 replacements.ClearQuery();
292 replacements.ClearRef();
294 return ReplaceComponents(replacements);
297 GURL GURL::GetAsReferrer() const {
298 if (!SchemeIsValidForReferrer())
301 if (!has_ref() && !has_username() && !has_password())
304 url::Replacements<char> replacements;
305 replacements.ClearRef();
306 replacements.ClearUsername();
307 replacements.ClearPassword();
308 return ReplaceComponents(replacements);
311 GURL GURL::GetWithEmptyPath() const {
312 // This doesn't make sense for invalid or nonstandard URLs, so return
314 if (!is_valid_ || !IsStandard())
317 // We could optimize this since we know that the URL is canonical, and we are
318 // appending a canonical path, so avoiding re-parsing.
320 if (parsed_.path.len == 0)
323 // Clear everything after the path.
324 other.parsed_.query.reset();
325 other.parsed_.ref.reset();
327 // Set the path, since the path is longer than one, we can just set the
328 // first character and resize.
329 other.spec_[other.parsed_.path.begin] = '/';
330 other.parsed_.path.len = 1;
331 other.spec_.resize(other.parsed_.path.begin + 1);
335 GURL GURL::GetWithoutFilename() const {
339 bool GURL::IsStandard() const {
340 return url::IsStandard(spec_.data(), parsed_.scheme);
343 bool GURL::IsAboutBlank() const {
344 if (!SchemeIs(url::kAboutScheme))
347 if (has_host() || has_username() || has_password() || has_port())
350 if (path() != url::kAboutBlankPath && path() != url::kAboutBlankWithHashPath)
356 bool GURL::SchemeIs(base::StringPiece lower_ascii_scheme) const {
357 DCHECK(base::IsStringASCII(lower_ascii_scheme));
358 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
360 if (parsed_.scheme.len <= 0)
361 return lower_ascii_scheme.empty();
362 return scheme_piece() == lower_ascii_scheme;
365 bool GURL::SchemeIsHTTPOrHTTPS() const {
366 return SchemeIs(url::kHttpScheme) || SchemeIs(url::kHttpsScheme);
369 bool GURL::SchemeIsValidForReferrer() const {
370 return is_valid_ && IsReferrerScheme(spec_.data(), parsed_.scheme);
373 bool GURL::SchemeIsWSOrWSS() const {
374 return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
377 int GURL::IntPort() const {
378 if (parsed_.port.is_nonempty())
379 return url::ParsePort(spec_.data(), parsed_.port);
380 return url::PORT_UNSPECIFIED;
383 int GURL::EffectiveIntPort() const {
384 int int_port = IntPort();
385 if (int_port == url::PORT_UNSPECIFIED && IsStandard())
386 return url::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin,
391 std::string GURL::ExtractFileName() const {
392 url::Component file_component;
393 url::ExtractFileName(spec_.data(), parsed_.path, &file_component);
394 return ComponentString(file_component);
397 std::string GURL::PathForRequest() const {
398 DCHECK(parsed_.path.len > 0)
399 << "Canonical path for requests should be non-empty";
400 if (parsed_.ref.len >= 0) {
401 // Clip off the reference when it exists. The reference starts after the
402 // #-sign, so we have to subtract one to also remove it.
403 return std::string(spec_, parsed_.path.begin,
404 parsed_.ref.begin - parsed_.path.begin - 1);
406 // Compute the actual path length, rather than depending on the spec's
407 // terminator. If we're an inner_url, our spec continues on into our outer
408 // URL's path/query/ref.
409 int path_len = parsed_.path.len;
410 if (parsed_.query.is_valid())
411 path_len = parsed_.query.end() - parsed_.path.begin;
413 return std::string(spec_, parsed_.path.begin, path_len);
416 std::string GURL::HostNoBrackets() const {
417 return HostNoBracketsPiece().as_string();
420 base::StringPiece GURL::HostNoBracketsPiece() const {
421 // If host looks like an IPv6 literal, strip the square brackets.
422 url::Component h(parsed_.host);
423 if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') {
427 return ComponentStringPiece(h);
430 std::string GURL::GetContent() const {
431 return is_valid_ ? ComponentString(parsed_.GetContent()) : std::string();
434 bool GURL::HostIsIPAddress() const {
435 return is_valid_ && url::HostIsIPAddress(host_piece());
438 const GURL& GURL::EmptyGURL() {
439 return empty_gurl.Get();
442 bool GURL::DomainIs(base::StringPiece canonical_domain) const {
446 // FileSystem URLs have empty host_piece, so check this first.
447 if (inner_url_ && SchemeIsFileSystem())
448 return inner_url_->DomainIs(canonical_domain);
449 return url::DomainIs(host_piece(), canonical_domain);
452 bool GURL::EqualsIgnoringRef(const GURL& other) const {
453 int ref_position = parsed_.CountCharactersBefore(url::Parsed::REF, true);
454 int ref_position_other =
455 other.parsed_.CountCharactersBefore(url::Parsed::REF, true);
456 return base::StringPiece(spec_).substr(0, ref_position) ==
457 base::StringPiece(other.spec_).substr(0, ref_position_other);
460 void GURL::Swap(GURL* other) {
461 spec_.swap(other->spec_);
462 std::swap(is_valid_, other->is_valid_);
463 std::swap(parsed_, other->parsed_);
464 inner_url_.swap(other->inner_url_);
467 size_t GURL::EstimateMemoryUsage() const {
468 return base::trace_event::EstimateMemoryUsage(spec_) +
469 base::trace_event::EstimateMemoryUsage(inner_url_) +
470 (parsed_.inner_parsed() ? sizeof(url::Parsed) : 0);
473 std::ostream& operator<<(std::ostream& out, const GURL& url) {
474 return out << url.possibly_invalid_spec();
477 bool operator==(const GURL& x, const GURL& y) {
478 return x.possibly_invalid_spec() == y.possibly_invalid_spec();
481 bool operator!=(const GURL& x, const GURL& y) {
485 bool operator==(const GURL& x, const base::StringPiece& spec) {
486 DCHECK_EQ(GURL(spec).possibly_invalid_spec(), spec);
487 return x.possibly_invalid_spec() == spec;
490 bool operator==(const base::StringPiece& spec, const GURL& x) {
494 bool operator!=(const GURL& x, const base::StringPiece& spec) {
498 bool operator!=(const base::StringPiece& spec, const GURL& x) {