Upload upstream chromium 85.0.4183.84
[platform/framework/web/chromium-efl.git] / url / gurl.cc
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.
4
5 #include "url/gurl.h"
6
7 #include <stddef.h>
8
9 #include <algorithm>
10 #include <ostream>
11 #include <utility>
12
13 #include "base/check_op.h"
14 #include "base/no_destructor.h"
15 #include "base/strings/string_piece.h"
16 #include "base/strings/string_util.h"
17 #include "base/trace_event/memory_usage_estimator.h"
18 #include "url/url_canon_stdstring.h"
19 #include "url/url_util.h"
20
21 GURL::GURL() : is_valid_(false) {
22 }
23
24 GURL::GURL(const GURL& other)
25     : spec_(other.spec_),
26       is_valid_(other.is_valid_),
27       parsed_(other.parsed_) {
28   if (other.inner_url_)
29     inner_url_.reset(new GURL(*other.inner_url_));
30   // Valid filesystem urls should always have an inner_url_.
31   DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_);
32 }
33
34 GURL::GURL(GURL&& other) noexcept
35     : spec_(std::move(other.spec_)),
36       is_valid_(other.is_valid_),
37       parsed_(other.parsed_),
38       inner_url_(std::move(other.inner_url_)) {
39   other.is_valid_ = false;
40   other.parsed_ = url::Parsed();
41 }
42
43 GURL::GURL(base::StringPiece url_string) {
44   InitCanonical(url_string, true);
45 }
46
47 GURL::GURL(base::StringPiece16 url_string) {
48   InitCanonical(url_string, true);
49 }
50
51 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
52   InitCanonical(base::StringPiece(url_string), false);
53 }
54
55 GURL::GURL(const char* canonical_spec,
56            size_t canonical_spec_len,
57            const url::Parsed& parsed,
58            bool is_valid)
59     : spec_(canonical_spec, canonical_spec_len),
60       is_valid_(is_valid),
61       parsed_(parsed) {
62   InitializeFromCanonicalSpec();
63 }
64
65 GURL::GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid)
66     : spec_(std::move(canonical_spec)), is_valid_(is_valid), parsed_(parsed) {
67   InitializeFromCanonicalSpec();
68 }
69
70 template<typename STR>
71 void GURL::InitCanonical(base::BasicStringPiece<STR> input_spec,
72                          bool trim_path_end) {
73   url::StdStringCanonOutput output(&spec_);
74   is_valid_ = url::Canonicalize(
75       input_spec.data(), static_cast<int>(input_spec.length()), trim_path_end,
76       NULL, &output, &parsed_);
77
78   output.Complete();  // Must be done before using string.
79   if (is_valid_ && SchemeIsFileSystem()) {
80     inner_url_.reset(new GURL(spec_.data(), parsed_.Length(),
81                               *parsed_.inner_parsed(), true));
82   }
83   // Valid URLs always have non-empty specs.
84   DCHECK(!is_valid_ || !spec_.empty());
85 }
86
87 void GURL::InitializeFromCanonicalSpec() {
88   if (is_valid_ && SchemeIsFileSystem()) {
89     inner_url_.reset(
90         new GURL(spec_.data(), parsed_.Length(),
91                  *parsed_.inner_parsed(), true));
92   }
93
94 #ifndef NDEBUG
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.
98   if (is_valid_) {
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);
112
113       DCHECK(test_url.is_valid_ == is_valid_);
114       DCHECK(test_url.spec_ == spec_);
115
116       DCHECK(test_url.parsed_.scheme == parsed_.scheme);
117       DCHECK(test_url.parsed_.username == parsed_.username);
118       DCHECK(test_url.parsed_.password == parsed_.password);
119       DCHECK(test_url.parsed_.host == parsed_.host);
120       DCHECK(test_url.parsed_.port == parsed_.port);
121       DCHECK(test_url.parsed_.path == parsed_.path);
122       DCHECK(test_url.parsed_.query == parsed_.query);
123       DCHECK(test_url.parsed_.ref == parsed_.ref);
124     }
125   }
126 #endif
127 }
128
129 GURL::~GURL() = default;
130
131 GURL& GURL::operator=(const GURL& other) {
132   spec_ = other.spec_;
133   is_valid_ = other.is_valid_;
134   parsed_ = other.parsed_;
135
136   if (!other.inner_url_)
137     inner_url_.reset();
138   else if (inner_url_)
139     *inner_url_ = *other.inner_url_;
140   else
141     inner_url_.reset(new GURL(*other.inner_url_));
142
143   return *this;
144 }
145
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_);
151
152   other.is_valid_ = false;
153   other.parsed_ = url::Parsed();
154   return *this;
155 }
156
157 const std::string& GURL::spec() const {
158   if (is_valid_ || spec_.empty())
159     return spec_;
160
161   DCHECK(false) << "Trying to get the spec of an invalid URL!";
162   return base::EmptyString();
163 }
164
165 bool GURL::operator<(const GURL& other) const {
166   return spec_ < other.spec_;
167 }
168
169 bool GURL::operator>(const GURL& other) const {
170   return spec_ > other.spec_;
171 }
172
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.
176   if (!is_valid_)
177     return GURL();
178
179   GURL result;
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.
186     return GURL();
187   }
188
189   output.Complete();
190   result.is_valid_ = true;
191   if (result.SchemeIsFileSystem()) {
192     result.inner_url_.reset(
193         new GURL(result.spec_.data(), result.parsed_.Length(),
194                  *result.parsed_.inner_parsed(), true));
195   }
196   return result;
197 }
198
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.
202   if (!is_valid_)
203     return GURL();
204
205   GURL result;
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.
212     return GURL();
213   }
214
215   output.Complete();
216   result.is_valid_ = true;
217   if (result.SchemeIsFileSystem()) {
218     result.inner_url_.reset(
219         new GURL(result.spec_.data(), result.parsed_.Length(),
220                  *result.parsed_.inner_parsed(), true));
221   }
222   return result;
223 }
224
225 // Note: code duplicated below (it's inconvenient to use a template here).
226 GURL GURL::ReplaceComponents(
227     const url::Replacements<char>& replacements) const {
228   GURL result;
229
230   // Not allowed for invalid URLs.
231   if (!is_valid_)
232     return GURL();
233
234   url::StdStringCanonOutput output(&result.spec_);
235   result.is_valid_ = url::ReplaceComponents(
236       spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
237       NULL, &output, &result.parsed_);
238
239   output.Complete();
240   if (result.is_valid_ && result.SchemeIsFileSystem()) {
241     result.inner_url_.reset(new GURL(result.spec_.data(),
242                                      result.parsed_.Length(),
243                                      *result.parsed_.inner_parsed(), true));
244   }
245   return result;
246 }
247
248 // Note: code duplicated above (it's inconvenient to use a template here).
249 GURL GURL::ReplaceComponents(
250     const url::Replacements<base::char16>& replacements) const {
251   GURL result;
252
253   // Not allowed for invalid URLs.
254   if (!is_valid_)
255     return GURL();
256
257   url::StdStringCanonOutput output(&result.spec_);
258   result.is_valid_ = url::ReplaceComponents(
259       spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
260       NULL, &output, &result.parsed_);
261
262   output.Complete();
263   if (result.is_valid_ && result.SchemeIsFileSystem()) {
264     result.inner_url_.reset(new GURL(result.spec_.data(),
265                                      result.parsed_.Length(),
266                                      *result.parsed_.inner_parsed(), true));
267   }
268   return result;
269 }
270
271 GURL GURL::GetOrigin() const {
272   // This doesn't make sense for invalid or nonstandard URLs, so return
273   // the empty URL.
274   if (!is_valid_ || !IsStandard())
275     return GURL();
276
277   if (SchemeIsFileSystem())
278     return inner_url_->GetOrigin();
279
280   url::Replacements<char> replacements;
281   replacements.ClearUsername();
282   replacements.ClearPassword();
283   replacements.ClearPath();
284   replacements.ClearQuery();
285   replacements.ClearRef();
286
287   return ReplaceComponents(replacements);
288 }
289
290 GURL GURL::GetAsReferrer() const {
291   if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme))
292     return GURL();
293
294   if (!has_ref() && !has_username() && !has_password())
295     return GURL(*this);
296
297   url::Replacements<char> replacements;
298   replacements.ClearRef();
299   replacements.ClearUsername();
300   replacements.ClearPassword();
301   return ReplaceComponents(replacements);
302 }
303
304 GURL GURL::GetWithEmptyPath() const {
305   // This doesn't make sense for invalid or nonstandard URLs, so return
306   // the empty URL.
307   if (!is_valid_ || !IsStandard())
308     return GURL();
309
310   // We could optimize this since we know that the URL is canonical, and we are
311   // appending a canonical path, so avoiding re-parsing.
312   GURL other(*this);
313   if (parsed_.path.len == 0)
314     return other;
315
316   // Clear everything after the path.
317   other.parsed_.query.reset();
318   other.parsed_.ref.reset();
319
320   // Set the path, since the path is longer than one, we can just set the
321   // first character and resize.
322   other.spec_[other.parsed_.path.begin] = '/';
323   other.parsed_.path.len = 1;
324   other.spec_.resize(other.parsed_.path.begin + 1);
325   return other;
326 }
327
328 GURL GURL::GetWithoutFilename() const {
329   return Resolve(".");
330 }
331
332 bool GURL::IsStandard() const {
333   return url::IsStandard(spec_.data(), parsed_.scheme);
334 }
335
336 bool GURL::IsAboutBlank() const {
337   return IsAboutUrl(url::kAboutBlankPath);
338 }
339
340 bool GURL::IsAboutSrcdoc() const {
341   return IsAboutUrl(url::kAboutSrcdocPath);
342 }
343
344 bool GURL::SchemeIs(base::StringPiece lower_ascii_scheme) const {
345   DCHECK(base::IsStringASCII(lower_ascii_scheme));
346   DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
347
348   if (parsed_.scheme.len <= 0)
349     return lower_ascii_scheme.empty();
350   return scheme_piece() == lower_ascii_scheme;
351 }
352
353 bool GURL::SchemeIsHTTPOrHTTPS() const {
354   return SchemeIs(url::kHttpScheme) || SchemeIs(url::kHttpsScheme);
355 }
356
357 bool GURL::SchemeIsWSOrWSS() const {
358   return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
359 }
360
361 bool GURL::SchemeIsCryptographic() const {
362   if (parsed_.scheme.len <= 0)
363     return false;
364   return SchemeIsCryptographic(scheme_piece());
365 }
366
367 bool GURL::SchemeIsCryptographic(base::StringPiece lower_ascii_scheme) {
368   DCHECK(base::IsStringASCII(lower_ascii_scheme));
369   DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
370
371   return lower_ascii_scheme == url::kHttpsScheme ||
372          lower_ascii_scheme == url::kWssScheme;
373 }
374
375 int GURL::IntPort() const {
376   if (parsed_.port.is_nonempty())
377     return url::ParsePort(spec_.data(), parsed_.port);
378   return url::PORT_UNSPECIFIED;
379 }
380
381 int GURL::EffectiveIntPort() const {
382   int int_port = IntPort();
383   if (int_port == url::PORT_UNSPECIFIED && IsStandard())
384     return url::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin,
385                                      parsed_.scheme.len);
386   return int_port;
387 }
388
389 std::string GURL::ExtractFileName() const {
390   url::Component file_component;
391   url::ExtractFileName(spec_.data(), parsed_.path, &file_component);
392   return ComponentString(file_component);
393 }
394
395 base::StringPiece GURL::PathForRequestPiece() const {
396   DCHECK(parsed_.path.len > 0)
397       << "Canonical path for requests should be non-empty";
398   if (parsed_.ref.len >= 0) {
399     // Clip off the reference when it exists. The reference starts after the
400     // #-sign, so we have to subtract one to also remove it.
401     return base::StringPiece(&spec_[parsed_.path.begin],
402                              parsed_.ref.begin - parsed_.path.begin - 1);
403   }
404   // Compute the actual path length, rather than depending on the spec's
405   // terminator. If we're an inner_url, our spec continues on into our outer
406   // URL's path/query/ref.
407   int path_len = parsed_.path.len;
408   if (parsed_.query.is_valid())
409     path_len = parsed_.query.end() - parsed_.path.begin;
410
411   return base::StringPiece(&spec_[parsed_.path.begin], path_len);
412 }
413
414 std::string GURL::PathForRequest() const {
415   return PathForRequestPiece().as_string();
416 }
417
418 std::string GURL::HostNoBrackets() const {
419   return HostNoBracketsPiece().as_string();
420 }
421
422 base::StringPiece GURL::HostNoBracketsPiece() const {
423   // If host looks like an IPv6 literal, strip the square brackets.
424   url::Component h(parsed_.host);
425   if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') {
426     h.begin++;
427     h.len -= 2;
428   }
429   return ComponentStringPiece(h);
430 }
431
432 std::string GURL::GetContent() const {
433   if (!is_valid_)
434     return std::string();
435   std::string content = ComponentString(parsed_.GetContent());
436   if (!SchemeIs(url::kJavaScriptScheme) && parsed_.ref.len >= 0)
437     content.erase(content.size() - parsed_.ref.len - 1);
438   return content;
439 }
440
441 bool GURL::HostIsIPAddress() const {
442   return is_valid_ && url::HostIsIPAddress(host_piece());
443 }
444
445 const GURL& GURL::EmptyGURL() {
446   static base::NoDestructor<GURL> empty_gurl;
447   return *empty_gurl;
448 }
449
450 bool GURL::DomainIs(base::StringPiece canonical_domain) const {
451   if (!is_valid_)
452     return false;
453
454   // FileSystem URLs have empty host_piece, so check this first.
455   if (inner_url_ && SchemeIsFileSystem())
456     return inner_url_->DomainIs(canonical_domain);
457   return url::DomainIs(host_piece(), canonical_domain);
458 }
459
460 bool GURL::EqualsIgnoringRef(const GURL& other) const {
461   int ref_position = parsed_.CountCharactersBefore(url::Parsed::REF, true);
462   int ref_position_other =
463       other.parsed_.CountCharactersBefore(url::Parsed::REF, true);
464   return base::StringPiece(spec_).substr(0, ref_position) ==
465          base::StringPiece(other.spec_).substr(0, ref_position_other);
466 }
467
468 void GURL::Swap(GURL* other) {
469   spec_.swap(other->spec_);
470   std::swap(is_valid_, other->is_valid_);
471   std::swap(parsed_, other->parsed_);
472   inner_url_.swap(other->inner_url_);
473 }
474
475 size_t GURL::EstimateMemoryUsage() const {
476   return base::trace_event::EstimateMemoryUsage(spec_) +
477          base::trace_event::EstimateMemoryUsage(inner_url_) +
478          (parsed_.inner_parsed() ? sizeof(url::Parsed) : 0);
479 }
480
481 bool GURL::IsAboutUrl(base::StringPiece allowed_path) const {
482   if (!SchemeIs(url::kAboutScheme))
483     return false;
484
485   if (has_host() || has_username() || has_password() || has_port())
486     return false;
487
488   if (!path_piece().starts_with(allowed_path))
489     return false;
490
491   if (path_piece().size() == allowed_path.size()) {
492     DCHECK_EQ(path_piece(), allowed_path);
493     return true;
494   }
495
496   if ((path_piece().size() == allowed_path.size() + 1) &&
497       path_piece().back() == '/') {
498     DCHECK_EQ(path_piece(), allowed_path.as_string() + '/');
499     return true;
500   }
501
502   return false;
503 }
504
505 std::ostream& operator<<(std::ostream& out, const GURL& url) {
506   return out << url.possibly_invalid_spec();
507 }
508
509 bool operator==(const GURL& x, const GURL& y) {
510   return x.possibly_invalid_spec() == y.possibly_invalid_spec();
511 }
512
513 bool operator!=(const GURL& x, const GURL& y) {
514   return !(x == y);
515 }
516
517 bool operator==(const GURL& x, const base::StringPiece& spec) {
518   DCHECK_EQ(GURL(spec).possibly_invalid_spec(), spec)
519       << "Comparisons of GURLs and strings must ensure as a precondition that "
520          "the string is fully canonicalized.";
521   return x.possibly_invalid_spec() == spec;
522 }
523
524 bool operator==(const base::StringPiece& spec, const GURL& x) {
525   return x == spec;
526 }
527
528 bool operator!=(const GURL& x, const base::StringPiece& spec) {
529   return !(x == spec);
530 }
531
532 bool operator!=(const base::StringPiece& spec, const GURL& x) {
533   return !(x == spec);
534 }