Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / url / url_canon_relative.cc
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.
4
5 // Canonicalizer functions for working with and resolving relative URLs.
6
7 #include <algorithm>
8
9 #include "base/logging.h"
10 #include "url/url_canon.h"
11 #include "url/url_canon_internal.h"
12 #include "url/url_constants.h"
13 #include "url/url_file.h"
14 #include "url/url_parse_internal.h"
15 #include "url/url_util.h"
16 #include "url/url_util_internal.h"
17
18 namespace url {
19
20 namespace {
21
22 // Firefox does a case-sensitive compare (which is probably wrong--Mozilla bug
23 // 379034), whereas IE is case-insensitive.
24 //
25 // We choose to be more permissive like IE. We don't need to worry about
26 // unescaping or anything here: neither IE or Firefox allow this. We also
27 // don't have to worry about invalid scheme characters since we are comparing
28 // against the canonical scheme of the base.
29 //
30 // The base URL should always be canonical, therefore it should be ASCII.
31 template<typename CHAR>
32 bool AreSchemesEqual(const char* base,
33                      const Component& base_scheme,
34                      const CHAR* cmp,
35                      const Component& cmp_scheme) {
36   if (base_scheme.len != cmp_scheme.len)
37     return false;
38   for (int i = 0; i < base_scheme.len; i++) {
39     // We assume the base is already canonical, so we don't have to
40     // canonicalize it.
41     if (CanonicalSchemeChar(cmp[cmp_scheme.begin + i]) !=
42         base[base_scheme.begin + i])
43       return false;
44   }
45   return true;
46 }
47
48 #ifdef WIN32
49
50 // Here, we also allow Windows paths to be represented as "/C:/" so we can be
51 // consistent about URL paths beginning with slashes. This function is like
52 // DoesBeginWindowsDrivePath except that it also requires a slash at the
53 // beginning.
54 template<typename CHAR>
55 bool DoesBeginSlashWindowsDriveSpec(const CHAR* spec, int start_offset,
56                                     int spec_len) {
57   if (start_offset >= spec_len)
58     return false;
59   return IsURLSlash(spec[start_offset]) &&
60          DoesBeginWindowsDriveSpec(spec, start_offset + 1, spec_len);
61 }
62
63 #endif  // WIN32
64
65 // See IsRelativeURL in the header file for usage.
66 template<typename CHAR>
67 bool DoIsRelativeURL(const char* base,
68                      const Parsed& base_parsed,
69                      const CHAR* url,
70                      int url_len,
71                      bool is_base_hierarchical,
72                      bool* is_relative,
73                      Component* relative_component) {
74   *is_relative = false;  // So we can default later to not relative.
75
76   // Trim whitespace and construct a new range for the substring.
77   int begin = 0;
78   TrimURL(url, &begin, &url_len);
79   if (begin >= url_len) {
80     // Empty URLs are relative, but do nothing.
81     if (!is_base_hierarchical) {
82       // Don't allow relative URLs if the base scheme doesn't support it.
83       return false;
84     }
85     *relative_component = Component(begin, 0);
86     *is_relative = true;
87     return true;
88   }
89
90 #ifdef WIN32
91   // We special case paths like "C:\foo" so they can link directly to the
92   // file on Windows (IE compatibility). The security domain stuff should
93   // prevent a link like this from actually being followed if its on a
94   // web page.
95   //
96   // We treat "C:/foo" as an absolute URL. We can go ahead and treat "/c:/"
97   // as relative, as this will just replace the path when the base scheme
98   // is a file and the answer will still be correct.
99   //
100   // We require strict backslashes when detecting UNC since two forward
101   // slashes should be treated a a relative URL with a hostname.
102   if (DoesBeginWindowsDriveSpec(url, begin, url_len) ||
103       DoesBeginUNCPath(url, begin, url_len, true))
104     return true;
105 #endif  // WIN32
106
107   // See if we've got a scheme, if not, we know this is a relative URL.
108   // BUT, just because we have a scheme, doesn't make it absolute.
109   // "http:foo.html" is a relative URL with path "foo.html". If the scheme is
110   // empty, we treat it as relative (":foo"), like IE does.
111   Component scheme;
112   const bool scheme_is_empty =
113       !ExtractScheme(url, url_len, &scheme) || scheme.len == 0;
114   if (scheme_is_empty) {
115     if (url[begin] == '#') {
116       // |url| is a bare fragment (e.g. "#foo"). This can be resolved against
117       // any base. Fall-through.
118     } else if (!is_base_hierarchical) {
119       // Don't allow relative URLs if the base scheme doesn't support it.
120       return false;
121     }
122
123     *relative_component = MakeRange(begin, url_len);
124     *is_relative = true;
125     return true;
126   }
127
128   // If the scheme isn't valid, then it's relative.
129   int scheme_end = scheme.end();
130   for (int i = scheme.begin; i < scheme_end; i++) {
131     if (!CanonicalSchemeChar(url[i])) {
132       if (!is_base_hierarchical) {
133         // Don't allow relative URLs if the base scheme doesn't support it.
134         return false;
135       }
136       *relative_component = MakeRange(begin, url_len);
137       *is_relative = true;
138       return true;
139     }
140   }
141
142   // If the scheme is not the same, then we can't count it as relative.
143   if (!AreSchemesEqual(base, base_parsed.scheme, url, scheme))
144     return true;
145
146   // When the scheme that they both share is not hierarchical, treat the
147   // incoming scheme as absolute (this way with the base of "data:foo",
148   // "data:bar" will be reported as absolute.
149   if (!is_base_hierarchical)
150     return true;
151
152   int colon_offset = scheme.end();
153
154   // If it's a filesystem URL, the only valid way to make it relative is not to
155   // supply a scheme. There's no equivalent to e.g. http:index.html.
156   if (CompareSchemeComponent(url, scheme, kFileSystemScheme))
157     return true;
158
159   // ExtractScheme guarantees that the colon immediately follows what it
160   // considers to be the scheme. CountConsecutiveSlashes will handle the
161   // case where the begin offset is the end of the input.
162   int num_slashes = CountConsecutiveSlashes(url, colon_offset + 1, url_len);
163
164   if (num_slashes == 0 || num_slashes == 1) {
165     // No slashes means it's a relative path like "http:foo.html". One slash
166     // is an absolute path. "http:/home/foo.html"
167     *is_relative = true;
168     *relative_component = MakeRange(colon_offset + 1, url_len);
169     return true;
170   }
171
172   // Two or more slashes after the scheme we treat as absolute.
173   return true;
174 }
175
176 // Copies all characters in the range [begin, end) of |spec| to the output,
177 // up until and including the last slash. There should be a slash in the
178 // range, if not, nothing will be copied.
179 //
180 // For stardard URLs the input should be canonical, but when resolving relative
181 // URLs on a non-standard base (like "data:") the input can be anything.
182 void CopyToLastSlash(const char* spec,
183                      int begin,
184                      int end,
185                      CanonOutput* output) {
186   // Find the last slash.
187   int last_slash = -1;
188   for (int i = end - 1; i >= begin; i--) {
189     if (spec[i] == '/' || spec[i] == '\\') {
190       last_slash = i;
191       break;
192     }
193   }
194   if (last_slash < 0)
195     return;  // No slash.
196
197   // Copy.
198   for (int i = begin; i <= last_slash; i++)
199     output->push_back(spec[i]);
200 }
201
202 // Copies a single component from the source to the output. This is used
203 // when resolving relative URLs and a given component is unchanged. Since the
204 // source should already be canonical, we don't have to do anything special,
205 // and the input is ASCII.
206 void CopyOneComponent(const char* source,
207                       const Component& source_component,
208                       CanonOutput* output,
209                       Component* output_component) {
210   if (source_component.len < 0) {
211     // This component is not present.
212     *output_component = Component();
213     return;
214   }
215
216   output_component->begin = output->length();
217   int source_end = source_component.end();
218   for (int i = source_component.begin; i < source_end; i++)
219     output->push_back(source[i]);
220   output_component->len = output->length() - output_component->begin;
221 }
222
223 #ifdef WIN32
224
225 // Called on Windows when the base URL is a file URL, this will copy the "C:"
226 // to the output, if there is a drive letter and if that drive letter is not
227 // being overridden by the relative URL. Otherwise, do nothing.
228 //
229 // It will return the index of the beginning of the next character in the
230 // base to be processed: if there is a "C:", the slash after it, or if
231 // there is no drive letter, the slash at the beginning of the path, or
232 // the end of the base. This can be used as the starting offset for further
233 // path processing.
234 template<typename CHAR>
235 int CopyBaseDriveSpecIfNecessary(const char* base_url,
236                                  int base_path_begin,
237                                  int base_path_end,
238                                  const CHAR* relative_url,
239                                  int path_start,
240                                  int relative_url_len,
241                                  CanonOutput* output) {
242   if (base_path_begin >= base_path_end)
243     return base_path_begin;  // No path.
244
245   // If the relative begins with a drive spec, don't do anything. The existing
246   // drive spec in the base will be replaced.
247   if (DoesBeginWindowsDriveSpec(relative_url, path_start, relative_url_len)) {
248     return base_path_begin;  // Relative URL path is "C:/foo"
249   }
250
251   // The path should begin with a slash (as all canonical paths do). We check
252   // if it is followed by a drive letter and copy it.
253   if (DoesBeginSlashWindowsDriveSpec(base_url,
254                                      base_path_begin,
255                                      base_path_end)) {
256     // Copy the two-character drive spec to the output. It will now look like
257     // "file:///C:" so the rest of it can be treated like a standard path.
258     output->push_back('/');
259     output->push_back(base_url[base_path_begin + 1]);
260     output->push_back(base_url[base_path_begin + 2]);
261     return base_path_begin + 3;
262   }
263
264   return base_path_begin;
265 }
266
267 #endif  // WIN32
268
269 // A subroutine of DoResolveRelativeURL, this resolves the URL knowning that
270 // the input is a relative path or less (query or ref).
271 template<typename CHAR>
272 bool DoResolveRelativePath(const char* base_url,
273                            const Parsed& base_parsed,
274                            bool base_is_file,
275                            const CHAR* relative_url,
276                            const Component& relative_component,
277                            CharsetConverter* query_converter,
278                            CanonOutput* output,
279                            Parsed* out_parsed) {
280   bool success = true;
281
282   // We know the authority section didn't change, copy it to the output. We
283   // also know we have a path so can copy up to there.
284   Component path, query, ref;
285   ParsePathInternal(relative_url, relative_component, &path, &query, &ref);
286
287   // Canonical URLs always have a path, so we can use that offset. Reserve
288   // enough room for the base URL, the new path, and some extra bytes for
289   // possible escaped characters.
290   output->ReserveSizeIfNeeded(
291       base_parsed.path.begin +
292       std::max(path.end(), std::max(query.end(), ref.end())));
293   output->Append(base_url, base_parsed.path.begin);
294
295   if (path.len > 0) {
296     // The path is replaced or modified.
297     int true_path_begin = output->length();
298
299     // For file: URLs on Windows, we don't want to treat the drive letter and
300     // colon as part of the path for relative file resolution when the
301     // incoming URL does not provide a drive spec. We save the true path
302     // beginning so we can fix it up after we are done.
303     int base_path_begin = base_parsed.path.begin;
304 #ifdef WIN32
305     if (base_is_file) {
306       base_path_begin = CopyBaseDriveSpecIfNecessary(
307           base_url, base_parsed.path.begin, base_parsed.path.end(),
308           relative_url, relative_component.begin, relative_component.end(),
309           output);
310       // Now the output looks like either "file://" or "file:///C:"
311       // and we can start appending the rest of the path. |base_path_begin|
312       // points to the character in the base that comes next.
313     }
314 #endif  // WIN32
315
316     if (IsURLSlash(relative_url[path.begin])) {
317       // Easy case: the path is an absolute path on the server, so we can
318       // just replace everything from the path on with the new versions.
319       // Since the input should be canonical hierarchical URL, we should
320       // always have a path.
321       success &= CanonicalizePath(relative_url, path,
322                                   output, &out_parsed->path);
323     } else {
324       // Relative path, replace the query, and reference. We take the
325       // original path with the file part stripped, and append the new path.
326       // The canonicalizer will take care of resolving ".." and "."
327       int path_begin = output->length();
328       CopyToLastSlash(base_url, base_path_begin, base_parsed.path.end(),
329                       output);
330       success &= CanonicalizePartialPath(relative_url, path, path_begin,
331                                          output);
332       out_parsed->path = MakeRange(path_begin, output->length());
333
334       // Copy the rest of the stuff after the path from the relative path.
335     }
336
337     // Finish with the query and reference part (these can't fail).
338     CanonicalizeQuery(relative_url, query, query_converter,
339                       output, &out_parsed->query);
340     CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
341
342     // Fix the path beginning to add back the "C:" we may have written above.
343     out_parsed->path = MakeRange(true_path_begin, out_parsed->path.end());
344     return success;
345   }
346
347   // If we get here, the path is unchanged: copy to output.
348   CopyOneComponent(base_url, base_parsed.path, output, &out_parsed->path);
349
350   if (query.is_valid()) {
351     // Just the query specified, replace the query and reference (ignore
352     // failures for refs)
353     CanonicalizeQuery(relative_url, query, query_converter,
354                       output, &out_parsed->query);
355     CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
356     return success;
357   }
358
359   // If we get here, the query is unchanged: copy to output. Note that the
360   // range of the query parameter doesn't include the question mark, so we
361   // have to add it manually if there is a component.
362   if (base_parsed.query.is_valid())
363     output->push_back('?');
364   CopyOneComponent(base_url, base_parsed.query, output, &out_parsed->query);
365
366   if (ref.is_valid()) {
367     // Just the reference specified: replace it (ignoring failures).
368     CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
369     return success;
370   }
371
372   // We should always have something to do in this function, the caller checks
373   // that some component is being replaced.
374   DCHECK(false) << "Not reached";
375   return success;
376 }
377
378 // Resolves a relative URL that contains a host. Typically, these will
379 // be of the form "//www.google.com/foo/bar?baz#ref" and the only thing which
380 // should be kept from the original URL is the scheme.
381 template<typename CHAR>
382 bool DoResolveRelativeHost(const char* base_url,
383                            const Parsed& base_parsed,
384                            const CHAR* relative_url,
385                            const Component& relative_component,
386                            CharsetConverter* query_converter,
387                            CanonOutput* output,
388                            Parsed* out_parsed) {
389   // Parse the relative URL, just like we would for anything following a
390   // scheme.
391   Parsed relative_parsed;  // Everything but the scheme is valid.
392   ParseAfterScheme(relative_url, relative_component.end(),
393                    relative_component.begin, &relative_parsed);
394
395   // Now we can just use the replacement function to replace all the necessary
396   // parts of the old URL with the new one.
397   Replacements<CHAR> replacements;
398   replacements.SetUsername(relative_url, relative_parsed.username);
399   replacements.SetPassword(relative_url, relative_parsed.password);
400   replacements.SetHost(relative_url, relative_parsed.host);
401   replacements.SetPort(relative_url, relative_parsed.port);
402   replacements.SetPath(relative_url, relative_parsed.path);
403   replacements.SetQuery(relative_url, relative_parsed.query);
404   replacements.SetRef(relative_url, relative_parsed.ref);
405
406   // Length() does not include the old scheme, so make sure to add it from the
407   // base URL.
408   output->ReserveSizeIfNeeded(
409       replacements.components().Length() +
410       base_parsed.CountCharactersBefore(Parsed::USERNAME, false));
411   SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
412   if (!GetStandardSchemeType(base_url, base_parsed.scheme, &scheme_type)) {
413     // A path with an authority section gets canonicalized under standard URL
414     // rules, even though the base was not known to be standard.
415     scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
416   }
417   return ReplaceStandardURL(base_url, base_parsed, replacements, scheme_type,
418                             query_converter, output, out_parsed);
419 }
420
421 // Resolves a relative URL that happens to be an absolute file path. Examples
422 // include: "//hostname/path", "/c:/foo", and "//hostname/c:/foo".
423 template<typename CHAR>
424 bool DoResolveAbsoluteFile(const CHAR* relative_url,
425                            const Component& relative_component,
426                            CharsetConverter* query_converter,
427                            CanonOutput* output,
428                            Parsed* out_parsed) {
429   // Parse the file URL. The file URl parsing function uses the same logic
430   // as we do for determining if the file is absolute, in which case it will
431   // not bother to look for a scheme.
432   Parsed relative_parsed;
433   ParseFileURL(&relative_url[relative_component.begin], relative_component.len,
434                &relative_parsed);
435
436   return CanonicalizeFileURL(&relative_url[relative_component.begin],
437                              relative_component.len, relative_parsed,
438                              query_converter, output, out_parsed);
439 }
440
441 // TODO(brettw) treat two slashes as root like Mozilla for FTP?
442 template<typename CHAR>
443 bool DoResolveRelativeURL(const char* base_url,
444                           const Parsed& base_parsed,
445                           bool base_is_file,
446                           const CHAR* relative_url,
447                           const Component& relative_component,
448                           CharsetConverter* query_converter,
449                           CanonOutput* output,
450                           Parsed* out_parsed) {
451   // |base_parsed| is the starting point for our output. Since we may have
452   // removed whitespace from |relative_url| before entering this method, we'll
453   // carry over the |potentially_dangling_markup| flag.
454   bool potentially_dangling_markup = out_parsed->potentially_dangling_markup;
455   *out_parsed = base_parsed;
456   if (potentially_dangling_markup)
457     out_parsed->potentially_dangling_markup = true;
458
459   // Sanity check: the input should have a host or we'll break badly below.
460   // We can only resolve relative URLs with base URLs that have hosts and
461   // paths (even the default path of "/" is OK).
462   //
463   // We allow hosts with no length so we can handle file URLs, for example.
464   if (base_parsed.path.len <= 0) {
465     // On error, return the input (resolving a relative URL on a non-relative
466     // base = the base).
467     int base_len = base_parsed.Length();
468     for (int i = 0; i < base_len; i++)
469       output->push_back(base_url[i]);
470     return false;
471   }
472
473   if (relative_component.len <= 0) {
474     // Empty relative URL, leave unchanged, only removing the ref component.
475     int base_len = base_parsed.Length();
476     base_len -= base_parsed.ref.len + 1;
477     out_parsed->ref.reset();
478     output->Append(base_url, base_len);
479     return true;
480   }
481
482   int num_slashes = CountConsecutiveSlashes(
483       relative_url, relative_component.begin, relative_component.end());
484
485 #ifdef WIN32
486   // On Windows, two slashes for a file path (regardless of which direction
487   // they are) means that it's UNC. Two backslashes on any base scheme mean
488   // that it's an absolute UNC path (we use the base_is_file flag to control
489   // how strict the UNC finder is).
490   //
491   // We also allow Windows absolute drive specs on any scheme (for example
492   // "c:\foo") like IE does. There must be no preceding slashes in this
493   // case (we reject anything like "/c:/foo") because that should be treated
494   // as a path. For file URLs, we allow any number of slashes since that would
495   // be setting the path.
496   //
497   // This assumes the absolute path resolver handles absolute URLs like this
498   // properly. DoCanonicalize does this.
499   int after_slashes = relative_component.begin + num_slashes;
500   if (DoesBeginUNCPath(relative_url, relative_component.begin,
501                        relative_component.end(), !base_is_file) ||
502       ((num_slashes == 0 || base_is_file) &&
503        DoesBeginWindowsDriveSpec(
504            relative_url, after_slashes, relative_component.end()))) {
505     return DoResolveAbsoluteFile(relative_url, relative_component,
506                                  query_converter, output, out_parsed);
507   }
508 #else
509   // Other platforms need explicit handling for file: URLs with multiple
510   // slashes because the generic scheme parsing always extracts a host, but a
511   // file: URL only has a host if it has exactly 2 slashes. Even if it does
512   // have a host, we want to use the special host detection logic for file
513   // URLs provided by DoResolveAbsoluteFile(), as opposed to the generic host
514   // detection logic, for consistency with parsing file URLs from scratch.
515   // This also handles the special case where the URL is only slashes,
516   // since that doesn't have a host part either.
517   if (base_is_file &&
518       (num_slashes >= 2 || num_slashes == relative_component.len)) {
519     return DoResolveAbsoluteFile(relative_url, relative_component,
520                                  query_converter, output, out_parsed);
521   }
522 #endif
523
524   // Any other double-slashes mean that this is relative to the scheme.
525   if (num_slashes >= 2) {
526     return DoResolveRelativeHost(base_url, base_parsed,
527                                  relative_url, relative_component,
528                                  query_converter, output, out_parsed);
529   }
530
531   // When we get here, we know that the relative URL is on the same host.
532   return DoResolveRelativePath(base_url, base_parsed, base_is_file,
533                                relative_url, relative_component,
534                                query_converter, output, out_parsed);
535 }
536
537 }  // namespace
538
539 bool IsRelativeURL(const char* base,
540                    const Parsed& base_parsed,
541                    const char* fragment,
542                    int fragment_len,
543                    bool is_base_hierarchical,
544                    bool* is_relative,
545                    Component* relative_component) {
546   return DoIsRelativeURL<char>(
547       base, base_parsed, fragment, fragment_len, is_base_hierarchical,
548       is_relative, relative_component);
549 }
550
551 bool IsRelativeURL(const char* base,
552                    const Parsed& base_parsed,
553                    const base::char16* fragment,
554                    int fragment_len,
555                    bool is_base_hierarchical,
556                    bool* is_relative,
557                    Component* relative_component) {
558   return DoIsRelativeURL<base::char16>(
559       base, base_parsed, fragment, fragment_len, is_base_hierarchical,
560       is_relative, relative_component);
561 }
562
563 bool ResolveRelativeURL(const char* base_url,
564                         const Parsed& base_parsed,
565                         bool base_is_file,
566                         const char* relative_url,
567                         const Component& relative_component,
568                         CharsetConverter* query_converter,
569                         CanonOutput* output,
570                         Parsed* out_parsed) {
571   return DoResolveRelativeURL<char>(
572       base_url, base_parsed, base_is_file, relative_url,
573       relative_component, query_converter, output, out_parsed);
574 }
575
576 bool ResolveRelativeURL(const char* base_url,
577                         const Parsed& base_parsed,
578                         bool base_is_file,
579                         const base::char16* relative_url,
580                         const Component& relative_component,
581                         CharsetConverter* query_converter,
582                         CanonOutput* output,
583                         Parsed* out_parsed) {
584   return DoResolveRelativeURL<base::char16>(
585       base_url, base_parsed, base_is_file, relative_url,
586       relative_component, query_converter, output, out_parsed);
587 }
588
589 }  // namespace url