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