Remove net_resources.rc
[chromium-blink-merge.git] / url / url_util.cc
blob5a19390b2199515dd7b84f2deac56cea36c61d99
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"
7 #include <string.h>
8 #include <vector>
10 #include "base/debug/leak_annotations.h"
11 #include "base/logging.h"
12 #include "base/strings/string_util.h"
13 #include "url/url_canon_internal.h"
14 #include "url/url_file.h"
15 #include "url/url_util_internal.h"
17 namespace url {
19 namespace {
21 const int kNumStandardURLSchemes = 8;
22 const char* kStandardURLSchemes[kNumStandardURLSchemes] = {
23 kHttpScheme,
24 kHttpsScheme,
25 kFileScheme, // Yes, file urls can have a hostname!
26 kFtpScheme,
27 kGopherScheme,
28 kWsScheme, // WebSocket.
29 kWssScheme, // WebSocket secure.
30 kFileSystemScheme,
33 // List of the currently installed standard schemes. This list is lazily
34 // initialized by InitStandardSchemes and is leaked on shutdown to prevent
35 // any destructors from being called that will slow us down or cause problems.
36 std::vector<const char*>* standard_schemes = NULL;
38 // See the LockStandardSchemes declaration in the header.
39 bool standard_schemes_locked = false;
41 // This template converts a given character type to the corresponding
42 // StringPiece type.
43 template<typename CHAR> struct CharToStringPiece {
45 template<> struct CharToStringPiece<char> {
46 typedef base::StringPiece Piece;
48 template<> struct CharToStringPiece<base::char16> {
49 typedef base::StringPiece16 Piece;
52 // Ensures that the standard_schemes list is initialized, does nothing if it
53 // already has values.
54 void InitStandardSchemes() {
55 if (standard_schemes)
56 return;
57 standard_schemes = new std::vector<const char*>;
58 for (int i = 0; i < kNumStandardURLSchemes; i++)
59 standard_schemes->push_back(kStandardURLSchemes[i]);
62 // Given a string and a range inside the string, compares it to the given
63 // lower-case |compare_to| buffer.
64 template<typename CHAR>
65 inline bool DoCompareSchemeComponent(const CHAR* spec,
66 const Component& component,
67 const char* compare_to) {
68 if (!component.is_nonempty())
69 return compare_to[0] == 0; // When component is empty, match empty scheme.
70 return base::LowerCaseEqualsASCII(
71 typename CharToStringPiece<CHAR>::Piece(
72 &spec[component.begin], component.len),
73 compare_to);
76 // Returns true if the given scheme identified by |scheme| within |spec| is one
77 // of the registered "standard" schemes.
78 template<typename CHAR>
79 bool DoIsStandard(const CHAR* spec, const Component& scheme) {
80 if (!scheme.is_nonempty())
81 return false; // Empty or invalid schemes are non-standard.
83 InitStandardSchemes();
84 for (size_t i = 0; i < standard_schemes->size(); i++) {
85 if (base::LowerCaseEqualsASCII(
86 typename CharToStringPiece<CHAR>::Piece(
87 &spec[scheme.begin], scheme.len),
88 standard_schemes->at(i)))
89 return true;
91 return false;
94 template<typename CHAR>
95 bool DoFindAndCompareScheme(const CHAR* str,
96 int str_len,
97 const char* compare,
98 Component* found_scheme) {
99 // Before extracting scheme, canonicalize the URL to remove any whitespace.
100 // This matches the canonicalization done in DoCanonicalize function.
101 RawCanonOutputT<CHAR> whitespace_buffer;
102 int spec_len;
103 const CHAR* spec = RemoveURLWhitespace(str, str_len,
104 &whitespace_buffer, &spec_len);
106 Component our_scheme;
107 if (!ExtractScheme(spec, spec_len, &our_scheme)) {
108 // No scheme.
109 if (found_scheme)
110 *found_scheme = Component();
111 return false;
113 if (found_scheme)
114 *found_scheme = our_scheme;
115 return DoCompareSchemeComponent(spec, our_scheme, compare);
118 template<typename CHAR>
119 bool DoCanonicalize(const CHAR* in_spec,
120 int in_spec_len,
121 bool trim_path_end,
122 CharsetConverter* charset_converter,
123 CanonOutput* output,
124 Parsed* output_parsed) {
125 // Remove any whitespace from the middle of the relative URL, possibly
126 // copying to the new buffer.
127 RawCanonOutputT<CHAR> whitespace_buffer;
128 int spec_len;
129 const CHAR* spec = RemoveURLWhitespace(in_spec, in_spec_len,
130 &whitespace_buffer, &spec_len);
132 Parsed parsed_input;
133 #ifdef WIN32
134 // For Windows, we allow things that look like absolute Windows paths to be
135 // fixed up magically to file URLs. This is done for IE compatability. For
136 // example, this will change "c:/foo" into a file URL rather than treating
137 // it as a URL with the protocol "c". It also works for UNC ("\\foo\bar.txt").
138 // There is similar logic in url_canon_relative.cc for
140 // For Max & Unix, we don't do this (the equivalent would be "/foo/bar" which
141 // has no meaning as an absolute path name. This is because browsers on Mac
142 // & Unix don't generally do this, so there is no compatibility reason for
143 // doing so.
144 if (DoesBeginUNCPath(spec, 0, spec_len, false) ||
145 DoesBeginWindowsDriveSpec(spec, 0, spec_len)) {
146 ParseFileURL(spec, spec_len, &parsed_input);
147 return CanonicalizeFileURL(spec, spec_len, parsed_input, charset_converter,
148 output, output_parsed);
150 #endif
152 Component scheme;
153 if (!ExtractScheme(spec, spec_len, &scheme))
154 return false;
156 // This is the parsed version of the input URL, we have to canonicalize it
157 // before storing it in our object.
158 bool success;
159 if (DoCompareSchemeComponent(spec, scheme, url::kFileScheme)) {
160 // File URLs are special.
161 ParseFileURL(spec, spec_len, &parsed_input);
162 success = CanonicalizeFileURL(spec, spec_len, parsed_input,
163 charset_converter, output, output_parsed);
164 } else if (DoCompareSchemeComponent(spec, scheme, url::kFileSystemScheme)) {
165 // Filesystem URLs are special.
166 ParseFileSystemURL(spec, spec_len, &parsed_input);
167 success = CanonicalizeFileSystemURL(spec, spec_len, parsed_input,
168 charset_converter, output,
169 output_parsed);
171 } else if (DoIsStandard(spec, scheme)) {
172 // All "normal" URLs.
173 ParseStandardURL(spec, spec_len, &parsed_input);
174 success = CanonicalizeStandardURL(spec, spec_len, parsed_input,
175 charset_converter, output, output_parsed);
177 } else if (DoCompareSchemeComponent(spec, scheme, url::kMailToScheme)) {
178 // Mailto are treated like a standard url with only a scheme, path, query
179 ParseMailtoURL(spec, spec_len, &parsed_input);
180 success = CanonicalizeMailtoURL(spec, spec_len, parsed_input, output,
181 output_parsed);
183 } else {
184 // "Weird" URLs like data: and javascript:
185 ParsePathURL(spec, spec_len, trim_path_end, &parsed_input);
186 success = CanonicalizePathURL(spec, spec_len, parsed_input, output,
187 output_parsed);
189 return success;
192 template<typename CHAR>
193 bool DoResolveRelative(const char* base_spec,
194 int base_spec_len,
195 const Parsed& base_parsed,
196 const CHAR* in_relative,
197 int in_relative_length,
198 CharsetConverter* charset_converter,
199 CanonOutput* output,
200 Parsed* output_parsed) {
201 // Remove any whitespace from the middle of the relative URL, possibly
202 // copying to the new buffer.
203 RawCanonOutputT<CHAR> whitespace_buffer;
204 int relative_length;
205 const CHAR* relative = RemoveURLWhitespace(in_relative, in_relative_length,
206 &whitespace_buffer,
207 &relative_length);
208 bool base_is_authority_based = false;
209 bool base_is_hierarchical = false;
210 if (base_spec &&
211 base_parsed.scheme.is_nonempty()) {
212 int after_scheme = base_parsed.scheme.end() + 1; // Skip past the colon.
213 int num_slashes = CountConsecutiveSlashes(base_spec, after_scheme,
214 base_spec_len);
215 base_is_authority_based = num_slashes > 1;
216 base_is_hierarchical = num_slashes > 0;
219 bool standard_base_scheme =
220 base_parsed.scheme.is_nonempty() &&
221 DoIsStandard(base_spec, base_parsed.scheme);
223 bool is_relative;
224 Component relative_component;
225 if (!IsRelativeURL(base_spec, base_parsed, relative, relative_length,
226 (base_is_hierarchical || standard_base_scheme),
227 &is_relative, &relative_component)) {
228 // Error resolving.
229 return false;
232 // Pretend for a moment that |base_spec| is a standard URL. Normally
233 // non-standard URLs are treated as PathURLs, but if the base has an
234 // authority we would like to preserve it.
235 if (is_relative && base_is_authority_based && !standard_base_scheme) {
236 Parsed base_parsed_authority;
237 ParseStandardURL(base_spec, base_spec_len, &base_parsed_authority);
238 if (base_parsed_authority.host.is_nonempty()) {
239 RawCanonOutputT<char> temporary_output;
240 bool did_resolve_succeed =
241 ResolveRelativeURL(base_spec, base_parsed_authority, false, relative,
242 relative_component, charset_converter,
243 &temporary_output, output_parsed);
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
246 // re-created.
247 DoCanonicalize(temporary_output.data(), temporary_output.length(), true,
248 charset_converter, output, output_parsed);
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,
257 output_parsed);
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,
267 int spec_len,
268 const Parsed& parsed,
269 const Replacements<CHAR>& replacements,
270 CharsetConverter* charset_converter,
271 CanonOutput* output,
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
298 : 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,
309 charset_converter,
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
324 // ref).
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,
336 out_parsed);
338 if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileSystemScheme)) {
339 return ReplaceFileSystemURL(spec, parsed, replacements, charset_converter,
340 output, out_parsed);
342 if (DoIsStandard(spec, parsed.scheme)) {
343 return ReplaceStandardURL(spec, parsed, replacements, charset_converter,
344 output, out_parsed);
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);
354 } // namespace
356 void Initialize() {
357 InitStandardSchemes();
360 void Shutdown() {
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
375 // scheme there.
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);
380 if (scheme_len == 0)
381 return;
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 ANNOTATE_LEAKING_OBJECT_PTR(dup_scheme);
387 memcpy(dup_scheme, new_scheme, scheme_len + 1);
389 InitStandardSchemes();
390 standard_schemes->push_back(dup_scheme);
393 void LockStandardSchemes() {
394 standard_schemes_locked = true;
397 bool IsStandard(const char* spec, const Component& scheme) {
398 return DoIsStandard(spec, scheme);
401 bool IsStandard(const base::char16* spec, const Component& scheme) {
402 return DoIsStandard(spec, scheme);
405 bool FindAndCompareScheme(const char* str,
406 int str_len,
407 const char* compare,
408 Component* found_scheme) {
409 return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
412 bool FindAndCompareScheme(const base::char16* str,
413 int str_len,
414 const char* compare,
415 Component* found_scheme) {
416 return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
419 bool Canonicalize(const char* spec,
420 int spec_len,
421 bool trim_path_end,
422 CharsetConverter* charset_converter,
423 CanonOutput* output,
424 Parsed* output_parsed) {
425 return DoCanonicalize(spec, spec_len, trim_path_end, charset_converter,
426 output, output_parsed);
429 bool Canonicalize(const base::char16* spec,
430 int spec_len,
431 bool trim_path_end,
432 CharsetConverter* charset_converter,
433 CanonOutput* output,
434 Parsed* output_parsed) {
435 return DoCanonicalize(spec, spec_len, trim_path_end, charset_converter,
436 output, output_parsed);
439 bool ResolveRelative(const char* base_spec,
440 int base_spec_len,
441 const Parsed& base_parsed,
442 const char* relative,
443 int relative_length,
444 CharsetConverter* charset_converter,
445 CanonOutput* output,
446 Parsed* output_parsed) {
447 return DoResolveRelative(base_spec, base_spec_len, base_parsed,
448 relative, relative_length,
449 charset_converter, output, output_parsed);
452 bool ResolveRelative(const char* base_spec,
453 int base_spec_len,
454 const Parsed& base_parsed,
455 const base::char16* relative,
456 int relative_length,
457 CharsetConverter* charset_converter,
458 CanonOutput* output,
459 Parsed* output_parsed) {
460 return DoResolveRelative(base_spec, base_spec_len, base_parsed,
461 relative, relative_length,
462 charset_converter, output, output_parsed);
465 bool ReplaceComponents(const char* spec,
466 int spec_len,
467 const Parsed& parsed,
468 const Replacements<char>& replacements,
469 CharsetConverter* charset_converter,
470 CanonOutput* output,
471 Parsed* out_parsed) {
472 return DoReplaceComponents(spec, spec_len, parsed, replacements,
473 charset_converter, output, out_parsed);
476 bool ReplaceComponents(const char* spec,
477 int spec_len,
478 const Parsed& parsed,
479 const Replacements<base::char16>& replacements,
480 CharsetConverter* charset_converter,
481 CanonOutput* output,
482 Parsed* out_parsed) {
483 return DoReplaceComponents(spec, spec_len, parsed, replacements,
484 charset_converter, output, out_parsed);
487 void DecodeURLEscapeSequences(const char* input,
488 int length,
489 CanonOutputW* output) {
490 RawCanonOutputT<char> unescaped_chars;
491 for (int i = 0; i < length; i++) {
492 if (input[i] == '%') {
493 unsigned char ch;
494 if (DecodeEscaped(input, &i, length, &ch)) {
495 unescaped_chars.push_back(ch);
496 } else {
497 // Invalid escape sequence, copy the percent literal.
498 unescaped_chars.push_back('%');
500 } else {
501 // Regular non-escaped 8-bit character.
502 unescaped_chars.push_back(input[i]);
506 // Convert that 8-bit to UTF-16. It's not clear IE does this at all to
507 // JavaScript URLs, but Firefox and Safari do.
508 for (int i = 0; i < unescaped_chars.length(); i++) {
509 unsigned char uch = static_cast<unsigned char>(unescaped_chars.at(i));
510 if (uch < 0x80) {
511 // Non-UTF-8, just append directly
512 output->push_back(uch);
513 } else {
514 // next_ch will point to the last character of the decoded
515 // character.
516 int next_character = i;
517 unsigned code_point;
518 if (ReadUTFChar(unescaped_chars.data(), &next_character,
519 unescaped_chars.length(), &code_point)) {
520 // Valid UTF-8 character, convert to UTF-16.
521 AppendUTF16Value(code_point, output);
522 i = next_character;
523 } else {
524 // If there are any sequences that are not valid UTF-8, we keep
525 // invalid code points and promote to UTF-16. We copy all characters
526 // from the current position to the end of the identified sequence.
527 while (i < next_character) {
528 output->push_back(static_cast<unsigned char>(unescaped_chars.at(i)));
529 i++;
531 output->push_back(static_cast<unsigned char>(unescaped_chars.at(i)));
537 void EncodeURIComponent(const char* input, int length, CanonOutput* output) {
538 for (int i = 0; i < length; ++i) {
539 unsigned char c = static_cast<unsigned char>(input[i]);
540 if (IsComponentChar(c))
541 output->push_back(c);
542 else
543 AppendEscapedChar(c, output);
547 bool CompareSchemeComponent(const char* spec,
548 const Component& component,
549 const char* compare_to) {
550 return DoCompareSchemeComponent(spec, component, compare_to);
553 bool CompareSchemeComponent(const base::char16* spec,
554 const Component& component,
555 const char* compare_to) {
556 return DoCompareSchemeComponent(spec, component, compare_to);
559 } // namespace url