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