Home | History | Annotate | Download | only in net
      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 "chrome/common/net/url_fixer_upper.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 "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"
     23 
     24 const char* URLFixerUpper::home_directory_override = NULL;
     25 
     26 namespace {
     27 
     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();
     38 
     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,
     42                                                   component_utf8.len);
     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());
     47   return component_16;
     48 }
     49 
     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)) {
     54     *parts = parts_utf8;
     55     return;
     56   }
     57 
     58   parts->scheme =
     59       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.scheme);
     60   parts ->username =
     61       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.username);
     62   parts->password =
     63       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.password);
     64   parts->host =
     65       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.host);
     66   parts->port =
     67       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.port);
     68   parts->path =
     69       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.path);
     70   parts->query =
     71       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.query);
     72   parts->ref =
     73       UTF8ComponentToUTF16Component(text_utf8, parts_utf8.ref);
     74 }
     75 
     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);
     84   string16 output16;
     85   TrimPositions result = TrimWhitespace(input16, positions, &output16);
     86   *output = UTF16ToUTF8(output16);
     87   return result;
     88 }
     89 
     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) {
     93 #if defined(OS_WIN)
     94   TrimWhitespace(text.value(), TRIM_ALL, output);
     95   replace(output->begin(), output->end(), '/', '\\');
     96 #else
     97   TrimWhitespaceUTF8(text.value(), TRIM_ALL, output);
     98 #endif
     99 }
    100 
    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())
    108     return false;
    109 
    110   if (!base::PathExists(file_path))
    111     return false;
    112 
    113   *full_path = file_path;
    114   return true;
    115 }
    116 
    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] == '~');
    122 
    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
    128     // just in case.
    129     if (!home)
    130       return text;
    131     return home + text.substr(1);
    132   }
    133 
    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.
    137 
    138 #if defined(OS_MACOSX)
    139   static const char kHome[] = "/Users/";
    140 #else
    141   static const char kHome[] = "/home/";
    142 #endif
    143   return kHome + text.substr(1);
    144 }
    145 #endif
    146 
    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());
    154 
    155   base::FilePath::StringType filename;
    156 #if defined(OS_WIN)
    157   base::FilePath input_path(UTF8ToWide(text));
    158   PrepareStringForFileOps(input_path, &filename);
    159 
    160   // Fixup Windows-style drive letters, where "C:" gets rewritten to "C|".
    161   if (filename.length() > 1 && filename[1] == '|')
    162     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);
    168 #endif
    169 
    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,
    175         NULL, NULL));
    176   }
    177 
    178   // Invalid file URL, just return the input.
    179   return text;
    180 }
    181 
    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())
    186     return;
    187 
    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(
    199           *domain,
    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))
    203     return;
    204 
    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);
    212 
    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);
    218   }
    219 }
    220 
    221 inline void FixupUsername(const std::string& text,
    222                           const url_parse::Component& part,
    223                           std::string* url) {
    224   if (!part.is_valid())
    225     return;
    226 
    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.
    231 }
    232 
    233 inline void FixupPassword(const std::string& text,
    234                           const url_parse::Component& part,
    235                           std::string* url) {
    236   if (!part.is_valid())
    237     return;
    238 
    239   // We don't fix up the password at the moment.
    240   url->append(":");
    241   url->append(text, part.begin, part.len);
    242 }
    243 
    244 void FixupHost(const std::string& text,
    245                const url_parse::Component& part,
    246                bool has_scheme,
    247                const std::string& desired_tld,
    248                std::string* url) {
    249   if (!part.is_valid())
    250     return;
    251 
    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);
    265   }
    266 
    267   // Add any user-specified TLD, if applicable.
    268   AddDesiredTLD(desired_tld, &domain);
    269 
    270   url->append(domain);
    271 }
    272 
    273 void FixupPort(const std::string& text,
    274                const url_parse::Component& part,
    275                std::string* url) {
    276   if (!part.is_valid())
    277     return;
    278 
    279   // We don't fix up the port at the moment.
    280   url->append(":");
    281   url->append(text, part.begin, part.len);
    282 }
    283 
    284 inline void FixupPath(const std::string& text,
    285                       const url_parse::Component& part,
    286                       std::string* url) {
    287   if (!part.is_valid() || part.len == 0) {
    288     // We should always have a path.
    289     url->append("/");
    290     return;
    291   }
    292 
    293   // Append the path as is.
    294   url->append(text, part.begin, part.len);
    295 }
    296 
    297 inline void FixupQuery(const std::string& text,
    298                        const url_parse::Component& part,
    299                        std::string* url) {
    300   if (!part.is_valid())
    301     return;
    302 
    303   // We don't fix up the query at the moment.
    304   url->append("?");
    305   url->append(text, part.begin, part.len);
    306 }
    307 
    308 inline void FixupRef(const std::string& text,
    309                      const url_parse::Component& part,
    310                      std::string* url) {
    311   if (!part.is_valid())
    312     return;
    313 
    314   // We don't fix up the ref at the moment.
    315   url->append("#");
    316   url->append(text, part.begin, part.len);
    317 }
    318 
    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]))
    326     ++port_end;
    327   if (port_end == port_start)
    328     return false;
    329 
    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]))
    333       return false;
    334   }
    335 
    336   return true;
    337 }
    338 
    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()),
    348                                 scheme_component)) {
    349     return false;
    350   }
    351 
    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))
    360     return false;
    361 
    362   // Strip the ':', and any trailing buffer space.
    363   DCHECK_EQ(0, canon_scheme_component.begin);
    364   canon_scheme->erase(canon_scheme_component.len);
    365 
    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)
    369     return false;
    370 
    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))
    375     return false;
    376 
    377   // Everything checks out.
    378   return true;
    379 }
    380 
    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
    383 // colon.
    384 std::string SegmentURLInternal(std::string* text, url_parse::Parsed* parts) {
    385   // Initialize the result.
    386   *parts = url_parse::Parsed();
    387 
    388   std::string trimmed;
    389   TrimWhitespaceUTF8(*text, TRIM_ALL, &trimmed);
    390   if (trimmed.empty())
    391     return std::string();  // Nothing to segment.
    392 
    393 #if defined(OS_WIN)
    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))
    397     return "file";
    398 #elif defined(OS_POSIX)
    399   if (base::FilePath::IsSeparator(trimmed.data()[0]) ||
    400       trimmed.data()[0] == '~')
    401     return "file";
    402 #endif
    403 
    404   // Otherwise, we need to look at things carefully.
    405   std::string scheme;
    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))
    414         found_scheme = true;
    415       else
    416         (*text)[semicolon] = ';';
    417     }
    418     if (!found_scheme) {
    419       // Couldn't determine the scheme, so just pick one.
    420       parts->scheme.reset();
    421       scheme.assign(StartsWithASCII(*text, "ftp.", false) ?
    422                     chrome::kFtpScheme : chrome::kHttpScheme);
    423     }
    424   }
    425 
    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())))))
    430     return scheme;
    431 
    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);
    436     return scheme;
    437   }
    438 
    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()),
    442                                 parts);
    443     return scheme;
    444   }
    445 
    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))
    450     ++first_nonwhite;
    451 
    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());
    458 
    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()),
    462                               parts);
    463 
    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);
    474 
    475   return scheme;
    476 }
    477 
    478 }  // namespace
    479 
    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);
    484 }
    485 
    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);
    493 }
    494 
    495 GURL URLFixerUpper::FixupURL(const std::string& text,
    496                              const std::string& desired_tld) {
    497   std::string trimmed;
    498   TrimWhitespaceUTF8(text, TRIM_ALL, &trimmed);
    499   if (trimmed.empty())
    500     return GURL();  // Nothing here.
    501 
    502   // Segment the URL.
    503   url_parse::Parsed parts;
    504   std::string scheme(SegmentURLInternal(&trimmed, &parts));
    505 
    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());
    515     }
    516   }
    517 
    518   // We handle the file scheme separately.
    519   if (scheme == chrome::kFileScheme)
    520     return GURL(parts.scheme.is_valid() ? text : FixupPath(text));
    521 
    522   // We handle the filesystem scheme separately.
    523   if (scheme == chrome::kFileSystemScheme) {
    524     if (parts.inner_parsed() && parts.inner_parsed()->scheme.is_valid())
    525       return GURL(text);
    526     return GURL();
    527   }
    528 
    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));
    532 
    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);
    539 
    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);
    546       url.append("@");
    547     }
    548 
    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);
    556 
    557     return GURL(url);
    558   }
    559 
    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);
    565   }
    566 
    567   return GURL(trimmed);
    568 }
    569 
    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
    574 // regular fixup.
    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);
    582   }
    583 
    584   // Allow funny input with extra whitespace and the wrong kind of slashes.
    585   base::FilePath::StringType trimmed;
    586   PrepareStringForFileOps(text, &trimmed);
    587 
    588   bool is_file = true;
    589   // Avoid recognizing definite non-file URLs as file paths.
    590   GURL gurl(trimmed);
    591   if (gurl.is_valid() && gurl.IsStandard())
    592     is_file = false;
    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.
    598 #if defined(OS_WIN)
    599     std::wstring unescaped = UTF8ToWide(net::UnescapeURLComponent(
    600         WideToUTF8(trimmed),
    601         net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS));
    602 #elif defined(OS_POSIX)
    603     std::string unescaped = net::UnescapeURLComponent(
    604         trimmed,
    605         net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
    606 #endif
    607 
    608     if (!ValidPathForFile(unescaped, &full_path))
    609       is_file = false;
    610   }
    611 
    612   // Put back the current directory if we saved it.
    613   if (!base_dir.empty())
    614     file_util::SetCurrentDirectory(old_cur_directory);
    615 
    616   if (is_file) {
    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,
    621           NULL, NULL)));
    622     // Invalid files fall through to regular processing.
    623   }
    624 
    625   // Fall back on regular fixup for this input.
    626 #if defined(OS_WIN)
    627   std::string text_utf8 = WideToUTF8(text.value());
    628 #elif defined(OS_POSIX)
    629   std::string text_utf8 = text.value();
    630 #endif
    631   return FixupURL(text_utf8, std::string());
    632 }
    633 
    634 void URLFixerUpper::OffsetComponent(int offset, url_parse::Component* part) {
    635   DCHECK(part);
    636 
    637   if (part->is_valid()) {
    638     // Offset the location of this component.
    639     part->begin += offset;
    640 
    641     // This part might not have existed in the original text.
    642     if (part->begin < 0)
    643       part->reset();
    644   }
    645 }
    646