fixup! Upload upstream chromium 85.0.4183.93
[platform/framework/web/chromium-efl.git] / url / url_util.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/url_util.h"
6
7 #include <stddef.h>
8 #include <string.h>
9 #include <atomic>
10
11 #include "base/check_op.h"
12 #include "base/compiler_specific.h"
13 #include "base/no_destructor.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "url/url_canon_internal.h"
17 #include "url/url_constants.h"
18 #include "url/url_file.h"
19 #include "url/url_util_internal.h"
20
21 namespace url {
22
23 namespace {
24
25 // A pair for representing a standard scheme name and the SchemeType for it.
26 struct SchemeWithType {
27   std::string scheme;
28   SchemeType type;
29 };
30
31 // List of currently registered schemes and associated properties.
32 struct SchemeRegistry {
33   // Standard format schemes (see header for details).
34   std::vector<SchemeWithType> standard_schemes = {
35       {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
36       {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
37       // Yes, file URLs can have a hostname, so file URLs should be handled as
38       // "standard". File URLs never have a port as specified by the SchemeType
39       // field.  Unlike other SCHEME_WITH_HOST schemes, the 'host' in a file
40       // URL may be empty, a behavior which is special-cased during
41       // canonicalization.
42       {kFileScheme, SCHEME_WITH_HOST},
43       {kFtpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
44       {kWssScheme,
45        SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},  // WebSocket secure.
46       {kWsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},  // WebSocket.
47       {kFileSystemScheme, SCHEME_WITHOUT_AUTHORITY},
48       {kQuicTransportScheme, SCHEME_WITH_HOST_AND_PORT},
49   };
50
51   // Schemes that are allowed for referrers.
52   //
53   // WARNING: Adding (1) a non-"standard" scheme or (2) a scheme whose URLs have
54   // opaque origins could lead to surprising behavior in some of the referrer
55   // generation logic. In order to avoid surprises, be sure to have adequate
56   // test coverage in each of the multiple code locations that compute
57   // referrers.
58   std::vector<SchemeWithType> referrer_schemes = {
59       {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
60       {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
61   };
62
63   // Schemes that do not trigger mixed content warning.
64   std::vector<std::string> secure_schemes = {
65       kHttpsScheme, kAboutScheme, kDataScheme, kQuicTransportScheme, kWssScheme,
66   };
67
68   // Schemes that normal pages cannot link to or access (i.e., with the same
69   // security rules as those applied to "file" URLs).
70   std::vector<std::string> local_schemes = {
71       kFileScheme,
72   };
73
74   // Schemes that cause pages loaded with them to not have access to pages
75   // loaded with any other URL scheme.
76   std::vector<std::string> no_access_schemes = {
77       kAboutScheme,
78       kJavaScriptScheme,
79       kDataScheme,
80   };
81
82   // Schemes that can be sent CORS requests.
83   std::vector<std::string> cors_enabled_schemes = {
84       kHttpsScheme,
85       kHttpScheme,
86       kDataScheme,
87   };
88
89   // Schemes that can be used by web to store data (local storage, etc).
90   std::vector<std::string> web_storage_schemes = {
91       kHttpsScheme, kHttpScheme, kFileScheme, kFtpScheme, kWssScheme, kWsScheme,
92   };
93
94   // Schemes that can bypass the Content-Security-Policy (CSP) checks.
95   std::vector<std::string> csp_bypassing_schemes = {};
96
97   // Schemes that are strictly empty documents, allowing them to commit
98   // synchronously.
99   std::vector<std::string> empty_document_schemes = {
100       kAboutScheme,
101   };
102
103   bool allow_non_standard_schemes = false;
104 };
105
106 // See the LockSchemeRegistries declaration in the header.
107 bool scheme_registries_locked = false;
108
109 // Ensure that the schemes aren't modified after first use.
110 static std::atomic<bool> g_scheme_registries_used{false};
111
112 // Gets the scheme registry without locking the schemes. This should *only* be
113 // used for adding schemes to the registry.
114 SchemeRegistry* GetSchemeRegistryWithoutLocking() {
115   static base::NoDestructor<SchemeRegistry> registry;
116   return registry.get();
117 }
118
119 const SchemeRegistry& GetSchemeRegistry() {
120 #if DCHECK_IS_ON()
121   g_scheme_registries_used.store(true);
122 #endif
123   return *GetSchemeRegistryWithoutLocking();
124 }
125
126 // Pass this enum through for methods which would like to know if whitespace
127 // removal is necessary.
128 enum WhitespaceRemovalPolicy {
129   REMOVE_WHITESPACE,
130   DO_NOT_REMOVE_WHITESPACE,
131 };
132
133 // This template converts a given character type to the corresponding
134 // StringPiece type.
135 template<typename CHAR> struct CharToStringPiece {
136 };
137 template<> struct CharToStringPiece<char> {
138   typedef base::StringPiece Piece;
139 };
140 template<> struct CharToStringPiece<base::char16> {
141   typedef base::StringPiece16 Piece;
142 };
143
144 // Given a string and a range inside the string, compares it to the given
145 // lower-case |compare_to| buffer.
146 template<typename CHAR>
147 inline bool DoCompareSchemeComponent(const CHAR* spec,
148                                      const Component& component,
149                                      const char* compare_to) {
150   if (!component.is_nonempty())
151     return compare_to[0] == 0;  // When component is empty, match empty scheme.
152   return base::LowerCaseEqualsASCII(
153       typename CharToStringPiece<CHAR>::Piece(
154           &spec[component.begin], component.len),
155       compare_to);
156 }
157
158 // Returns true and sets |type| to the SchemeType of the given scheme
159 // identified by |scheme| within |spec| if in |schemes|.
160 template<typename CHAR>
161 bool DoIsInSchemes(const CHAR* spec,
162                    const Component& scheme,
163                    SchemeType* type,
164                    const std::vector<SchemeWithType>& schemes) {
165   if (!scheme.is_nonempty())
166     return false;  // Empty or invalid schemes are non-standard.
167
168   for (const SchemeWithType& scheme_with_type : schemes) {
169     if (base::LowerCaseEqualsASCII(typename CharToStringPiece<CHAR>::Piece(
170                                        &spec[scheme.begin], scheme.len),
171                                    scheme_with_type.scheme)) {
172       *type = scheme_with_type.type;
173       return true;
174     }
175   }
176   return false;
177 }
178
179 template<typename CHAR>
180 bool DoIsStandard(const CHAR* spec, const Component& scheme, SchemeType* type) {
181   return DoIsInSchemes(spec, scheme, type,
182                        GetSchemeRegistry().standard_schemes);
183 }
184
185
186 template<typename CHAR>
187 bool DoFindAndCompareScheme(const CHAR* str,
188                             int str_len,
189                             const char* compare,
190                             Component* found_scheme) {
191   // Before extracting scheme, canonicalize the URL to remove any whitespace.
192   // This matches the canonicalization done in DoCanonicalize function.
193   STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
194   int spec_len;
195   const CHAR* spec =
196       RemoveURLWhitespace(str, str_len, &whitespace_buffer, &spec_len, nullptr);
197
198   Component our_scheme;
199   if (!ExtractScheme(spec, spec_len, &our_scheme)) {
200     // No scheme.
201     if (found_scheme)
202       *found_scheme = Component();
203     return false;
204   }
205   if (found_scheme)
206     *found_scheme = our_scheme;
207   return DoCompareSchemeComponent(spec, our_scheme, compare);
208 }
209
210 template <typename CHAR>
211 bool DoCanonicalize(const CHAR* spec,
212                     int spec_len,
213                     bool trim_path_end,
214                     WhitespaceRemovalPolicy whitespace_policy,
215                     CharsetConverter* charset_converter,
216                     CanonOutput* output,
217                     Parsed* output_parsed) {
218   output->ReserveSizeIfNeeded(spec_len);
219
220   // Remove any whitespace from the middle of the relative URL if necessary.
221   // Possibly this will result in copying to the new buffer.
222   STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
223   if (whitespace_policy == REMOVE_WHITESPACE) {
224     spec = RemoveURLWhitespace(spec, spec_len, &whitespace_buffer, &spec_len,
225                                &output_parsed->potentially_dangling_markup);
226   }
227
228   Parsed parsed_input;
229 #ifdef WIN32
230   // For Windows, we allow things that look like absolute Windows paths to be
231   // fixed up magically to file URLs. This is done for IE compatibility. For
232   // example, this will change "c:/foo" into a file URL rather than treating
233   // it as a URL with the protocol "c". It also works for UNC ("\\foo\bar.txt").
234   // There is similar logic in url_canon_relative.cc for
235   //
236   // For Max & Unix, we don't do this (the equivalent would be "/foo/bar" which
237   // has no meaning as an absolute path name. This is because browsers on Mac
238   // & Unix don't generally do this, so there is no compatibility reason for
239   // doing so.
240   if (DoesBeginUNCPath(spec, 0, spec_len, false) ||
241       DoesBeginWindowsDriveSpec(spec, 0, spec_len)) {
242     ParseFileURL(spec, spec_len, &parsed_input);
243     return CanonicalizeFileURL(spec, spec_len, parsed_input, charset_converter,
244                                output, output_parsed);
245   }
246 #endif
247
248   Component scheme;
249   if (!ExtractScheme(spec, spec_len, &scheme))
250     return false;
251
252   // This is the parsed version of the input URL, we have to canonicalize it
253   // before storing it in our object.
254   bool success;
255   SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
256   if (DoCompareSchemeComponent(spec, scheme, url::kFileScheme)) {
257     // File URLs are special.
258     ParseFileURL(spec, spec_len, &parsed_input);
259     success = CanonicalizeFileURL(spec, spec_len, parsed_input,
260                                   charset_converter, output, output_parsed);
261   } else if (DoCompareSchemeComponent(spec, scheme, url::kFileSystemScheme)) {
262     // Filesystem URLs are special.
263     ParseFileSystemURL(spec, spec_len, &parsed_input);
264     success = CanonicalizeFileSystemURL(spec, spec_len, parsed_input,
265                                         charset_converter, output,
266                                         output_parsed);
267
268   } else if (DoIsStandard(spec, scheme, &scheme_type)) {
269     // All "normal" URLs.
270     ParseStandardURL(spec, spec_len, &parsed_input);
271     success = CanonicalizeStandardURL(spec, spec_len, parsed_input, scheme_type,
272                                       charset_converter, output, output_parsed);
273
274   } else if (DoCompareSchemeComponent(spec, scheme, url::kMailToScheme)) {
275     // Mailto URLs are treated like standard URLs, with only a scheme, path,
276     // and query.
277     ParseMailtoURL(spec, spec_len, &parsed_input);
278     success = CanonicalizeMailtoURL(spec, spec_len, parsed_input, output,
279                                     output_parsed);
280
281   } else {
282     // "Weird" URLs like data: and javascript:.
283     ParsePathURL(spec, spec_len, trim_path_end, &parsed_input);
284     success = CanonicalizePathURL(spec, spec_len, parsed_input, output,
285                                   output_parsed);
286   }
287   return success;
288 }
289
290 template<typename CHAR>
291 bool DoResolveRelative(const char* base_spec,
292                        int base_spec_len,
293                        const Parsed& base_parsed,
294                        const CHAR* in_relative,
295                        int in_relative_length,
296                        CharsetConverter* charset_converter,
297                        CanonOutput* output,
298                        Parsed* output_parsed) {
299   // Remove any whitespace from the middle of the relative URL, possibly
300   // copying to the new buffer.
301   STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
302   int relative_length;
303   const CHAR* relative = RemoveURLWhitespace(
304       in_relative, in_relative_length, &whitespace_buffer, &relative_length,
305       &output_parsed->potentially_dangling_markup);
306
307   bool base_is_authority_based = false;
308   bool base_is_hierarchical = false;
309   if (base_spec &&
310       base_parsed.scheme.is_nonempty()) {
311     int after_scheme = base_parsed.scheme.end() + 1;  // Skip past the colon.
312     int num_slashes = CountConsecutiveSlashes(base_spec, after_scheme,
313                                               base_spec_len);
314     base_is_authority_based = num_slashes > 1;
315     base_is_hierarchical = num_slashes > 0;
316   }
317
318   SchemeType unused_scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
319   bool standard_base_scheme =
320       base_parsed.scheme.is_nonempty() &&
321       DoIsStandard(base_spec, base_parsed.scheme, &unused_scheme_type);
322
323   bool is_relative;
324   Component relative_component;
325   if (!IsRelativeURL(base_spec, base_parsed, relative, relative_length,
326                      (base_is_hierarchical || standard_base_scheme),
327                      &is_relative, &relative_component)) {
328     // Error resolving.
329     return false;
330   }
331
332   // Don't reserve buffer space here. Instead, reserve in DoCanonicalize and
333   // ReserveRelativeURL, to enable more accurate buffer sizes.
334
335   // Pretend for a moment that |base_spec| is a standard URL. Normally
336   // non-standard URLs are treated as PathURLs, but if the base has an
337   // authority we would like to preserve it.
338   if (is_relative && base_is_authority_based && !standard_base_scheme) {
339     Parsed base_parsed_authority;
340     ParseStandardURL(base_spec, base_spec_len, &base_parsed_authority);
341     if (base_parsed_authority.host.is_nonempty()) {
342       STACK_UNINITIALIZED RawCanonOutputT<char> temporary_output;
343       bool did_resolve_succeed =
344           ResolveRelativeURL(base_spec, base_parsed_authority, false, relative,
345                              relative_component, charset_converter,
346                              &temporary_output, output_parsed);
347       // The output_parsed is incorrect at this point (because it was built
348       // based on base_parsed_authority instead of base_parsed) and needs to be
349       // re-created.
350       DoCanonicalize(temporary_output.data(), temporary_output.length(), true,
351                      REMOVE_WHITESPACE, charset_converter, output,
352                      output_parsed);
353       return did_resolve_succeed;
354     }
355   } else if (is_relative) {
356     // Relative, resolve and canonicalize.
357     bool file_base_scheme = base_parsed.scheme.is_nonempty() &&
358         DoCompareSchemeComponent(base_spec, base_parsed.scheme, kFileScheme);
359     return ResolveRelativeURL(base_spec, base_parsed, file_base_scheme, relative,
360                               relative_component, charset_converter, output,
361                               output_parsed);
362   }
363
364   // Not relative, canonicalize the input.
365   return DoCanonicalize(relative, relative_length, true,
366                         DO_NOT_REMOVE_WHITESPACE, charset_converter, output,
367                         output_parsed);
368 }
369
370 template<typename CHAR>
371 bool DoReplaceComponents(const char* spec,
372                          int spec_len,
373                          const Parsed& parsed,
374                          const Replacements<CHAR>& replacements,
375                          CharsetConverter* charset_converter,
376                          CanonOutput* output,
377                          Parsed* out_parsed) {
378   // If the scheme is overridden, just do a simple string substitution and
379   // re-parse the whole thing. There are lots of edge cases that we really don't
380   // want to deal with. Like what happens if I replace "http://e:8080/foo"
381   // with a file. Does it become "file:///E:/8080/foo" where the port number
382   // becomes part of the path? Parsing that string as a file URL says "yes"
383   // but almost no sane rule for dealing with the components individually would
384   // come up with that.
385   //
386   // Why allow these crazy cases at all? Programatically, there is almost no
387   // case for replacing the scheme. The most common case for hitting this is
388   // in JS when building up a URL using the location object. In this case, the
389   // JS code expects the string substitution behavior:
390   //   http://www.w3.org/TR/2008/WD-html5-20080610/structured.html#common3
391   if (replacements.IsSchemeOverridden()) {
392     // Canonicalize the new scheme so it is 8-bit and can be concatenated with
393     // the existing spec.
394     STACK_UNINITIALIZED RawCanonOutput<128> scheme_replaced;
395     Component scheme_replaced_parsed;
396     CanonicalizeScheme(replacements.sources().scheme,
397                        replacements.components().scheme,
398                        &scheme_replaced, &scheme_replaced_parsed);
399
400     // We can assume that the input is canonicalized, which means it always has
401     // a colon after the scheme (or where the scheme would be).
402     int spec_after_colon = parsed.scheme.is_valid() ? parsed.scheme.end() + 1
403                                                     : 1;
404     if (spec_len - spec_after_colon > 0) {
405       scheme_replaced.Append(&spec[spec_after_colon],
406                              spec_len - spec_after_colon);
407     }
408
409     // We now need to completely re-parse the resulting string since its meaning
410     // may have changed with the different scheme.
411     STACK_UNINITIALIZED RawCanonOutput<128> recanonicalized;
412     Parsed recanonicalized_parsed;
413     DoCanonicalize(scheme_replaced.data(), scheme_replaced.length(), true,
414                    REMOVE_WHITESPACE, charset_converter, &recanonicalized,
415                    &recanonicalized_parsed);
416
417     // Recurse using the version with the scheme already replaced. This will now
418     // use the replacement rules for the new scheme.
419     //
420     // Warning: this code assumes that ReplaceComponents will re-check all
421     // components for validity. This is because we can't fail if DoCanonicalize
422     // failed above since theoretically the thing making it fail could be
423     // getting replaced here. If ReplaceComponents didn't re-check everything,
424     // we wouldn't know if something *not* getting replaced is a problem.
425     // If the scheme-specific replacers are made more intelligent so they don't
426     // re-check everything, we should instead re-canonicalize the whole thing
427     // after this call to check validity (this assumes replacing the scheme is
428     // much much less common than other types of replacements, like clearing the
429     // ref).
430     Replacements<CHAR> replacements_no_scheme = replacements;
431     replacements_no_scheme.SetScheme(NULL, Component());
432     return DoReplaceComponents(recanonicalized.data(), recanonicalized.length(),
433                                recanonicalized_parsed, replacements_no_scheme,
434                                charset_converter, output, out_parsed);
435   }
436
437   // TODO(csharrison): We could be smarter about size to reserve if this is done
438   // in callers below, and the code checks to see which components are being
439   // replaced, and with what length. If this ends up being a hot spot it should
440   // be changed.
441   output->ReserveSizeIfNeeded(spec_len);
442
443   // If we get here, then we know the scheme doesn't need to be replaced, so can
444   // just key off the scheme in the spec to know how to do the replacements.
445   if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileScheme)) {
446     return ReplaceFileURL(spec, parsed, replacements, charset_converter, output,
447                           out_parsed);
448   }
449   if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileSystemScheme)) {
450     return ReplaceFileSystemURL(spec, parsed, replacements, charset_converter,
451                                 output, out_parsed);
452   }
453   SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
454   if (DoIsStandard(spec, parsed.scheme, &scheme_type)) {
455     return ReplaceStandardURL(spec, parsed, replacements, scheme_type,
456                               charset_converter, output, out_parsed);
457   }
458   if (DoCompareSchemeComponent(spec, parsed.scheme, url::kMailToScheme)) {
459     return ReplaceMailtoURL(spec, parsed, replacements, output, out_parsed);
460   }
461
462   // Default is a path URL.
463   return ReplacePathURL(spec, parsed, replacements, output, out_parsed);
464 }
465
466 void DoSchemeModificationPreamble() {
467   // If this assert triggers, it means you've called Add*Scheme after
468   // the SchemeRegistry has been used.
469   //
470   // This normally means you're trying to set up a new scheme too late or using
471   // the SchemeRegistry too early in your application's init process. Make sure
472   // that you haven't added any static GURL initializers in tests.
473   DCHECK(!g_scheme_registries_used.load())
474       << "Trying to add a scheme after the lists have been used.";
475
476   // If this assert triggers, it means you've called Add*Scheme after
477   // LockSchemeRegistries has been called (see the header file for
478   // LockSchemeRegistries for more).
479   //
480   // This normally means you're trying to set up a new scheme too late in your
481   // application's init process. Locate where your app does this initialization
482   // and calls LockSchemeRegistries, and add your new scheme there.
483   DCHECK(!scheme_registries_locked)
484       << "Trying to add a scheme after the lists have been locked.";
485 }
486
487 void DoAddScheme(const char* new_scheme, std::vector<std::string>* schemes) {
488   DoSchemeModificationPreamble();
489   DCHECK(schemes);
490   DCHECK(strlen(new_scheme) > 0);
491   DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
492   DCHECK(std::find(schemes->begin(), schemes->end(), new_scheme) ==
493          schemes->end());
494   schemes->push_back(new_scheme);
495 }
496
497 void DoAddSchemeWithType(const char* new_scheme,
498                          SchemeType type,
499                          std::vector<SchemeWithType>* schemes) {
500   DoSchemeModificationPreamble();
501   DCHECK(schemes);
502   DCHECK(strlen(new_scheme) > 0);
503   DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
504   DCHECK(std::find_if(schemes->begin(), schemes->end(),
505                       [&new_scheme](const SchemeWithType& scheme) {
506                         return scheme.scheme == new_scheme;
507                       }) == schemes->end());
508   schemes->push_back({new_scheme, type});
509 }
510
511 }  // namespace
512
513 void ClearSchemesForTests() {
514   DCHECK(!g_scheme_registries_used.load())
515       << "Schemes already used "
516       << "(use ScopedSchemeRegistryForTests to relax for tests).";
517   DCHECK(!scheme_registries_locked)
518       << "Schemes already locked "
519       << "(use ScopedSchemeRegistryForTests to relax for tests).";
520   *GetSchemeRegistryWithoutLocking() = SchemeRegistry();
521 }
522
523 class ScopedSchemeRegistryInternal {
524  public:
525   ScopedSchemeRegistryInternal()
526       : registry_(std::make_unique<SchemeRegistry>(
527             *GetSchemeRegistryWithoutLocking())) {
528     g_scheme_registries_used.store(false);
529     scheme_registries_locked = false;
530   }
531   ~ScopedSchemeRegistryInternal() {
532     *GetSchemeRegistryWithoutLocking() = *registry_;
533     g_scheme_registries_used.store(true);
534     scheme_registries_locked = true;
535   }
536
537  private:
538   std::unique_ptr<SchemeRegistry> registry_;
539 };
540
541 ScopedSchemeRegistryForTests::ScopedSchemeRegistryForTests()
542     : internal_(std::make_unique<ScopedSchemeRegistryInternal>()) {}
543
544 ScopedSchemeRegistryForTests::~ScopedSchemeRegistryForTests() = default;
545
546 void EnableNonStandardSchemesForAndroidWebView() {
547   DoSchemeModificationPreamble();
548   GetSchemeRegistryWithoutLocking()->allow_non_standard_schemes = true;
549 }
550
551 bool AllowNonStandardSchemesForAndroidWebView() {
552   return GetSchemeRegistry().allow_non_standard_schemes;
553 }
554
555 void AddStandardScheme(const char* new_scheme, SchemeType type) {
556   DoAddSchemeWithType(new_scheme, type,
557                       &GetSchemeRegistryWithoutLocking()->standard_schemes);
558 }
559
560 void AddReferrerScheme(const char* new_scheme, SchemeType type) {
561   DoAddSchemeWithType(new_scheme, type,
562                       &GetSchemeRegistryWithoutLocking()->referrer_schemes);
563 }
564
565 void AddSecureScheme(const char* new_scheme) {
566   DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->secure_schemes);
567 }
568
569 const std::vector<std::string>& GetSecureSchemes() {
570   return GetSchemeRegistry().secure_schemes;
571 }
572
573 void AddLocalScheme(const char* new_scheme) {
574   DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->local_schemes);
575 }
576
577 const std::vector<std::string>& GetLocalSchemes() {
578   return GetSchemeRegistry().local_schemes;
579 }
580
581 void AddNoAccessScheme(const char* new_scheme) {
582   DoAddScheme(new_scheme,
583               &GetSchemeRegistryWithoutLocking()->no_access_schemes);
584 }
585
586 const std::vector<std::string>& GetNoAccessSchemes() {
587   return GetSchemeRegistry().no_access_schemes;
588 }
589
590 void AddCorsEnabledScheme(const char* new_scheme) {
591   DoAddScheme(new_scheme,
592               &GetSchemeRegistryWithoutLocking()->cors_enabled_schemes);
593 }
594
595 const std::vector<std::string>& GetCorsEnabledSchemes() {
596   return GetSchemeRegistry().cors_enabled_schemes;
597 }
598
599 void AddWebStorageScheme(const char* new_scheme) {
600   DoAddScheme(new_scheme,
601               &GetSchemeRegistryWithoutLocking()->web_storage_schemes);
602 }
603
604 const std::vector<std::string>& GetWebStorageSchemes() {
605   return GetSchemeRegistry().web_storage_schemes;
606 }
607
608 void AddCSPBypassingScheme(const char* new_scheme) {
609   DoAddScheme(new_scheme,
610               &GetSchemeRegistryWithoutLocking()->csp_bypassing_schemes);
611 }
612
613 const std::vector<std::string>& GetCSPBypassingSchemes() {
614   return GetSchemeRegistry().csp_bypassing_schemes;
615 }
616
617 void AddEmptyDocumentScheme(const char* new_scheme) {
618   DoAddScheme(new_scheme,
619               &GetSchemeRegistryWithoutLocking()->empty_document_schemes);
620 }
621
622 const std::vector<std::string>& GetEmptyDocumentSchemes() {
623   return GetSchemeRegistry().empty_document_schemes;
624 }
625
626 void LockSchemeRegistries() {
627   scheme_registries_locked = true;
628 }
629
630 bool IsStandard(const char* spec, const Component& scheme) {
631   SchemeType unused_scheme_type;
632   return DoIsStandard(spec, scheme, &unused_scheme_type);
633 }
634
635 bool GetStandardSchemeType(const char* spec,
636                            const Component& scheme,
637                            SchemeType* type) {
638   return DoIsStandard(spec, scheme, type);
639 }
640
641 bool GetStandardSchemeType(const base::char16* spec,
642                            const Component& scheme,
643                            SchemeType* type) {
644   return DoIsStandard(spec, scheme, type);
645 }
646
647 bool IsStandard(const base::char16* spec, const Component& scheme) {
648   SchemeType unused_scheme_type;
649   return DoIsStandard(spec, scheme, &unused_scheme_type);
650 }
651
652 bool IsReferrerScheme(const char* spec, const Component& scheme) {
653   SchemeType unused_scheme_type;
654   return DoIsInSchemes(spec, scheme, &unused_scheme_type,
655                        GetSchemeRegistry().referrer_schemes);
656 }
657
658 bool FindAndCompareScheme(const char* str,
659                           int str_len,
660                           const char* compare,
661                           Component* found_scheme) {
662   return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
663 }
664
665 bool FindAndCompareScheme(const base::char16* str,
666                           int str_len,
667                           const char* compare,
668                           Component* found_scheme) {
669   return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
670 }
671
672 bool DomainIs(base::StringPiece canonical_host,
673               base::StringPiece canonical_domain) {
674   if (canonical_host.empty() || canonical_domain.empty())
675     return false;
676
677   // If the host name ends with a dot but the input domain doesn't, then we
678   // ignore the dot in the host name.
679   size_t host_len = canonical_host.length();
680   if (canonical_host.back() == '.' && canonical_domain.back() != '.')
681     --host_len;
682
683   if (host_len < canonical_domain.length())
684     return false;
685
686   // |host_first_pos| is the start of the compared part of the host name, not
687   // start of the whole host name.
688   const char* host_first_pos =
689       canonical_host.data() + host_len - canonical_domain.length();
690
691   if (base::StringPiece(host_first_pos, canonical_domain.length()) !=
692       canonical_domain) {
693     return false;
694   }
695
696   // Make sure there aren't extra characters in host before the compared part;
697   // if the host name is longer than the input domain name, then the character
698   // immediately before the compared part should be a dot. For example,
699   // www.google.com has domain "google.com", but www.iamnotgoogle.com does not.
700   if (canonical_domain[0] != '.' && host_len > canonical_domain.length() &&
701       *(host_first_pos - 1) != '.') {
702     return false;
703   }
704
705   return true;
706 }
707
708 bool HostIsIPAddress(base::StringPiece host) {
709   STACK_UNINITIALIZED url::RawCanonOutputT<char, 128> ignored_output;
710   url::CanonHostInfo host_info;
711   url::CanonicalizeIPAddress(host.data(), Component(0, host.length()),
712                              &ignored_output, &host_info);
713   return host_info.IsIPAddress();
714 }
715
716 bool Canonicalize(const char* spec,
717                   int spec_len,
718                   bool trim_path_end,
719                   CharsetConverter* charset_converter,
720                   CanonOutput* output,
721                   Parsed* output_parsed) {
722   return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
723                         charset_converter, output, output_parsed);
724 }
725
726 bool Canonicalize(const base::char16* spec,
727                   int spec_len,
728                   bool trim_path_end,
729                   CharsetConverter* charset_converter,
730                   CanonOutput* output,
731                   Parsed* output_parsed) {
732   return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
733                         charset_converter, output, output_parsed);
734 }
735
736 bool ResolveRelative(const char* base_spec,
737                      int base_spec_len,
738                      const Parsed& base_parsed,
739                      const char* relative,
740                      int relative_length,
741                      CharsetConverter* charset_converter,
742                      CanonOutput* output,
743                      Parsed* output_parsed) {
744   return DoResolveRelative(base_spec, base_spec_len, base_parsed,
745                            relative, relative_length,
746                            charset_converter, output, output_parsed);
747 }
748
749 bool ResolveRelative(const char* base_spec,
750                      int base_spec_len,
751                      const Parsed& base_parsed,
752                      const base::char16* relative,
753                      int relative_length,
754                      CharsetConverter* charset_converter,
755                      CanonOutput* output,
756                      Parsed* output_parsed) {
757   return DoResolveRelative(base_spec, base_spec_len, base_parsed,
758                            relative, relative_length,
759                            charset_converter, output, output_parsed);
760 }
761
762 bool ReplaceComponents(const char* spec,
763                        int spec_len,
764                        const Parsed& parsed,
765                        const Replacements<char>& replacements,
766                        CharsetConverter* charset_converter,
767                        CanonOutput* output,
768                        Parsed* out_parsed) {
769   return DoReplaceComponents(spec, spec_len, parsed, replacements,
770                              charset_converter, output, out_parsed);
771 }
772
773 bool ReplaceComponents(const char* spec,
774                        int spec_len,
775                        const Parsed& parsed,
776                        const Replacements<base::char16>& replacements,
777                        CharsetConverter* charset_converter,
778                        CanonOutput* output,
779                        Parsed* out_parsed) {
780   return DoReplaceComponents(spec, spec_len, parsed, replacements,
781                              charset_converter, output, out_parsed);
782 }
783
784 void DecodeURLEscapeSequences(const char* input,
785                               int length,
786                               DecodeURLMode mode,
787                               CanonOutputW* output) {
788   STACK_UNINITIALIZED RawCanonOutputT<char> unescaped_chars;
789   for (int i = 0; i < length; i++) {
790     if (input[i] == '%') {
791       unsigned char ch;
792       if (DecodeEscaped(input, &i, length, &ch)) {
793         unescaped_chars.push_back(ch);
794       } else {
795         // Invalid escape sequence, copy the percent literal.
796         unescaped_chars.push_back('%');
797       }
798     } else {
799       // Regular non-escaped 8-bit character.
800       unescaped_chars.push_back(input[i]);
801     }
802   }
803
804   int output_initial_length = output->length();
805   // Convert that 8-bit to UTF-16. It's not clear IE does this at all to
806   // JavaScript URLs, but Firefox and Safari do.
807   for (int i = 0; i < unescaped_chars.length(); i++) {
808     unsigned char uch = static_cast<unsigned char>(unescaped_chars.at(i));
809     if (uch < 0x80) {
810       // Non-UTF-8, just append directly
811       output->push_back(uch);
812     } else {
813       // next_ch will point to the last character of the decoded
814       // character.
815       int next_character = i;
816       unsigned code_point;
817       if (ReadUTFChar(unescaped_chars.data(), &next_character,
818                       unescaped_chars.length(), &code_point)) {
819         // Valid UTF-8 character, convert to UTF-16.
820         AppendUTF16Value(code_point, output);
821         i = next_character;
822       } else if (mode == DecodeURLMode::kUTF8) {
823         DCHECK_EQ(code_point, 0xFFFDU);
824         AppendUTF16Value(code_point, output);
825         i = next_character;
826       } else {
827         // If there are any sequences that are not valid UTF-8, we
828         // revert |output| changes, and promote any bytes to UTF-16. We
829         // copy all characters from the beginning to the end of the
830         // identified sequence.
831         output->set_length(output_initial_length);
832         for (int j = 0; j < unescaped_chars.length(); ++j)
833           output->push_back(static_cast<unsigned char>(unescaped_chars.at(j)));
834         break;
835       }
836     }
837   }
838 }
839
840 void EncodeURIComponent(const char* input, int length, CanonOutput* output) {
841   for (int i = 0; i < length; ++i) {
842     unsigned char c = static_cast<unsigned char>(input[i]);
843     if (IsComponentChar(c))
844       output->push_back(c);
845     else
846       AppendEscapedChar(c, output);
847   }
848 }
849
850 bool CompareSchemeComponent(const char* spec,
851                             const Component& component,
852                             const char* compare_to) {
853   return DoCompareSchemeComponent(spec, component, compare_to);
854 }
855
856 bool CompareSchemeComponent(const base::char16* spec,
857                             const Component& component,
858                             const char* compare_to) {
859   return DoCompareSchemeComponent(spec, component, compare_to);
860 }
861
862 }  // namespace url