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 "chrome/common/net/url_fixer_upper.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 "chrome/common/url_constants.h"
17 #include "net/base/escape.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* URLFixerUpper::home_directory_override
= NULL
;
28 // TODO(estade): Remove these ugly, ugly functions. They are only used in
29 // SegmentURL. A url_parse::Parsed object keeps track of a bunch of indices into
30 // a url string, and these need to be updated when the URL is converted from
31 // UTF8 to UTF16. Instead of this after-the-fact adjustment, we should parse it
32 // in the correct string format to begin with.
33 url_parse::Component
UTF8ComponentToUTF16Component(
34 const std::string
& text_utf8
,
35 const url_parse::Component
& component_utf8
) {
36 if (component_utf8
.len
== -1)
37 return url_parse::Component();
39 std::string before_component_string
=
40 text_utf8
.substr(0, component_utf8
.begin
);
41 std::string component_string
= text_utf8
.substr(component_utf8
.begin
,
43 base::string16 before_component_string_16
=
44 base::UTF8ToUTF16(before_component_string
);
45 base::string16 component_string_16
= base::UTF8ToUTF16(component_string
);
46 url_parse::Component
component_16(before_component_string_16
.length(),
47 component_string_16
.length());
51 void UTF8PartsToUTF16Parts(const std::string
& text_utf8
,
52 const url_parse::Parsed
& parts_utf8
,
53 url_parse::Parsed
* parts
) {
54 if (IsStringASCII(text_utf8
)) {
60 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.scheme
);
62 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.username
);
64 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.password
);
66 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.host
);
68 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.port
);
70 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.path
);
72 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.query
);
74 UTF8ComponentToUTF16Component(text_utf8
, parts_utf8
.ref
);
77 TrimPositions
TrimWhitespaceUTF8(const std::string
& input
,
78 TrimPositions positions
,
79 std::string
* output
) {
80 // This implementation is not so fast since it converts the text encoding
81 // twice. Please feel free to file a bug if this function hurts the
82 // performance of Chrome.
83 DCHECK(IsStringUTF8(input
));
84 base::string16 input16
= base::UTF8ToUTF16(input
);
85 base::string16 output16
;
86 TrimPositions result
= 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 TrimWhitespace(text
.value(), TRIM_ALL
, output
);
96 replace(output
->begin(), output
->end(), '/', '\\');
98 TrimWhitespaceUTF8(text
.value(), 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 (URLFixerUpper::home_directory_override
)
127 home
= URLFixerUpper::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
, std::string(),
175 net::kFormatUrlOmitUsernamePassword
, net::UnescapeRule::NORMAL
, NULL
,
179 // Invalid file URL, just return the input.
183 // Checks |domain| to see if a valid TLD is already present. If not, appends
184 // |desired_tld| to the domain, and prepends "www." unless it's already present.
185 void AddDesiredTLD(const std::string
& desired_tld
, std::string
* domain
) {
186 if (desired_tld
.empty() || domain
->empty())
189 // Check the TLD. If the return value is positive, we already have a TLD, so
190 // abort. If the return value is std::string::npos, there's no valid host,
191 // but we can try to append a TLD anyway, since the host may become valid once
192 // the TLD is attached -- for example, "999999999999" is detected as a broken
193 // IP address and marked invalid, but attaching ".com" makes it legal. When
194 // the return value is 0, there's a valid host with no known TLD, so we can
195 // definitely append the user's TLD. We disallow unknown registries here so
196 // users can input "mail.yahoo" and hit ctrl-enter to get
197 // "www.mail.yahoo.com".
198 const size_t registry_length
=
199 net::registry_controlled_domains::GetRegistryLength(
201 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES
,
202 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
);
203 if ((registry_length
!= 0) && (registry_length
!= std::string::npos
))
206 // Add the suffix at the end of the domain.
207 const size_t domain_length(domain
->length());
208 DCHECK_GT(domain_length
, 0U);
209 DCHECK_NE(desired_tld
[0], '.');
210 if ((*domain
)[domain_length
- 1] != '.')
211 domain
->push_back('.');
212 domain
->append(desired_tld
);
214 // Now, if the domain begins with "www.", stop.
215 const std::string
prefix("www.");
216 if (domain
->compare(0, prefix
.length(), prefix
) != 0) {
217 // Otherwise, add www. to the beginning of the URL.
218 domain
->insert(0, prefix
);
222 inline void FixupUsername(const std::string
& text
,
223 const url_parse::Component
& part
,
225 if (!part
.is_valid())
228 // We don't fix up the username at the moment.
229 url
->append(text
, part
.begin
, part
.len
);
230 // Do not append the trailing '@' because we might need to include the user's
231 // password. FixupURL itself will append the '@' for us.
234 inline void FixupPassword(const std::string
& text
,
235 const url_parse::Component
& part
,
237 if (!part
.is_valid())
240 // We don't fix up the password at the moment.
242 url
->append(text
, part
.begin
, part
.len
);
245 void FixupHost(const std::string
& text
,
246 const url_parse::Component
& part
,
248 const std::string
& desired_tld
,
250 if (!part
.is_valid())
253 // Make domain valid.
254 // Strip all leading dots and all but one trailing dot, unless the user only
255 // typed dots, in which case their input is totally invalid and we should just
256 // leave it unchanged.
257 std::string
domain(text
, part
.begin
, part
.len
);
258 const size_t first_nondot(domain
.find_first_not_of('.'));
259 if (first_nondot
!= std::string::npos
) {
260 domain
.erase(0, first_nondot
);
261 size_t last_nondot(domain
.find_last_not_of('.'));
262 DCHECK(last_nondot
!= std::string::npos
);
263 last_nondot
+= 2; // Point at second period in ending string
264 if (last_nondot
< domain
.length())
265 domain
.erase(last_nondot
);
268 // Add any user-specified TLD, if applicable.
269 AddDesiredTLD(desired_tld
, &domain
);
274 void FixupPort(const std::string
& text
,
275 const url_parse::Component
& part
,
277 if (!part
.is_valid())
280 // We don't fix up the port at the moment.
282 url
->append(text
, part
.begin
, part
.len
);
285 inline void FixupPath(const std::string
& text
,
286 const url_parse::Component
& part
,
288 if (!part
.is_valid() || part
.len
== 0) {
289 // We should always have a path.
294 // Append the path as is.
295 url
->append(text
, part
.begin
, part
.len
);
298 inline void FixupQuery(const std::string
& text
,
299 const url_parse::Component
& part
,
301 if (!part
.is_valid())
304 // We don't fix up the query at the moment.
306 url
->append(text
, part
.begin
, part
.len
);
309 inline void FixupRef(const std::string
& text
,
310 const url_parse::Component
& part
,
312 if (!part
.is_valid())
315 // We don't fix up the ref at the moment.
317 url
->append(text
, part
.begin
, part
.len
);
320 bool HasPort(const std::string
& original_text
,
321 const url_parse::Component
& scheme_component
) {
322 // Find the range between the ":" and the "/".
323 size_t port_start
= scheme_component
.end() + 1;
324 size_t port_end
= port_start
;
325 while ((port_end
< original_text
.length()) &&
326 !url_parse::IsAuthorityTerminator(original_text
[port_end
]))
328 if (port_end
== port_start
)
331 // Scan the range to see if it is entirely digits.
332 for (size_t i
= port_start
; i
< port_end
; ++i
) {
333 if (!IsAsciiDigit(original_text
[i
]))
340 // Try to extract a valid scheme from the beginning of |text|.
341 // If successful, set |scheme_component| to the text range where the scheme
342 // was located, and fill |canon_scheme| with its canonicalized form.
343 // Otherwise, return false and leave the outputs in an indeterminate state.
344 bool GetValidScheme(const std::string
&text
,
345 url_parse::Component
* scheme_component
,
346 std::string
* canon_scheme
) {
347 // Locate everything up to (but not including) the first ':'
348 if (!url_parse::ExtractScheme(text
.data(), static_cast<int>(text
.length()),
353 // Make sure the scheme contains only valid characters, and convert
354 // to lowercase. This also catches IPv6 literals like [::1], because
355 // brackets are not in the whitelist.
356 url_canon::StdStringCanonOutput
canon_scheme_output(canon_scheme
);
357 url_parse::Component canon_scheme_component
;
358 if (!url_canon::CanonicalizeScheme(text
.data(), *scheme_component
,
359 &canon_scheme_output
,
360 &canon_scheme_component
))
363 // Strip the ':', and any trailing buffer space.
364 DCHECK_EQ(0, canon_scheme_component
.begin
);
365 canon_scheme
->erase(canon_scheme_component
.len
);
367 // We need to fix up the segmentation for "www.example.com:/". For this
368 // case, we guess that schemes with a "." are not actually schemes.
369 if (canon_scheme
->find('.') != std::string::npos
)
372 // We need to fix up the segmentation for "www:123/". For this case, we
373 // will add an HTTP scheme later and make the URL parser happy.
374 // TODO(pkasting): Maybe we should try to use GURL's parser for this?
375 if (HasPort(text
, *scheme_component
))
378 // Everything checks out.
382 // Performs the work for URLFixerUpper::SegmentURL. |text| may be modified on
383 // output on success: a semicolon following a valid scheme is replaced with a
385 std::string
SegmentURLInternal(std::string
* text
, url_parse::Parsed
* parts
) {
386 // Initialize the result.
387 *parts
= url_parse::Parsed();
390 TrimWhitespaceUTF8(*text
, TRIM_ALL
, &trimmed
);
392 return std::string(); // Nothing to segment.
395 int trimmed_length
= static_cast<int>(trimmed
.length());
396 if (url_parse::DoesBeginWindowsDriveSpec(trimmed
.data(), 0, trimmed_length
) ||
397 url_parse::DoesBeginUNCPath(trimmed
.data(), 0, trimmed_length
, true))
399 #elif defined(OS_POSIX)
400 if (base::FilePath::IsSeparator(trimmed
.data()[0]) ||
401 trimmed
.data()[0] == '~')
405 // Otherwise, we need to look at things carefully.
407 if (!GetValidScheme(*text
, &parts
->scheme
, &scheme
)) {
408 // Try again if there is a ';' in the text. If changing it to a ':' results
409 // in a scheme being found, continue processing with the modified text.
410 bool found_scheme
= false;
411 size_t semicolon
= text
->find(';');
412 if (semicolon
!= 0 && semicolon
!= std::string::npos
) {
413 (*text
)[semicolon
] = ':';
414 if (GetValidScheme(*text
, &parts
->scheme
, &scheme
))
417 (*text
)[semicolon
] = ';';
420 // Couldn't determine the scheme, so just pick one.
421 parts
->scheme
.reset();
422 scheme
.assign(StartsWithASCII(*text
, "ftp.", false) ?
423 content::kFtpScheme
: content::kHttpScheme
);
427 // Proceed with about and chrome schemes, but not file or nonstandard schemes.
428 if ((scheme
!= chrome::kAboutScheme
) && (scheme
!= chrome::kChromeUIScheme
) &&
429 ((scheme
== content::kFileScheme
) || !url_util::IsStandard(scheme
.c_str(),
430 url_parse::Component(0, static_cast<int>(scheme
.length())))))
433 if (scheme
== content::kFileSystemScheme
) {
434 // Have the GURL parser do the heavy lifting for us.
435 url_parse::ParseFileSystemURL(text
->data(),
436 static_cast<int>(text
->length()), parts
);
440 if (parts
->scheme
.is_valid()) {
441 // Have the GURL parser do the heavy lifting for us.
442 url_parse::ParseStandardURL(text
->data(), static_cast<int>(text
->length()),
447 // We need to add a scheme in order for ParseStandardURL to be happy.
448 // Find the first non-whitespace character.
449 std::string::iterator first_nonwhite
= text
->begin();
450 while ((first_nonwhite
!= text
->end()) && IsWhitespace(*first_nonwhite
))
453 // Construct the text to parse by inserting the scheme.
454 std::string
inserted_text(scheme
);
455 inserted_text
.append(content::kStandardSchemeSeparator
);
456 std::string
text_to_parse(text
->begin(), first_nonwhite
);
457 text_to_parse
.append(inserted_text
);
458 text_to_parse
.append(first_nonwhite
, text
->end());
460 // Have the GURL parser do the heavy lifting for us.
461 url_parse::ParseStandardURL(text_to_parse
.data(),
462 static_cast<int>(text_to_parse
.length()),
465 // Offset the results of the parse to match the original text.
466 const int offset
= -static_cast<int>(inserted_text
.length());
467 URLFixerUpper::OffsetComponent(offset
, &parts
->scheme
);
468 URLFixerUpper::OffsetComponent(offset
, &parts
->username
);
469 URLFixerUpper::OffsetComponent(offset
, &parts
->password
);
470 URLFixerUpper::OffsetComponent(offset
, &parts
->host
);
471 URLFixerUpper::OffsetComponent(offset
, &parts
->port
);
472 URLFixerUpper::OffsetComponent(offset
, &parts
->path
);
473 URLFixerUpper::OffsetComponent(offset
, &parts
->query
);
474 URLFixerUpper::OffsetComponent(offset
, &parts
->ref
);
481 std::string
URLFixerUpper::SegmentURL(const std::string
& text
,
482 url_parse::Parsed
* parts
) {
483 std::string
mutable_text(text
);
484 return SegmentURLInternal(&mutable_text
, parts
);
487 base::string16
URLFixerUpper::SegmentURL(const base::string16
& text
,
488 url_parse::Parsed
* parts
) {
489 std::string text_utf8
= base::UTF16ToUTF8(text
);
490 url_parse::Parsed parts_utf8
;
491 std::string scheme_utf8
= SegmentURL(text_utf8
, &parts_utf8
);
492 UTF8PartsToUTF16Parts(text_utf8
, parts_utf8
, parts
);
493 return base::UTF8ToUTF16(scheme_utf8
);
496 GURL
URLFixerUpper::FixupURL(const std::string
& text
,
497 const std::string
& desired_tld
) {
499 TrimWhitespaceUTF8(text
, TRIM_ALL
, &trimmed
);
501 return GURL(); // Nothing here.
504 url_parse::Parsed parts
;
505 std::string
scheme(SegmentURLInternal(&trimmed
, &parts
));
507 // For view-source: URLs, we strip "view-source:", do fixup, and stick it back
508 // on. This allows us to handle things like "view-source:google.com".
509 if (scheme
== content::kViewSourceScheme
) {
510 // Reject "view-source:view-source:..." to avoid deep recursion.
511 std::string
view_source(content::kViewSourceScheme
+ std::string(":"));
512 if (!StartsWithASCII(text
, view_source
+ view_source
, false)) {
513 return GURL(content::kViewSourceScheme
+ std::string(":") +
514 FixupURL(trimmed
.substr(scheme
.length() + 1),
515 desired_tld
).possibly_invalid_spec());
519 // We handle the file scheme separately.
520 if (scheme
== content::kFileScheme
)
521 return GURL(parts
.scheme
.is_valid() ? text
: FixupPath(text
));
523 // We handle the filesystem scheme separately.
524 if (scheme
== content::kFileSystemScheme
) {
525 if (parts
.inner_parsed() && parts
.inner_parsed()->scheme
.is_valid())
530 // Parse and rebuild about: and chrome: URLs, except about:blank.
531 bool chrome_url
= !LowerCaseEqualsASCII(trimmed
, content::kAboutBlankURL
) &&
532 ((scheme
== chrome::kAboutScheme
) || (scheme
== chrome::kChromeUIScheme
));
534 // For some schemes whose layouts we understand, we rebuild it.
535 if (chrome_url
|| url_util::IsStandard(scheme
.c_str(),
536 url_parse::Component(0, static_cast<int>(scheme
.length())))) {
537 // Replace the about: scheme with the chrome: scheme.
538 std::string
url(chrome_url
? chrome::kChromeUIScheme
: scheme
);
539 url
.append(content::kStandardSchemeSeparator
);
541 // We need to check whether the |username| is valid because it is our
542 // responsibility to append the '@' to delineate the user information from
543 // the host portion of the URL.
544 if (parts
.username
.is_valid()) {
545 FixupUsername(trimmed
, parts
.username
, &url
);
546 FixupPassword(trimmed
, parts
.password
, &url
);
550 FixupHost(trimmed
, parts
.host
, parts
.scheme
.is_valid(), desired_tld
, &url
);
551 if (chrome_url
&& !parts
.host
.is_valid())
552 url
.append(chrome::kChromeUIDefaultHost
);
553 FixupPort(trimmed
, parts
.port
, &url
);
554 FixupPath(trimmed
, parts
.path
, &url
);
555 FixupQuery(trimmed
, parts
.query
, &url
);
556 FixupRef(trimmed
, parts
.ref
, &url
);
561 // In the worst-case, we insert a scheme if the URL lacks one.
562 if (!parts
.scheme
.is_valid()) {
563 std::string
fixed_scheme(scheme
);
564 fixed_scheme
.append(content::kStandardSchemeSeparator
);
565 trimmed
.insert(0, fixed_scheme
);
568 return GURL(trimmed
);
571 // The rules are different here than for regular fixup, since we need to handle
572 // input like "hello.html" and know to look in the current directory. Regular
573 // fixup will look for cues that it is actually a file path before trying to
574 // figure out what file it is. If our logic doesn't work, we will fall back on
576 GURL
URLFixerUpper::FixupRelativeFile(const base::FilePath
& base_dir
,
577 const base::FilePath
& text
) {
578 base::FilePath old_cur_directory
;
579 if (!base_dir
.empty()) {
580 // Save the old current directory before we move to the new one.
581 file_util::GetCurrentDirectory(&old_cur_directory
);
582 file_util::SetCurrentDirectory(base_dir
);
585 // Allow funny input with extra whitespace and the wrong kind of slashes.
586 base::FilePath::StringType trimmed
;
587 PrepareStringForFileOps(text
, &trimmed
);
590 // Avoid recognizing definite non-file URLs as file paths.
592 if (gurl
.is_valid() && gurl
.IsStandard())
594 base::FilePath full_path
;
595 if (is_file
&& !ValidPathForFile(trimmed
, &full_path
)) {
596 // Not a path as entered, try unescaping it in case the user has
597 // escaped things. We need to go through 8-bit since the escaped values
598 // only represent 8-bit values.
600 std::wstring unescaped
= base::UTF8ToWide(net::UnescapeURLComponent(
601 base::WideToUTF8(trimmed
),
602 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
));
603 #elif defined(OS_POSIX)
604 std::string unescaped
= net::UnescapeURLComponent(
606 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
);
609 if (!ValidPathForFile(unescaped
, &full_path
))
613 // Put back the current directory if we saved it.
614 if (!base_dir
.empty())
615 file_util::SetCurrentDirectory(old_cur_directory
);
618 GURL file_url
= net::FilePathToFileURL(full_path
);
619 if (file_url
.is_valid())
620 return GURL(base::UTF16ToUTF8(net::FormatUrl(file_url
, std::string(),
621 net::kFormatUrlOmitUsernamePassword
, net::UnescapeRule::NORMAL
, NULL
,
623 // Invalid files fall through to regular processing.
626 // Fall back on regular fixup for this input.
628 std::string text_utf8
= base::WideToUTF8(text
.value());
629 #elif defined(OS_POSIX)
630 std::string text_utf8
= text
.value();
632 return FixupURL(text_utf8
, std::string());
635 void URLFixerUpper::OffsetComponent(int offset
, url_parse::Component
* part
) {
638 if (part
->is_valid()) {
639 // Offset the location of this component.
640 part
->begin
+= offset
;
642 // This part might not have existed in the original text.