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 // Canonicalizer functions for working with and resolving relative URLs.
10 #include "base/check_op.h"
11 #include "base/strings/string_util.h"
12 #include "url/url_canon.h"
13 #include "url/url_canon_internal.h"
14 #include "url/url_constants.h"
15 #include "url/url_file.h"
16 #include "url/url_parse_internal.h"
17 #include "url/url_util.h"
18 #include "url/url_util_internal.h"
24 // Firefox does a case-sensitive compare (which is probably wrong--Mozilla bug
25 // 379034), whereas IE is case-insensitive.
27 // We choose to be more permissive like IE. We don't need to worry about
28 // unescaping or anything here: neither IE or Firefox allow this. We also
29 // don't have to worry about invalid scheme characters since we are comparing
30 // against the canonical scheme of the base.
32 // The base URL should always be canonical, therefore it should be ASCII.
33 template<typename CHAR>
34 bool AreSchemesEqual(const char* base,
35 const Component& base_scheme,
37 const Component& cmp_scheme) {
38 if (base_scheme.len != cmp_scheme.len)
40 for (int i = 0; i < base_scheme.len; i++) {
41 // We assume the base is already canonical, so we don't have to
43 if (CanonicalSchemeChar(cmp[cmp_scheme.begin + i]) !=
44 base[base_scheme.begin + i])
52 // Here, we also allow Windows paths to be represented as "/C:/" so we can be
53 // consistent about URL paths beginning with slashes. This function is like
54 // DoesBeginWindowsDrivePath except that it also requires a slash at the
56 template<typename CHAR>
57 bool DoesBeginSlashWindowsDriveSpec(const CHAR* spec, int start_offset,
59 if (start_offset >= spec_len)
61 return IsURLSlash(spec[start_offset]) &&
62 DoesBeginWindowsDriveSpec(spec, start_offset + 1, spec_len);
67 template <typename CHAR>
68 bool IsValidScheme(const CHAR* url, const Component& scheme) {
69 // Caller should ensure that the |scheme| is not empty.
70 DCHECK_NE(0, scheme.len);
72 // From https://url.spec.whatwg.org/#scheme-start-state:
73 // scheme start state:
74 // 1. If c is an ASCII alpha, append c, lowercased, to buffer, and set
75 // state to scheme state.
76 // 2. Otherwise, if state override is not given, set state to no scheme
77 // state, and decrease pointer by one.
78 // 3. Otherwise, validation error, return failure.
79 // Note that both step 2 and step 3 mean that the scheme was not valid.
80 if (!base::IsAsciiAlpha(url[scheme.begin]))
83 // From https://url.spec.whatwg.org/#scheme-state:
85 // 1. If c is an ASCII alphanumeric, U+002B (+), U+002D (-), or U+002E
86 // (.), append c, lowercased, to buffer.
87 // 2. Otherwise, if c is U+003A (:), then [...]
89 // We begin at |scheme.begin + 1|, because the character at |scheme.begin| has
90 // already been checked by base::IsAsciiAlpha above.
91 int scheme_end = scheme.end();
92 for (int i = scheme.begin + 1; i < scheme_end; i++) {
93 if (!CanonicalSchemeChar(url[i]))
100 // See IsRelativeURL in the header file for usage.
101 template<typename CHAR>
102 bool DoIsRelativeURL(const char* base,
103 const Parsed& base_parsed,
106 bool is_base_hierarchical,
108 Component* relative_component) {
109 *is_relative = false; // So we can default later to not relative.
111 // Trim whitespace and construct a new range for the substring.
113 TrimURL(url, &begin, &url_len);
114 if (begin >= url_len) {
115 // Empty URLs are relative, but do nothing.
116 if (!is_base_hierarchical) {
117 // Don't allow relative URLs if the base scheme doesn't support it.
120 *relative_component = Component(begin, 0);
126 // We special case paths like "C:\foo" so they can link directly to the
127 // file on Windows (IE compatibility). The security domain stuff should
128 // prevent a link like this from actually being followed if its on a
131 // We treat "C:/foo" as an absolute URL. We can go ahead and treat "/c:/"
132 // as relative, as this will just replace the path when the base scheme
133 // is a file and the answer will still be correct.
135 // We require strict backslashes when detecting UNC since two forward
136 // slashes should be treated a a relative URL with a hostname.
137 if (DoesBeginWindowsDriveSpec(url, begin, url_len) ||
138 DoesBeginUNCPath(url, begin, url_len, true))
142 // See if we've got a scheme, if not, we know this is a relative URL.
143 // BUT, just because we have a scheme, doesn't make it absolute.
144 // "http:foo.html" is a relative URL with path "foo.html". If the scheme is
145 // empty, we treat it as relative (":foo"), like IE does.
147 const bool scheme_is_empty =
148 !ExtractScheme(url, url_len, &scheme) || scheme.len == 0;
149 if (scheme_is_empty) {
150 if (url[begin] == '#') {
151 // |url| is a bare fragment (e.g. "#foo"). This can be resolved against
152 // any base. Fall-through.
153 } else if (!is_base_hierarchical) {
154 // Don't allow relative URLs if the base scheme doesn't support it.
158 *relative_component = MakeRange(begin, url_len);
163 // If the scheme isn't valid, then it's relative.
164 if (!IsValidScheme(url, scheme)) {
165 if (!is_base_hierarchical) {
166 // Don't allow relative URLs if the base scheme doesn't support it.
169 *relative_component = MakeRange(begin, url_len);
174 // If the scheme is not the same, then we can't count it as relative.
175 if (!AreSchemesEqual(base, base_parsed.scheme, url, scheme))
178 // When the scheme that they both share is not hierarchical, treat the
179 // incoming scheme as absolute (this way with the base of "data:foo",
180 // "data:bar" will be reported as absolute.
181 if (!is_base_hierarchical)
184 int colon_offset = scheme.end();
186 // If it's a filesystem URL, the only valid way to make it relative is not to
187 // supply a scheme. There's no equivalent to e.g. http:index.html.
188 if (CompareSchemeComponent(url, scheme, kFileSystemScheme))
191 // ExtractScheme guarantees that the colon immediately follows what it
192 // considers to be the scheme. CountConsecutiveSlashes will handle the
193 // case where the begin offset is the end of the input.
194 int num_slashes = CountConsecutiveSlashes(url, colon_offset + 1, url_len);
196 if (num_slashes == 0 || num_slashes == 1) {
197 // No slashes means it's a relative path like "http:foo.html". One slash
198 // is an absolute path. "http:/home/foo.html"
200 *relative_component = MakeRange(colon_offset + 1, url_len);
204 // Two or more slashes after the scheme we treat as absolute.
208 // Copies all characters in the range [begin, end) of |spec| to the output,
209 // up until and including the last slash. There should be a slash in the
210 // range, if not, nothing will be copied.
212 // For stardard URLs the input should be canonical, but when resolving relative
213 // URLs on a non-standard base (like "data:") the input can be anything.
214 void CopyToLastSlash(const char* spec,
217 CanonOutput* output) {
218 // Find the last slash.
220 for (int i = end - 1; i >= begin; i--) {
221 if (spec[i] == '/' || spec[i] == '\\') {
230 for (int i = begin; i <= last_slash; i++)
231 output->push_back(spec[i]);
234 // Copies a single component from the source to the output. This is used
235 // when resolving relative URLs and a given component is unchanged. Since the
236 // source should already be canonical, we don't have to do anything special,
237 // and the input is ASCII.
238 void CopyOneComponent(const char* source,
239 const Component& source_component,
241 Component* output_component) {
242 if (source_component.len < 0) {
243 // This component is not present.
244 *output_component = Component();
248 output_component->begin = output->length();
249 int source_end = source_component.end();
250 for (int i = source_component.begin; i < source_end; i++)
251 output->push_back(source[i]);
252 output_component->len = output->length() - output_component->begin;
257 // Called on Windows when the base URL is a file URL, this will copy the "C:"
258 // to the output, if there is a drive letter and if that drive letter is not
259 // being overridden by the relative URL. Otherwise, do nothing.
261 // It will return the index of the beginning of the next character in the
262 // base to be processed: if there is a "C:", the slash after it, or if
263 // there is no drive letter, the slash at the beginning of the path, or
264 // the end of the base. This can be used as the starting offset for further
266 template<typename CHAR>
267 int CopyBaseDriveSpecIfNecessary(const char* base_url,
270 const CHAR* relative_url,
272 int relative_url_len,
273 CanonOutput* output) {
274 if (base_path_begin >= base_path_end)
275 return base_path_begin; // No path.
277 // If the relative begins with a drive spec, don't do anything. The existing
278 // drive spec in the base will be replaced.
279 if (DoesBeginWindowsDriveSpec(relative_url, path_start, relative_url_len)) {
280 return base_path_begin; // Relative URL path is "C:/foo"
283 // The path should begin with a slash (as all canonical paths do). We check
284 // if it is followed by a drive letter and copy it.
285 if (DoesBeginSlashWindowsDriveSpec(base_url,
288 // Copy the two-character drive spec to the output. It will now look like
289 // "file:///C:" so the rest of it can be treated like a standard path.
290 output->push_back('/');
291 output->push_back(base_url[base_path_begin + 1]);
292 output->push_back(base_url[base_path_begin + 2]);
293 return base_path_begin + 3;
296 return base_path_begin;
301 // A subroutine of DoResolveRelativeURL, this resolves the URL knowning that
302 // the input is a relative path or less (query or ref).
303 template<typename CHAR>
304 bool DoResolveRelativePath(const char* base_url,
305 const Parsed& base_parsed,
307 const CHAR* relative_url,
308 const Component& relative_component,
309 CharsetConverter* query_converter,
311 Parsed* out_parsed) {
314 // We know the authority section didn't change, copy it to the output. We
315 // also know we have a path so can copy up to there.
316 Component path, query, ref;
317 ParsePathInternal(relative_url, relative_component, &path, &query, &ref);
319 // Canonical URLs always have a path, so we can use that offset. Reserve
320 // enough room for the base URL, the new path, and some extra bytes for
321 // possible escaped characters.
322 output->ReserveSizeIfNeeded(base_parsed.path.begin +
323 std::max({path.end(), query.end(), ref.end()}));
324 output->Append(base_url, base_parsed.path.begin);
327 // The path is replaced or modified.
328 int true_path_begin = output->length();
330 // For file: URLs on Windows, we don't want to treat the drive letter and
331 // colon as part of the path for relative file resolution when the
332 // incoming URL does not provide a drive spec. We save the true path
333 // beginning so we can fix it up after we are done.
334 int base_path_begin = base_parsed.path.begin;
337 base_path_begin = CopyBaseDriveSpecIfNecessary(
338 base_url, base_parsed.path.begin, base_parsed.path.end(),
339 relative_url, relative_component.begin, relative_component.end(),
341 // Now the output looks like either "file://" or "file:///C:"
342 // and we can start appending the rest of the path. |base_path_begin|
343 // points to the character in the base that comes next.
347 if (IsURLSlash(relative_url[path.begin])) {
348 // Easy case: the path is an absolute path on the server, so we can
349 // just replace everything from the path on with the new versions.
350 // Since the input should be canonical hierarchical URL, we should
351 // always have a path.
352 success &= CanonicalizePath(relative_url, path,
353 output, &out_parsed->path);
355 // Relative path, replace the query, and reference. We take the
356 // original path with the file part stripped, and append the new path.
357 // The canonicalizer will take care of resolving ".." and "."
358 int path_begin = output->length();
359 CopyToLastSlash(base_url, base_path_begin, base_parsed.path.end(),
361 success &= CanonicalizePartialPath(relative_url, path, path_begin,
363 out_parsed->path = MakeRange(path_begin, output->length());
365 // Copy the rest of the stuff after the path from the relative path.
368 // Finish with the query and reference part (these can't fail).
369 CanonicalizeQuery(relative_url, query, query_converter,
370 output, &out_parsed->query);
371 CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
373 // Fix the path beginning to add back the "C:" we may have written above.
374 out_parsed->path = MakeRange(true_path_begin, out_parsed->path.end());
378 // If we get here, the path is unchanged: copy to output.
379 CopyOneComponent(base_url, base_parsed.path, output, &out_parsed->path);
381 if (query.is_valid()) {
382 // Just the query specified, replace the query and reference (ignore
383 // failures for refs)
384 CanonicalizeQuery(relative_url, query, query_converter,
385 output, &out_parsed->query);
386 CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
390 // If we get here, the query is unchanged: copy to output. Note that the
391 // range of the query parameter doesn't include the question mark, so we
392 // have to add it manually if there is a component.
393 if (base_parsed.query.is_valid())
394 output->push_back('?');
395 CopyOneComponent(base_url, base_parsed.query, output, &out_parsed->query);
397 if (ref.is_valid()) {
398 // Just the reference specified: replace it (ignoring failures).
399 CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
403 // We should always have something to do in this function, the caller checks
404 // that some component is being replaced.
405 DCHECK(false) << "Not reached";
409 // Resolves a relative URL that contains a host. Typically, these will
410 // be of the form "//www.google.com/foo/bar?baz#ref" and the only thing which
411 // should be kept from the original URL is the scheme.
412 template<typename CHAR>
413 bool DoResolveRelativeHost(const char* base_url,
414 const Parsed& base_parsed,
415 const CHAR* relative_url,
416 const Component& relative_component,
417 CharsetConverter* query_converter,
419 Parsed* out_parsed) {
420 // Parse the relative URL, just like we would for anything following a
422 Parsed relative_parsed; // Everything but the scheme is valid.
423 ParseAfterScheme(relative_url, relative_component.end(),
424 relative_component.begin, &relative_parsed);
426 // Now we can just use the replacement function to replace all the necessary
427 // parts of the old URL with the new one.
428 Replacements<CHAR> replacements;
429 replacements.SetUsername(relative_url, relative_parsed.username);
430 replacements.SetPassword(relative_url, relative_parsed.password);
431 replacements.SetHost(relative_url, relative_parsed.host);
432 replacements.SetPort(relative_url, relative_parsed.port);
433 replacements.SetPath(relative_url, relative_parsed.path);
434 replacements.SetQuery(relative_url, relative_parsed.query);
435 replacements.SetRef(relative_url, relative_parsed.ref);
437 // Length() does not include the old scheme, so make sure to add it from the
439 output->ReserveSizeIfNeeded(
440 replacements.components().Length() +
441 base_parsed.CountCharactersBefore(Parsed::USERNAME, false));
442 SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
443 if (!GetStandardSchemeType(base_url, base_parsed.scheme, &scheme_type)) {
444 // A path with an authority section gets canonicalized under standard URL
445 // rules, even though the base was not known to be standard.
446 scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
448 return ReplaceStandardURL(base_url, base_parsed, replacements, scheme_type,
449 query_converter, output, out_parsed);
452 // Resolves a relative URL that happens to be an absolute file path. Examples
453 // include: "//hostname/path", "/c:/foo", and "//hostname/c:/foo".
454 template<typename CHAR>
455 bool DoResolveAbsoluteFile(const CHAR* relative_url,
456 const Component& relative_component,
457 CharsetConverter* query_converter,
459 Parsed* out_parsed) {
460 // Parse the file URL. The file URl parsing function uses the same logic
461 // as we do for determining if the file is absolute, in which case it will
462 // not bother to look for a scheme.
463 Parsed relative_parsed;
464 ParseFileURL(&relative_url[relative_component.begin], relative_component.len,
467 return CanonicalizeFileURL(&relative_url[relative_component.begin],
468 relative_component.len, relative_parsed,
469 query_converter, output, out_parsed);
472 // TODO(brettw) treat two slashes as root like Mozilla for FTP?
473 template<typename CHAR>
474 bool DoResolveRelativeURL(const char* base_url,
475 const Parsed& base_parsed,
477 const CHAR* relative_url,
478 const Component& relative_component,
479 CharsetConverter* query_converter,
481 Parsed* out_parsed) {
482 // |base_parsed| is the starting point for our output. Since we may have
483 // removed whitespace from |relative_url| before entering this method, we'll
484 // carry over the |potentially_dangling_markup| flag.
485 bool potentially_dangling_markup = out_parsed->potentially_dangling_markup;
486 *out_parsed = base_parsed;
487 if (potentially_dangling_markup)
488 out_parsed->potentially_dangling_markup = true;
490 // Sanity check: the input should have a host or we'll break badly below.
491 // We can only resolve relative URLs with base URLs that have hosts and
492 // paths (even the default path of "/" is OK).
494 // We allow hosts with no length so we can handle file URLs, for example.
495 if (base_parsed.path.len <= 0) {
496 // On error, return the input (resolving a relative URL on a non-relative
498 int base_len = base_parsed.Length();
499 for (int i = 0; i < base_len; i++)
500 output->push_back(base_url[i]);
504 if (relative_component.len <= 0) {
505 // Empty relative URL, leave unchanged, only removing the ref component.
506 int base_len = base_parsed.Length();
507 base_len -= base_parsed.ref.len + 1;
508 out_parsed->ref.reset();
509 output->Append(base_url, base_len);
513 int num_slashes = CountConsecutiveSlashes(
514 relative_url, relative_component.begin, relative_component.end());
517 // On Windows, two slashes for a file path (regardless of which direction
518 // they are) means that it's UNC. Two backslashes on any base scheme mean
519 // that it's an absolute UNC path (we use the base_is_file flag to control
520 // how strict the UNC finder is).
522 // We also allow Windows absolute drive specs on any scheme (for example
523 // "c:\foo") like IE does. There must be no preceding slashes in this
524 // case (we reject anything like "/c:/foo") because that should be treated
525 // as a path. For file URLs, we allow any number of slashes since that would
526 // be setting the path.
528 // This assumes the absolute path resolver handles absolute URLs like this
529 // properly. DoCanonicalize does this.
530 int after_slashes = relative_component.begin + num_slashes;
531 if (DoesBeginUNCPath(relative_url, relative_component.begin,
532 relative_component.end(), !base_is_file) ||
533 ((num_slashes == 0 || base_is_file) &&
534 DoesBeginWindowsDriveSpec(
535 relative_url, after_slashes, relative_component.end()))) {
536 return DoResolveAbsoluteFile(relative_url, relative_component,
537 query_converter, output, out_parsed);
540 // Other platforms need explicit handling for file: URLs with multiple
541 // slashes because the generic scheme parsing always extracts a host, but a
542 // file: URL only has a host if it has exactly 2 slashes. Even if it does
543 // have a host, we want to use the special host detection logic for file
544 // URLs provided by DoResolveAbsoluteFile(), as opposed to the generic host
545 // detection logic, for consistency with parsing file URLs from scratch.
546 // This also handles the special case where the URL is only slashes,
547 // since that doesn't have a host part either.
549 (num_slashes >= 2 || num_slashes == relative_component.len)) {
550 return DoResolveAbsoluteFile(relative_url, relative_component,
551 query_converter, output, out_parsed);
555 // Any other double-slashes mean that this is relative to the scheme.
556 if (num_slashes >= 2) {
557 return DoResolveRelativeHost(base_url, base_parsed,
558 relative_url, relative_component,
559 query_converter, output, out_parsed);
562 // When we get here, we know that the relative URL is on the same host.
563 return DoResolveRelativePath(base_url, base_parsed, base_is_file,
564 relative_url, relative_component,
565 query_converter, output, out_parsed);
570 bool IsRelativeURL(const char* base,
571 const Parsed& base_parsed,
572 const char* fragment,
574 bool is_base_hierarchical,
576 Component* relative_component) {
577 return DoIsRelativeURL<char>(
578 base, base_parsed, fragment, fragment_len, is_base_hierarchical,
579 is_relative, relative_component);
582 bool IsRelativeURL(const char* base,
583 const Parsed& base_parsed,
584 const base::char16* fragment,
586 bool is_base_hierarchical,
588 Component* relative_component) {
589 return DoIsRelativeURL<base::char16>(
590 base, base_parsed, fragment, fragment_len, is_base_hierarchical,
591 is_relative, relative_component);
594 bool ResolveRelativeURL(const char* base_url,
595 const Parsed& base_parsed,
597 const char* relative_url,
598 const Component& relative_component,
599 CharsetConverter* query_converter,
601 Parsed* out_parsed) {
602 return DoResolveRelativeURL<char>(
603 base_url, base_parsed, base_is_file, relative_url,
604 relative_component, query_converter, output, out_parsed);
607 bool ResolveRelativeURL(const char* base_url,
608 const Parsed& base_parsed,
610 const base::char16* relative_url,
611 const Component& relative_component,
612 CharsetConverter* query_converter,
614 Parsed* out_parsed) {
615 return DoResolveRelativeURL<base::char16>(
616 base_url, base_parsed, base_is_file, relative_url,
617 relative_component, query_converter, output, out_parsed);