Home | History | Annotate | Download | only in url_fixer
      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.
      4 
      5 #include "components/url_fixer/url_fixer.h"
      6 
      7 #include <algorithm>
      8 
      9 #if defined(OS_POSIX)
     10 #include "base/environment.h"
     11 #endif
     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"
     23 
     24 const char* url_fixer::home_directory_override = NULL;
     25 
     26 namespace {
     27 
     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";
     32 
     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();
     43 
     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());
     53   return component_16;
     54 }
     55 
     56 void UTF8PartsToUTF16Parts(const std::string& text_utf8,
     57                            const url::Parsed& parts_utf8,
     58                            url::Parsed* parts) {
     59   if (base::IsStringASCII(text_utf8)) {
     60     *parts = parts_utf8;
     61     return;
     62   }
     63 
     64   parts->scheme = UTF8ComponentToUTF16Component(text_utf8, parts_utf8.scheme);
     65   parts->username =
     66       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.username);
     67   parts->password =
     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);
     74 }
     75 
     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);
     88   return result;
     89 }
     90 
     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) {
     94 #if defined(OS_WIN)
     95   base::TrimWhitespace(text.value(), base::TRIM_ALL, output);
     96   replace(output->begin(), output->end(), '/', '\\');
     97 #else
     98   TrimWhitespaceUTF8(text.value(), base::TRIM_ALL, output);
     99 #endif
    100 }
    101 
    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())
    109     return false;
    110 
    111   if (!base::PathExists(file_path))
    112     return false;
    113 
    114   *full_path = file_path;
    115   return true;
    116 }
    117 
    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] == '~');
    123 
    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
    129     // just in case.
    130     if (!home)
    131       return text;
    132     return home + text.substr(1);
    133   }
    134 
    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.
    138 
    139 #if defined(OS_MACOSX)
    140   static const char kHome[] = "/Users/";
    141 #else
    142   static const char kHome[] = "/home/";
    143 #endif
    144   return kHome + text.substr(1);
    145 }
    146 #endif
    147 
    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());
    155 
    156   base::FilePath::StringType filename;
    157 #if defined(OS_WIN)
    158   base::FilePath input_path(base::UTF8ToWide(text));
    159   PrepareStringForFileOps(input_path, &filename);
    160 
    161   // Fixup Windows-style drive letters, where "C:" gets rewritten to "C|".
    162   if (filename.length() > 1 && filename[1] == '|')
    163     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);
    169 #endif
    170 
    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,
    175                                             std::string(),
    176                                             net::kFormatUrlOmitUsernamePassword,
    177                                             net::UnescapeRule::NORMAL,
    178                                             NULL,
    179                                             NULL,
    180                                             NULL));
    181   }
    182 
    183   // Invalid file URL, just return the input.
    184   return text;
    185 }
    186 
    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())
    191     return;
    192 
    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(
    204           *domain,
    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))
    208     return;
    209 
    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);
    217 
    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);
    223   }
    224 }
    225 
    226 inline void FixupUsername(const std::string& text,
    227                           const url::Component& part,
    228                           std::string* url) {
    229   if (!part.is_valid())
    230     return;
    231 
    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.
    236 }
    237 
    238 inline void FixupPassword(const std::string& text,
    239                           const url::Component& part,
    240                           std::string* url) {
    241   if (!part.is_valid())
    242     return;
    243 
    244   // We don't fix up the password at the moment.
    245   url->append(":");
    246   url->append(text, part.begin, part.len);
    247 }
    248 
    249 void FixupHost(const std::string& text,
    250                const url::Component& part,
    251                bool has_scheme,
    252                const std::string& desired_tld,
    253                std::string* url) {
    254   if (!part.is_valid())
    255     return;
    256 
    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);
    270   }
    271 
    272   // Add any user-specified TLD, if applicable.
    273   AddDesiredTLD(desired_tld, &domain);
    274 
    275   url->append(domain);
    276 }
    277 
    278 void FixupPort(const std::string& text,
    279                const url::Component& part,
    280                std::string* url) {
    281   if (!part.is_valid())
    282     return;
    283 
    284   // We don't fix up the port at the moment.
    285   url->append(":");
    286   url->append(text, part.begin, part.len);
    287 }
    288 
    289 inline void FixupPath(const std::string& text,
    290                       const url::Component& part,
    291                       std::string* url) {
    292   if (!part.is_valid() || part.len == 0) {
    293     // We should always have a path.
    294     url->append("/");
    295     return;
    296   }
    297 
    298   // Append the path as is.
    299   url->append(text, part.begin, part.len);
    300 }
    301 
    302 inline void FixupQuery(const std::string& text,
    303                        const url::Component& part,
    304                        std::string* url) {
    305   if (!part.is_valid())
    306     return;
    307 
    308   // We don't fix up the query at the moment.
    309   url->append("?");
    310   url->append(text, part.begin, part.len);
    311 }
    312 
    313 inline void FixupRef(const std::string& text,
    314                      const url::Component& part,
    315                      std::string* url) {
    316   if (!part.is_valid())
    317     return;
    318 
    319   // We don't fix up the ref at the moment.
    320   url->append("#");
    321   url->append(text, part.begin, part.len);
    322 }
    323 
    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]))
    331     ++port_end;
    332   if (port_end == port_start)
    333     return false;
    334 
    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]))
    338       return false;
    339   }
    340 
    341   return true;
    342 }
    343 
    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();
    352 
    353   // Locate everything up to (but not including) the first ':'
    354   if (!url::ExtractScheme(
    355           text.data(), static_cast<int>(text.length()), scheme_component)) {
    356     return false;
    357   }
    358 
    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(),
    365                                *scheme_component,
    366                                &canon_scheme_output,
    367                                &canon_scheme_component)) {
    368     return false;
    369   }
    370 
    371   // Strip the ':', and any trailing buffer space.
    372   DCHECK_EQ(0, canon_scheme_component.begin);
    373   canon_scheme->erase(canon_scheme_component.len);
    374 
    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)
    378     return false;
    379 
    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))
    384     return false;
    385 
    386   // Everything checks out.
    387   return true;
    388 }
    389 
    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
    392 // colon.
    393 std::string SegmentURLInternal(std::string* text, url::Parsed* parts) {
    394   // Initialize the result.
    395   *parts = url::Parsed();
    396 
    397   std::string trimmed;
    398   TrimWhitespaceUTF8(*text, base::TRIM_ALL, &trimmed);
    399   if (trimmed.empty())
    400     return std::string();  // Nothing to segment.
    401 
    402 #if defined(OS_WIN)
    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))
    406     return "file";
    407 #elif defined(OS_POSIX)
    408   if (base::FilePath::IsSeparator(trimmed.data()[0]) ||
    409       trimmed.data()[0] == '~')
    410     return "file";
    411 #endif
    412 
    413   // Otherwise, we need to look at things carefully.
    414   std::string scheme;
    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))
    423         found_scheme = true;
    424       else
    425         (*text)[semicolon] = ';';
    426     }
    427     if (!found_scheme) {
    428       // Couldn't determine the scheme, so just pick one.
    429       parts->scheme.reset();
    430       scheme = StartsWithASCII(*text, "ftp.", false) ? url::kFtpScheme
    431                                                      : url::kHttpScheme;
    432     }
    433   }
    434 
    435   // Proceed with about and chrome schemes, but not file or nonstandard schemes.
    436   if ((scheme != url::kAboutScheme) && (scheme != kChromeUIScheme) &&
    437       ((scheme == url::kFileScheme) ||
    438        !url::IsStandard(
    439            scheme.c_str(),
    440            url::Component(0, static_cast<int>(scheme.length()))))) {
    441     return scheme;
    442   }
    443 
    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);
    448     return scheme;
    449   }
    450 
    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);
    455     return scheme;
    456   }
    457 
    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))
    462     ++first_nonwhite;
    463 
    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());
    470 
    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);
    474 
    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);
    485 
    486   return scheme;
    487 }
    488 
    489 }  // namespace
    490 
    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);
    494 }
    495 
    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);
    503 }
    504 
    505 GURL url_fixer::FixupURL(const std::string& text,
    506                          const std::string& desired_tld) {
    507   std::string trimmed;
    508   TrimWhitespaceUTF8(text, base::TRIM_ALL, &trimmed);
    509   if (trimmed.empty())
    510     return GURL();  // Nothing here.
    511 
    512   // Segment the URL.
    513   url::Parsed parts;
    514   std::string scheme(SegmentURLInternal(&trimmed, &parts));
    515 
    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());
    525     }
    526   }
    527 
    528   // We handle the file scheme separately.
    529   if (scheme == url::kFileScheme)
    530     return GURL(parts.scheme.is_valid() ? text : FixupPath(text));
    531 
    532   // We handle the filesystem scheme separately.
    533   if (scheme == url::kFileSystemScheme) {
    534     if (parts.inner_parsed() && parts.inner_parsed()->scheme.is_valid())
    535       return GURL(text);
    536     return GURL();
    537   }
    538 
    539   // Parse and rebuild about: and chrome: URLs, except about:blank.
    540   bool chrome_url =
    541       !LowerCaseEqualsASCII(trimmed, url::kAboutBlankURL) &&
    542       ((scheme == url::kAboutScheme) || (scheme == kChromeUIScheme));
    543 
    544   // For some schemes whose layouts we understand, we rebuild it.
    545   if (chrome_url ||
    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);
    551 
    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);
    558       url.append("@");
    559     }
    560 
    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);
    568 
    569     return GURL(url);
    570   }
    571 
    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);
    577   }
    578 
    579   return GURL(trimmed);
    580 }
    581 
    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
    586 // regular fixup.
    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);
    594   }
    595 
    596   // Allow funny input with extra whitespace and the wrong kind of slashes.
    597   base::FilePath::StringType trimmed;
    598   PrepareStringForFileOps(text, &trimmed);
    599 
    600   bool is_file = true;
    601   // Avoid recognizing definite non-file URLs as file paths.
    602   GURL gurl(trimmed);
    603   if (gurl.is_valid() && gurl.IsStandard())
    604     is_file = false;
    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.
    610 #if defined(OS_WIN)
    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(
    616         trimmed,
    617         net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
    618 #endif
    619 
    620     if (!ValidPathForFile(unescaped, &full_path))
    621       is_file = false;
    622   }
    623 
    624   // Put back the current directory if we saved it.
    625   if (!base_dir.empty())
    626     base::SetCurrentDirectory(old_cur_directory);
    627 
    628   if (is_file) {
    629     GURL file_url = net::FilePathToFileURL(full_path);
    630     if (file_url.is_valid())
    631       return GURL(
    632           base::UTF16ToUTF8(net::FormatUrl(file_url,
    633                                            std::string(),
    634                                            net::kFormatUrlOmitUsernamePassword,
    635                                            net::UnescapeRule::NORMAL,
    636                                            NULL,
    637                                            NULL,
    638                                            NULL)));
    639     // Invalid files fall through to regular processing.
    640   }
    641 
    642 // Fall back on regular fixup for this input.
    643 #if defined(OS_WIN)
    644   std::string text_utf8 = base::WideToUTF8(text.value());
    645 #elif defined(OS_POSIX)
    646   std::string text_utf8 = text.value();
    647 #endif
    648   return FixupURL(text_utf8, std::string());
    649 }
    650 
    651 void url_fixer::OffsetComponent(int offset, url::Component* part) {
    652   DCHECK(part);
    653 
    654   if (part->is_valid()) {
    655     // Offset the location of this component.
    656     part->begin += offset;
    657 
    658     // This part might not have existed in the original text.
    659     if (part->begin < 0)
    660       part->reset();
    661   }
    662 }
    663