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>
AreSchemesEqual(const char * base,const Component & base_scheme,const CHAR * cmp,const Component & cmp_scheme)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>
DoesBeginSlashWindowsDriveSpec(const CHAR * spec,int start_offset,int spec_len)58 bool DoesBeginSlashWindowsDriveSpec(const CHAR* spec, int start_offset,
59 int spec_len) {
60 if (start_offset >= spec_len)
61 return false;
62 return IsSlashOrBackslash(spec[start_offset]) &&
63 DoesBeginWindowsDriveSpec(spec, start_offset + 1, spec_len);
64 }
65
66 #endif // WIN32
67
68 template <typename CHAR>
IsValidScheme(const CHAR * url,const Component & scheme)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>
DoIsRelativeURL(const char * base,const Parsed & base_parsed,const CHAR * url,int url_len,bool is_base_hierarchical,bool * is_relative,Component * relative_component)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 // |url| is a bare fragment (e.g. "#foo:bar"). This can be resolved
168 // against any base. Fall-through.
169 } else if (!is_base_hierarchical) {
170 // Don't allow relative URLs if the base scheme doesn't support it.
171 return false;
172 }
173 *relative_component = MakeRange(begin, url_len);
174 *is_relative = true;
175 return true;
176 }
177
178 // If base scheme is not standard, or the schemes are different, we can't
179 // count it as relative.
180 //
181 // URL Standard: https://url.spec.whatwg.org/#scheme-state
182 //
183 // scheme state:
184 // > 2.6. Otherwise, if url is special, base is non-null, and base’s scheme is
185 // > url’s scheme:
186 if ((IsUsingStandardCompliantNonSpecialSchemeURLParsing() &&
187 !IsStandard(base, base_parsed.scheme)) ||
188 !AreSchemesEqual(base, base_parsed.scheme, url, scheme)) {
189 return true;
190 }
191
192 // When the scheme that they both share is not hierarchical, treat the
193 // incoming scheme as absolute (this way with the base of "data:foo",
194 // "data:bar" will be reported as absolute.
195 if (!is_base_hierarchical)
196 return true;
197
198 int colon_offset = scheme.end();
199
200 // If it's a filesystem URL, the only valid way to make it relative is not to
201 // supply a scheme. There's no equivalent to e.g. http:index.html.
202 if (CompareSchemeComponent(url, scheme, kFileSystemScheme))
203 return true;
204
205 // ExtractScheme guarantees that the colon immediately follows what it
206 // considers to be the scheme. CountConsecutiveSlashes will handle the
207 // case where the begin offset is the end of the input.
208 int num_slashes = CountConsecutiveSlashes(url, colon_offset + 1, url_len);
209
210 if (num_slashes == 0 || num_slashes == 1) {
211 // No slashes means it's a relative path like "http:foo.html". One slash
212 // is an absolute path. "http:/home/foo.html"
213 *is_relative = true;
214 *relative_component = MakeRange(colon_offset + 1, url_len);
215 return true;
216 }
217
218 // Two or more slashes after the scheme we treat as absolute.
219 return true;
220 }
221
222 // Copies all characters in the range [begin, end) of |spec| to the output,
223 // up until and including the last slash. There should be a slash in the
224 // range, if not, nothing will be copied.
225 //
226 // For stardard URLs the input should be canonical, but when resolving relative
227 // URLs on a non-standard base (like "data:") the input can be anything.
CopyToLastSlash(const char * spec,int begin,int end,CanonOutput * output)228 void CopyToLastSlash(const char* spec,
229 int begin,
230 int end,
231 CanonOutput* output) {
232 // Find the last slash.
233 int last_slash = -1;
234 for (int i = end - 1; i >= begin; i--) {
235 if (spec[i] == '/' || spec[i] == '\\') {
236 last_slash = i;
237 break;
238 }
239 }
240 if (last_slash < 0)
241 return; // No slash.
242
243 // Copy.
244 for (int i = begin; i <= last_slash; i++)
245 output->push_back(spec[i]);
246 }
247
248 // Copies a single component from the source to the output. This is used
249 // when resolving relative URLs and a given component is unchanged. Since the
250 // source should already be canonical, we don't have to do anything special,
251 // and the input is ASCII.
CopyOneComponent(const char * source,const Component & source_component,CanonOutput * output,Component * output_component)252 void CopyOneComponent(const char* source,
253 const Component& source_component,
254 CanonOutput* output,
255 Component* output_component) {
256 if (!source_component.is_valid()) {
257 // This component is not present.
258 *output_component = Component();
259 return;
260 }
261
262 output_component->begin = output->length();
263 int source_end = source_component.end();
264 for (int i = source_component.begin; i < source_end; i++)
265 output->push_back(source[i]);
266 output_component->len = output->length() - output_component->begin;
267 }
268
269 #ifdef WIN32
270
271 // Called on Windows when the base URL is a file URL, this will copy the "C:"
272 // to the output, if there is a drive letter and if that drive letter is not
273 // being overridden by the relative URL. Otherwise, do nothing.
274 //
275 // It will return the index of the beginning of the next character in the
276 // base to be processed: if there is a "C:", the slash after it, or if
277 // there is no drive letter, the slash at the beginning of the path, or
278 // the end of the base. This can be used as the starting offset for further
279 // path processing.
280 template<typename CHAR>
CopyBaseDriveSpecIfNecessary(const char * base_url,int base_path_begin,int base_path_end,const CHAR * relative_url,int path_start,int relative_url_len,CanonOutput * output)281 int CopyBaseDriveSpecIfNecessary(const char* base_url,
282 int base_path_begin,
283 int base_path_end,
284 const CHAR* relative_url,
285 int path_start,
286 int relative_url_len,
287 CanonOutput* output) {
288 if (base_path_begin >= base_path_end)
289 return base_path_begin; // No path.
290
291 // If the relative begins with a drive spec, don't do anything. The existing
292 // drive spec in the base will be replaced.
293 if (DoesBeginWindowsDriveSpec(relative_url, path_start, relative_url_len)) {
294 return base_path_begin; // Relative URL path is "C:/foo"
295 }
296
297 // The path should begin with a slash (as all canonical paths do). We check
298 // if it is followed by a drive letter and copy it.
299 if (DoesBeginSlashWindowsDriveSpec(base_url,
300 base_path_begin,
301 base_path_end)) {
302 // Copy the two-character drive spec to the output. It will now look like
303 // "file:///C:" so the rest of it can be treated like a standard path.
304 output->push_back('/');
305 output->push_back(base_url[base_path_begin + 1]);
306 output->push_back(base_url[base_path_begin + 2]);
307 return base_path_begin + 3;
308 }
309
310 return base_path_begin;
311 }
312
313 #endif // WIN32
314
315 // A subroutine of DoResolveRelativeURL, this resolves the URL knowning that
316 // the input is a relative path or less (query or ref).
317 template <typename CHAR>
DoResolveRelativePath(const char * base_url,const Parsed & base_parsed,bool base_is_file,const CHAR * relative_url,const Component & relative_component,CharsetConverter * query_converter,CanonMode canon_mode,CanonOutput * output,Parsed * out_parsed)318 bool DoResolveRelativePath(const char* base_url,
319 const Parsed& base_parsed,
320 bool base_is_file,
321 const CHAR* relative_url,
322 const Component& relative_component,
323 CharsetConverter* query_converter,
324 CanonMode canon_mode,
325 CanonOutput* output,
326 Parsed* out_parsed) {
327 bool success = true;
328
329 // We know the authority section didn't change, copy it to the output. We
330 // also know we have a path so can copy up to there.
331 Component path, query, ref;
332 ParsePathInternal(relative_url, relative_component, &path, &query, &ref);
333
334 // Canonical URLs always have a path, so we can use that offset. Reserve
335 // enough room for the base URL, the new path, and some extra bytes for
336 // possible escaped characters.
337 output->ReserveSizeIfNeeded(base_parsed.path.begin +
338 std::max({path.end(), query.end(), ref.end()}));
339
340 // Append a base URL up to the beginning of base URL's path.
341 if (base_parsed.path.is_empty()) {
342 // A non-special URL may have an empty path (e.g. "git://host"). In these
343 // cases, attempting to use `base_parsed.path` is invalid.
344 output->Append(base_url, base_parsed.Length());
345 } else if (url::IsUsingStandardCompliantNonSpecialSchemeURLParsing() &&
346 !base_parsed.host.is_valid() &&
347 // Exclude a file URL and an URL with an inner-path because we are
348 // interested in only non-special URLs here.
349 //
350 // If we don't exclude a file URL here, for example, `new
351 // URL("test", "file:///tmp").href` will result in
352 // "file:/tmp/mock/test" instead of "file:///tmp/mock/test".
353 !base_is_file && !base_parsed.inner_parsed()) {
354 // The URL is a path-only non-special URL. e.g. "git:/path".
355 //
356 // In this case, we can't use `base_parsed.path.begin` because it may append
357 // "/." wrongly if the URL is, for example, "git:/.//a", where
358 // `base_parsed.path` represents "//a", instead of "/.//a". We want to
359 // append "git:", instead of "git:/.".
360 //
361 // Fortunately, we can use `base_parsed.scheme.end()` here because we don't
362 // need to append a user, a password, a host, nor a port when a host is
363 // invalid.
364 output->Append(base_url, base_parsed.scheme.end());
365 output->Append(":");
366 } else {
367 output->Append(base_url, base_parsed.path.begin);
368 }
369
370 if (path.is_nonempty()) {
371 // The path is replaced or modified.
372 int true_path_begin = output->length();
373
374 // For file: URLs on Windows, we don't want to treat the drive letter and
375 // colon as part of the path for relative file resolution when the
376 // incoming URL does not provide a drive spec. We save the true path
377 // beginning so we can fix it up after we are done.
378 int base_path_begin = base_parsed.path.begin;
379 #ifdef WIN32
380 if (base_is_file) {
381 base_path_begin = CopyBaseDriveSpecIfNecessary(
382 base_url, base_parsed.path.begin, base_parsed.path.end(),
383 relative_url, relative_component.begin, relative_component.end(),
384 output);
385 // Now the output looks like either "file://" or "file:///C:"
386 // and we can start appending the rest of the path. |base_path_begin|
387 // points to the character in the base that comes next.
388 }
389 #endif // WIN32
390
391 if (IsSlashOrBackslash(relative_url[path.begin])) {
392 // Easy case: the path is an absolute path on the server, so we can
393 // just replace everything from the path on with the new versions.
394 // Since the input should be canonical hierarchical URL, we should
395 // always have a path.
396 success &= CanonicalizePath(relative_url, path,
397 output, &out_parsed->path);
398 } else {
399 // Relative path, replace the query, and reference. We take the
400 // original path with the file part stripped, and append the new path.
401 // The canonicalizer will take care of resolving ".." and "."
402 size_t path_begin = output->length();
403
404 if (base_parsed.path.is_empty() && !path.is_empty()) {
405 // Ensure a leading "/" is present before appending a non-empty relative
406 // path when the base URL's path is empty, as can occur with non-special
407 // URLs. This prevents incorrect path concatenation, such as resolving
408 // "path" based on "git://host" resulting in "git://hostpath" instead of
409 // the intended "git://host/path".
410 output->push_back('/');
411 }
412
413 CopyToLastSlash(base_url, base_path_begin, base_parsed.path.end(),
414 output);
415 success &= CanonicalizePartialPathInternal(relative_url, path, path_begin,
416 canon_mode, output);
417 out_parsed->path = MakeRange(path_begin, output->length());
418
419 // Copy the rest of the stuff after the path from the relative path.
420 }
421
422 // To avoid path being treated as the host, prepend "/." to the path".
423 //
424 // Example:
425 //
426 // > const url = new URL("/.//path", "git:/");
427 // > url.href
428 // => The result should be "git:/.//path", instead of "git://path".
429 if (IsUsingStandardCompliantNonSpecialSchemeURLParsing() &&
430 !base_parsed.host.is_valid() && out_parsed->path.is_valid() &&
431 out_parsed->path.as_string_view_on(output->view().data())
432 .starts_with("//")) {
433 size_t prior_output_length = output->length();
434 output->Insert(out_parsed->path.begin, "/.");
435 // Adjust path.
436 out_parsed->path.begin += output->length() - prior_output_length;
437 true_path_begin = out_parsed->path.begin;
438 }
439 // Finish with the query and reference part (these can't fail).
440 CanonicalizeQuery(relative_url, query, query_converter,
441 output, &out_parsed->query);
442 CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
443
444 // Fix the path beginning to add back the "C:" we may have written above.
445 out_parsed->path = MakeRange(true_path_begin, out_parsed->path.end());
446 return success;
447 }
448
449 // If we get here, the path is unchanged: copy to output.
450 CopyOneComponent(base_url, base_parsed.path, output, &out_parsed->path);
451
452 if (query.is_valid()) {
453 // Just the query specified, replace the query and reference (ignore
454 // failures for refs)
455 CanonicalizeQuery(relative_url, query, query_converter,
456 output, &out_parsed->query);
457 CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
458 return success;
459 }
460
461 // If we get here, the query is unchanged: copy to output. Note that the
462 // range of the query parameter doesn't include the question mark, so we
463 // have to add it manually if there is a component.
464 if (base_parsed.query.is_valid())
465 output->push_back('?');
466 CopyOneComponent(base_url, base_parsed.query, output, &out_parsed->query);
467
468 if (ref.is_valid()) {
469 // Just the reference specified: replace it (ignoring failures).
470 CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
471 return success;
472 }
473
474 // We should always have something to do in this function, the caller checks
475 // that some component is being replaced.
476 DCHECK(false) << "Not reached";
477 return success;
478 }
479
480 // Resolves a relative URL that contains a host. Typically, these will
481 // be of the form "//www.google.com/foo/bar?baz#ref" and the only thing which
482 // should be kept from the original URL is the scheme.
483 template<typename CHAR>
DoResolveRelativeHost(const char * base_url,const Parsed & base_parsed,const CHAR * relative_url,const Component & relative_component,CharsetConverter * query_converter,CanonOutput * output,Parsed * out_parsed)484 bool DoResolveRelativeHost(const char* base_url,
485 const Parsed& base_parsed,
486 const CHAR* relative_url,
487 const Component& relative_component,
488 CharsetConverter* query_converter,
489 CanonOutput* output,
490 Parsed* out_parsed) {
491 SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
492 const bool is_standard_scheme =
493 GetStandardSchemeType(base_url, base_parsed.scheme, &scheme_type);
494
495 // Parse the relative URL, just like we would for anything following a
496 // scheme.
497 Parsed relative_parsed; // Everything but the scheme is valid.
498
499 if (IsUsingStandardCompliantNonSpecialSchemeURLParsing() &&
500 !is_standard_scheme) {
501 ParseAfterNonSpecialScheme(relative_url, relative_component.end(),
502 relative_component.begin, &relative_parsed);
503 } else {
504 ParseAfterSpecialScheme(relative_url, relative_component.end(),
505 relative_component.begin, &relative_parsed);
506 }
507
508 // Now we can just use the replacement function to replace all the necessary
509 // parts of the old URL with the new one.
510 Replacements<CHAR> replacements;
511 replacements.SetUsername(relative_url, relative_parsed.username);
512 replacements.SetPassword(relative_url, relative_parsed.password);
513 replacements.SetHost(relative_url, relative_parsed.host);
514 replacements.SetPort(relative_url, relative_parsed.port);
515 replacements.SetPath(relative_url, relative_parsed.path);
516 replacements.SetQuery(relative_url, relative_parsed.query);
517 replacements.SetRef(relative_url, relative_parsed.ref);
518
519 // Length() does not include the old scheme, so make sure to add it from the
520 // base URL.
521 output->ReserveSizeIfNeeded(
522 replacements.components().Length() +
523 base_parsed.CountCharactersBefore(Parsed::USERNAME, false));
524 if (!is_standard_scheme) {
525 if (IsUsingStandardCompliantNonSpecialSchemeURLParsing()) {
526 return ReplaceNonSpecialURL(base_url, base_parsed, replacements,
527 query_converter, *output, *out_parsed);
528 }
529 // A path with an authority section gets canonicalized under standard URL
530 // rules, even though the base was not known to be standard.
531 scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
532 }
533 return ReplaceStandardURL(base_url, base_parsed, replacements, scheme_type,
534 query_converter, output, out_parsed);
535 }
536
537 // Resolves a relative URL that happens to be an absolute file path. Examples
538 // include: "//hostname/path", "/c:/foo", and "//hostname/c:/foo".
539 template<typename CHAR>
DoResolveAbsoluteFile(const CHAR * relative_url,const Component & relative_component,CharsetConverter * query_converter,CanonOutput * output,Parsed * out_parsed)540 bool DoResolveAbsoluteFile(const CHAR* relative_url,
541 const Component& relative_component,
542 CharsetConverter* query_converter,
543 CanonOutput* output,
544 Parsed* out_parsed) {
545 // Parse the file URL. The file URl parsing function uses the same logic
546 // as we do for determining if the file is absolute, in which case it will
547 // not bother to look for a scheme.
548 Parsed relative_parsed;
549 ParseFileURL(&relative_url[relative_component.begin], relative_component.len,
550 &relative_parsed);
551
552 return CanonicalizeFileURL(&relative_url[relative_component.begin],
553 relative_component.len, relative_parsed,
554 query_converter, output, out_parsed);
555 }
556
557 // TODO(brettw) treat two slashes as root like Mozilla for FTP?
558 template<typename CHAR>
DoResolveRelativeURL(const char * base_url,const Parsed & base_parsed,bool base_is_file,const CHAR * relative_url,const Component & relative_component,CharsetConverter * query_converter,CanonOutput * output,Parsed * out_parsed)559 bool DoResolveRelativeURL(const char* base_url,
560 const Parsed& base_parsed,
561 bool base_is_file,
562 const CHAR* relative_url,
563 const Component& relative_component,
564 CharsetConverter* query_converter,
565 CanonOutput* output,
566 Parsed* out_parsed) {
567 // |base_parsed| is the starting point for our output. Since we may have
568 // removed whitespace from |relative_url| before entering this method, we'll
569 // carry over the |potentially_dangling_markup| flag.
570 bool potentially_dangling_markup = out_parsed->potentially_dangling_markup;
571 *out_parsed = base_parsed;
572 if (potentially_dangling_markup)
573 out_parsed->potentially_dangling_markup = true;
574
575 // A flag-dependent condition check is necessary here because non-special URLs
576 // may have an empty path if StandardCompliantNonSpecialSchemeURLParsing flag
577 // is enabled.
578 //
579 // TODO(crbug.com/1416006): Remove the following comment when we enable the
580 // flag. The comment makes sense only when the flag is disabled.
581 //
582 // > Sanity check: the input should have a host or we'll break badly below.
583 // > We can only resolve relative URLs with base URLs that have hosts and
584 // > paths (even the default path of "/" is OK).
585 // >
586 // > We allow hosts with no length so we can handle file URLs, for example.
587 if (IsUsingStandardCompliantNonSpecialSchemeURLParsing()
588 ? base_parsed.scheme.is_empty()
589 : base_parsed.path.is_empty()) {
590 // On error, return the input (resolving a relative URL on a
591 // non-relative base = the base).
592 int base_len = base_parsed.Length();
593 for (int i = 0; i < base_len; i++) {
594 output->push_back(base_url[i]);
595 }
596 return false;
597 }
598
599 if (relative_component.is_empty()) {
600 // Empty relative URL, leave unchanged, only removing the ref component.
601 int base_len = base_parsed.Length();
602 base_len -= base_parsed.ref.len + 1;
603 out_parsed->ref.reset();
604 output->Append(base_url, base_len);
605 return true;
606 }
607
608 int num_slashes = CountConsecutiveSlashes(
609 relative_url, relative_component.begin, relative_component.end());
610
611 #ifdef WIN32
612 // On Windows, two slashes for a file path (regardless of which direction
613 // they are) means that it's UNC. Two backslashes on any base scheme mean
614 // that it's an absolute UNC path (we use the base_is_file flag to control
615 // how strict the UNC finder is).
616 //
617 // We also allow Windows absolute drive specs on any scheme (for example
618 // "c:\foo") like IE does. There must be no preceding slashes in this
619 // case (we reject anything like "/c:/foo") because that should be treated
620 // as a path. For file URLs, we allow any number of slashes since that would
621 // be setting the path.
622 //
623 // This assumes the absolute path resolver handles absolute URLs like this
624 // properly. DoCanonicalize does this.
625 int after_slashes = relative_component.begin + num_slashes;
626 if (DoesBeginUNCPath(relative_url, relative_component.begin,
627 relative_component.end(), !base_is_file) ||
628 ((num_slashes == 0 || base_is_file) &&
629 DoesBeginWindowsDriveSpec(
630 relative_url, after_slashes, relative_component.end()))) {
631 return DoResolveAbsoluteFile(relative_url, relative_component,
632 query_converter, output, out_parsed);
633 }
634 #else
635 // Other platforms need explicit handling for file: URLs with multiple
636 // slashes because the generic scheme parsing always extracts a host, but a
637 // file: URL only has a host if it has exactly 2 slashes. Even if it does
638 // have a host, we want to use the special host detection logic for file
639 // URLs provided by DoResolveAbsoluteFile(), as opposed to the generic host
640 // detection logic, for consistency with parsing file URLs from scratch.
641 if (base_is_file && num_slashes >= 2) {
642 return DoResolveAbsoluteFile(relative_url, relative_component,
643 query_converter, output, out_parsed);
644 }
645 #endif
646
647 // Any other double-slashes mean that this is relative to the scheme.
648 if (num_slashes >= 2) {
649 return DoResolveRelativeHost(base_url, base_parsed,
650 relative_url, relative_component,
651 query_converter, output, out_parsed);
652 }
653
654 // When we get here, we know that the relative URL is on the same host.
655 return DoResolveRelativePath(
656 base_url, base_parsed, base_is_file, relative_url, relative_component,
657 query_converter,
658 // TODO(crbug.com/1416006): Support Non-special URLs
659 CanonMode::kSpecialURL, output, out_parsed);
660 }
661
662 } // namespace
663
IsRelativeURL(const char * base,const Parsed & base_parsed,const char * fragment,int fragment_len,bool is_base_hierarchical,bool * is_relative,Component * relative_component)664 bool IsRelativeURL(const char* base,
665 const Parsed& base_parsed,
666 const char* fragment,
667 int fragment_len,
668 bool is_base_hierarchical,
669 bool* is_relative,
670 Component* relative_component) {
671 return DoIsRelativeURL<char>(
672 base, base_parsed, fragment, fragment_len, is_base_hierarchical,
673 is_relative, relative_component);
674 }
675
IsRelativeURL(const char * base,const Parsed & base_parsed,const char16_t * fragment,int fragment_len,bool is_base_hierarchical,bool * is_relative,Component * relative_component)676 bool IsRelativeURL(const char* base,
677 const Parsed& base_parsed,
678 const char16_t* fragment,
679 int fragment_len,
680 bool is_base_hierarchical,
681 bool* is_relative,
682 Component* relative_component) {
683 return DoIsRelativeURL<char16_t>(base, base_parsed, fragment, fragment_len,
684 is_base_hierarchical, is_relative,
685 relative_component);
686 }
687
ResolveRelativeURL(const char * base_url,const Parsed & base_parsed,bool base_is_file,const char * relative_url,const Component & relative_component,CharsetConverter * query_converter,CanonOutput * output,Parsed * out_parsed)688 bool ResolveRelativeURL(const char* base_url,
689 const Parsed& base_parsed,
690 bool base_is_file,
691 const char* relative_url,
692 const Component& relative_component,
693 CharsetConverter* query_converter,
694 CanonOutput* output,
695 Parsed* out_parsed) {
696 return DoResolveRelativeURL<char>(
697 base_url, base_parsed, base_is_file, relative_url,
698 relative_component, query_converter, output, out_parsed);
699 }
700
ResolveRelativeURL(const char * base_url,const Parsed & base_parsed,bool base_is_file,const char16_t * relative_url,const Component & relative_component,CharsetConverter * query_converter,CanonOutput * output,Parsed * out_parsed)701 bool ResolveRelativeURL(const char* base_url,
702 const Parsed& base_parsed,
703 bool base_is_file,
704 const char16_t* relative_url,
705 const Component& relative_component,
706 CharsetConverter* query_converter,
707 CanonOutput* output,
708 Parsed* out_parsed) {
709 return DoResolveRelativeURL<char16_t>(base_url, base_parsed, base_is_file,
710 relative_url, relative_component,
711 query_converter, output, out_parsed);
712 }
713
714 } // namespace url
715