1 // Copyright (c) 2012 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.
5 #include "components/url_fixer/url_fixer.h"
10 #include "base/environment.h"
12 #include "base/file_util.h"
13 #include "base/logging.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "net/base/escape.h"
17 #include "net/base/filename_util.h"
18 #include "net/base/net_util.h"
19 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
20 #include "url/url_file.h"
21 #include "url/url_parse.h"
22 #include "url/url_util.h"
24 const char* url_fixer::home_directory_override
= NULL
;
28 // Hardcode these constants to avoid dependences on //chrome and //content.
29 const char kChromeUIScheme
[] = "chrome";
30 const char kChromeUIDefaultHost
[] = "version";
31 const char kViewSourceScheme
[] = "view-source";
33 // TODO(estade): Remove these ugly, ugly functions. They are only used in
34 // SegmentURL. A url::Parsed object keeps track of a bunch of indices into
35 // a url string, and these need to be updated when the URL is converted from
36 // UTF8 to UTF16. Instead of this after-the-fact adjustment, we should parse it
37 // in the correct string format to begin with.
38 url::Component
UTF8ComponentToUTF16Component(
39 const std::string
& text_utf8
,
40 const url::Component
& component_utf8
) {
41 if (component_utf8
.len
== -1)
42 return url::Component();
44 std::string before_component_string
=
45 text_utf8
.substr(0, component_utf8
.begin
);
46 std::string component_string
=
47 text_utf8
.substr(component_utf8
.begin
, component_utf8
.len
);
48 base::string16 before_component_string_16
=
49 base::UTF8ToUTF16(before_component_string
);
50 base::string16 component_string_16
= base::UTF8ToUTF16(component_string
);
51 url::Component
component_16(before_component_string_16
.length(),
52 component_string_16
.length());
56 void UTF8PartsToUTF16Parts(const std::string
& text_utf8
,
57 const url::Parsed
& parts_utf8
,
59 if (base::IsStringASCII(text_utf8
)) {
64 parts
->scheme
= UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.scheme
);
66 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.username
);
68 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.password
);
69 parts
->host
= UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.host
);
70 parts
->port
= UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.port
);
71 parts
->path
= UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.path
);
72 parts
->query
= UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.query
);
73 parts
->ref
= UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.ref
);
76 base::TrimPositions
TrimWhitespaceUTF8(const std::string
& input
,
77 base::TrimPositions positions
,
78 std::string
* output
) {
79 // This implementation is not so fast since it converts the text encoding
80 // twice. Please feel free to file a bug if this function hurts the
81 // performance of Chrome.
82 DCHECK(base::IsStringUTF8(input
));
83 base::string16 input16
= base::UTF8ToUTF16(input
);
84 base::string16 output16
;
85 base::TrimPositions result
=
86 base::TrimWhitespace(input16
, positions
, &output16
);
87 *output
= base::UTF16ToUTF8(output16
);
91 // does some basic fixes for input that we want to test for file-ness
92 void PrepareStringForFileOps(const base::FilePath
& text
,
93 base::FilePath::StringType
* output
) {
95 base::TrimWhitespace(text
.value(), base::TRIM_ALL
, output
);
96 replace(output
->begin(), output
->end(), '/', '\\');
98 TrimWhitespaceUTF8(text
.value(), base::TRIM_ALL
, output
);
102 // Tries to create a full path from |text|. If the result is valid and the
103 // file exists, returns true and sets |full_path| to the result. Otherwise,
104 // returns false and leaves |full_path| unchanged.
105 bool ValidPathForFile(const base::FilePath::StringType
& text
,
106 base::FilePath
* full_path
) {
107 base::FilePath file_path
= base::MakeAbsoluteFilePath(base::FilePath(text
));
108 if (file_path
.empty())
111 if (!base::PathExists(file_path
))
114 *full_path
= file_path
;
118 #if defined(OS_POSIX)
119 // Given a path that starts with ~, return a path that starts with an
120 // expanded-out /user/foobar directory.
121 std::string
FixupHomedir(const std::string
& text
) {
122 DCHECK(text
.length() > 0 && text
[0] == '~');
124 if (text
.length() == 1 || text
[1] == '/') {
125 const char* home
= getenv(base::env_vars::kHome
);
126 if (url_fixer::home_directory_override
)
127 home
= url_fixer::home_directory_override
;
128 // We'll probably break elsewhere if $HOME is undefined, but check here
132 return home
+ text
.substr(1);
135 // Otherwise, this is a path like ~foobar/baz, where we must expand to
136 // user foobar's home directory. Officially, we should use getpwent(),
137 // but that is a nasty blocking call.
139 #if defined(OS_MACOSX)
140 static const char kHome
[] = "/Users/";
142 static const char kHome
[] = "/home/";
144 return kHome
+ text
.substr(1);
148 // Tries to create a file: URL from |text| if it looks like a filename, even if
149 // it doesn't resolve as a valid path or to an existing file. Returns a
150 // (possibly invalid) file: URL in |fixed_up_url| for input beginning
151 // with a drive specifier or "\\". Returns the unchanged input in other cases
152 // (including file: URLs: these don't look like filenames).
153 std::string
FixupPath(const std::string
& text
) {
154 DCHECK(!text
.empty());
156 base::FilePath::StringType filename
;
158 base::FilePath
input_path(base::UTF8ToWide(text
));
159 PrepareStringForFileOps(input_path
, &filename
);
161 // Fixup Windows-style drive letters, where "C:" gets rewritten to "C|".
162 if (filename
.length() > 1 && filename
[1] == '|')
164 #elif defined(OS_POSIX)
165 base::FilePath
input_path(text
);
166 PrepareStringForFileOps(input_path
, &filename
);
167 if (filename
.length() > 0 && filename
[0] == '~')
168 filename
= FixupHomedir(filename
);
171 // Here, we know the input looks like a file.
172 GURL file_url
= net::FilePathToFileURL(base::FilePath(filename
));
173 if (file_url
.is_valid()) {
174 return base::UTF16ToUTF8(net::FormatUrl(file_url
,
176 net::kFormatUrlOmitUsernamePassword
,
177 net::UnescapeRule::NORMAL
,
183 // Invalid file URL, just return the input.
187 // Checks |domain| to see if a valid TLD is already present. If not, appends
188 // |desired_tld| to the domain, and prepends "www." unless it's already present.
189 void AddDesiredTLD(const std::string
& desired_tld
, std::string
* domain
) {
190 if (desired_tld
.empty() || domain
->empty())
193 // Check the TLD. If the return value is positive, we already have a TLD, so
194 // abort. If the return value is std::string::npos, there's no valid host,
195 // but we can try to append a TLD anyway, since the host may become valid once
196 // the TLD is attached -- for example, "999999999999" is detected as a broken
197 // IP address and marked invalid, but attaching ".com" makes it legal. When
198 // the return value is 0, there's a valid host with no known TLD, so we can
199 // definitely append the user's TLD. We disallow unknown registries here so
200 // users can input "mail.yahoo" and hit ctrl-enter to get
201 // "www.mail.yahoo.com".
202 const size_t registry_length
=
203 net::registry_controlled_domains::GetRegistryLength(
205 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES
,
206 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
);
207 if ((registry_length
!= 0) && (registry_length
!= std::string::npos
))
210 // Add the suffix at the end of the domain.
211 const size_t domain_length(domain
->length());
212 DCHECK_GT(domain_length
, 0U);
213 DCHECK_NE(desired_tld
[0], '.');
214 if ((*domain
)[domain_length
- 1] != '.')
215 domain
->push_back('.');
216 domain
->append(desired_tld
);
218 // Now, if the domain begins with "www.", stop.
219 const std::string
prefix("www.");
220 if (domain
->compare(0, prefix
.length(), prefix
) != 0) {
221 // Otherwise, add www. to the beginning of the URL.
222 domain
->insert(0, prefix
);
226 inline void FixupUsername(const std::string
& text
,
227 const url::Component
& part
,
229 if (!part
.is_valid())
232 // We don't fix up the username at the moment.
233 url
->append(text
, part
.begin
, part
.len
);
234 // Do not append the trailing '@' because we might need to include the user's
235 // password. FixupURL itself will append the '@' for us.
238 inline void FixupPassword(const std::string
& text
,
239 const url::Component
& part
,
241 if (!part
.is_valid())
244 // We don't fix up the password at the moment.
246 url
->append(text
, part
.begin
, part
.len
);
249 void FixupHost(const std::string
& text
,
250 const url::Component
& part
,
252 const std::string
& desired_tld
,
254 if (!part
.is_valid())
257 // Make domain valid.
258 // Strip all leading dots and all but one trailing dot, unless the user only
259 // typed dots, in which case their input is totally invalid and we should just
260 // leave it unchanged.
261 std::string
domain(text
, part
.begin
, part
.len
);
262 const size_t first_nondot(domain
.find_first_not_of('.'));
263 if (first_nondot
!= std::string::npos
) {
264 domain
.erase(0, first_nondot
);
265 size_t last_nondot(domain
.find_last_not_of('.'));
266 DCHECK(last_nondot
!= std::string::npos
);
267 last_nondot
+= 2; // Point at second period in ending string
268 if (last_nondot
< domain
.length())
269 domain
.erase(last_nondot
);
272 // Add any user-specified TLD, if applicable.
273 AddDesiredTLD(desired_tld
, &domain
);
278 void FixupPort(const std::string
& text
,
279 const url::Component
& part
,
281 if (!part
.is_valid())
284 // We don't fix up the port at the moment.
286 url
->append(text
, part
.begin
, part
.len
);
289 inline void FixupPath(const std::string
& text
,
290 const url::Component
& part
,
292 if (!part
.is_valid() || part
.len
== 0) {
293 // We should always have a path.
298 // Append the path as is.
299 url
->append(text
, part
.begin
, part
.len
);
302 inline void FixupQuery(const std::string
& text
,
303 const url::Component
& part
,
305 if (!part
.is_valid())
308 // We don't fix up the query at the moment.
310 url
->append(text
, part
.begin
, part
.len
);
313 inline void FixupRef(const std::string
& text
,
314 const url::Component
& part
,
316 if (!part
.is_valid())
319 // We don't fix up the ref at the moment.
321 url
->append(text
, part
.begin
, part
.len
);
324 bool HasPort(const std::string
& original_text
,
325 const url::Component
& scheme_component
) {
326 // Find the range between the ":" and the "/".
327 size_t port_start
= scheme_component
.end() + 1;
328 size_t port_end
= port_start
;
329 while ((port_end
< original_text
.length()) &&
330 !url::IsAuthorityTerminator(original_text
[port_end
]))
332 if (port_end
== port_start
)
335 // Scan the range to see if it is entirely digits.
336 for (size_t i
= port_start
; i
< port_end
; ++i
) {
337 if (!IsAsciiDigit(original_text
[i
]))
344 // Try to extract a valid scheme from the beginning of |text|.
345 // If successful, set |scheme_component| to the text range where the scheme
346 // was located, and fill |canon_scheme| with its canonicalized form.
347 // Otherwise, return false and leave the outputs in an indeterminate state.
348 bool GetValidScheme(const std::string
& text
,
349 url::Component
* scheme_component
,
350 std::string
* canon_scheme
) {
351 canon_scheme
->clear();
353 // Locate everything up to (but not including) the first ':'
354 if (!url::ExtractScheme(
355 text
.data(), static_cast<int>(text
.length()), scheme_component
)) {
359 // Make sure the scheme contains only valid characters, and convert
360 // to lowercase. This also catches IPv6 literals like [::1], because
361 // brackets are not in the whitelist.
362 url::StdStringCanonOutput
canon_scheme_output(canon_scheme
);
363 url::Component canon_scheme_component
;
364 if (!url::CanonicalizeScheme(text
.data(),
366 &canon_scheme_output
,
367 &canon_scheme_component
)) {
371 // Strip the ':', and any trailing buffer space.
372 DCHECK_EQ(0, canon_scheme_component
.begin
);
373 canon_scheme
->erase(canon_scheme_component
.len
);
375 // We need to fix up the segmentation for "www.example.com:/". For this
376 // case, we guess that schemes with a "." are not actually schemes.
377 if (canon_scheme
->find('.') != std::string::npos
)
380 // We need to fix up the segmentation for "www:123/". For this case, we
381 // will add an HTTP scheme later and make the URL parser happy.
382 // TODO(pkasting): Maybe we should try to use GURL's parser for this?
383 if (HasPort(text
, *scheme_component
))
386 // Everything checks out.
390 // Performs the work for url_fixer::SegmentURL. |text| may be modified on
391 // output on success: a semicolon following a valid scheme is replaced with a
393 std::string
SegmentURLInternal(std::string
* text
, url::Parsed
* parts
) {
394 // Initialize the result.
395 *parts
= url::Parsed();
398 TrimWhitespaceUTF8(*text
, base::TRIM_ALL
, &trimmed
);
400 return std::string(); // Nothing to segment.
403 int trimmed_length
= static_cast<int>(trimmed
.length());
404 if (url::DoesBeginWindowsDriveSpec(trimmed
.data(), 0, trimmed_length
) ||
405 url::DoesBeginUNCPath(trimmed
.data(), 0, trimmed_length
, true))
407 #elif defined(OS_POSIX)
408 if (base::FilePath::IsSeparator(trimmed
.data()[0]) ||
409 trimmed
.data()[0] == '~')
413 // Otherwise, we need to look at things carefully.
415 if (!GetValidScheme(*text
, &parts
->scheme
, &scheme
)) {
416 // Try again if there is a ';' in the text. If changing it to a ':' results
417 // in a scheme being found, continue processing with the modified text.
418 bool found_scheme
= false;
419 size_t semicolon
= text
->find(';');
420 if (semicolon
!= 0 && semicolon
!= std::string::npos
) {
421 (*text
)[semicolon
] = ':';
422 if (GetValidScheme(*text
, &parts
->scheme
, &scheme
))
425 (*text
)[semicolon
] = ';';
428 // Couldn't determine the scheme, so just pick one.
429 parts
->scheme
.reset();
430 scheme
= StartsWithASCII(*text
, "ftp.", false) ? url::kFtpScheme
435 // Proceed with about and chrome schemes, but not file or nonstandard schemes.
436 if ((scheme
!= url::kAboutScheme
) && (scheme
!= kChromeUIScheme
) &&
437 ((scheme
== url::kFileScheme
) ||
440 url::Component(0, static_cast<int>(scheme
.length()))))) {
444 if (scheme
== url::kFileSystemScheme
) {
445 // Have the GURL parser do the heavy lifting for us.
446 url::ParseFileSystemURL(
447 text
->data(), static_cast<int>(text
->length()), parts
);
451 if (parts
->scheme
.is_valid()) {
452 // Have the GURL parser do the heavy lifting for us.
453 url::ParseStandardURL(
454 text
->data(), static_cast<int>(text
->length()), parts
);
458 // We need to add a scheme in order for ParseStandardURL to be happy.
459 // Find the first non-whitespace character.
460 std::string::iterator first_nonwhite
= text
->begin();
461 while ((first_nonwhite
!= text
->end()) && IsWhitespace(*first_nonwhite
))
464 // Construct the text to parse by inserting the scheme.
465 std::string
inserted_text(scheme
);
466 inserted_text
.append(url::kStandardSchemeSeparator
);
467 std::string
text_to_parse(text
->begin(), first_nonwhite
);
468 text_to_parse
.append(inserted_text
);
469 text_to_parse
.append(first_nonwhite
, text
->end());
471 // Have the GURL parser do the heavy lifting for us.
472 url::ParseStandardURL(
473 text_to_parse
.data(), static_cast<int>(text_to_parse
.length()), parts
);
475 // Offset the results of the parse to match the original text.
476 const int offset
= -static_cast<int>(inserted_text
.length());
477 url_fixer::OffsetComponent(offset
, &parts
->scheme
);
478 url_fixer::OffsetComponent(offset
, &parts
->username
);
479 url_fixer::OffsetComponent(offset
, &parts
->password
);
480 url_fixer::OffsetComponent(offset
, &parts
->host
);
481 url_fixer::OffsetComponent(offset
, &parts
->port
);
482 url_fixer::OffsetComponent(offset
, &parts
->path
);
483 url_fixer::OffsetComponent(offset
, &parts
->query
);
484 url_fixer::OffsetComponent(offset
, &parts
->ref
);
491 std::string
url_fixer::SegmentURL(const std::string
& text
, url::Parsed
* parts
) {
492 std::string
mutable_text(text
);
493 return SegmentURLInternal(&mutable_text
, parts
);
496 base::string16
url_fixer::SegmentURL(const base::string16
& text
,
497 url::Parsed
* parts
) {
498 std::string text_utf8
= base::UTF16ToUTF8(text
);
499 url::Parsed parts_utf8
;
500 std::string scheme_utf8
= SegmentURL(text_utf8
, &parts_utf8
);
501 UTF8PartsToUTF16Parts(text_utf8
, parts_utf8
, parts
);
502 return base::UTF8ToUTF16(scheme_utf8
);
505 GURL
url_fixer::FixupURL(const std::string
& text
,
506 const std::string
& desired_tld
) {
508 TrimWhitespaceUTF8(text
, base::TRIM_ALL
, &trimmed
);
510 return GURL(); // Nothing here.
514 std::string
scheme(SegmentURLInternal(&trimmed
, &parts
));
516 // For view-source: URLs, we strip "view-source:", do fixup, and stick it back
517 // on. This allows us to handle things like "view-source:google.com".
518 if (scheme
== kViewSourceScheme
) {
519 // Reject "view-source:view-source:..." to avoid deep recursion.
520 std::string
view_source(kViewSourceScheme
+ std::string(":"));
521 if (!StartsWithASCII(text
, view_source
+ view_source
, false)) {
522 return GURL(kViewSourceScheme
+ std::string(":") +
523 FixupURL(trimmed
.substr(scheme
.length() + 1), desired_tld
)
524 .possibly_invalid_spec());
528 // We handle the file scheme separately.
529 if (scheme
== url::kFileScheme
)
530 return GURL(parts
.scheme
.is_valid() ? text
: FixupPath(text
));
532 // We handle the filesystem scheme separately.
533 if (scheme
== url::kFileSystemScheme
) {
534 if (parts
.inner_parsed() && parts
.inner_parsed()->scheme
.is_valid())
539 // Parse and rebuild about: and chrome: URLs, except about:blank.
541 !LowerCaseEqualsASCII(trimmed
, url::kAboutBlankURL
) &&
542 ((scheme
== url::kAboutScheme
) || (scheme
== kChromeUIScheme
));
544 // For some schemes whose layouts we understand, we rebuild it.
546 url::IsStandard(scheme
.c_str(),
547 url::Component(0, static_cast<int>(scheme
.length())))) {
548 // Replace the about: scheme with the chrome: scheme.
549 std::string
url(chrome_url
? kChromeUIScheme
: scheme
);
550 url
.append(url::kStandardSchemeSeparator
);
552 // We need to check whether the |username| is valid because it is our
553 // responsibility to append the '@' to delineate the user information from
554 // the host portion of the URL.
555 if (parts
.username
.is_valid()) {
556 FixupUsername(trimmed
, parts
.username
, &url
);
557 FixupPassword(trimmed
, parts
.password
, &url
);
561 FixupHost(trimmed
, parts
.host
, parts
.scheme
.is_valid(), desired_tld
, &url
);
562 if (chrome_url
&& !parts
.host
.is_valid())
563 url
.append(kChromeUIDefaultHost
);
564 FixupPort(trimmed
, parts
.port
, &url
);
565 FixupPath(trimmed
, parts
.path
, &url
);
566 FixupQuery(trimmed
, parts
.query
, &url
);
567 FixupRef(trimmed
, parts
.ref
, &url
);
572 // In the worst-case, we insert a scheme if the URL lacks one.
573 if (!parts
.scheme
.is_valid()) {
574 std::string
fixed_scheme(scheme
);
575 fixed_scheme
.append(url::kStandardSchemeSeparator
);
576 trimmed
.insert(0, fixed_scheme
);
579 return GURL(trimmed
);
582 // The rules are different here than for regular fixup, since we need to handle
583 // input like "hello.html" and know to look in the current directory. Regular
584 // fixup will look for cues that it is actually a file path before trying to
585 // figure out what file it is. If our logic doesn't work, we will fall back on
587 GURL
url_fixer::FixupRelativeFile(const base::FilePath
& base_dir
,
588 const base::FilePath
& text
) {
589 base::FilePath old_cur_directory
;
590 if (!base_dir
.empty()) {
591 // Save the old current directory before we move to the new one.
592 base::GetCurrentDirectory(&old_cur_directory
);
593 base::SetCurrentDirectory(base_dir
);
596 // Allow funny input with extra whitespace and the wrong kind of slashes.
597 base::FilePath::StringType trimmed
;
598 PrepareStringForFileOps(text
, &trimmed
);
601 // Avoid recognizing definite non-file URLs as file paths.
603 if (gurl
.is_valid() && gurl
.IsStandard())
605 base::FilePath full_path
;
606 if (is_file
&& !ValidPathForFile(trimmed
, &full_path
)) {
607 // Not a path as entered, try unescaping it in case the user has
608 // escaped things. We need to go through 8-bit since the escaped values
609 // only represent 8-bit values.
611 std::wstring unescaped
= base::UTF8ToWide(net::UnescapeURLComponent(
612 base::WideToUTF8(trimmed
),
613 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
));
614 #elif defined(OS_POSIX)
615 std::string unescaped
= net::UnescapeURLComponent(
617 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
);
620 if (!ValidPathForFile(unescaped
, &full_path
))
624 // Put back the current directory if we saved it.
625 if (!base_dir
.empty())
626 base::SetCurrentDirectory(old_cur_directory
);
629 GURL file_url
= net::FilePathToFileURL(full_path
);
630 if (file_url
.is_valid())
632 base::UTF16ToUTF8(net::FormatUrl(file_url
,
634 net::kFormatUrlOmitUsernamePassword
,
635 net::UnescapeRule::NORMAL
,
639 // Invalid files fall through to regular processing.
642 // Fall back on regular fixup for this input.
644 std::string text_utf8
= base::WideToUTF8(text
.value());
645 #elif defined(OS_POSIX)
646 std::string text_utf8
= text
.value();
648 return FixupURL(text_utf8
, std::string());
651 void url_fixer::OffsetComponent(int offset
, url::Component
* part
) {
654 if (part
->is_valid()) {
655 // Offset the location of this component.
656 part
->begin
+= offset
;
658 // This part might not have existed in the original text.