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
GURL()24 GURL::GURL() : is_valid_(false) {
25 }
26
GURL(const GURL & other)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
GURL(GURL && other)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
GURL(std::string_view url_string)46 GURL::GURL(std::string_view url_string) {
47 InitCanonical(url_string, true);
48 }
49
GURL(std::u16string_view url_string)50 GURL::GURL(std::u16string_view url_string) {
51 InitCanonical(url_string, true);
52 }
53
GURL(const std::string & url_string,RetainWhiteSpaceSelector)54 GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) {
55 InitCanonical(url_string, false);
56 }
57
GURL(const char * canonical_spec,size_t canonical_spec_len,const url::Parsed & parsed,bool is_valid)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
GURL(std::string canonical_spec,const url::Parsed & parsed,bool is_valid)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>
InitCanonical(T input_spec,bool trim_path_end)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
InitializeFromCanonicalSpec()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
operator =(const GURL & other)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
operator =(GURL && other)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
spec() const158 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 DUMP_WILL_BE_NOTREACHED_NORETURN()
165 << "Trying to get the spec of an invalid URL!";
166 return base::EmptyString();
167 }
168
operator <(const GURL & other) const169 bool GURL::operator<(const GURL& other) const {
170 return spec_ < other.spec_;
171 }
172
operator >(const GURL & other) const173 bool GURL::operator>(const GURL& other) const {
174 return spec_ > other.spec_;
175 }
176
177 // Note: code duplicated below (it's inconvenient to use a template here).
Resolve(std::string_view relative) const178 GURL GURL::Resolve(std::string_view relative) const {
179 // Not allowed for invalid URLs.
180 if (!is_valid_)
181 return GURL();
182
183 GURL result;
184 url::StdStringCanonOutput output(&result.spec_);
185 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
186 parsed_, relative.data(),
187 static_cast<int>(relative.length()),
188 nullptr, &output, &result.parsed_)) {
189 // Error resolving, return an empty URL.
190 return GURL();
191 }
192
193 output.Complete();
194 result.is_valid_ = true;
195 if (result.SchemeIsFileSystem()) {
196 result.inner_url_ =
197 std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
198 *result.parsed_.inner_parsed(), true);
199 }
200 return result;
201 }
202
203 // Note: code duplicated above (it's inconvenient to use a template here).
Resolve(std::u16string_view relative) const204 GURL GURL::Resolve(std::u16string_view relative) const {
205 // Not allowed for invalid URLs.
206 if (!is_valid_)
207 return GURL();
208
209 GURL result;
210 url::StdStringCanonOutput output(&result.spec_);
211 if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()),
212 parsed_, relative.data(),
213 static_cast<int>(relative.length()),
214 nullptr, &output, &result.parsed_)) {
215 // Error resolving, return an empty URL.
216 return GURL();
217 }
218
219 output.Complete();
220 result.is_valid_ = true;
221 if (result.SchemeIsFileSystem()) {
222 result.inner_url_ =
223 std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(),
224 *result.parsed_.inner_parsed(), true);
225 }
226 return result;
227 }
228
229 // Note: code duplicated below (it's inconvenient to use a template here).
ReplaceComponents(const Replacements & replacements) const230 GURL GURL::ReplaceComponents(const Replacements& replacements) const {
231 GURL result;
232
233 // Not allowed for invalid URLs.
234 if (!is_valid_)
235 return GURL();
236
237 url::StdStringCanonOutput output(&result.spec_);
238 result.is_valid_ = url::ReplaceComponents(
239 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
240 NULL, &output, &result.parsed_);
241
242 output.Complete();
243
244 result.ProcessFileSystemURLAfterReplaceComponents();
245 return result;
246 }
247
248 // Note: code duplicated above (it's inconvenient to use a template here).
ReplaceComponents(const ReplacementsW & replacements) const249 GURL GURL::ReplaceComponents(const ReplacementsW& replacements) const {
250 GURL result;
251
252 // Not allowed for invalid URLs.
253 if (!is_valid_)
254 return GURL();
255
256 url::StdStringCanonOutput output(&result.spec_);
257 result.is_valid_ = url::ReplaceComponents(
258 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
259 NULL, &output, &result.parsed_);
260
261 output.Complete();
262
263 result.ProcessFileSystemURLAfterReplaceComponents();
264
265 return result;
266 }
267
ProcessFileSystemURLAfterReplaceComponents()268 void GURL::ProcessFileSystemURLAfterReplaceComponents() {
269 if (!is_valid_)
270 return;
271 if (SchemeIsFileSystem()) {
272 inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(),
273 *parsed_.inner_parsed(), true);
274 }
275 }
276
DeprecatedGetOriginAsURL() const277 GURL GURL::DeprecatedGetOriginAsURL() const {
278 // This doesn't make sense for invalid or nonstandard URLs, so return
279 // the empty URL.
280 if (!is_valid_ || !IsStandard())
281 return GURL();
282
283 if (SchemeIsFileSystem())
284 return inner_url_->DeprecatedGetOriginAsURL();
285
286 Replacements replacements;
287 replacements.ClearUsername();
288 replacements.ClearPassword();
289 replacements.ClearPath();
290 replacements.ClearQuery();
291 replacements.ClearRef();
292
293 return ReplaceComponents(replacements);
294 }
295
GetAsReferrer() const296 GURL GURL::GetAsReferrer() const {
297 if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme))
298 return GURL();
299
300 if (!has_ref() && !has_username() && !has_password())
301 return GURL(*this);
302
303 Replacements replacements;
304 replacements.ClearRef();
305 replacements.ClearUsername();
306 replacements.ClearPassword();
307 return ReplaceComponents(replacements);
308 }
309
GetWithEmptyPath() const310 GURL GURL::GetWithEmptyPath() const {
311 // This doesn't make sense for invalid or nonstandard URLs, so return
312 // the empty URL.
313 if (!is_valid_ || !IsStandard())
314 return GURL();
315
316 // We could optimize this since we know that the URL is canonical, and we are
317 // appending a canonical path, so avoiding re-parsing.
318 GURL other(*this);
319 if (parsed_.path.len == 0)
320 return other;
321
322 // Clear everything after the path.
323 other.parsed_.query.reset();
324 other.parsed_.ref.reset();
325
326 // Set the path, since the path is longer than one, we can just set the
327 // first character and resize.
328 other.spec_[other.parsed_.path.begin] = '/';
329 other.parsed_.path.len = 1;
330 other.spec_.resize(other.parsed_.path.begin + 1);
331 return other;
332 }
333
GetWithoutFilename() const334 GURL GURL::GetWithoutFilename() const {
335 return Resolve(".");
336 }
337
GetWithoutRef() const338 GURL GURL::GetWithoutRef() const {
339 if (!has_ref())
340 return GURL(*this);
341
342 Replacements replacements;
343 replacements.ClearRef();
344 return ReplaceComponents(replacements);
345 }
346
IsStandard() const347 bool GURL::IsStandard() const {
348 return url::IsStandard(spec_.data(), parsed_.scheme);
349 }
350
IsAboutBlank() const351 bool GURL::IsAboutBlank() const {
352 return IsAboutUrl(url::kAboutBlankPath);
353 }
354
IsAboutSrcdoc() const355 bool GURL::IsAboutSrcdoc() const {
356 return IsAboutUrl(url::kAboutSrcdocPath);
357 }
358
SchemeIs(std::string_view lower_ascii_scheme) const359 bool GURL::SchemeIs(std::string_view lower_ascii_scheme) const {
360 DCHECK(base::IsStringASCII(lower_ascii_scheme));
361 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
362
363 if (!has_scheme())
364 return lower_ascii_scheme.empty();
365 return scheme_piece() == lower_ascii_scheme;
366 }
367
SchemeIsHTTPOrHTTPS() const368 bool GURL::SchemeIsHTTPOrHTTPS() const {
369 return SchemeIs(url::kHttpsScheme) || SchemeIs(url::kHttpScheme);
370 }
371
SchemeIsWSOrWSS() const372 bool GURL::SchemeIsWSOrWSS() const {
373 return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme);
374 }
375
SchemeIsCryptographic() const376 bool GURL::SchemeIsCryptographic() const {
377 if (!has_scheme())
378 return false;
379 return SchemeIsCryptographic(scheme_piece());
380 }
381
SchemeIsCryptographic(std::string_view lower_ascii_scheme)382 bool GURL::SchemeIsCryptographic(std::string_view lower_ascii_scheme) {
383 DCHECK(base::IsStringASCII(lower_ascii_scheme));
384 DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme);
385
386 return lower_ascii_scheme == url::kHttpsScheme ||
387 lower_ascii_scheme == url::kWssScheme;
388 }
389
SchemeIsLocal() const390 bool GURL::SchemeIsLocal() const {
391 // The `filesystem:` scheme is not in the Fetch spec, but Chromium still
392 // supports it in large part. It should be treated as a local scheme too.
393 return SchemeIs(url::kAboutScheme) || SchemeIs(url::kBlobScheme) ||
394 SchemeIs(url::kDataScheme) || SchemeIs(url::kFileSystemScheme);
395 }
396
IntPort() const397 int GURL::IntPort() const {
398 if (parsed_.port.is_nonempty())
399 return url::ParsePort(spec_.data(), parsed_.port);
400 return url::PORT_UNSPECIFIED;
401 }
402
EffectiveIntPort() const403 int GURL::EffectiveIntPort() const {
404 int int_port = IntPort();
405 if (int_port == url::PORT_UNSPECIFIED && IsStandard())
406 return url::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin,
407 parsed_.scheme.len);
408 return int_port;
409 }
410
ExtractFileName() const411 std::string GURL::ExtractFileName() const {
412 url::Component file_component;
413 url::ExtractFileName(spec_.data(), parsed_.path, &file_component);
414 return ComponentString(file_component);
415 }
416
PathForRequestPiece() const417 std::string_view GURL::PathForRequestPiece() const {
418 DCHECK(parsed_.path.is_nonempty())
419 << "Canonical path for requests should be non-empty";
420 if (parsed_.ref.is_valid()) {
421 // Clip off the reference when it exists. The reference starts after the
422 // #-sign, so we have to subtract one to also remove it.
423 return std::string_view(spec_).substr(
424 parsed_.path.begin, parsed_.ref.begin - parsed_.path.begin - 1);
425 }
426 // Compute the actual path length, rather than depending on the spec's
427 // terminator. If we're an inner_url, our spec continues on into our outer
428 // URL's path/query/ref.
429 int path_len = parsed_.path.len;
430 if (parsed_.query.is_valid())
431 path_len = parsed_.query.end() - parsed_.path.begin;
432
433 return std::string_view(spec_).substr(parsed_.path.begin, path_len);
434 }
435
PathForRequest() const436 std::string GURL::PathForRequest() const {
437 return std::string(PathForRequestPiece());
438 }
439
HostNoBrackets() const440 std::string GURL::HostNoBrackets() const {
441 return std::string(HostNoBracketsPiece());
442 }
443
HostNoBracketsPiece() const444 std::string_view GURL::HostNoBracketsPiece() const {
445 // If host looks like an IPv6 literal, strip the square brackets.
446 url::Component h(parsed_.host);
447 if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') {
448 h.begin++;
449 h.len -= 2;
450 }
451 return ComponentStringPiece(h);
452 }
453
GetContent() const454 std::string GURL::GetContent() const {
455 return std::string(GetContentPiece());
456 }
457
GetContentPiece() const458 std::string_view GURL::GetContentPiece() const {
459 if (!is_valid_)
460 return std::string_view();
461 url::Component content_component = parsed_.GetContent();
462 if (!SchemeIs(url::kJavaScriptScheme) && parsed_.ref.is_valid())
463 content_component.len -= parsed_.ref.len + 1;
464 return ComponentStringPiece(content_component);
465 }
466
HostIsIPAddress() const467 bool GURL::HostIsIPAddress() const {
468 return is_valid_ && url::HostIsIPAddress(host_piece());
469 }
470
EmptyGURL()471 const GURL& GURL::EmptyGURL() {
472 static base::NoDestructor<GURL> empty_gurl;
473 return *empty_gurl;
474 }
475
DomainIs(std::string_view canonical_domain) const476 bool GURL::DomainIs(std::string_view canonical_domain) const {
477 if (!is_valid_)
478 return false;
479
480 // FileSystem URLs have empty host_piece, so check this first.
481 if (inner_url_ && SchemeIsFileSystem())
482 return inner_url_->DomainIs(canonical_domain);
483 return url::DomainIs(host_piece(), canonical_domain);
484 }
485
EqualsIgnoringRef(const GURL & other) const486 bool GURL::EqualsIgnoringRef(const GURL& other) const {
487 int ref_position = parsed_.CountCharactersBefore(url::Parsed::REF, true);
488 int ref_position_other =
489 other.parsed_.CountCharactersBefore(url::Parsed::REF, true);
490 return std::string_view(spec_).substr(0, ref_position) ==
491 std::string_view(other.spec_).substr(0, ref_position_other);
492 }
493
Swap(GURL * other)494 void GURL::Swap(GURL* other) {
495 spec_.swap(other->spec_);
496 std::swap(is_valid_, other->is_valid_);
497 std::swap(parsed_, other->parsed_);
498 inner_url_.swap(other->inner_url_);
499 }
500
EstimateMemoryUsage() const501 size_t GURL::EstimateMemoryUsage() const {
502 return base::trace_event::EstimateMemoryUsage(spec_) +
503 base::trace_event::EstimateMemoryUsage(inner_url_) +
504 (parsed_.inner_parsed() ? sizeof(url::Parsed) : 0);
505 }
506
IsAboutUrl(std::string_view allowed_path) const507 bool GURL::IsAboutUrl(std::string_view allowed_path) const {
508 if (!SchemeIs(url::kAboutScheme))
509 return false;
510
511 if (has_host() || has_username() || has_password() || has_port())
512 return false;
513
514 return IsAboutPath(path_piece(), allowed_path);
515 }
516
517 // static
IsAboutPath(std::string_view actual_path,std::string_view allowed_path)518 bool GURL::IsAboutPath(std::string_view actual_path,
519 std::string_view allowed_path) {
520 if (!base::StartsWith(actual_path, allowed_path))
521 return false;
522
523 if (actual_path.size() == allowed_path.size()) {
524 DCHECK_EQ(actual_path, allowed_path);
525 return true;
526 }
527
528 if ((actual_path.size() == allowed_path.size() + 1) &&
529 actual_path.back() == '/') {
530 DCHECK_EQ(actual_path, std::string(allowed_path) + '/');
531 return true;
532 }
533
534 return false;
535 }
536
WriteIntoTrace(perfetto::TracedValue context) const537 void GURL::WriteIntoTrace(perfetto::TracedValue context) const {
538 std::move(context).WriteString(possibly_invalid_spec());
539 }
540
operator <<(std::ostream & out,const GURL & url)541 std::ostream& operator<<(std::ostream& out, const GURL& url) {
542 return out << url.possibly_invalid_spec();
543 }
544
operator ==(const GURL & x,const GURL & y)545 bool operator==(const GURL& x, const GURL& y) {
546 return x.possibly_invalid_spec() == y.possibly_invalid_spec();
547 }
548
operator !=(const GURL & x,const GURL & y)549 bool operator!=(const GURL& x, const GURL& y) {
550 return !(x == y);
551 }
552
operator ==(const GURL & x,std::string_view spec)553 bool operator==(const GURL& x, std::string_view spec) {
554 DCHECK_EQ(GURL(spec).possibly_invalid_spec(), spec)
555 << "Comparisons of GURLs and strings must ensure as a precondition that "
556 "the string is fully canonicalized.";
557 return x.possibly_invalid_spec() == spec;
558 }
559
operator ==(std::string_view spec,const GURL & x)560 bool operator==(std::string_view spec, const GURL& x) {
561 return x == spec;
562 }
563
operator !=(const GURL & x,std::string_view spec)564 bool operator!=(const GURL& x, std::string_view spec) {
565 return !(x == spec);
566 }
567
operator !=(std::string_view spec,const GURL & x)568 bool operator!=(std::string_view spec, const GURL& x) {
569 return !(x == spec);
570 }
571
572 namespace url::debug {
573
ScopedUrlCrashKey(base::debug::CrashKeyString * crash_key,const GURL & url)574 ScopedUrlCrashKey::ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key,
575 const GURL& url)
576 : scoped_string_value_(
577 crash_key,
578 url.is_empty() ? "<empty url>" : url.possibly_invalid_spec()) {}
579
580 ScopedUrlCrashKey::~ScopedUrlCrashKey() = default;
581
582 } // namespace url::debug
583