Fix for Geolocation webTCT failures
[platform/framework/web/chromium-efl.git] / url / url_util.cc
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "url/url_util.h"
6
7 #include <stddef.h>
8 #include <string.h>
9
10 #include <atomic>
11 #include <ostream>
12
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"
22
23 namespace url {
24
25 namespace {
26
27 // A pair for representing a standard scheme name and the SchemeType for it.
28 struct SchemeWithType {
29   std::string scheme;
30   SchemeType type;
31 };
32
33 // A pair for representing a scheme and a custom protocol handler for it.
34 //
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 {
39   std::string scheme;
40   std::string handler;
41 };
42
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
53       // canonicalization.
54       {kFileScheme, SCHEME_WITH_HOST},
55       {kFtpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
56       {kWssScheme,
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},
66 #endif
67   };
68
69   // Schemes that are allowed for referrers.
70   //
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
75   // referrers.
76   std::vector<SchemeWithType> referrer_schemes = {
77       {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
78       {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
79   };
80
81   // Schemes that do not trigger mixed content warning.
82   std::vector<std::string> secure_schemes = {
83       kHttpsScheme,
84       kWssScheme,
85       kDataScheme,
86       kAboutScheme,
87   };
88
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 = {
92       kFileScheme,
93   };
94
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 = {
98       kAboutScheme,
99       kJavaScriptScheme,
100       kDataScheme,
101   };
102
103   // Schemes that can be sent CORS requests.
104   std::vector<std::string> cors_enabled_schemes = {
105       kHttpsScheme,
106       kHttpScheme,
107       kDataScheme,
108   };
109
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,
113   };
114
115   // Schemes that can bypass the Content-Security-Policy (CSP) checks.
116   std::vector<std::string> csp_bypassing_schemes = {};
117
118   // Schemes that are strictly empty documents, allowing them to commit
119   // synchronously.
120   std::vector<std::string> empty_document_schemes = {
121       kAboutScheme,
122   };
123
124   // Schemes with a predefined default custom handler.
125   std::vector<SchemeWithHandler> predefined_handler_schemes;
126
127   bool allow_non_standard_schemes = false;
128 };
129
130 // See the LockSchemeRegistries declaration in the header.
131 bool scheme_registries_locked = false;
132
133 // Ensure that the schemes aren't modified after first use.
134 static std::atomic<bool> g_scheme_registries_used{false};
135
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();
141 }
142
143 const SchemeRegistry& GetSchemeRegistry() {
144 #if DCHECK_IS_ON()
145   g_scheme_registries_used.store(true);
146 #endif
147   return *GetSchemeRegistryWithoutLocking();
148 }
149
150 // Pass this enum through for methods which would like to know if whitespace
151 // removal is necessary.
152 enum WhitespaceRemovalPolicy {
153   REMOVE_WHITESPACE,
154   DO_NOT_REMOVE_WHITESPACE,
155 };
156
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),
167       compare_to);
168 }
169
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,
175                    SchemeType* type,
176                    const std::vector<SchemeWithType>& schemes) {
177   if (scheme.is_empty())
178     return false;  // Empty or invalid schemes are non-standard.
179
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;
185       return true;
186     }
187   }
188   return false;
189 }
190
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);
195 }
196
197
198 template<typename CHAR>
199 bool DoFindAndCompareScheme(const CHAR* str,
200                             int str_len,
201                             const char* compare,
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;
206   int spec_len;
207   const CHAR* spec =
208       RemoveURLWhitespace(str, str_len, &whitespace_buffer, &spec_len, nullptr);
209
210   Component our_scheme;
211   if (!ExtractScheme(spec, spec_len, &our_scheme)) {
212     // No scheme.
213     if (found_scheme)
214       *found_scheme = Component();
215     return false;
216   }
217   if (found_scheme)
218     *found_scheme = our_scheme;
219   return DoCompareSchemeComponent(spec, our_scheme, compare);
220 }
221
222 template <typename CHAR>
223 bool DoCanonicalize(const CHAR* spec,
224                     int spec_len,
225                     bool trim_path_end,
226                     WhitespaceRemovalPolicy whitespace_policy,
227                     CharsetConverter* charset_converter,
228                     CanonOutput* output,
229                     Parsed* output_parsed) {
230   // Trim leading C0 control characters and spaces.
231   int begin = 0;
232   TrimURL(spec, &begin, &spec_len, trim_path_end);
233   DCHECK(0 <= begin && begin <= spec_len);
234   spec += begin;
235   spec_len -= begin;
236
237   output->ReserveSizeIfNeeded(spec_len);
238
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);
245   }
246
247   Parsed parsed_input;
248 #ifdef WIN32
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
254   //
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
258   // doing so.
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);
264   }
265 #endif
266
267   Component scheme;
268   if (!ExtractScheme(spec, spec_len, &scheme))
269     return false;
270
271   // This is the parsed version of the input URL, we have to canonicalize it
272   // before storing it in our object.
273   bool success;
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,
285                                         output_parsed);
286
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);
292
293   } else if (DoCompareSchemeComponent(spec, scheme, url::kMailToScheme)) {
294     // Mailto URLs are treated like standard URLs, with only a scheme, path,
295     // and query.
296     ParseMailtoURL(spec, spec_len, &parsed_input);
297     success = CanonicalizeMailtoURL(spec, spec_len, parsed_input, output,
298                                     output_parsed);
299
300   } else {
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,
304                                   output_parsed);
305   }
306   return success;
307 }
308
309 template<typename CHAR>
310 bool DoResolveRelative(const char* base_spec,
311                        int base_spec_len,
312                        const Parsed& base_parsed,
313                        const CHAR* in_relative,
314                        int in_relative_length,
315                        CharsetConverter* charset_converter,
316                        CanonOutput* output,
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;
321   int relative_length;
322   const CHAR* relative = RemoveURLWhitespace(
323       in_relative, in_relative_length, &whitespace_buffer, &relative_length,
324       &output_parsed->potentially_dangling_markup);
325
326   bool base_is_authority_based = false;
327   bool base_is_hierarchical = false;
328   if (base_spec &&
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,
332                                               base_spec_len);
333     base_is_authority_based = num_slashes > 1;
334     base_is_hierarchical = num_slashes > 0;
335   }
336
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);
341
342   bool is_relative;
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)) {
347     // Error resolving.
348     return false;
349   }
350
351   // Don't reserve buffer space here. Instead, reserve in DoCanonicalize and
352   // ReserveRelativeURL, to enable more accurate buffer sizes.
353
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
368       // re-created.
369       DoCanonicalize(temporary_output.data(), temporary_output.length(), true,
370                      REMOVE_WHITESPACE, charset_converter, output,
371                      output_parsed);
372       return did_resolve_succeed;
373     }
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,
380                               output_parsed);
381   }
382
383   // Not relative, canonicalize the input.
384   return DoCanonicalize(relative, relative_length, true,
385                         DO_NOT_REMOVE_WHITESPACE, charset_converter, output,
386                         output_parsed);
387 }
388
389 template<typename CHAR>
390 bool DoReplaceComponents(const char* spec,
391                          int spec_len,
392                          const Parsed& parsed,
393                          const Replacements<CHAR>& replacements,
394                          CharsetConverter* charset_converter,
395                          CanonOutput* output,
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.
404   //
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);
418
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
422                                                     : 1;
423     if (spec_len - spec_after_colon > 0) {
424       scheme_replaced.Append(&spec[spec_after_colon],
425                              spec_len - spec_after_colon);
426     }
427
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);
435
436     // Recurse using the version with the scheme already replaced. This will now
437     // use the replacement rules for the new scheme.
438     //
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
448     // ref).
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
454     // closed.
455     if (parsed.potentially_dangling_markup) {
456       out_parsed->potentially_dangling_markup = true;
457     }
458     return DoReplaceComponents(recanonicalized.data(), recanonicalized.length(),
459                                recanonicalized_parsed, replacements_no_scheme,
460                                charset_converter, output, out_parsed);
461   }
462
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
466   // be changed.
467   output->ReserveSizeIfNeeded(spec_len);
468
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,
473                           out_parsed);
474   }
475   if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileSystemScheme)) {
476     return ReplaceFileSystemURL(spec, parsed, replacements, charset_converter,
477                                 output, out_parsed);
478   }
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);
483   }
484   if (DoCompareSchemeComponent(spec, parsed.scheme, url::kMailToScheme)) {
485     return ReplaceMailtoURL(spec, parsed, replacements, output, out_parsed);
486   }
487
488   // Default is a path URL.
489   return ReplacePathURL(spec, parsed, replacements, output, out_parsed);
490 }
491
492 void DoSchemeModificationPreamble() {
493   // If this assert triggers, it means you've called Add*Scheme after
494   // the SchemeRegistry has been used.
495   //
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.";
501
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).
505   //
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.";
511 }
512
513 void DoAddSchemeWithHandler(const char* new_scheme,
514                             const char* handler,
515                             std::vector<SchemeWithHandler>* schemes) {
516   DoSchemeModificationPreamble();
517   DCHECK(schemes);
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});
523 }
524
525 void DoAddScheme(const char* new_scheme, std::vector<std::string>* schemes) {
526   DoSchemeModificationPreamble();
527   DCHECK(schemes);
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);
532 }
533
534 void DoAddSchemeWithType(const char* new_scheme,
535                          SchemeType type,
536                          std::vector<SchemeWithType>* schemes) {
537   DoSchemeModificationPreamble();
538   DCHECK(schemes);
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});
543 }
544
545 }  // namespace
546
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();
555 }
556
557 class ScopedSchemeRegistryInternal {
558  public:
559   ScopedSchemeRegistryInternal()
560       : registry_(std::make_unique<SchemeRegistry>(
561             *GetSchemeRegistryWithoutLocking())) {
562     g_scheme_registries_used.store(false);
563     scheme_registries_locked = false;
564   }
565   ~ScopedSchemeRegistryInternal() {
566     *GetSchemeRegistryWithoutLocking() = *registry_;
567     g_scheme_registries_used.store(true);
568     scheme_registries_locked = true;
569   }
570
571  private:
572   std::unique_ptr<SchemeRegistry> registry_;
573 };
574
575 ScopedSchemeRegistryForTests::ScopedSchemeRegistryForTests()
576     : internal_(std::make_unique<ScopedSchemeRegistryInternal>()) {}
577
578 ScopedSchemeRegistryForTests::~ScopedSchemeRegistryForTests() = default;
579
580 void EnableNonStandardSchemesForAndroidWebView() {
581   DoSchemeModificationPreamble();
582   GetSchemeRegistryWithoutLocking()->allow_non_standard_schemes = true;
583 }
584
585 bool AllowNonStandardSchemesForAndroidWebView() {
586   return GetSchemeRegistry().allow_non_standard_schemes;
587 }
588
589 void AddStandardScheme(const char* new_scheme, SchemeType type) {
590   DoAddSchemeWithType(new_scheme, type,
591                       &GetSchemeRegistryWithoutLocking()->standard_schemes);
592 }
593
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);
599   }
600   return result;
601 }
602
603 void AddReferrerScheme(const char* new_scheme, SchemeType type) {
604   DoAddSchemeWithType(new_scheme, type,
605                       &GetSchemeRegistryWithoutLocking()->referrer_schemes);
606 }
607
608 void AddSecureScheme(const char* new_scheme) {
609   DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->secure_schemes);
610 }
611
612 const std::vector<std::string>& GetSecureSchemes() {
613   return GetSchemeRegistry().secure_schemes;
614 }
615
616 void AddLocalScheme(const char* new_scheme) {
617   DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->local_schemes);
618 }
619
620 const std::vector<std::string>& GetLocalSchemes() {
621   return GetSchemeRegistry().local_schemes;
622 }
623
624 void AddNoAccessScheme(const char* new_scheme) {
625   DoAddScheme(new_scheme,
626               &GetSchemeRegistryWithoutLocking()->no_access_schemes);
627 }
628
629 const std::vector<std::string>& GetNoAccessSchemes() {
630   return GetSchemeRegistry().no_access_schemes;
631 }
632
633 void AddCorsEnabledScheme(const char* new_scheme) {
634   DoAddScheme(new_scheme,
635               &GetSchemeRegistryWithoutLocking()->cors_enabled_schemes);
636 }
637
638 const std::vector<std::string>& GetCorsEnabledSchemes() {
639   return GetSchemeRegistry().cors_enabled_schemes;
640 }
641
642 void AddWebStorageScheme(const char* new_scheme) {
643   DoAddScheme(new_scheme,
644               &GetSchemeRegistryWithoutLocking()->web_storage_schemes);
645 }
646
647 const std::vector<std::string>& GetWebStorageSchemes() {
648   return GetSchemeRegistry().web_storage_schemes;
649 }
650
651 void AddCSPBypassingScheme(const char* new_scheme) {
652   DoAddScheme(new_scheme,
653               &GetSchemeRegistryWithoutLocking()->csp_bypassing_schemes);
654 }
655
656 const std::vector<std::string>& GetCSPBypassingSchemes() {
657   return GetSchemeRegistry().csp_bypassing_schemes;
658 }
659
660 void AddEmptyDocumentScheme(const char* new_scheme) {
661   DoAddScheme(new_scheme,
662               &GetSchemeRegistryWithoutLocking()->empty_document_schemes);
663 }
664
665 const std::vector<std::string>& GetEmptyDocumentSchemes() {
666   return GetSchemeRegistry().empty_document_schemes;
667 }
668
669 void AddPredefinedHandlerScheme(const char* new_scheme, const char* handler) {
670   DoAddSchemeWithHandler(
671       new_scheme, handler,
672       &GetSchemeRegistryWithoutLocking()->predefined_handler_schemes);
673 }
674
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);
681   }
682   return result;
683 }
684
685 void LockSchemeRegistries() {
686   scheme_registries_locked = true;
687 }
688
689 bool IsStandard(const char* spec, const Component& scheme) {
690   SchemeType unused_scheme_type;
691   return DoIsStandard(spec, scheme, &unused_scheme_type);
692 }
693
694 bool GetStandardSchemeType(const char* spec,
695                            const Component& scheme,
696                            SchemeType* type) {
697   return DoIsStandard(spec, scheme, type);
698 }
699
700 bool GetStandardSchemeType(const char16_t* spec,
701                            const Component& scheme,
702                            SchemeType* type) {
703   return DoIsStandard(spec, scheme, type);
704 }
705
706 bool IsStandard(const char16_t* spec, const Component& scheme) {
707   SchemeType unused_scheme_type;
708   return DoIsStandard(spec, scheme, &unused_scheme_type);
709 }
710
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);
715 }
716
717 bool FindAndCompareScheme(const char* str,
718                           int str_len,
719                           const char* compare,
720                           Component* found_scheme) {
721   return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
722 }
723
724 bool FindAndCompareScheme(const char16_t* str,
725                           int str_len,
726                           const char* compare,
727                           Component* found_scheme) {
728   return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
729 }
730
731 bool DomainIs(std::string_view canonical_host,
732               std::string_view canonical_domain) {
733   if (canonical_host.empty() || canonical_domain.empty())
734     return false;
735
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() != '.')
740     --host_len;
741
742   if (host_len < canonical_domain.length())
743     return false;
744
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();
749
750   if (std::string_view(host_first_pos, canonical_domain.length()) !=
751       canonical_domain) {
752     return false;
753   }
754
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) != '.') {
761     return false;
762   }
763
764   return true;
765 }
766
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();
773 }
774
775 bool Canonicalize(const char* spec,
776                   int spec_len,
777                   bool trim_path_end,
778                   CharsetConverter* charset_converter,
779                   CanonOutput* output,
780                   Parsed* output_parsed) {
781   return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
782                         charset_converter, output, output_parsed);
783 }
784
785 bool Canonicalize(const char16_t* spec,
786                   int spec_len,
787                   bool trim_path_end,
788                   CharsetConverter* charset_converter,
789                   CanonOutput* output,
790                   Parsed* output_parsed) {
791   return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
792                         charset_converter, output, output_parsed);
793 }
794
795 bool ResolveRelative(const char* base_spec,
796                      int base_spec_len,
797                      const Parsed& base_parsed,
798                      const char* relative,
799                      int relative_length,
800                      CharsetConverter* charset_converter,
801                      CanonOutput* output,
802                      Parsed* output_parsed) {
803   return DoResolveRelative(base_spec, base_spec_len, base_parsed,
804                            relative, relative_length,
805                            charset_converter, output, output_parsed);
806 }
807
808 bool ResolveRelative(const char* base_spec,
809                      int base_spec_len,
810                      const Parsed& base_parsed,
811                      const char16_t* relative,
812                      int relative_length,
813                      CharsetConverter* charset_converter,
814                      CanonOutput* output,
815                      Parsed* output_parsed) {
816   return DoResolveRelative(base_spec, base_spec_len, base_parsed,
817                            relative, relative_length,
818                            charset_converter, output, output_parsed);
819 }
820
821 bool ReplaceComponents(const char* spec,
822                        int spec_len,
823                        const Parsed& parsed,
824                        const Replacements<char>& replacements,
825                        CharsetConverter* charset_converter,
826                        CanonOutput* output,
827                        Parsed* out_parsed) {
828   return DoReplaceComponents(spec, spec_len, parsed, replacements,
829                              charset_converter, output, out_parsed);
830 }
831
832 bool ReplaceComponents(const char* spec,
833                        int spec_len,
834                        const Parsed& parsed,
835                        const Replacements<char16_t>& replacements,
836                        CharsetConverter* charset_converter,
837                        CanonOutput* output,
838                        Parsed* out_parsed) {
839   return DoReplaceComponents(spec, spec_len, parsed, replacements,
840                              charset_converter, output, out_parsed);
841 }
842
843 void DecodeURLEscapeSequences(std::string_view input,
844                               DecodeURLMode mode,
845                               CanonOutputW* output) {
846   if (input.empty()) {
847     return;
848   }
849
850   STACK_UNINITIALIZED RawCanonOutputT<char> unescaped_chars;
851   for (size_t i = 0; i < input.length(); i++) {
852     if (input[i] == '%') {
853       unsigned char ch;
854       if (DecodeEscaped(input.data(), &i, input.length(), &ch)) {
855         unescaped_chars.push_back(ch);
856       } else {
857         // Invalid escape sequence, copy the percent literal.
858         unescaped_chars.push_back('%');
859       }
860     } else {
861       // Regular non-escaped 8-bit character.
862       unescaped_chars.push_back(input[i]);
863     }
864   }
865
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));
872     if (uch < 0x80) {
873       // Non-UTF-8, just append directly
874       output->push_back(uch);
875     } else {
876       // next_ch will point to the last character of the decoded
877       // character.
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);
884         i = next_character;
885       } else if (mode == DecodeURLMode::kUTF8) {
886         DCHECK_EQ(code_point, 0xFFFD);
887         AppendUTF16Value(code_point, output);
888         i = next_character;
889       } else {
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)));
897         break;
898       }
899     }
900   }
901 }
902
903 void EncodeURIComponent(std::string_view input, CanonOutput* output) {
904   for (unsigned char c : input) {
905     if (IsComponentChar(c)) {
906       output->push_back(c);
907     } else {
908       AppendEscapedChar(c, output);
909     }
910   }
911 }
912
913 bool IsURIComponentChar(char c) {
914   return IsComponentChar(c);
915 }
916
917 bool CompareSchemeComponent(const char* spec,
918                             const Component& component,
919                             const char* compare_to) {
920   return DoCompareSchemeComponent(spec, component, compare_to);
921 }
922
923 bool CompareSchemeComponent(const char16_t* spec,
924                             const Component& component,
925                             const char* compare_to) {
926   return DoCompareSchemeComponent(spec, component, compare_to);
927 }
928
929 bool HasInvalidURLEscapeSequences(std::string_view input) {
930   for (size_t i = 0; i < input.size(); i++) {
931     if (input[i] == '%') {
932       unsigned char ch;
933       if (!DecodeEscaped(input.data(), &i, input.size(), &ch)) {
934         return true;
935       }
936     }
937   }
938   return false;
939 }
940
941 }  // namespace url