Upload upstream chromium 67.0.3396
[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
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"
19
20 namespace {
21
22 static base::LazyInstance<std::string>::Leaky empty_string =
23     LAZY_INSTANCE_INITIALIZER;
24 static base::LazyInstance<GURL>::Leaky empty_gurl = LAZY_INSTANCE_INITIALIZER;
25
26 }  // namespace
27
28 GURL::GURL() : is_valid_(false) {
29 }
30
31 GURL::GURL(const GURL& other)
32     : spec_(other.spec_),
33       is_valid_(other.is_valid_),
34       parsed_(other.parsed_) {
35   if (other.inner_url_)
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_);
39 }
40
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();
48 }
49
50 GURL::GURL(base::StringPiece url_string) {
51   InitCanonical(url_string, true);
52 }
53
54 GURL::GURL(base::StringPiece16 url_string) {
55   InitCanonical(url_string, true);
56 }
57
58 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
59   InitCanonical(base::StringPiece(url_string), false);
60 }
61
62 GURL::GURL(const char* canonical_spec,
63            size_t canonical_spec_len,
64            const url::Parsed& parsed,
65            bool is_valid)
66     : spec_(canonical_spec, canonical_spec_len),
67       is_valid_(is_valid),
68       parsed_(parsed) {
69   InitializeFromCanonicalSpec();
70 }
71
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();
75 }
76
77 template<typename STR>
78 void GURL::InitCanonical(base::BasicStringPiece<STR> input_spec,
79                          bool trim_path_end) {
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_);
84
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));
89   }
90   // Valid URLs always have non-empty specs.
91   DCHECK(!is_valid_ || !spec_.empty());
92 }
93
94 void GURL::InitializeFromCanonicalSpec() {
95   if (is_valid_ && SchemeIsFileSystem()) {
96     inner_url_.reset(
97         new GURL(spec_.data(), parsed_.Length(),
98                  *parsed_.inner_parsed(), true));
99   }
100
101 #ifndef NDEBUG
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.
105   if (is_valid_) {
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);
119
120       DCHECK(test_url.is_valid_ == is_valid_);
121       DCHECK(test_url.spec_ == spec_);
122
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);
131     }
132   }
133 #endif
134 }
135
136 GURL::~GURL() = default;
137
138 GURL& GURL::operator=(const GURL& other) {
139   spec_ = other.spec_;
140   is_valid_ = other.is_valid_;
141   parsed_ = other.parsed_;
142
143   if (!other.inner_url_)
144     inner_url_.reset();
145   else if (inner_url_)
146     *inner_url_ = *other.inner_url_;
147   else
148     inner_url_.reset(new GURL(*other.inner_url_));
149
150   return *this;
151 }
152
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_);
158
159   other.is_valid_ = false;
160   other.parsed_ = url::Parsed();
161   return *this;
162 }
163
164 const std::string& GURL::spec() const {
165   if (is_valid_ || spec_.empty())
166     return spec_;
167
168   DCHECK(false) << "Trying to get the spec of an invalid URL!";
169   return empty_string.Get();
170 }
171
172 bool GURL::operator<(const GURL& other) const {
173   return spec_ < other.spec_;
174 }
175
176 bool GURL::operator>(const GURL& other) const {
177   return spec_ > other.spec_;
178 }
179
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.
183   if (!is_valid_)
184     return GURL();
185
186   GURL result;
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.
193     return GURL();
194   }
195
196   output.Complete();
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));
202   }
203   return result;
204 }
205
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.
209   if (!is_valid_)
210     return GURL();
211
212   GURL result;
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.
219     return GURL();
220   }
221
222   output.Complete();
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));
228   }
229   return result;
230 }
231
232 // Note: code duplicated below (it's inconvenient to use a template here).
233 GURL GURL::ReplaceComponents(
234     const url::Replacements<char>& replacements) const {
235   GURL result;
236
237   // Not allowed for invalid URLs.
238   if (!is_valid_)
239     return GURL();
240
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_);
245
246   output.Complete();
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));
251   }
252   return result;
253 }
254
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 {
258   GURL result;
259
260   // Not allowed for invalid URLs.
261   if (!is_valid_)
262     return GURL();
263
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_);
268
269   output.Complete();
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));
274   }
275   return result;
276 }
277
278 GURL GURL::GetOrigin() const {
279   // This doesn't make sense for invalid or nonstandard URLs, so return
280   // the empty URL.
281   if (!is_valid_ || !IsStandard())
282     return GURL();
283
284   if (SchemeIsFileSystem())
285     return inner_url_->GetOrigin();
286
287   url::Replacements<char> replacements;
288   replacements.ClearUsername();
289   replacements.ClearPassword();
290   replacements.ClearPath();
291   replacements.ClearQuery();
292   replacements.ClearRef();
293
294   return ReplaceComponents(replacements);
295 }
296
297 GURL GURL::GetAsReferrer() const {
298   if (!SchemeIsValidForReferrer())
299     return GURL();
300
301   if (!has_ref() && !has_username() && !has_password())
302     return GURL(*this);
303
304   url::Replacements<char> replacements;
305   replacements.ClearRef();
306   replacements.ClearUsername();
307   replacements.ClearPassword();
308   return ReplaceComponents(replacements);
309 }
310
311 GURL GURL::GetWithEmptyPath() const {
312   // This doesn't make sense for invalid or nonstandard URLs, so return
313   // the empty URL.
314   if (!is_valid_ || !IsStandard())
315     return GURL();
316
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.
319   GURL other(*this);
320   if (parsed_.path.len == 0)
321     return other;
322
323   // Clear everything after the path.
324   other.parsed_.query.reset();
325   other.parsed_.ref.reset();
326
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);
332   return other;
333 }
334
335 GURL GURL::GetWithoutFilename() const {
336   return Resolve(".");
337 }
338
339 bool GURL::IsStandard() const {
340   return url::IsStandard(spec_.data(), parsed_.scheme);
341 }
342
343 bool GURL::IsAboutBlank() const {
344   if (!SchemeIs(url::kAboutScheme))
345     return false;
346
347   if (has_host() || has_username() || has_password() || has_port())
348     return false;
349
350   if (path() != url::kAboutBlankPath && path() != url::kAboutBlankWithHashPath)
351     return false;
352
353   return true;
354 }
355
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);
359
360   if (parsed_.scheme.len <= 0)
361     return lower_ascii_scheme.empty();
362   return scheme_piece() == lower_ascii_scheme;
363 }
364
365 bool GURL::SchemeIsHTTPOrHTTPS() const {
366   return SchemeIs(url::kHttpScheme) || SchemeIs(url::kHttpsScheme);
367 }
368
369 bool GURL::SchemeIsValidForReferrer() const {
370   return is_valid_ && IsReferrerScheme(spec_.data(), parsed_.scheme);
371 }
372
373 bool GURL::SchemeIsWSOrWSS() const {
374   return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
375 }
376
377 int GURL::IntPort() const {
378   if (parsed_.port.is_nonempty())
379     return url::ParsePort(spec_.data(), parsed_.port);
380   return url::PORT_UNSPECIFIED;
381 }
382
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,
387                                      parsed_.scheme.len);
388   return int_port;
389 }
390
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);
395 }
396
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);
405   }
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;
412
413   return std::string(spec_, parsed_.path.begin, path_len);
414 }
415
416 std::string GURL::HostNoBrackets() const {
417   return HostNoBracketsPiece().as_string();
418 }
419
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] == ']') {
424     h.begin++;
425     h.len -= 2;
426   }
427   return ComponentStringPiece(h);
428 }
429
430 std::string GURL::GetContent() const {
431   return is_valid_ ? ComponentString(parsed_.GetContent()) : std::string();
432 }
433
434 bool GURL::HostIsIPAddress() const {
435   return is_valid_ && url::HostIsIPAddress(host_piece());
436 }
437
438 const GURL& GURL::EmptyGURL() {
439   return empty_gurl.Get();
440 }
441
442 bool GURL::DomainIs(base::StringPiece canonical_domain) const {
443   if (!is_valid_)
444     return false;
445
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);
450 }
451
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);
458 }
459
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_);
465 }
466
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);
471 }
472
473 std::ostream& operator<<(std::ostream& out, const GURL& url) {
474   return out << url.possibly_invalid_spec();
475 }
476
477 bool operator==(const GURL& x, const GURL& y) {
478   return x.possibly_invalid_spec() == y.possibly_invalid_spec();
479 }
480
481 bool operator!=(const GURL& x, const GURL& y) {
482   return !(x == y);
483 }
484
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;
488 }
489
490 bool operator==(const base::StringPiece& spec, const GURL& x) {
491   return x == spec;
492 }
493
494 bool operator!=(const GURL& x, const base::StringPiece& spec) {
495   return !(x == spec);
496 }
497
498 bool operator!=(const base::StringPiece& spec, const GURL& x) {
499   return !(x == spec);
500 }