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