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.
5 #include "url/url_util.h"
13 #include "base/check_op.h"
14 #include "base/compiler_specific.h"
15 #include "base/containers/contains.h"
16 #include "base/no_destructor.h"
17 #include "base/strings/string_util.h"
18 #include "url/url_canon_internal.h"
19 #include "url/url_constants.h"
20 #include "url/url_file.h"
21 #include "url/url_util_internal.h"
27 // A pair for representing a standard scheme name and the SchemeType for it.
28 struct SchemeWithType {
33 // A pair for representing a scheme and a custom protocol handler for it.
35 // This pair of strings must be normalized protocol handler parameters as
36 // described in the Custom Handler specification.
37 // https://html.spec.whatwg.org/multipage/system-state.html#normalize-protocol-handler-parameters
38 struct SchemeWithHandler {
43 // List of currently registered schemes and associated properties.
44 struct SchemeRegistry {
45 // Standard format schemes (see header for details).
46 std::vector<SchemeWithType> standard_schemes = {
47 {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
48 {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
49 // Yes, file URLs can have a hostname, so file URLs should be handled as
50 // "standard". File URLs never have a port as specified by the SchemeType
51 // field. Unlike other SCHEME_WITH_HOST schemes, the 'host' in a file
52 // URL may be empty, a behavior which is special-cased during
54 {kFileScheme, SCHEME_WITH_HOST},
55 {kFtpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
57 SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // WebSocket secure.
58 {kWsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // WebSocket.
59 {kFileSystemScheme, SCHEME_WITHOUT_AUTHORITY},
60 #if BUILDFLAG(IS_TIZEN_TV)
61 {kDvbScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
62 {kTVKeyScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
63 {kOpAppScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
64 {kHbbTVCarouselScheme, SCHEME_WITH_HOST},
65 {kCIScheme, SCHEME_WITH_HOST},
69 // Schemes that are allowed for referrers.
71 // WARNING: Adding (1) a non-"standard" scheme or (2) a scheme whose URLs have
72 // opaque origins could lead to surprising behavior in some of the referrer
73 // generation logic. In order to avoid surprises, be sure to have adequate
74 // test coverage in each of the multiple code locations that compute
76 std::vector<SchemeWithType> referrer_schemes = {
77 {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
78 {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
81 // Schemes that do not trigger mixed content warning.
82 std::vector<std::string> secure_schemes = {
89 // Schemes that normal pages cannot link to or access (i.e., with the same
90 // security rules as those applied to "file" URLs).
91 std::vector<std::string> local_schemes = {
95 // Schemes that cause pages loaded with them to not have access to pages
96 // loaded with any other URL scheme.
97 std::vector<std::string> no_access_schemes = {
103 // Schemes that can be sent CORS requests.
104 std::vector<std::string> cors_enabled_schemes = {
110 // Schemes that can be used by web to store data (local storage, etc).
111 std::vector<std::string> web_storage_schemes = {
112 kHttpsScheme, kHttpScheme, kFileScheme, kFtpScheme, kWssScheme, kWsScheme,
115 // Schemes that can bypass the Content-Security-Policy (CSP) checks.
116 std::vector<std::string> csp_bypassing_schemes = {};
118 // Schemes that are strictly empty documents, allowing them to commit
120 std::vector<std::string> empty_document_schemes = {
124 // Schemes with a predefined default custom handler.
125 std::vector<SchemeWithHandler> predefined_handler_schemes;
127 bool allow_non_standard_schemes = false;
130 // See the LockSchemeRegistries declaration in the header.
131 bool scheme_registries_locked = false;
133 // Ensure that the schemes aren't modified after first use.
134 static std::atomic<bool> g_scheme_registries_used{false};
136 // Gets the scheme registry without locking the schemes. This should *only* be
137 // used for adding schemes to the registry.
138 SchemeRegistry* GetSchemeRegistryWithoutLocking() {
139 static base::NoDestructor<SchemeRegistry> registry;
140 return registry.get();
143 const SchemeRegistry& GetSchemeRegistry() {
145 g_scheme_registries_used.store(true);
147 return *GetSchemeRegistryWithoutLocking();
150 // Pass this enum through for methods which would like to know if whitespace
151 // removal is necessary.
152 enum WhitespaceRemovalPolicy {
154 DO_NOT_REMOVE_WHITESPACE,
157 // Given a string and a range inside the string, compares it to the given
158 // lower-case |compare_to| buffer.
159 template<typename CHAR>
160 inline bool DoCompareSchemeComponent(const CHAR* spec,
161 const Component& component,
162 const char* compare_to) {
163 if (component.is_empty())
164 return compare_to[0] == 0; // When component is empty, match empty scheme.
165 return base::EqualsCaseInsensitiveASCII(
166 std::basic_string_view(&spec[component.begin], component.len),
170 // Returns true and sets |type| to the SchemeType of the given scheme
171 // identified by |scheme| within |spec| if in |schemes|.
172 template<typename CHAR>
173 bool DoIsInSchemes(const CHAR* spec,
174 const Component& scheme,
176 const std::vector<SchemeWithType>& schemes) {
177 if (scheme.is_empty())
178 return false; // Empty or invalid schemes are non-standard.
180 for (const SchemeWithType& scheme_with_type : schemes) {
181 if (base::EqualsCaseInsensitiveASCII(
182 std::basic_string_view(&spec[scheme.begin], scheme.len),
183 scheme_with_type.scheme)) {
184 *type = scheme_with_type.type;
191 template<typename CHAR>
192 bool DoIsStandard(const CHAR* spec, const Component& scheme, SchemeType* type) {
193 return DoIsInSchemes(spec, scheme, type,
194 GetSchemeRegistry().standard_schemes);
198 template<typename CHAR>
199 bool DoFindAndCompareScheme(const CHAR* str,
202 Component* found_scheme) {
203 // Before extracting scheme, canonicalize the URL to remove any whitespace.
204 // This matches the canonicalization done in DoCanonicalize function.
205 STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
208 RemoveURLWhitespace(str, str_len, &whitespace_buffer, &spec_len, nullptr);
210 Component our_scheme;
211 if (!ExtractScheme(spec, spec_len, &our_scheme)) {
214 *found_scheme = Component();
218 *found_scheme = our_scheme;
219 return DoCompareSchemeComponent(spec, our_scheme, compare);
222 template <typename CHAR>
223 bool DoCanonicalize(const CHAR* spec,
226 WhitespaceRemovalPolicy whitespace_policy,
227 CharsetConverter* charset_converter,
229 Parsed* output_parsed) {
230 // Trim leading C0 control characters and spaces.
232 TrimURL(spec, &begin, &spec_len, trim_path_end);
233 DCHECK(0 <= begin && begin <= spec_len);
237 output->ReserveSizeIfNeeded(spec_len);
239 // Remove any whitespace from the middle of the relative URL if necessary.
240 // Possibly this will result in copying to the new buffer.
241 STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
242 if (whitespace_policy == REMOVE_WHITESPACE) {
243 spec = RemoveURLWhitespace(spec, spec_len, &whitespace_buffer, &spec_len,
244 &output_parsed->potentially_dangling_markup);
249 // For Windows, we allow things that look like absolute Windows paths to be
250 // fixed up magically to file URLs. This is done for IE compatibility. For
251 // example, this will change "c:/foo" into a file URL rather than treating
252 // it as a URL with the protocol "c". It also works for UNC ("\\foo\bar.txt").
253 // There is similar logic in url_canon_relative.cc for
255 // For Max & Unix, we don't do this (the equivalent would be "/foo/bar" which
256 // has no meaning as an absolute path name. This is because browsers on Mac
257 // & Unix don't generally do this, so there is no compatibility reason for
259 if (DoesBeginUNCPath(spec, 0, spec_len, false) ||
260 DoesBeginWindowsDriveSpec(spec, 0, spec_len)) {
261 ParseFileURL(spec, spec_len, &parsed_input);
262 return CanonicalizeFileURL(spec, spec_len, parsed_input, charset_converter,
263 output, output_parsed);
268 if (!ExtractScheme(spec, spec_len, &scheme))
271 // This is the parsed version of the input URL, we have to canonicalize it
272 // before storing it in our object.
274 SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
275 if (DoCompareSchemeComponent(spec, scheme, url::kFileScheme)) {
276 // File URLs are special.
277 ParseFileURL(spec, spec_len, &parsed_input);
278 success = CanonicalizeFileURL(spec, spec_len, parsed_input,
279 charset_converter, output, output_parsed);
280 } else if (DoCompareSchemeComponent(spec, scheme, url::kFileSystemScheme)) {
281 // Filesystem URLs are special.
282 ParseFileSystemURL(spec, spec_len, &parsed_input);
283 success = CanonicalizeFileSystemURL(spec, spec_len, parsed_input,
284 charset_converter, output,
287 } else if (DoIsStandard(spec, scheme, &scheme_type)) {
288 // All "normal" URLs.
289 ParseStandardURL(spec, spec_len, &parsed_input);
290 success = CanonicalizeStandardURL(spec, spec_len, parsed_input, scheme_type,
291 charset_converter, output, output_parsed);
293 } else if (DoCompareSchemeComponent(spec, scheme, url::kMailToScheme)) {
294 // Mailto URLs are treated like standard URLs, with only a scheme, path,
296 ParseMailtoURL(spec, spec_len, &parsed_input);
297 success = CanonicalizeMailtoURL(spec, spec_len, parsed_input, output,
301 // "Weird" URLs like data: and javascript:.
302 ParsePathURL(spec, spec_len, trim_path_end, &parsed_input);
303 success = CanonicalizePathURL(spec, spec_len, parsed_input, output,
309 template<typename CHAR>
310 bool DoResolveRelative(const char* base_spec,
312 const Parsed& base_parsed,
313 const CHAR* in_relative,
314 int in_relative_length,
315 CharsetConverter* charset_converter,
317 Parsed* output_parsed) {
318 // Remove any whitespace from the middle of the relative URL, possibly
319 // copying to the new buffer.
320 STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
322 const CHAR* relative = RemoveURLWhitespace(
323 in_relative, in_relative_length, &whitespace_buffer, &relative_length,
324 &output_parsed->potentially_dangling_markup);
326 bool base_is_authority_based = false;
327 bool base_is_hierarchical = false;
329 base_parsed.scheme.is_nonempty()) {
330 int after_scheme = base_parsed.scheme.end() + 1; // Skip past the colon.
331 int num_slashes = CountConsecutiveSlashes(base_spec, after_scheme,
333 base_is_authority_based = num_slashes > 1;
334 base_is_hierarchical = num_slashes > 0;
337 SchemeType unused_scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
338 bool standard_base_scheme =
339 base_parsed.scheme.is_nonempty() &&
340 DoIsStandard(base_spec, base_parsed.scheme, &unused_scheme_type);
343 Component relative_component;
344 if (!IsRelativeURL(base_spec, base_parsed, relative, relative_length,
345 (base_is_hierarchical || standard_base_scheme),
346 &is_relative, &relative_component)) {
351 // Don't reserve buffer space here. Instead, reserve in DoCanonicalize and
352 // ReserveRelativeURL, to enable more accurate buffer sizes.
354 // Pretend for a moment that |base_spec| is a standard URL. Normally
355 // non-standard URLs are treated as PathURLs, but if the base has an
356 // authority we would like to preserve it.
357 if (is_relative && base_is_authority_based && !standard_base_scheme) {
358 Parsed base_parsed_authority;
359 ParseStandardURL(base_spec, base_spec_len, &base_parsed_authority);
360 if (base_parsed_authority.host.is_nonempty()) {
361 STACK_UNINITIALIZED RawCanonOutputT<char> temporary_output;
362 bool did_resolve_succeed =
363 ResolveRelativeURL(base_spec, base_parsed_authority, false, relative,
364 relative_component, charset_converter,
365 &temporary_output, output_parsed);
366 // The output_parsed is incorrect at this point (because it was built
367 // based on base_parsed_authority instead of base_parsed) and needs to be
369 DoCanonicalize(temporary_output.data(), temporary_output.length(), true,
370 REMOVE_WHITESPACE, charset_converter, output,
372 return did_resolve_succeed;
374 } else if (is_relative) {
375 // Relative, resolve and canonicalize.
376 bool file_base_scheme = base_parsed.scheme.is_nonempty() &&
377 DoCompareSchemeComponent(base_spec, base_parsed.scheme, kFileScheme);
378 return ResolveRelativeURL(base_spec, base_parsed, file_base_scheme, relative,
379 relative_component, charset_converter, output,
383 // Not relative, canonicalize the input.
384 return DoCanonicalize(relative, relative_length, true,
385 DO_NOT_REMOVE_WHITESPACE, charset_converter, output,
389 template<typename CHAR>
390 bool DoReplaceComponents(const char* spec,
392 const Parsed& parsed,
393 const Replacements<CHAR>& replacements,
394 CharsetConverter* charset_converter,
396 Parsed* out_parsed) {
397 // If the scheme is overridden, just do a simple string substitution and
398 // re-parse the whole thing. There are lots of edge cases that we really don't
399 // want to deal with. Like what happens if I replace "http://e:8080/foo"
400 // with a file. Does it become "file:///E:/8080/foo" where the port number
401 // becomes part of the path? Parsing that string as a file URL says "yes"
402 // but almost no sane rule for dealing with the components individually would
403 // come up with that.
405 // Why allow these crazy cases at all? Programatically, there is almost no
406 // case for replacing the scheme. The most common case for hitting this is
407 // in JS when building up a URL using the location object. In this case, the
408 // JS code expects the string substitution behavior:
409 // http://www.w3.org/TR/2008/WD-html5-20080610/structured.html#common3
410 if (replacements.IsSchemeOverridden()) {
411 // Canonicalize the new scheme so it is 8-bit and can be concatenated with
412 // the existing spec.
413 STACK_UNINITIALIZED RawCanonOutput<128> scheme_replaced;
414 Component scheme_replaced_parsed;
415 CanonicalizeScheme(replacements.sources().scheme,
416 replacements.components().scheme,
417 &scheme_replaced, &scheme_replaced_parsed);
419 // We can assume that the input is canonicalized, which means it always has
420 // a colon after the scheme (or where the scheme would be).
421 int spec_after_colon = parsed.scheme.is_valid() ? parsed.scheme.end() + 1
423 if (spec_len - spec_after_colon > 0) {
424 scheme_replaced.Append(&spec[spec_after_colon],
425 spec_len - spec_after_colon);
428 // We now need to completely re-parse the resulting string since its meaning
429 // may have changed with the different scheme.
430 STACK_UNINITIALIZED RawCanonOutput<128> recanonicalized;
431 Parsed recanonicalized_parsed;
432 DoCanonicalize(scheme_replaced.data(), scheme_replaced.length(), true,
433 REMOVE_WHITESPACE, charset_converter, &recanonicalized,
434 &recanonicalized_parsed);
436 // Recurse using the version with the scheme already replaced. This will now
437 // use the replacement rules for the new scheme.
439 // Warning: this code assumes that ReplaceComponents will re-check all
440 // components for validity. This is because we can't fail if DoCanonicalize
441 // failed above since theoretically the thing making it fail could be
442 // getting replaced here. If ReplaceComponents didn't re-check everything,
443 // we wouldn't know if something *not* getting replaced is a problem.
444 // If the scheme-specific replacers are made more intelligent so they don't
445 // re-check everything, we should instead re-canonicalize the whole thing
446 // after this call to check validity (this assumes replacing the scheme is
447 // much much less common than other types of replacements, like clearing the
449 Replacements<CHAR> replacements_no_scheme = replacements;
450 replacements_no_scheme.SetScheme(NULL, Component());
451 // If the input URL has potentially dangling markup, set the flag on the
452 // output too. Note that in some cases the replacement gets rid of the
453 // potentially dangling markup, but this ok since the check will fail
455 if (parsed.potentially_dangling_markup) {
456 out_parsed->potentially_dangling_markup = true;
458 return DoReplaceComponents(recanonicalized.data(), recanonicalized.length(),
459 recanonicalized_parsed, replacements_no_scheme,
460 charset_converter, output, out_parsed);
463 // TODO(csharrison): We could be smarter about size to reserve if this is done
464 // in callers below, and the code checks to see which components are being
465 // replaced, and with what length. If this ends up being a hot spot it should
467 output->ReserveSizeIfNeeded(spec_len);
469 // If we get here, then we know the scheme doesn't need to be replaced, so can
470 // just key off the scheme in the spec to know how to do the replacements.
471 if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileScheme)) {
472 return ReplaceFileURL(spec, parsed, replacements, charset_converter, output,
475 if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileSystemScheme)) {
476 return ReplaceFileSystemURL(spec, parsed, replacements, charset_converter,
479 SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
480 if (DoIsStandard(spec, parsed.scheme, &scheme_type)) {
481 return ReplaceStandardURL(spec, parsed, replacements, scheme_type,
482 charset_converter, output, out_parsed);
484 if (DoCompareSchemeComponent(spec, parsed.scheme, url::kMailToScheme)) {
485 return ReplaceMailtoURL(spec, parsed, replacements, output, out_parsed);
488 // Default is a path URL.
489 return ReplacePathURL(spec, parsed, replacements, output, out_parsed);
492 void DoSchemeModificationPreamble() {
493 // If this assert triggers, it means you've called Add*Scheme after
494 // the SchemeRegistry has been used.
496 // This normally means you're trying to set up a new scheme too late or using
497 // the SchemeRegistry too early in your application's init process.
498 DCHECK(!g_scheme_registries_used.load())
499 << "Trying to add a scheme after the lists have been used. "
500 "Make sure that you haven't added any static GURL initializers in tests.";
502 // If this assert triggers, it means you've called Add*Scheme after
503 // LockSchemeRegistries has been called (see the header file for
504 // LockSchemeRegistries for more).
506 // This normally means you're trying to set up a new scheme too late in your
507 // application's init process. Locate where your app does this initialization
508 // and calls LockSchemeRegistries, and add your new scheme there.
509 DCHECK(!scheme_registries_locked)
510 << "Trying to add a scheme after the lists have been locked.";
513 void DoAddSchemeWithHandler(const char* new_scheme,
515 std::vector<SchemeWithHandler>* schemes) {
516 DoSchemeModificationPreamble();
518 DCHECK(strlen(new_scheme) > 0);
519 DCHECK(strlen(handler) > 0);
520 DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
521 DCHECK(!base::Contains(*schemes, new_scheme, &SchemeWithHandler::scheme));
522 schemes->push_back({new_scheme, handler});
525 void DoAddScheme(const char* new_scheme, std::vector<std::string>* schemes) {
526 DoSchemeModificationPreamble();
528 DCHECK(strlen(new_scheme) > 0);
529 DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
530 DCHECK(!base::Contains(*schemes, new_scheme));
531 schemes->push_back(new_scheme);
534 void DoAddSchemeWithType(const char* new_scheme,
536 std::vector<SchemeWithType>* schemes) {
537 DoSchemeModificationPreamble();
539 DCHECK(strlen(new_scheme) > 0);
540 DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
541 DCHECK(!base::Contains(*schemes, new_scheme, &SchemeWithType::scheme));
542 schemes->push_back({new_scheme, type});
547 void ClearSchemesForTests() {
548 DCHECK(!g_scheme_registries_used.load())
549 << "Schemes already used "
550 << "(use ScopedSchemeRegistryForTests to relax for tests).";
551 DCHECK(!scheme_registries_locked)
552 << "Schemes already locked "
553 << "(use ScopedSchemeRegistryForTests to relax for tests).";
554 *GetSchemeRegistryWithoutLocking() = SchemeRegistry();
557 class ScopedSchemeRegistryInternal {
559 ScopedSchemeRegistryInternal()
560 : registry_(std::make_unique<SchemeRegistry>(
561 *GetSchemeRegistryWithoutLocking())) {
562 g_scheme_registries_used.store(false);
563 scheme_registries_locked = false;
565 ~ScopedSchemeRegistryInternal() {
566 *GetSchemeRegistryWithoutLocking() = *registry_;
567 g_scheme_registries_used.store(true);
568 scheme_registries_locked = true;
572 std::unique_ptr<SchemeRegistry> registry_;
575 ScopedSchemeRegistryForTests::ScopedSchemeRegistryForTests()
576 : internal_(std::make_unique<ScopedSchemeRegistryInternal>()) {}
578 ScopedSchemeRegistryForTests::~ScopedSchemeRegistryForTests() = default;
580 void EnableNonStandardSchemesForAndroidWebView() {
581 DoSchemeModificationPreamble();
582 GetSchemeRegistryWithoutLocking()->allow_non_standard_schemes = true;
585 bool AllowNonStandardSchemesForAndroidWebView() {
586 return GetSchemeRegistry().allow_non_standard_schemes;
589 void AddStandardScheme(const char* new_scheme, SchemeType type) {
590 DoAddSchemeWithType(new_scheme, type,
591 &GetSchemeRegistryWithoutLocking()->standard_schemes);
594 std::vector<std::string> GetStandardSchemes() {
595 std::vector<std::string> result;
596 result.reserve(GetSchemeRegistry().standard_schemes.size());
597 for (const auto& entry : GetSchemeRegistry().standard_schemes) {
598 result.push_back(entry.scheme);
603 void AddReferrerScheme(const char* new_scheme, SchemeType type) {
604 DoAddSchemeWithType(new_scheme, type,
605 &GetSchemeRegistryWithoutLocking()->referrer_schemes);
608 void AddSecureScheme(const char* new_scheme) {
609 DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->secure_schemes);
612 const std::vector<std::string>& GetSecureSchemes() {
613 return GetSchemeRegistry().secure_schemes;
616 void AddLocalScheme(const char* new_scheme) {
617 DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->local_schemes);
620 const std::vector<std::string>& GetLocalSchemes() {
621 return GetSchemeRegistry().local_schemes;
624 void AddNoAccessScheme(const char* new_scheme) {
625 DoAddScheme(new_scheme,
626 &GetSchemeRegistryWithoutLocking()->no_access_schemes);
629 const std::vector<std::string>& GetNoAccessSchemes() {
630 return GetSchemeRegistry().no_access_schemes;
633 void AddCorsEnabledScheme(const char* new_scheme) {
634 DoAddScheme(new_scheme,
635 &GetSchemeRegistryWithoutLocking()->cors_enabled_schemes);
638 const std::vector<std::string>& GetCorsEnabledSchemes() {
639 return GetSchemeRegistry().cors_enabled_schemes;
642 void AddWebStorageScheme(const char* new_scheme) {
643 DoAddScheme(new_scheme,
644 &GetSchemeRegistryWithoutLocking()->web_storage_schemes);
647 const std::vector<std::string>& GetWebStorageSchemes() {
648 return GetSchemeRegistry().web_storage_schemes;
651 void AddCSPBypassingScheme(const char* new_scheme) {
652 DoAddScheme(new_scheme,
653 &GetSchemeRegistryWithoutLocking()->csp_bypassing_schemes);
656 const std::vector<std::string>& GetCSPBypassingSchemes() {
657 return GetSchemeRegistry().csp_bypassing_schemes;
660 void AddEmptyDocumentScheme(const char* new_scheme) {
661 DoAddScheme(new_scheme,
662 &GetSchemeRegistryWithoutLocking()->empty_document_schemes);
665 const std::vector<std::string>& GetEmptyDocumentSchemes() {
666 return GetSchemeRegistry().empty_document_schemes;
669 void AddPredefinedHandlerScheme(const char* new_scheme, const char* handler) {
670 DoAddSchemeWithHandler(
672 &GetSchemeRegistryWithoutLocking()->predefined_handler_schemes);
675 std::vector<std::pair<std::string, std::string>> GetPredefinedHandlerSchemes() {
676 std::vector<std::pair<std::string, std::string>> result;
677 result.reserve(GetSchemeRegistry().predefined_handler_schemes.size());
678 for (const SchemeWithHandler& entry :
679 GetSchemeRegistry().predefined_handler_schemes) {
680 result.emplace_back(entry.scheme, entry.handler);
685 void LockSchemeRegistries() {
686 scheme_registries_locked = true;
689 bool IsStandard(const char* spec, const Component& scheme) {
690 SchemeType unused_scheme_type;
691 return DoIsStandard(spec, scheme, &unused_scheme_type);
694 bool GetStandardSchemeType(const char* spec,
695 const Component& scheme,
697 return DoIsStandard(spec, scheme, type);
700 bool GetStandardSchemeType(const char16_t* spec,
701 const Component& scheme,
703 return DoIsStandard(spec, scheme, type);
706 bool IsStandard(const char16_t* spec, const Component& scheme) {
707 SchemeType unused_scheme_type;
708 return DoIsStandard(spec, scheme, &unused_scheme_type);
711 bool IsReferrerScheme(const char* spec, const Component& scheme) {
712 SchemeType unused_scheme_type;
713 return DoIsInSchemes(spec, scheme, &unused_scheme_type,
714 GetSchemeRegistry().referrer_schemes);
717 bool FindAndCompareScheme(const char* str,
720 Component* found_scheme) {
721 return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
724 bool FindAndCompareScheme(const char16_t* str,
727 Component* found_scheme) {
728 return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
731 bool DomainIs(std::string_view canonical_host,
732 std::string_view canonical_domain) {
733 if (canonical_host.empty() || canonical_domain.empty())
736 // If the host name ends with a dot but the input domain doesn't, then we
737 // ignore the dot in the host name.
738 size_t host_len = canonical_host.length();
739 if (canonical_host.back() == '.' && canonical_domain.back() != '.')
742 if (host_len < canonical_domain.length())
745 // |host_first_pos| is the start of the compared part of the host name, not
746 // start of the whole host name.
747 const char* host_first_pos =
748 canonical_host.data() + host_len - canonical_domain.length();
750 if (std::string_view(host_first_pos, canonical_domain.length()) !=
755 // Make sure there aren't extra characters in host before the compared part;
756 // if the host name is longer than the input domain name, then the character
757 // immediately before the compared part should be a dot. For example,
758 // www.google.com has domain "google.com", but www.iamnotgoogle.com does not.
759 if (canonical_domain[0] != '.' && host_len > canonical_domain.length() &&
760 *(host_first_pos - 1) != '.') {
767 bool HostIsIPAddress(std::string_view host) {
768 STACK_UNINITIALIZED url::RawCanonOutputT<char, 128> ignored_output;
769 url::CanonHostInfo host_info;
770 url::CanonicalizeIPAddress(host.data(), Component(0, host.length()),
771 &ignored_output, &host_info);
772 return host_info.IsIPAddress();
775 bool Canonicalize(const char* spec,
778 CharsetConverter* charset_converter,
780 Parsed* output_parsed) {
781 return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
782 charset_converter, output, output_parsed);
785 bool Canonicalize(const char16_t* spec,
788 CharsetConverter* charset_converter,
790 Parsed* output_parsed) {
791 return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
792 charset_converter, output, output_parsed);
795 bool ResolveRelative(const char* base_spec,
797 const Parsed& base_parsed,
798 const char* relative,
800 CharsetConverter* charset_converter,
802 Parsed* output_parsed) {
803 return DoResolveRelative(base_spec, base_spec_len, base_parsed,
804 relative, relative_length,
805 charset_converter, output, output_parsed);
808 bool ResolveRelative(const char* base_spec,
810 const Parsed& base_parsed,
811 const char16_t* relative,
813 CharsetConverter* charset_converter,
815 Parsed* output_parsed) {
816 return DoResolveRelative(base_spec, base_spec_len, base_parsed,
817 relative, relative_length,
818 charset_converter, output, output_parsed);
821 bool ReplaceComponents(const char* spec,
823 const Parsed& parsed,
824 const Replacements<char>& replacements,
825 CharsetConverter* charset_converter,
827 Parsed* out_parsed) {
828 return DoReplaceComponents(spec, spec_len, parsed, replacements,
829 charset_converter, output, out_parsed);
832 bool ReplaceComponents(const char* spec,
834 const Parsed& parsed,
835 const Replacements<char16_t>& replacements,
836 CharsetConverter* charset_converter,
838 Parsed* out_parsed) {
839 return DoReplaceComponents(spec, spec_len, parsed, replacements,
840 charset_converter, output, out_parsed);
843 void DecodeURLEscapeSequences(std::string_view input,
845 CanonOutputW* output) {
850 STACK_UNINITIALIZED RawCanonOutputT<char> unescaped_chars;
851 for (size_t i = 0; i < input.length(); i++) {
852 if (input[i] == '%') {
854 if (DecodeEscaped(input.data(), &i, input.length(), &ch)) {
855 unescaped_chars.push_back(ch);
857 // Invalid escape sequence, copy the percent literal.
858 unescaped_chars.push_back('%');
861 // Regular non-escaped 8-bit character.
862 unescaped_chars.push_back(input[i]);
866 int output_initial_length = output->length();
867 // Convert that 8-bit to UTF-16. It's not clear IE does this at all to
868 // JavaScript URLs, but Firefox and Safari do.
869 size_t unescaped_length = unescaped_chars.length();
870 for (size_t i = 0; i < unescaped_length; i++) {
871 unsigned char uch = static_cast<unsigned char>(unescaped_chars.at(i));
873 // Non-UTF-8, just append directly
874 output->push_back(uch);
876 // next_ch will point to the last character of the decoded
878 size_t next_character = i;
879 base_icu::UChar32 code_point;
880 if (ReadUTFCharLossy(unescaped_chars.data(), &next_character,
881 unescaped_length, &code_point)) {
882 // Valid UTF-8 character, convert to UTF-16.
883 AppendUTF16Value(code_point, output);
885 } else if (mode == DecodeURLMode::kUTF8) {
886 DCHECK_EQ(code_point, 0xFFFD);
887 AppendUTF16Value(code_point, output);
890 // If there are any sequences that are not valid UTF-8, we
891 // revert |output| changes, and promote any bytes to UTF-16. We
892 // copy all characters from the beginning to the end of the
893 // identified sequence.
894 output->set_length(output_initial_length);
895 for (size_t j = 0; j < unescaped_chars.length(); ++j)
896 output->push_back(static_cast<unsigned char>(unescaped_chars.at(j)));
903 void EncodeURIComponent(std::string_view input, CanonOutput* output) {
904 for (unsigned char c : input) {
905 if (IsComponentChar(c)) {
906 output->push_back(c);
908 AppendEscapedChar(c, output);
913 bool IsURIComponentChar(char c) {
914 return IsComponentChar(c);
917 bool CompareSchemeComponent(const char* spec,
918 const Component& component,
919 const char* compare_to) {
920 return DoCompareSchemeComponent(spec, component, compare_to);
923 bool CompareSchemeComponent(const char16_t* spec,
924 const Component& component,
925 const char* compare_to) {
926 return DoCompareSchemeComponent(spec, component, compare_to);
929 bool HasInvalidURLEscapeSequences(std::string_view input) {
930 for (size_t i = 0; i < input.size(); i++) {
931 if (input[i] == '%') {
933 if (!DecodeEscaped(input.data(), &i, input.size(), &ch)) {