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 string16 before_component_string_16 = UTF8ToUTF16(before_component_string);
44 string16 component_string_16 = UTF8ToUTF16(component_string);
45 url_parse::Component component_16(before_component_string_16.length(),
46 component_string_16.length());
50 void UTF8PartsToUTF16Parts(const std::string& text_utf8,
51 const url_parse::Parsed& parts_utf8,
52 url_parse::Parsed* parts) {
53 if (IsStringASCII(text_utf8)) {
59 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.scheme);
61 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.username);
63 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.password);
65 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.host);
67 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.port);
69 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.path);
71 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.query);
73 UTF8ComponentToUTF16Component(text_utf8, parts_utf8.ref);
76 TrimPositions TrimWhitespaceUTF8(const std::string& input,
77 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(IsStringUTF8(input));
83 string16 input16 = UTF8ToUTF16(input);
85 TrimPositions result = TrimWhitespace(input16, positions, &output16);
86 *output = UTF16ToUTF8(output16);
90 // does some basic fixes for input that we want to test for file-ness
91 void PrepareStringForFileOps(const base::FilePath& text,
92 base::FilePath::StringType* output) {
94 TrimWhitespace(text.value(), TRIM_ALL, output);
95 replace(output->begin(), output->end(), '/', '\\');
97 TrimWhitespaceUTF8(text.value(), TRIM_ALL, output);
101 // Tries to create a full path from |text|. If the result is valid and the
102 // file exists, returns true and sets |full_path| to the result. Otherwise,
103 // returns false and leaves |full_path| unchanged.
104 bool ValidPathForFile(const base::FilePath::StringType& text,
105 base::FilePath* full_path) {
106 base::FilePath file_path = base::MakeAbsoluteFilePath(base::FilePath(text));
107 if (file_path.empty())
110 if (!base::PathExists(file_path))
113 *full_path = file_path;
117 #if defined(OS_POSIX)
118 // Given a path that starts with ~, return a path that starts with an
119 // expanded-out /user/foobar directory.
120 std::string FixupHomedir(const std::string& text) {
121 DCHECK(text.length() > 0 && text[0] == '~');
123 if (text.length() == 1 || text[1] == '/') {
124 const char* home = getenv(base::env_vars::kHome);
125 if (URLFixerUpper::home_directory_override)
126 home = URLFixerUpper::home_directory_override;
127 // We'll probably break elsewhere if $HOME is undefined, but check here
131 return home + text.substr(1);
134 // Otherwise, this is a path like ~foobar/baz, where we must expand to
135 // user foobar's home directory. Officially, we should use getpwent(),
136 // but that is a nasty blocking call.
138 #if defined(OS_MACOSX)
139 static const char kHome[] = "/Users/";
141 static const char kHome[] = "/home/";
143 return kHome + text.substr(1);
147 // Tries to create a file: URL from |text| if it looks like a filename, even if
148 // it doesn't resolve as a valid path or to an existing file. Returns a
149 // (possibly invalid) file: URL in |fixed_up_url| for input beginning
150 // with a drive specifier or "\\". Returns the unchanged input in other cases
151 // (including file: URLs: these don't look like filenames).
152 std::string FixupPath(const std::string& text) {
153 DCHECK(!text.empty());
155 base::FilePath::StringType filename;
157 base::FilePath input_path(UTF8ToWide(text));
158 PrepareStringForFileOps(input_path, &filename);
160 // Fixup Windows-style drive letters, where "C:" gets rewritten to "C|".
161 if (filename.length() > 1 && filename[1] == '|')
163 #elif defined(OS_POSIX)
164 base::FilePath input_path(text);
165 PrepareStringForFileOps(input_path, &filename);
166 if (filename.length() > 0 && filename[0] == '~')
167 filename = FixupHomedir(filename);
170 // Here, we know the input looks like a file.
171 GURL file_url = net::FilePathToFileURL(base::FilePath(filename));
172 if (file_url.is_valid()) {
173 return UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
174 net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::NORMAL, NULL,
178 // Invalid file URL, just return the input.
182 // Checks |domain| to see if a valid TLD is already present. If not, appends
183 // |desired_tld| to the domain, and prepends "www." unless it's already present.
184 void AddDesiredTLD(const std::string& desired_tld, std::string* domain) {
185 if (desired_tld.empty() || domain->empty())
188 // Check the TLD. If the return value is positive, we already have a TLD, so
189 // abort. If the return value is std::string::npos, there's no valid host,
190 // but we can try to append a TLD anyway, since the host may become valid once
191 // the TLD is attached -- for example, "999999999999" is detected as a broken
192 // IP address and marked invalid, but attaching ".com" makes it legal. When
193 // the return value is 0, there's a valid host with no known TLD, so we can
194 // definitely append the user's TLD. We disallow unknown registries here so
195 // users can input "mail.yahoo" and hit ctrl-enter to get
196 // "www.mail.yahoo.com".
197 const size_t registry_length =
198 net::registry_controlled_domains::GetRegistryLength(
200 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
201 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
202 if ((registry_length != 0) && (registry_length != std::string::npos))
205 // Add the suffix at the end of the domain.
206 const size_t domain_length(domain->length());
207 DCHECK_GT(domain_length, 0U);
208 DCHECK_NE(desired_tld[0], '.');
209 if ((*domain)[domain_length - 1] != '.')
210 domain->push_back('.');
211 domain->append(desired_tld);
213 // Now, if the domain begins with "www.", stop.
214 const std::string prefix("www.");
215 if (domain->compare(0, prefix.length(), prefix) != 0) {
216 // Otherwise, add www. to the beginning of the URL.
217 domain->insert(0, prefix);
221 inline void FixupUsername(const std::string& text,
222 const url_parse::Component& part,
224 if (!part.is_valid())
227 // We don't fix up the username at the moment.
228 url->append(text, part.begin, part.len);
229 // Do not append the trailing '@' because we might need to include the user's
230 // password. FixupURL itself will append the '@' for us.
233 inline void FixupPassword(const std::string& text,
234 const url_parse::Component& part,
236 if (!part.is_valid())
239 // We don't fix up the password at the moment.
241 url->append(text, part.begin, part.len);
244 void FixupHost(const std::string& text,
245 const url_parse::Component& part,
247 const std::string& desired_tld,
249 if (!part.is_valid())
252 // Make domain valid.
253 // Strip all leading dots and all but one trailing dot, unless the user only
254 // typed dots, in which case their input is totally invalid and we should just
255 // leave it unchanged.
256 std::string domain(text, part.begin, part.len);
257 const size_t first_nondot(domain.find_first_not_of('.'));
258 if (first_nondot != std::string::npos) {
259 domain.erase(0, first_nondot);
260 size_t last_nondot(domain.find_last_not_of('.'));
261 DCHECK(last_nondot != std::string::npos);
262 last_nondot += 2; // Point at second period in ending string
263 if (last_nondot < domain.length())
264 domain.erase(last_nondot);
267 // Add any user-specified TLD, if applicable.
268 AddDesiredTLD(desired_tld, &domain);
273 void FixupPort(const std::string& text,
274 const url_parse::Component& part,
276 if (!part.is_valid())
279 // We don't fix up the port at the moment.
281 url->append(text, part.begin, part.len);
284 inline void FixupPath(const std::string& text,
285 const url_parse::Component& part,
287 if (!part.is_valid() || part.len == 0) {
288 // We should always have a path.
293 // Append the path as is.
294 url->append(text, part.begin, part.len);
297 inline void FixupQuery(const std::string& text,
298 const url_parse::Component& part,
300 if (!part.is_valid())
303 // We don't fix up the query at the moment.
305 url->append(text, part.begin, part.len);
308 inline void FixupRef(const std::string& text,
309 const url_parse::Component& part,
311 if (!part.is_valid())
314 // We don't fix up the ref at the moment.
316 url->append(text, part.begin, part.len);
319 bool HasPort(const std::string& original_text,
320 const url_parse::Component& scheme_component) {
321 // Find the range between the ":" and the "/".
322 size_t port_start = scheme_component.end() + 1;
323 size_t port_end = port_start;
324 while ((port_end < original_text.length()) &&
325 !url_parse::IsAuthorityTerminator(original_text[port_end]))
327 if (port_end == port_start)
330 // Scan the range to see if it is entirely digits.
331 for (size_t i = port_start; i < port_end; ++i) {
332 if (!IsAsciiDigit(original_text[i]))
339 // Try to extract a valid scheme from the beginning of |text|.
340 // If successful, set |scheme_component| to the text range where the scheme
341 // was located, and fill |canon_scheme| with its canonicalized form.
342 // Otherwise, return false and leave the outputs in an indeterminate state.
343 bool GetValidScheme(const std::string &text,
344 url_parse::Component* scheme_component,
345 std::string* canon_scheme) {
346 // Locate everything up to (but not including) the first ':'
347 if (!url_parse::ExtractScheme(text.data(), static_cast<int>(text.length()),
352 // Make sure the scheme contains only valid characters, and convert
353 // to lowercase. This also catches IPv6 literals like [::1], because
354 // brackets are not in the whitelist.
355 url_canon::StdStringCanonOutput canon_scheme_output(canon_scheme);
356 url_parse::Component canon_scheme_component;
357 if (!url_canon::CanonicalizeScheme(text.data(), *scheme_component,
358 &canon_scheme_output,
359 &canon_scheme_component))
362 // Strip the ':', and any trailing buffer space.
363 DCHECK_EQ(0, canon_scheme_component.begin);
364 canon_scheme->erase(canon_scheme_component.len);
366 // We need to fix up the segmentation for "www.example.com:/". For this
367 // case, we guess that schemes with a "." are not actually schemes.
368 if (canon_scheme->find('.') != std::string::npos)
371 // We need to fix up the segmentation for "www:123/". For this case, we
372 // will add an HTTP scheme later and make the URL parser happy.
373 // TODO(pkasting): Maybe we should try to use GURL's parser for this?
374 if (HasPort(text, *scheme_component))
377 // Everything checks out.
381 // Performs the work for URLFixerUpper::SegmentURL. |text| may be modified on
382 // output on success: a semicolon following a valid scheme is replaced with a
384 std::string SegmentURLInternal(std::string* text, url_parse::Parsed* parts) {
385 // Initialize the result.
386 *parts = url_parse::Parsed();
389 TrimWhitespaceUTF8(*text, TRIM_ALL, &trimmed);
391 return std::string(); // Nothing to segment.
394 int trimmed_length = static_cast<int>(trimmed.length());
395 if (url_parse::DoesBeginWindowsDriveSpec(trimmed.data(), 0, trimmed_length) ||
396 url_parse::DoesBeginUNCPath(trimmed.data(), 0, trimmed_length, true))
398 #elif defined(OS_POSIX)
399 if (base::FilePath::IsSeparator(trimmed.data()[0]) ||
400 trimmed.data()[0] == '~')
404 // Otherwise, we need to look at things carefully.
406 if (!GetValidScheme(*text, &parts->scheme, &scheme)) {
407 // Try again if there is a ';' in the text. If changing it to a ':' results
408 // in a scheme being found, continue processing with the modified text.
409 bool found_scheme = false;
410 size_t semicolon = text->find(';');
411 if (semicolon != 0 && semicolon != std::string::npos) {
412 (*text)[semicolon] = ':';
413 if (GetValidScheme(*text, &parts->scheme, &scheme))
416 (*text)[semicolon] = ';';
419 // Couldn't determine the scheme, so just pick one.
420 parts->scheme.reset();
421 scheme.assign(StartsWithASCII(*text, "ftp.", false) ?
422 chrome::kFtpScheme : content::kHttpScheme);
426 // Proceed with about and chrome schemes, but not file or nonstandard schemes.
427 if ((scheme != chrome::kAboutScheme) && (scheme != chrome::kChromeUIScheme) &&
428 ((scheme == chrome::kFileScheme) || !url_util::IsStandard(scheme.c_str(),
429 url_parse::Component(0, static_cast<int>(scheme.length())))))
432 if (scheme == chrome::kFileSystemScheme) {
433 // Have the GURL parser do the heavy lifting for us.
434 url_parse::ParseFileSystemURL(text->data(),
435 static_cast<int>(text->length()), parts);
439 if (parts->scheme.is_valid()) {
440 // Have the GURL parser do the heavy lifting for us.
441 url_parse::ParseStandardURL(text->data(), static_cast<int>(text->length()),
446 // We need to add a scheme in order for ParseStandardURL to be happy.
447 // Find the first non-whitespace character.
448 std::string::iterator first_nonwhite = text->begin();
449 while ((first_nonwhite != text->end()) && IsWhitespace(*first_nonwhite))
452 // Construct the text to parse by inserting the scheme.
453 std::string inserted_text(scheme);
454 inserted_text.append(content::kStandardSchemeSeparator);
455 std::string text_to_parse(text->begin(), first_nonwhite);
456 text_to_parse.append(inserted_text);
457 text_to_parse.append(first_nonwhite, text->end());
459 // Have the GURL parser do the heavy lifting for us.
460 url_parse::ParseStandardURL(text_to_parse.data(),
461 static_cast<int>(text_to_parse.length()),
464 // Offset the results of the parse to match the original text.
465 const int offset = -static_cast<int>(inserted_text.length());
466 URLFixerUpper::OffsetComponent(offset, &parts->scheme);
467 URLFixerUpper::OffsetComponent(offset, &parts->username);
468 URLFixerUpper::OffsetComponent(offset, &parts->password);
469 URLFixerUpper::OffsetComponent(offset, &parts->host);
470 URLFixerUpper::OffsetComponent(offset, &parts->port);
471 URLFixerUpper::OffsetComponent(offset, &parts->path);
472 URLFixerUpper::OffsetComponent(offset, &parts->query);
473 URLFixerUpper::OffsetComponent(offset, &parts->ref);
480 std::string URLFixerUpper::SegmentURL(const std::string& text,
481 url_parse::Parsed* parts) {
482 std::string mutable_text(text);
483 return SegmentURLInternal(&mutable_text, parts);
486 string16 URLFixerUpper::SegmentURL(const string16& text,
487 url_parse::Parsed* parts) {
488 std::string text_utf8 = UTF16ToUTF8(text);
489 url_parse::Parsed parts_utf8;
490 std::string scheme_utf8 = SegmentURL(text_utf8, &parts_utf8);
491 UTF8PartsToUTF16Parts(text_utf8, parts_utf8, parts);
492 return UTF8ToUTF16(scheme_utf8);
495 GURL URLFixerUpper::FixupURL(const std::string& text,
496 const std::string& desired_tld) {
498 TrimWhitespaceUTF8(text, TRIM_ALL, &trimmed);
500 return GURL(); // Nothing here.
503 url_parse::Parsed parts;
504 std::string scheme(SegmentURLInternal(&trimmed, &parts));
506 // For view-source: URLs, we strip "view-source:", do fixup, and stick it back
507 // on. This allows us to handle things like "view-source:google.com".
508 if (scheme == content::kViewSourceScheme) {
509 // Reject "view-source:view-source:..." to avoid deep recursion.
510 std::string view_source(content::kViewSourceScheme + std::string(":"));
511 if (!StartsWithASCII(text, view_source + view_source, false)) {
512 return GURL(content::kViewSourceScheme + std::string(":") +
513 FixupURL(trimmed.substr(scheme.length() + 1),
514 desired_tld).possibly_invalid_spec());
518 // We handle the file scheme separately.
519 if (scheme == chrome::kFileScheme)
520 return GURL(parts.scheme.is_valid() ? text : FixupPath(text));
522 // We handle the filesystem scheme separately.
523 if (scheme == chrome::kFileSystemScheme) {
524 if (parts.inner_parsed() && parts.inner_parsed()->scheme.is_valid())
529 // Parse and rebuild about: and chrome: URLs, except about:blank.
530 bool chrome_url = !LowerCaseEqualsASCII(trimmed, content::kAboutBlankURL) &&
531 ((scheme == chrome::kAboutScheme) || (scheme == chrome::kChromeUIScheme));
533 // For some schemes whose layouts we understand, we rebuild it.
534 if (chrome_url || url_util::IsStandard(scheme.c_str(),
535 url_parse::Component(0, static_cast<int>(scheme.length())))) {
536 // Replace the about: scheme with the chrome: scheme.
537 std::string url(chrome_url ? chrome::kChromeUIScheme : scheme);
538 url.append(content::kStandardSchemeSeparator);
540 // We need to check whether the |username| is valid because it is our
541 // responsibility to append the '@' to delineate the user information from
542 // the host portion of the URL.
543 if (parts.username.is_valid()) {
544 FixupUsername(trimmed, parts.username, &url);
545 FixupPassword(trimmed, parts.password, &url);
549 FixupHost(trimmed, parts.host, parts.scheme.is_valid(), desired_tld, &url);
550 if (chrome_url && !parts.host.is_valid())
551 url.append(chrome::kChromeUIDefaultHost);
552 FixupPort(trimmed, parts.port, &url);
553 FixupPath(trimmed, parts.path, &url);
554 FixupQuery(trimmed, parts.query, &url);
555 FixupRef(trimmed, parts.ref, &url);
560 // In the worst-case, we insert a scheme if the URL lacks one.
561 if (!parts.scheme.is_valid()) {
562 std::string fixed_scheme(scheme);
563 fixed_scheme.append(content::kStandardSchemeSeparator);
564 trimmed.insert(0, fixed_scheme);
567 return GURL(trimmed);
570 // The rules are different here than for regular fixup, since we need to handle
571 // input like "hello.html" and know to look in the current directory. Regular
572 // fixup will look for cues that it is actually a file path before trying to
573 // figure out what file it is. If our logic doesn't work, we will fall back on
575 GURL URLFixerUpper::FixupRelativeFile(const base::FilePath& base_dir,
576 const base::FilePath& text) {
577 base::FilePath old_cur_directory;
578 if (!base_dir.empty()) {
579 // Save the old current directory before we move to the new one.
580 file_util::GetCurrentDirectory(&old_cur_directory);
581 file_util::SetCurrentDirectory(base_dir);
584 // Allow funny input with extra whitespace and the wrong kind of slashes.
585 base::FilePath::StringType trimmed;
586 PrepareStringForFileOps(text, &trimmed);
589 // Avoid recognizing definite non-file URLs as file paths.
591 if (gurl.is_valid() && gurl.IsStandard())
593 base::FilePath full_path;
594 if (is_file && !ValidPathForFile(trimmed, &full_path)) {
595 // Not a path as entered, try unescaping it in case the user has
596 // escaped things. We need to go through 8-bit since the escaped values
597 // only represent 8-bit values.
599 std::wstring unescaped = UTF8ToWide(net::UnescapeURLComponent(
601 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS));
602 #elif defined(OS_POSIX)
603 std::string unescaped = net::UnescapeURLComponent(
605 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
608 if (!ValidPathForFile(unescaped, &full_path))
612 // Put back the current directory if we saved it.
613 if (!base_dir.empty())
614 file_util::SetCurrentDirectory(old_cur_directory);
617 GURL file_url = net::FilePathToFileURL(full_path);
618 if (file_url.is_valid())
619 return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
620 net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::NORMAL, NULL,
622 // Invalid files fall through to regular processing.
625 // Fall back on regular fixup for this input.
627 std::string text_utf8 = WideToUTF8(text.value());
628 #elif defined(OS_POSIX)
629 std::string text_utf8 = text.value();
631 return FixupURL(text_utf8, std::string());
634 void URLFixerUpper::OffsetComponent(int offset, url_parse::Component* part) {
637 if (part->is_valid()) {
638 // Offset the location of this component.
639 part->begin += offset;
641 // This part might not have existed in the original text.