Fix for Geolocation webTCT failures
[platform/framework/web/chromium-efl.git] / url / gurl.cc
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 #include "url/gurl.h"
6
7 #include <stddef.h>
8
9 #include <algorithm>
10 #include <memory>
11 #include <ostream>
12 #include <string_view>
13 #include <utility>
14
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"
23
24 GURL::GURL() : is_valid_(false) {
25 }
26
27 GURL::GURL(const GURL& other)
28     : spec_(other.spec_),
29       is_valid_(other.is_valid_),
30       parsed_(other.parsed_) {
31   if (other.inner_url_)
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_);
35 }
36
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();
44 }
45
46 GURL::GURL(std::string_view url_string) {
47   InitCanonical(url_string, true);
48 }
49
50 GURL::GURL(std::u16string_view url_string) {
51   InitCanonical(url_string, true);
52 }
53
54 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
55   InitCanonical(url_string, false);
56 }
57
58 GURL::GURL(const char* canonical_spec,
59            size_t canonical_spec_len,
60            const url::Parsed& parsed,
61            bool is_valid)
62     : spec_(canonical_spec, canonical_spec_len),
63       is_valid_(is_valid),
64       parsed_(parsed) {
65   InitializeFromCanonicalSpec();
66 }
67
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();
71 }
72
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_);
79
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);
84   }
85   // Valid URLs always have non-empty specs.
86   DCHECK(!is_valid_ || !spec_.empty());
87 }
88
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);
93   }
94
95 #ifndef NDEBUG
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.
99   if (is_valid_) {
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);
113
114       DCHECK_EQ(test_url.is_valid_, is_valid_);
115       DCHECK_EQ(test_url.spec_, spec_);
116
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);
125     }
126   }
127 #endif
128 }
129
130 GURL::~GURL() = default;
131
132 GURL& GURL::operator=(const GURL& other) {
133   spec_ = other.spec_;
134   is_valid_ = other.is_valid_;
135   parsed_ = other.parsed_;
136
137   if (!other.inner_url_)
138     inner_url_.reset();
139   else if (inner_url_)
140     *inner_url_ = *other.inner_url_;
141   else
142     inner_url_ = std::make_unique<GURL>(*other.inner_url_);
143
144   return *this;
145 }
146
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_);
152
153   other.is_valid_ = false;
154   other.parsed_ = url::Parsed();
155   return *this;
156 }
157
158 const std::string& GURL::spec() const {
159   if (is_valid_ || spec_.empty())
160     return spec_;
161
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();
166 }
167
168 bool GURL::operator<(const GURL& other) const {
169   return spec_ < other.spec_;
170 }
171
172 bool GURL::operator>(const GURL& other) const {
173   return spec_ > other.spec_;
174 }
175
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.
179   if (!is_valid_)
180     return GURL();
181
182   GURL result;
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.
189     return GURL();
190   }
191
192   output.Complete();
193   result.is_valid_ = true;
194   if (result.SchemeIsFileSystem()) {
195     result.inner_url_ =
196         std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
197                                *result.parsed_.inner_parsed(), true);
198   }
199   return result;
200 }
201
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.
205   if (!is_valid_)
206     return GURL();
207
208   GURL result;
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.
215     return GURL();
216   }
217
218   output.Complete();
219   result.is_valid_ = true;
220   if (result.SchemeIsFileSystem()) {
221     result.inner_url_ =
222         std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
223                                *result.parsed_.inner_parsed(), true);
224   }
225   return result;
226 }
227
228 // Note: code duplicated below (it's inconvenient to use a template here).
229 GURL GURL::ReplaceComponents(const Replacements& replacements) const {
230   GURL result;
231
232   // Not allowed for invalid URLs.
233   if (!is_valid_)
234     return GURL();
235
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_);
240
241   output.Complete();
242
243   result.ProcessFileSystemURLAfterReplaceComponents();
244   return result;
245 }
246
247 // Note: code duplicated above (it's inconvenient to use a template here).
248 GURL GURL::ReplaceComponents(const ReplacementsW& replacements) const {
249   GURL result;
250
251   // Not allowed for invalid URLs.
252   if (!is_valid_)
253     return GURL();
254
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_);
259
260   output.Complete();
261
262   result.ProcessFileSystemURLAfterReplaceComponents();
263
264   return result;
265 }
266
267 void GURL::ProcessFileSystemURLAfterReplaceComponents() {
268   if (!is_valid_)
269     return;
270   if (SchemeIsFileSystem()) {
271     inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
272                                         *parsed_.inner_parsed(), true);
273   }
274 }
275
276 GURL GURL::DeprecatedGetOriginAsURL() const {
277   // This doesn't make sense for invalid or nonstandard URLs, so return
278   // the empty URL.
279   if (!is_valid_ || !IsStandard())
280     return GURL();
281
282   if (SchemeIsFileSystem())
283     return inner_url_->DeprecatedGetOriginAsURL();
284
285   Replacements replacements;
286   replacements.ClearUsername();
287   replacements.ClearPassword();
288   replacements.ClearPath();
289   replacements.ClearQuery();
290   replacements.ClearRef();
291
292   return ReplaceComponents(replacements);
293 }
294
295 GURL GURL::GetAsReferrer() const {
296   if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme))
297     return GURL();
298
299   if (!has_ref() && !has_username() && !has_password())
300     return GURL(*this);
301
302   Replacements replacements;
303   replacements.ClearRef();
304   replacements.ClearUsername();
305   replacements.ClearPassword();
306   return ReplaceComponents(replacements);
307 }
308
309 GURL GURL::GetWithEmptyPath() const {
310   // This doesn't make sense for invalid or nonstandard URLs, so return
311   // the empty URL.
312   if (!is_valid_ || !IsStandard())
313     return GURL();
314
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.
317   GURL other(*this);
318   if (parsed_.path.len == 0)
319     return other;
320
321   // Clear everything after the path.
322   other.parsed_.query.reset();
323   other.parsed_.ref.reset();
324
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);
330   return other;
331 }
332
333 GURL GURL::GetWithoutFilename() const {
334   return Resolve(".");
335 }
336
337 GURL GURL::GetWithoutRef() const {
338   if (!has_ref())
339     return GURL(*this);
340
341   Replacements replacements;
342   replacements.ClearRef();
343   return ReplaceComponents(replacements);
344 }
345
346 bool GURL::IsStandard() const {
347   return url::IsStandard(spec_.data(), parsed_.scheme);
348 }
349
350 bool GURL::IsAboutBlank() const {
351   return IsAboutUrl(url::kAboutBlankPath);
352 }
353
354 bool GURL::IsAboutSrcdoc() const {
355   return IsAboutUrl(url::kAboutSrcdocPath);
356 }
357
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);
361
362   if (!has_scheme())
363     return lower_ascii_scheme.empty();
364   return scheme_piece() == lower_ascii_scheme;
365 }
366
367 bool GURL::SchemeIsHTTPOrHTTPS() const {
368   return SchemeIs(url::kHttpsScheme) || SchemeIs(url::kHttpScheme);
369 }
370
371 bool GURL::SchemeIsWSOrWSS() const {
372   return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
373 }
374
375 bool GURL::SchemeIsCryptographic() const {
376   if (!has_scheme())
377     return false;
378   return SchemeIsCryptographic(scheme_piece());
379 }
380
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);
384
385   return lower_ascii_scheme == url::kHttpsScheme ||
386          lower_ascii_scheme == url::kWssScheme;
387 }
388
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);
394 }
395
396 int GURL::IntPort() const {
397   if (parsed_.port.is_nonempty())
398     return url::ParsePort(spec_.data(), parsed_.port);
399   return url::PORT_UNSPECIFIED;
400 }
401
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,
406                                      parsed_.scheme.len);
407   return int_port;
408 }
409
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);
414 }
415
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);
424   }
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;
431
432   return std::string_view(spec_).substr(parsed_.path.begin, path_len);
433 }
434
435 std::string GURL::PathForRequest() const {
436   return std::string(PathForRequestPiece());
437 }
438
439 std::string GURL::HostNoBrackets() const {
440   return std::string(HostNoBracketsPiece());
441 }
442
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] == ']') {
447     h.begin++;
448     h.len -= 2;
449   }
450   return ComponentStringPiece(h);
451 }
452
453 std::string GURL::GetContent() const {
454   return std::string(GetContentPiece());
455 }
456
457 std::string_view GURL::GetContentPiece() const {
458   if (!is_valid_)
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);
464 }
465
466 bool GURL::HostIsIPAddress() const {
467   return is_valid_ && url::HostIsIPAddress(host_piece());
468 }
469
470 const GURL& GURL::EmptyGURL() {
471   static base::NoDestructor<GURL> empty_gurl;
472   return *empty_gurl;
473 }
474
475 bool GURL::DomainIs(std::string_view canonical_domain) const {
476   if (!is_valid_)
477     return false;
478
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);
483 }
484
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);
491 }
492
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_);
498 }
499
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);
504 }
505
506 bool GURL::IsAboutUrl(std::string_view allowed_path) const {
507   if (!SchemeIs(url::kAboutScheme))
508     return false;
509
510   if (has_host() || has_username() || has_password() || has_port())
511     return false;
512
513   return IsAboutPath(path_piece(), allowed_path);
514 }
515
516 // static
517 bool GURL::IsAboutPath(std::string_view actual_path,
518                        std::string_view allowed_path) {
519   if (!base::StartsWith(actual_path, allowed_path))
520     return false;
521
522   if (actual_path.size() == allowed_path.size()) {
523     DCHECK_EQ(actual_path, allowed_path);
524     return true;
525   }
526
527   if ((actual_path.size() == allowed_path.size() + 1) &&
528       actual_path.back() == '/') {
529     DCHECK_EQ(actual_path, std::string(allowed_path) + '/');
530     return true;
531   }
532
533   return false;
534 }
535
536 void GURL::WriteIntoTrace(perfetto::TracedValue context) const {
537   std::move(context).WriteString(possibly_invalid_spec());
538 }
539
540 std::ostream& operator<<(std::ostream& out, const GURL& url) {
541   return out << url.possibly_invalid_spec();
542 }
543
544 bool operator==(const GURL& x, const GURL& y) {
545   return x.possibly_invalid_spec() == y.possibly_invalid_spec();
546 }
547
548 bool operator!=(const GURL& x, const GURL& y) {
549   return !(x == y);
550 }
551
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;
557 }
558
559 bool operator==(std::string_view spec, const GURL& x) {
560   return x == spec;
561 }
562
563 bool operator!=(const GURL& x, std::string_view spec) {
564   return !(x == spec);
565 }
566
567 bool operator!=(std::string_view spec, const GURL& x) {
568   return !(x == spec);
569 }
570
571 namespace url::debug {
572
573 ScopedUrlCrashKey::ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key,
574                                      const GURL& url)
575     : scoped_string_value_(
576           crash_key,
577           url.is_empty() ? "<empty url>" : url.possibly_invalid_spec()) {}
578
579 ScopedUrlCrashKey::~ScopedUrlCrashKey() = default;
580
581 }  // namespace url::debug