This source file includes following definitions.
- UTF8ComponentToUTF16Component
- UTF8PartsToUTF16Parts
- TrimWhitespaceUTF8
- PrepareStringForFileOps
- ValidPathForFile
- FixupHomedir
- FixupPath
- AddDesiredTLD
- FixupUsername
- FixupPassword
- FixupHost
- FixupPort
- FixupPath
- FixupQuery
- FixupRef
- HasPort
- GetValidScheme
- SegmentURLInternal
- SegmentURL
- SegmentURL
- FixupURL
- FixupRelativeFile
- OffsetComponent
#include "chrome/common/net/url_fixer_upper.h"
#include <algorithm>
#if defined(OS_POSIX)
#include "base/environment.h"
#endif
#include "base/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/url_constants.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "url/url_file.h"
#include "url/url_parse.h"
#include "url/url_util.h"
const char* URLFixerUpper::home_directory_override = NULL;
namespace {
url_parse::Component UTF8ComponentToUTF16Component(
const std::string& text_utf8,
const url_parse::Component& component_utf8) {
if (component_utf8.len == -1)
return url_parse::Component();
std::string before_component_string =
text_utf8.substr(0, component_utf8.begin);
std::string component_string = text_utf8.substr(component_utf8.begin,
component_utf8.len);
base::string16 before_component_string_16 =
base::UTF8ToUTF16(before_component_string);
base::string16 component_string_16 = base::UTF8ToUTF16(component_string);
url_parse::Component component_16(before_component_string_16.length(),
component_string_16.length());
return component_16;
}
void UTF8PartsToUTF16Parts(const std::string& text_utf8,
const url_parse::Parsed& parts_utf8,
url_parse::Parsed* parts) {
if (IsStringASCII(text_utf8)) {
*parts = parts_utf8;
return;
}
parts->scheme =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.scheme);
parts ->username =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.username);
parts->password =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.password);
parts->host =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.host);
parts->port =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.port);
parts->path =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.path);
parts->query =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.query);
parts->ref =
UTF8ComponentToUTF16Component(text_utf8, parts_utf8.ref);
}
base::TrimPositions TrimWhitespaceUTF8(const std::string& input,
base::TrimPositions positions,
std::string* output) {
DCHECK(IsStringUTF8(input));
base::string16 input16 = base::UTF8ToUTF16(input);
base::string16 output16;
base::TrimPositions result =
base::TrimWhitespace(input16, positions, &output16);
*output = base::UTF16ToUTF8(output16);
return result;
}
void PrepareStringForFileOps(const base::FilePath& text,
base::FilePath::StringType* output) {
#if defined(OS_WIN)
base::TrimWhitespace(text.value(), base::TRIM_ALL, output);
replace(output->begin(), output->end(), '/', '\\');
#else
TrimWhitespaceUTF8(text.value(), base::TRIM_ALL, output);
#endif
}
bool ValidPathForFile(const base::FilePath::StringType& text,
base::FilePath* full_path) {
base::FilePath file_path = base::MakeAbsoluteFilePath(base::FilePath(text));
if (file_path.empty())
return false;
if (!base::PathExists(file_path))
return false;
*full_path = file_path;
return true;
}
#if defined(OS_POSIX)
std::string FixupHomedir(const std::string& text) {
DCHECK(text.length() > 0 && text[0] == '~');
if (text.length() == 1 || text[1] == '/') {
const char* home = getenv(base::env_vars::kHome);
if (URLFixerUpper::home_directory_override)
home = URLFixerUpper::home_directory_override;
if (!home)
return text;
return home + text.substr(1);
}
#if defined(OS_MACOSX)
static const char kHome[] = "/Users/";
#else
static const char kHome[] = "/home/";
#endif
return kHome + text.substr(1);
}
#endif
std::string FixupPath(const std::string& text) {
DCHECK(!text.empty());
base::FilePath::StringType filename;
#if defined(OS_WIN)
base::FilePath input_path(base::UTF8ToWide(text));
PrepareStringForFileOps(input_path, &filename);
if (filename.length() > 1 && filename[1] == '|')
filename[1] = ':';
#elif defined(OS_POSIX)
base::FilePath input_path(text);
PrepareStringForFileOps(input_path, &filename);
if (filename.length() > 0 && filename[0] == '~')
filename = FixupHomedir(filename);
#endif
GURL file_url = net::FilePathToFileURL(base::FilePath(filename));
if (file_url.is_valid()) {
return base::UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::NORMAL, NULL,
NULL, NULL));
}
return text;
}
void AddDesiredTLD(const std::string& desired_tld, std::string* domain) {
if (desired_tld.empty() || domain->empty())
return;
const size_t registry_length =
net::registry_controlled_domains::GetRegistryLength(
*domain,
net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
if ((registry_length != 0) && (registry_length != std::string::npos))
return;
const size_t domain_length(domain->length());
DCHECK_GT(domain_length, 0U);
DCHECK_NE(desired_tld[0], '.');
if ((*domain)[domain_length - 1] != '.')
domain->push_back('.');
domain->append(desired_tld);
const std::string prefix("www.");
if (domain->compare(0, prefix.length(), prefix) != 0) {
domain->insert(0, prefix);
}
}
inline void FixupUsername(const std::string& text,
const url_parse::Component& part,
std::string* url) {
if (!part.is_valid())
return;
url->append(text, part.begin, part.len);
}
inline void FixupPassword(const std::string& text,
const url_parse::Component& part,
std::string* url) {
if (!part.is_valid())
return;
url->append(":");
url->append(text, part.begin, part.len);
}
void FixupHost(const std::string& text,
const url_parse::Component& part,
bool has_scheme,
const std::string& desired_tld,
std::string* url) {
if (!part.is_valid())
return;
std::string domain(text, part.begin, part.len);
const size_t first_nondot(domain.find_first_not_of('.'));
if (first_nondot != std::string::npos) {
domain.erase(0, first_nondot);
size_t last_nondot(domain.find_last_not_of('.'));
DCHECK(last_nondot != std::string::npos);
last_nondot += 2;
if (last_nondot < domain.length())
domain.erase(last_nondot);
}
AddDesiredTLD(desired_tld, &domain);
url->append(domain);
}
void FixupPort(const std::string& text,
const url_parse::Component& part,
std::string* url) {
if (!part.is_valid())
return;
url->append(":");
url->append(text, part.begin, part.len);
}
inline void FixupPath(const std::string& text,
const url_parse::Component& part,
std::string* url) {
if (!part.is_valid() || part.len == 0) {
url->append("/");
return;
}
url->append(text, part.begin, part.len);
}
inline void FixupQuery(const std::string& text,
const url_parse::Component& part,
std::string* url) {
if (!part.is_valid())
return;
url->append("?");
url->append(text, part.begin, part.len);
}
inline void FixupRef(const std::string& text,
const url_parse::Component& part,
std::string* url) {
if (!part.is_valid())
return;
url->append("#");
url->append(text, part.begin, part.len);
}
bool HasPort(const std::string& original_text,
const url_parse::Component& scheme_component) {
size_t port_start = scheme_component.end() + 1;
size_t port_end = port_start;
while ((port_end < original_text.length()) &&
!url_parse::IsAuthorityTerminator(original_text[port_end]))
++port_end;
if (port_end == port_start)
return false;
for (size_t i = port_start; i < port_end; ++i) {
if (!IsAsciiDigit(original_text[i]))
return false;
}
return true;
}
bool GetValidScheme(const std::string& text,
url_parse::Component* scheme_component,
std::string* canon_scheme) {
canon_scheme->clear();
if (!url_parse::ExtractScheme(text.data(), static_cast<int>(text.length()),
scheme_component)) {
return false;
}
url_canon::StdStringCanonOutput canon_scheme_output(canon_scheme);
url_parse::Component canon_scheme_component;
if (!url_canon::CanonicalizeScheme(text.data(), *scheme_component,
&canon_scheme_output,
&canon_scheme_component))
return false;
DCHECK_EQ(0, canon_scheme_component.begin);
canon_scheme->erase(canon_scheme_component.len);
if (canon_scheme->find('.') != std::string::npos)
return false;
if (HasPort(text, *scheme_component))
return false;
return true;
}
std::string SegmentURLInternal(std::string* text, url_parse::Parsed* parts) {
*parts = url_parse::Parsed();
std::string trimmed;
TrimWhitespaceUTF8(*text, base::TRIM_ALL, &trimmed);
if (trimmed.empty())
return std::string();
#if defined(OS_WIN)
int trimmed_length = static_cast<int>(trimmed.length());
if (url_parse::DoesBeginWindowsDriveSpec(trimmed.data(), 0, trimmed_length) ||
url_parse::DoesBeginUNCPath(trimmed.data(), 0, trimmed_length, true))
return "file";
#elif defined(OS_POSIX)
if (base::FilePath::IsSeparator(trimmed.data()[0]) ||
trimmed.data()[0] == '~')
return "file";
#endif
std::string scheme;
if (!GetValidScheme(*text, &parts->scheme, &scheme)) {
bool found_scheme = false;
size_t semicolon = text->find(';');
if (semicolon != 0 && semicolon != std::string::npos) {
(*text)[semicolon] = ':';
if (GetValidScheme(*text, &parts->scheme, &scheme))
found_scheme = true;
else
(*text)[semicolon] = ';';
}
if (!found_scheme) {
parts->scheme.reset();
scheme = StartsWithASCII(*text, "ftp.", false) ?
content::kFtpScheme : content::kHttpScheme;
}
}
if ((scheme != content::kAboutScheme) &&
(scheme != content::kChromeUIScheme) &&
((scheme == content::kFileScheme) ||
!url_util::IsStandard(
scheme.c_str(),
url_parse::Component(0, static_cast<int>(scheme.length())))))
return scheme;
if (scheme == content::kFileSystemScheme) {
url_parse::ParseFileSystemURL(text->data(),
static_cast<int>(text->length()), parts);
return scheme;
}
if (parts->scheme.is_valid()) {
url_parse::ParseStandardURL(text->data(), static_cast<int>(text->length()),
parts);
return scheme;
}
std::string::iterator first_nonwhite = text->begin();
while ((first_nonwhite != text->end()) && IsWhitespace(*first_nonwhite))
++first_nonwhite;
std::string inserted_text(scheme);
inserted_text.append(content::kStandardSchemeSeparator);
std::string text_to_parse(text->begin(), first_nonwhite);
text_to_parse.append(inserted_text);
text_to_parse.append(first_nonwhite, text->end());
url_parse::ParseStandardURL(text_to_parse.data(),
static_cast<int>(text_to_parse.length()),
parts);
const int offset = -static_cast<int>(inserted_text.length());
URLFixerUpper::OffsetComponent(offset, &parts->scheme);
URLFixerUpper::OffsetComponent(offset, &parts->username);
URLFixerUpper::OffsetComponent(offset, &parts->password);
URLFixerUpper::OffsetComponent(offset, &parts->host);
URLFixerUpper::OffsetComponent(offset, &parts->port);
URLFixerUpper::OffsetComponent(offset, &parts->path);
URLFixerUpper::OffsetComponent(offset, &parts->query);
URLFixerUpper::OffsetComponent(offset, &parts->ref);
return scheme;
}
}
std::string URLFixerUpper::SegmentURL(const std::string& text,
url_parse::Parsed* parts) {
std::string mutable_text(text);
return SegmentURLInternal(&mutable_text, parts);
}
base::string16 URLFixerUpper::SegmentURL(const base::string16& text,
url_parse::Parsed* parts) {
std::string text_utf8 = base::UTF16ToUTF8(text);
url_parse::Parsed parts_utf8;
std::string scheme_utf8 = SegmentURL(text_utf8, &parts_utf8);
UTF8PartsToUTF16Parts(text_utf8, parts_utf8, parts);
return base::UTF8ToUTF16(scheme_utf8);
}
GURL URLFixerUpper::FixupURL(const std::string& text,
const std::string& desired_tld) {
std::string trimmed;
TrimWhitespaceUTF8(text, base::TRIM_ALL, &trimmed);
if (trimmed.empty())
return GURL();
url_parse::Parsed parts;
std::string scheme(SegmentURLInternal(&trimmed, &parts));
if (scheme == content::kViewSourceScheme) {
std::string view_source(content::kViewSourceScheme + std::string(":"));
if (!StartsWithASCII(text, view_source + view_source, false)) {
return GURL(content::kViewSourceScheme + std::string(":") +
FixupURL(trimmed.substr(scheme.length() + 1),
desired_tld).possibly_invalid_spec());
}
}
if (scheme == content::kFileScheme)
return GURL(parts.scheme.is_valid() ? text : FixupPath(text));
if (scheme == content::kFileSystemScheme) {
if (parts.inner_parsed() && parts.inner_parsed()->scheme.is_valid())
return GURL(text);
return GURL();
}
bool chrome_url = !LowerCaseEqualsASCII(trimmed, content::kAboutBlankURL) &&
((scheme == content::kAboutScheme) ||
(scheme == content::kChromeUIScheme));
if (chrome_url || url_util::IsStandard(scheme.c_str(),
url_parse::Component(0, static_cast<int>(scheme.length())))) {
std::string url(chrome_url ? content::kChromeUIScheme : scheme);
url.append(content::kStandardSchemeSeparator);
if (parts.username.is_valid()) {
FixupUsername(trimmed, parts.username, &url);
FixupPassword(trimmed, parts.password, &url);
url.append("@");
}
FixupHost(trimmed, parts.host, parts.scheme.is_valid(), desired_tld, &url);
if (chrome_url && !parts.host.is_valid())
url.append(chrome::kChromeUIDefaultHost);
FixupPort(trimmed, parts.port, &url);
FixupPath(trimmed, parts.path, &url);
FixupQuery(trimmed, parts.query, &url);
FixupRef(trimmed, parts.ref, &url);
return GURL(url);
}
if (!parts.scheme.is_valid()) {
std::string fixed_scheme(scheme);
fixed_scheme.append(content::kStandardSchemeSeparator);
trimmed.insert(0, fixed_scheme);
}
return GURL(trimmed);
}
GURL URLFixerUpper::FixupRelativeFile(const base::FilePath& base_dir,
const base::FilePath& text) {
base::FilePath old_cur_directory;
if (!base_dir.empty()) {
base::GetCurrentDirectory(&old_cur_directory);
base::SetCurrentDirectory(base_dir);
}
base::FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
GURL gurl(trimmed);
if (gurl.is_valid() && gurl.IsStandard())
is_file = false;
base::FilePath full_path;
if (is_file && !ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = base::UTF8ToWide(net::UnescapeURLComponent(
base::WideToUTF8(trimmed),
net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = net::UnescapeURLComponent(
trimmed,
net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
base::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(base::UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, net::UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = base::WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
void URLFixerUpper::OffsetComponent(int offset, url_parse::Component* part) {
DCHECK(part);
if (part->is_valid()) {
part->begin += offset;
if (part->begin < 0)
part->reset();
}
}