1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "url/url_util.h"
10 #include "base/logging.h"
11 #include "url/url_canon_internal.h"
12 #include "url/url_file.h"
13 #include "url/url_util_internal.h"
19 // ASCII-specific tolower. The standard library's tolower is locale sensitive,
20 // so we don't want to use it here.
22 inline Char
ToLowerASCII(Char c
) {
23 return (c
>= 'A' && c
<= 'Z') ? (c
+ ('a' - 'A')) : c
;
26 // Backend for LowerCaseEqualsASCII.
27 template<typename Iter
>
28 inline bool DoLowerCaseEqualsASCII(Iter a_begin
, Iter a_end
, const char* b
) {
29 for (Iter it
= a_begin
; it
!= a_end
; ++it
, ++b
) {
30 if (!*b
|| ToLowerASCII(*it
) != *b
)
36 const int kNumStandardURLSchemes
= 8;
37 const char* kStandardURLSchemes
[kNumStandardURLSchemes
] = {
40 kFileScheme
, // Yes, file urls can have a hostname!
43 kWsScheme
, // WebSocket.
44 kWssScheme
, // WebSocket secure.
48 // List of the currently installed standard schemes. This list is lazily
49 // initialized by InitStandardSchemes and is leaked on shutdown to prevent
50 // any destructors from being called that will slow us down or cause problems.
51 std::vector
<const char*>* standard_schemes
= NULL
;
53 // See the LockStandardSchemes declaration in the header.
54 bool standard_schemes_locked
= false;
56 // Ensures that the standard_schemes list is initialized, does nothing if it
57 // already has values.
58 void InitStandardSchemes() {
61 standard_schemes
= new std::vector
<const char*>;
62 for (int i
= 0; i
< kNumStandardURLSchemes
; i
++)
63 standard_schemes
->push_back(kStandardURLSchemes
[i
]);
66 // Given a string and a range inside the string, compares it to the given
67 // lower-case |compare_to| buffer.
68 template<typename CHAR
>
69 inline bool DoCompareSchemeComponent(const CHAR
* spec
,
70 const Component
& component
,
71 const char* compare_to
) {
72 if (!component
.is_nonempty())
73 return compare_to
[0] == 0; // When component is empty, match empty scheme.
74 return LowerCaseEqualsASCII(&spec
[component
.begin
],
75 &spec
[component
.end()],
79 // Returns true if the given scheme identified by |scheme| within |spec| is one
80 // of the registered "standard" schemes.
81 template<typename CHAR
>
82 bool DoIsStandard(const CHAR
* spec
, const Component
& scheme
) {
83 if (!scheme
.is_nonempty())
84 return false; // Empty or invalid schemes are non-standard.
86 InitStandardSchemes();
87 for (size_t i
= 0; i
< standard_schemes
->size(); i
++) {
88 if (LowerCaseEqualsASCII(&spec
[scheme
.begin
], &spec
[scheme
.end()],
89 standard_schemes
->at(i
)))
95 template<typename CHAR
>
96 bool DoFindAndCompareScheme(const CHAR
* str
,
99 Component
* found_scheme
) {
100 // Before extracting scheme, canonicalize the URL to remove any whitespace.
101 // This matches the canonicalization done in DoCanonicalize function.
102 RawCanonOutputT
<CHAR
> whitespace_buffer
;
104 const CHAR
* spec
= RemoveURLWhitespace(str
, str_len
,
105 &whitespace_buffer
, &spec_len
);
107 Component our_scheme
;
108 if (!ExtractScheme(spec
, spec_len
, &our_scheme
)) {
111 *found_scheme
= Component();
115 *found_scheme
= our_scheme
;
116 return DoCompareSchemeComponent(spec
, our_scheme
, compare
);
119 template<typename CHAR
>
120 bool DoCanonicalize(const CHAR
* in_spec
,
123 CharsetConverter
* charset_converter
,
125 Parsed
* output_parsed
) {
126 // Remove any whitespace from the middle of the relative URL, possibly
127 // copying to the new buffer.
128 RawCanonOutputT
<CHAR
> whitespace_buffer
;
130 const CHAR
* spec
= RemoveURLWhitespace(in_spec
, in_spec_len
,
131 &whitespace_buffer
, &spec_len
);
135 // For Windows, we allow things that look like absolute Windows paths to be
136 // fixed up magically to file URLs. This is done for IE compatability. For
137 // example, this will change "c:/foo" into a file URL rather than treating
138 // it as a URL with the protocol "c". It also works for UNC ("\\foo\bar.txt").
139 // There is similar logic in url_canon_relative.cc for
141 // For Max & Unix, we don't do this (the equivalent would be "/foo/bar" which
142 // has no meaning as an absolute path name. This is because browsers on Mac
143 // & Unix don't generally do this, so there is no compatibility reason for
145 if (DoesBeginUNCPath(spec
, 0, spec_len
, false) ||
146 DoesBeginWindowsDriveSpec(spec
, 0, spec_len
)) {
147 ParseFileURL(spec
, spec_len
, &parsed_input
);
148 return CanonicalizeFileURL(spec
, spec_len
, parsed_input
, charset_converter
,
149 output
, output_parsed
);
154 if (!ExtractScheme(spec
, spec_len
, &scheme
))
157 // This is the parsed version of the input URL, we have to canonicalize it
158 // before storing it in our object.
160 if (DoCompareSchemeComponent(spec
, scheme
, url::kFileScheme
)) {
161 // File URLs are special.
162 ParseFileURL(spec
, spec_len
, &parsed_input
);
163 success
= CanonicalizeFileURL(spec
, spec_len
, parsed_input
,
164 charset_converter
, output
, output_parsed
);
165 } else if (DoCompareSchemeComponent(spec
, scheme
, url::kFileSystemScheme
)) {
166 // Filesystem URLs are special.
167 ParseFileSystemURL(spec
, spec_len
, &parsed_input
);
168 success
= CanonicalizeFileSystemURL(spec
, spec_len
, parsed_input
,
169 charset_converter
, output
,
172 } else if (DoIsStandard(spec
, scheme
)) {
173 // All "normal" URLs.
174 ParseStandardURL(spec
, spec_len
, &parsed_input
);
175 success
= CanonicalizeStandardURL(spec
, spec_len
, parsed_input
,
176 charset_converter
, output
, output_parsed
);
178 } else if (DoCompareSchemeComponent(spec
, scheme
, url::kMailToScheme
)) {
179 // Mailto are treated like a standard url with only a scheme, path, query
180 ParseMailtoURL(spec
, spec_len
, &parsed_input
);
181 success
= CanonicalizeMailtoURL(spec
, spec_len
, parsed_input
, output
,
185 // "Weird" URLs like data: and javascript:
186 ParsePathURL(spec
, spec_len
, trim_path_end
, &parsed_input
);
187 success
= CanonicalizePathURL(spec
, spec_len
, parsed_input
, output
,
193 template<typename CHAR
>
194 bool DoResolveRelative(const char* base_spec
,
196 const Parsed
& base_parsed
,
197 const CHAR
* in_relative
,
198 int in_relative_length
,
199 CharsetConverter
* charset_converter
,
201 Parsed
* output_parsed
) {
202 // Remove any whitespace from the middle of the relative URL, possibly
203 // copying to the new buffer.
204 RawCanonOutputT
<CHAR
> whitespace_buffer
;
206 const CHAR
* relative
= RemoveURLWhitespace(in_relative
, in_relative_length
,
209 bool base_is_authority_based
= false;
210 bool base_is_hierarchical
= false;
212 base_parsed
.scheme
.is_nonempty()) {
213 int after_scheme
= base_parsed
.scheme
.end() + 1; // Skip past the colon.
214 int num_slashes
= CountConsecutiveSlashes(base_spec
, after_scheme
,
216 base_is_authority_based
= num_slashes
> 1;
217 base_is_hierarchical
= num_slashes
> 0;
220 bool standard_base_scheme
=
221 base_parsed
.scheme
.is_nonempty() &&
222 DoIsStandard(base_spec
, base_parsed
.scheme
);
225 Component relative_component
;
226 if (!IsRelativeURL(base_spec
, base_parsed
, relative
, relative_length
,
227 (base_is_hierarchical
|| standard_base_scheme
),
228 &is_relative
, &relative_component
)) {
233 // Pretend for a moment that |base_spec| is a standard URL. Normally
234 // non-standard URLs are treated as PathURLs, but if the base has an
235 // authority we would like to preserve it.
236 if (is_relative
&& base_is_authority_based
&& !standard_base_scheme
) {
237 Parsed base_parsed_authority
;
238 ParseStandardURL(base_spec
, base_spec_len
, &base_parsed_authority
);
239 if (base_parsed_authority
.host
.is_nonempty()) {
240 bool did_resolve_succeed
=
241 ResolveRelativeURL(base_spec
, base_parsed_authority
, false, relative
,
242 relative_component
, charset_converter
, output
,
244 // The output_parsed is incorrect at this point (because it was built
245 // based on base_parsed_authority instead of base_parsed) and needs to be
247 ParsePathURL(output
->data(), output
->length(), true,
249 return did_resolve_succeed
;
251 } else if (is_relative
) {
252 // Relative, resolve and canonicalize.
253 bool file_base_scheme
= base_parsed
.scheme
.is_nonempty() &&
254 DoCompareSchemeComponent(base_spec
, base_parsed
.scheme
, kFileScheme
);
255 return ResolveRelativeURL(base_spec
, base_parsed
, file_base_scheme
, relative
,
256 relative_component
, charset_converter
, output
,
260 // Not relative, canonicalize the input.
261 return DoCanonicalize(relative
, relative_length
, true, charset_converter
,
262 output
, output_parsed
);
265 template<typename CHAR
>
266 bool DoReplaceComponents(const char* spec
,
268 const Parsed
& parsed
,
269 const Replacements
<CHAR
>& replacements
,
270 CharsetConverter
* charset_converter
,
272 Parsed
* out_parsed
) {
273 // If the scheme is overridden, just do a simple string substitution and
274 // reparse the whole thing. There are lots of edge cases that we really don't
275 // want to deal with. Like what happens if I replace "http://e:8080/foo"
276 // with a file. Does it become "file:///E:/8080/foo" where the port number
277 // becomes part of the path? Parsing that string as a file URL says "yes"
278 // but almost no sane rule for dealing with the components individually would
279 // come up with that.
281 // Why allow these crazy cases at all? Programatically, there is almost no
282 // case for replacing the scheme. The most common case for hitting this is
283 // in JS when building up a URL using the location object. In this case, the
284 // JS code expects the string substitution behavior:
285 // http://www.w3.org/TR/2008/WD-html5-20080610/structured.html#common3
286 if (replacements
.IsSchemeOverridden()) {
287 // Canonicalize the new scheme so it is 8-bit and can be concatenated with
288 // the existing spec.
289 RawCanonOutput
<128> scheme_replaced
;
290 Component scheme_replaced_parsed
;
291 CanonicalizeScheme(replacements
.sources().scheme
,
292 replacements
.components().scheme
,
293 &scheme_replaced
, &scheme_replaced_parsed
);
295 // We can assume that the input is canonicalized, which means it always has
296 // a colon after the scheme (or where the scheme would be).
297 int spec_after_colon
= parsed
.scheme
.is_valid() ? parsed
.scheme
.end() + 1
299 if (spec_len
- spec_after_colon
> 0) {
300 scheme_replaced
.Append(&spec
[spec_after_colon
],
301 spec_len
- spec_after_colon
);
304 // We now need to completely re-parse the resulting string since its meaning
305 // may have changed with the different scheme.
306 RawCanonOutput
<128> recanonicalized
;
307 Parsed recanonicalized_parsed
;
308 DoCanonicalize(scheme_replaced
.data(), scheme_replaced
.length(), true,
310 &recanonicalized
, &recanonicalized_parsed
);
312 // Recurse using the version with the scheme already replaced. This will now
313 // use the replacement rules for the new scheme.
315 // Warning: this code assumes that ReplaceComponents will re-check all
316 // components for validity. This is because we can't fail if DoCanonicalize
317 // failed above since theoretically the thing making it fail could be
318 // getting replaced here. If ReplaceComponents didn't re-check everything,
319 // we wouldn't know if something *not* getting replaced is a problem.
320 // If the scheme-specific replacers are made more intelligent so they don't
321 // re-check everything, we should instead recanonicalize the whole thing
322 // after this call to check validity (this assumes replacing the scheme is
323 // much much less common than other types of replacements, like clearing the
325 Replacements
<CHAR
> replacements_no_scheme
= replacements
;
326 replacements_no_scheme
.SetScheme(NULL
, Component());
327 return DoReplaceComponents(recanonicalized
.data(), recanonicalized
.length(),
328 recanonicalized_parsed
, replacements_no_scheme
,
329 charset_converter
, output
, out_parsed
);
332 // If we get here, then we know the scheme doesn't need to be replaced, so can
333 // just key off the scheme in the spec to know how to do the replacements.
334 if (DoCompareSchemeComponent(spec
, parsed
.scheme
, url::kFileScheme
)) {
335 return ReplaceFileURL(spec
, parsed
, replacements
, charset_converter
, output
,
338 if (DoCompareSchemeComponent(spec
, parsed
.scheme
, url::kFileSystemScheme
)) {
339 return ReplaceFileSystemURL(spec
, parsed
, replacements
, charset_converter
,
342 if (DoIsStandard(spec
, parsed
.scheme
)) {
343 return ReplaceStandardURL(spec
, parsed
, replacements
, charset_converter
,
346 if (DoCompareSchemeComponent(spec
, parsed
.scheme
, url::kMailToScheme
)) {
347 return ReplaceMailtoURL(spec
, parsed
, replacements
, output
, out_parsed
);
350 // Default is a path URL.
351 return ReplacePathURL(spec
, parsed
, replacements
, output
, out_parsed
);
357 InitStandardSchemes();
361 if (standard_schemes
) {
362 delete standard_schemes
;
363 standard_schemes
= NULL
;
367 void AddStandardScheme(const char* new_scheme
) {
368 // If this assert triggers, it means you've called AddStandardScheme after
369 // LockStandardSchemes have been called (see the header file for
370 // LockStandardSchemes for more).
372 // This normally means you're trying to set up a new standard scheme too late
373 // in your application's init process. Locate where your app does this
374 // initialization and calls LockStandardScheme, and add your new standard
376 DCHECK(!standard_schemes_locked
) <<
377 "Trying to add a standard scheme after the list has been locked.";
379 size_t scheme_len
= strlen(new_scheme
);
383 // Dulicate the scheme into a new buffer and add it to the list of standard
384 // schemes. This pointer will be leaked on shutdown.
385 char* dup_scheme
= new char[scheme_len
+ 1];
386 memcpy(dup_scheme
, new_scheme
, scheme_len
+ 1);
388 InitStandardSchemes();
389 standard_schemes
->push_back(dup_scheme
);
392 void LockStandardSchemes() {
393 standard_schemes_locked
= true;
396 bool IsStandard(const char* spec
, const Component
& scheme
) {
397 return DoIsStandard(spec
, scheme
);
400 bool IsStandard(const base::char16
* spec
, const Component
& scheme
) {
401 return DoIsStandard(spec
, scheme
);
404 bool FindAndCompareScheme(const char* str
,
407 Component
* found_scheme
) {
408 return DoFindAndCompareScheme(str
, str_len
, compare
, found_scheme
);
411 bool FindAndCompareScheme(const base::char16
* str
,
414 Component
* found_scheme
) {
415 return DoFindAndCompareScheme(str
, str_len
, compare
, found_scheme
);
418 bool Canonicalize(const char* spec
,
421 CharsetConverter
* charset_converter
,
423 Parsed
* output_parsed
) {
424 return DoCanonicalize(spec
, spec_len
, trim_path_end
, charset_converter
,
425 output
, output_parsed
);
428 bool Canonicalize(const base::char16
* spec
,
431 CharsetConverter
* charset_converter
,
433 Parsed
* output_parsed
) {
434 return DoCanonicalize(spec
, spec_len
, trim_path_end
, charset_converter
,
435 output
, output_parsed
);
438 bool ResolveRelative(const char* base_spec
,
440 const Parsed
& base_parsed
,
441 const char* relative
,
443 CharsetConverter
* charset_converter
,
445 Parsed
* output_parsed
) {
446 return DoResolveRelative(base_spec
, base_spec_len
, base_parsed
,
447 relative
, relative_length
,
448 charset_converter
, output
, output_parsed
);
451 bool ResolveRelative(const char* base_spec
,
453 const Parsed
& base_parsed
,
454 const base::char16
* relative
,
456 CharsetConverter
* charset_converter
,
458 Parsed
* output_parsed
) {
459 return DoResolveRelative(base_spec
, base_spec_len
, base_parsed
,
460 relative
, relative_length
,
461 charset_converter
, output
, output_parsed
);
464 bool ReplaceComponents(const char* spec
,
466 const Parsed
& parsed
,
467 const Replacements
<char>& replacements
,
468 CharsetConverter
* charset_converter
,
470 Parsed
* out_parsed
) {
471 return DoReplaceComponents(spec
, spec_len
, parsed
, replacements
,
472 charset_converter
, output
, out_parsed
);
475 bool ReplaceComponents(const char* spec
,
477 const Parsed
& parsed
,
478 const Replacements
<base::char16
>& replacements
,
479 CharsetConverter
* charset_converter
,
481 Parsed
* out_parsed
) {
482 return DoReplaceComponents(spec
, spec_len
, parsed
, replacements
,
483 charset_converter
, output
, out_parsed
);
486 // Front-ends for LowerCaseEqualsASCII.
487 bool LowerCaseEqualsASCII(const char* a_begin
,
490 return DoLowerCaseEqualsASCII(a_begin
, a_end
, b
);
493 bool LowerCaseEqualsASCII(const char* a_begin
,
497 while (a_begin
!= a_end
&& b_begin
!= b_end
&&
498 ToLowerASCII(*a_begin
) == *b_begin
) {
502 return a_begin
== a_end
&& b_begin
== b_end
;
505 bool LowerCaseEqualsASCII(const base::char16
* a_begin
,
506 const base::char16
* a_end
,
508 return DoLowerCaseEqualsASCII(a_begin
, a_end
, b
);
511 void DecodeURLEscapeSequences(const char* input
,
513 CanonOutputW
* output
) {
514 RawCanonOutputT
<char> unescaped_chars
;
515 for (int i
= 0; i
< length
; i
++) {
516 if (input
[i
] == '%') {
518 if (DecodeEscaped(input
, &i
, length
, &ch
)) {
519 unescaped_chars
.push_back(ch
);
521 // Invalid escape sequence, copy the percent literal.
522 unescaped_chars
.push_back('%');
525 // Regular non-escaped 8-bit character.
526 unescaped_chars
.push_back(input
[i
]);
530 // Convert that 8-bit to UTF-16. It's not clear IE does this at all to
531 // JavaScript URLs, but Firefox and Safari do.
532 for (int i
= 0; i
< unescaped_chars
.length(); i
++) {
533 unsigned char uch
= static_cast<unsigned char>(unescaped_chars
.at(i
));
535 // Non-UTF-8, just append directly
536 output
->push_back(uch
);
538 // next_ch will point to the last character of the decoded
540 int next_character
= i
;
542 if (ReadUTFChar(unescaped_chars
.data(), &next_character
,
543 unescaped_chars
.length(), &code_point
)) {
544 // Valid UTF-8 character, convert to UTF-16.
545 AppendUTF16Value(code_point
, output
);
548 // If there are any sequences that are not valid UTF-8, we keep
549 // invalid code points and promote to UTF-16. We copy all characters
550 // from the current position to the end of the identified sequence.
551 while (i
< next_character
) {
552 output
->push_back(static_cast<unsigned char>(unescaped_chars
.at(i
)));
555 output
->push_back(static_cast<unsigned char>(unescaped_chars
.at(i
)));
561 void EncodeURIComponent(const char* input
, int length
, CanonOutput
* output
) {
562 for (int i
= 0; i
< length
; ++i
) {
563 unsigned char c
= static_cast<unsigned char>(input
[i
]);
564 if (IsComponentChar(c
))
565 output
->push_back(c
);
567 AppendEscapedChar(c
, output
);
571 bool CompareSchemeComponent(const char* spec
,
572 const Component
& component
,
573 const char* compare_to
) {
574 return DoCompareSchemeComponent(spec
, component
, compare_to
);
577 bool CompareSchemeComponent(const base::char16
* spec
,
578 const Component
& component
,
579 const char* compare_to
) {
580 return DoCompareSchemeComponent(spec
, component
, compare_to
);