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