[M108 Migration][HBBTV] Implement ewk_context_register_jsplugin_mime_types API
[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 <utility>
13
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"
22
23 GURL::GURL() : is_valid_(false) {
24 }
25
26 GURL::GURL(const GURL& other)
27     : spec_(other.spec_),
28       is_valid_(other.is_valid_),
29       parsed_(other.parsed_) {
30   if (other.inner_url_)
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_);
34 }
35
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();
43 }
44
45 GURL::GURL(base::StringPiece url_string) {
46   InitCanonical(url_string, true);
47 }
48
49 GURL::GURL(base::StringPiece16 url_string) {
50   InitCanonical(url_string, true);
51 }
52
53 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
54   InitCanonical(url_string, false);
55 }
56
57 GURL::GURL(const char* canonical_spec,
58            size_t canonical_spec_len,
59            const url::Parsed& parsed,
60            bool is_valid)
61     : spec_(canonical_spec, canonical_spec_len),
62       is_valid_(is_valid),
63       parsed_(parsed) {
64   InitializeFromCanonicalSpec();
65 }
66
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();
70 }
71
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_);
78
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);
83   }
84   // Valid URLs always have non-empty specs.
85   DCHECK(!is_valid_ || !spec_.empty());
86 }
87
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);
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_EQ(test_url.is_valid_, is_valid_);
114       DCHECK_EQ(test_url.spec_, spec_);
115
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);
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_ = std::make_unique<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_ =
193         std::make_unique<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_ =
219         std::make_unique<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(const Replacements& replacements) const {
227   GURL result;
228
229   // Not allowed for invalid URLs.
230   if (!is_valid_)
231     return GURL();
232
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_);
237
238   output.Complete();
239
240   result.ProcessFileSystemURLAfterReplaceComponents();
241   return result;
242 }
243
244 // Note: code duplicated above (it's inconvenient to use a template here).
245 GURL GURL::ReplaceComponents(const ReplacementsW& replacements) const {
246   GURL result;
247
248   // Not allowed for invalid URLs.
249   if (!is_valid_)
250     return GURL();
251
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_);
256
257   output.Complete();
258
259   result.ProcessFileSystemURLAfterReplaceComponents();
260
261   return result;
262 }
263
264 void GURL::ProcessFileSystemURLAfterReplaceComponents() {
265   if (!is_valid_)
266     return;
267   if (SchemeIsFileSystem()) {
268     inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
269                                         *parsed_.inner_parsed(), true);
270   }
271 }
272
273 GURL GURL::DeprecatedGetOriginAsURL() const {
274   // This doesn't make sense for invalid or nonstandard URLs, so return
275   // the empty URL.
276   if (!is_valid_ || !IsStandard())
277     return GURL();
278
279   if (SchemeIsFileSystem())
280     return inner_url_->DeprecatedGetOriginAsURL();
281
282   Replacements replacements;
283   replacements.ClearUsername();
284   replacements.ClearPassword();
285   replacements.ClearPath();
286   replacements.ClearQuery();
287   replacements.ClearRef();
288
289   return ReplaceComponents(replacements);
290 }
291
292 GURL GURL::GetAsReferrer() const {
293   if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme))
294     return GURL();
295
296   if (!has_ref() && !has_username() && !has_password())
297     return GURL(*this);
298
299   Replacements replacements;
300   replacements.ClearRef();
301   replacements.ClearUsername();
302   replacements.ClearPassword();
303   return ReplaceComponents(replacements);
304 }
305
306 GURL GURL::GetWithEmptyPath() const {
307   // This doesn't make sense for invalid or nonstandard URLs, so return
308   // the empty URL.
309   if (!is_valid_ || !IsStandard())
310     return GURL();
311
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.
314   GURL other(*this);
315   if (parsed_.path.len == 0)
316     return other;
317
318   // Clear everything after the path.
319   other.parsed_.query.reset();
320   other.parsed_.ref.reset();
321
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);
327   return other;
328 }
329
330 GURL GURL::GetWithoutFilename() const {
331   return Resolve(".");
332 }
333
334 bool GURL::IsStandard() const {
335   return url::IsStandard(spec_.data(), parsed_.scheme);
336 }
337
338 bool GURL::IsAboutBlank() const {
339   return IsAboutUrl(url::kAboutBlankPath);
340 }
341
342 bool GURL::IsAboutSrcdoc() const {
343   return IsAboutUrl(url::kAboutSrcdocPath);
344 }
345
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);
349
350   if (!has_scheme())
351     return lower_ascii_scheme.empty();
352   return scheme_piece() == lower_ascii_scheme;
353 }
354
355 bool GURL::SchemeIsHTTPOrHTTPS() const {
356   return SchemeIs(url::kHttpScheme) || SchemeIs(url::kHttpsScheme);
357 }
358
359 bool GURL::SchemeIsWSOrWSS() const {
360   return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
361 }
362
363 bool GURL::SchemeIsCryptographic() const {
364   if (!has_scheme())
365     return false;
366   return SchemeIsCryptographic(scheme_piece());
367 }
368
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);
372
373   return lower_ascii_scheme == url::kHttpsScheme ||
374          lower_ascii_scheme == url::kWssScheme;
375 }
376
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);
382 }
383
384 int GURL::IntPort() const {
385   if (parsed_.port.is_nonempty())
386     return url::ParsePort(spec_.data(), parsed_.port);
387   return url::PORT_UNSPECIFIED;
388 }
389
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,
394                                      parsed_.scheme.len);
395   return int_port;
396 }
397
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);
402 }
403
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);
412   }
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;
419
420   return base::StringPiece(&spec_[parsed_.path.begin], path_len);
421 }
422
423 std::string GURL::PathForRequest() const {
424   return std::string(PathForRequestPiece());
425 }
426
427 std::string GURL::HostNoBrackets() const {
428   return std::string(HostNoBracketsPiece());
429 }
430
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] == ']') {
435     h.begin++;
436     h.len -= 2;
437   }
438   return ComponentStringPiece(h);
439 }
440
441 std::string GURL::GetContent() const {
442   return std::string(GetContentPiece());
443 }
444
445 base::StringPiece GURL::GetContentPiece() const {
446   if (!is_valid_)
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);
452 }
453
454 bool GURL::HostIsIPAddress() const {
455   return is_valid_ && url::HostIsIPAddress(host_piece());
456 }
457
458 const GURL& GURL::EmptyGURL() {
459   static base::NoDestructor<GURL> empty_gurl;
460   return *empty_gurl;
461 }
462
463 bool GURL::DomainIs(base::StringPiece canonical_domain) const {
464   if (!is_valid_)
465     return false;
466
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);
471 }
472
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);
479 }
480
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_);
486 }
487
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);
492 }
493
494 bool GURL::IsAboutUrl(base::StringPiece allowed_path) const {
495   if (!SchemeIs(url::kAboutScheme))
496     return false;
497
498   if (has_host() || has_username() || has_password() || has_port())
499     return false;
500
501   return IsAboutPath(path_piece(), allowed_path);
502 }
503
504 // static
505 bool GURL::IsAboutPath(base::StringPiece actual_path,
506                        base::StringPiece allowed_path) {
507   if (!base::StartsWith(actual_path, allowed_path))
508     return false;
509
510   if (actual_path.size() == allowed_path.size()) {
511     DCHECK_EQ(actual_path, allowed_path);
512     return true;
513   }
514
515   if ((actual_path.size() == allowed_path.size() + 1) &&
516       actual_path.back() == '/') {
517     DCHECK_EQ(actual_path, std::string(allowed_path) + '/');
518     return true;
519   }
520
521   return false;
522 }
523
524 void GURL::WriteIntoTrace(perfetto::TracedValue context) const {
525   std::move(context).WriteString(possibly_invalid_spec());
526 }
527
528 std::ostream& operator<<(std::ostream& out, const GURL& url) {
529   return out << url.possibly_invalid_spec();
530 }
531
532 bool operator==(const GURL& x, const GURL& y) {
533   return x.possibly_invalid_spec() == y.possibly_invalid_spec();
534 }
535
536 bool operator!=(const GURL& x, const GURL& y) {
537   return !(x == y);
538 }
539
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;
545 }
546
547 bool operator==(const base::StringPiece& spec, const GURL& x) {
548   return x == spec;
549 }
550
551 bool operator!=(const GURL& x, const base::StringPiece& spec) {
552   return !(x == spec);
553 }
554
555 bool operator!=(const base::StringPiece& spec, const GURL& x) {
556   return !(x == spec);
557 }
558
559 namespace url::debug {
560
561 ScopedUrlCrashKey::ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key,
562                                      const GURL& url)
563     : scoped_string_value_(
564           crash_key,
565           url.is_empty() ? "<empty url>" : url.possibly_invalid_spec()) {}
566
567 ScopedUrlCrashKey::~ScopedUrlCrashKey() = default;
568
569 }  // namespace url::debug