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