code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_canon_ip.h"
#include <stdint.h>
#include <stdlib.h>
#include <limits>
#include "base/check.h"
#include "url/url_canon_internal.h"
#include "url/url_features.h"
namespace url {
namespace {
// Converts one of the character types that represent a numerical base to the
// corresponding base.
int BaseForType(SharedCharTypes type) {
switch (type) {
case CHAR_HEX:
return 16;
case CHAR_DEC:
return 10;
case CHAR_OCT:
return 8;
default:
return 0;
}
}
// Converts an IPv4 component to a 32-bit number, while checking for overflow.
//
// Possible return values:
// - IPV4 - The number was valid, and did not overflow.
// - BROKEN - The input was numeric, but too large for a 32-bit field.
// - NEUTRAL - Input was not numeric.
//
// The input is assumed to be ASCII. The components are assumed to be non-empty.
template<typename CHAR>
CanonHostInfo::Family IPv4ComponentToNumber(const CHAR* spec,
const Component& component,
uint32_t* number) {
// Empty components are considered non-numeric.
if (component.is_empty())
return CanonHostInfo::NEUTRAL;
// Figure out the base
SharedCharTypes base;
int base_prefix_len = 0; // Size of the prefix for this base.
if (spec[component.begin] == '0') {
// Either hex or dec, or a standalone zero.
if (component.len == 1) {
base = CHAR_DEC;
} else if (spec[component.begin + 1] == 'X' ||
spec[component.begin + 1] == 'x') {
base = CHAR_HEX;
base_prefix_len = 2;
} else {
base = CHAR_OCT;
base_prefix_len = 1;
}
} else {
base = CHAR_DEC;
}
// Extend the prefix to consume all leading zeros.
while (base_prefix_len < component.len &&
spec[component.begin + base_prefix_len] == '0')
base_prefix_len++;
// Put the component, minus any base prefix, into a NULL-terminated buffer so
// we can call the standard library. Because leading zeros have already been
// discarded, filling the entire buffer is guaranteed to trigger the 32-bit
// overflow check.
const int kMaxComponentLen = 16;
char buf[kMaxComponentLen + 1]; // digits + '\0'
int dest_i = 0;
bool may_be_broken_octal = false;
for (int i = component.begin + base_prefix_len; i < component.end(); i++) {
if (spec[i] >= 0x80)
return CanonHostInfo::NEUTRAL;
// We know the input is 7-bit, so convert to narrow (if this is the wide
// version of the template) by casting.
char input = static_cast<char>(spec[i]);
// Validate that this character is OK for the given base.
if (!IsCharOfType(input, base)) {
if (IsCharOfType(input, CHAR_DEC)) {
// Entirely numeric components with leading 0s that aren't octal are
// considered broken.
may_be_broken_octal = true;
} else {
return CanonHostInfo::NEUTRAL;
}
}
// Fill the buffer, if there's space remaining. This check allows us to
// verify that all characters are numeric, even those that don't fit.
if (dest_i < kMaxComponentLen)
buf[dest_i++] = input;
}
if (may_be_broken_octal)
return CanonHostInfo::BROKEN;
buf[dest_i] = '\0';
// Use the 64-bit strtoi so we get a big number (no hex, decimal, or octal
// number can overflow a 64-bit number in <= 16 characters).
uint64_t num = _strtoui64(buf, NULL, BaseForType(base));
// Check for 32-bit overflow.
if (num > std::numeric_limits<uint32_t>::max())
return CanonHostInfo::BROKEN;
// No overflow. Success!
*number = static_cast<uint32_t>(num);
return CanonHostInfo::IPV4;
}
// See declaration of IPv4AddressToNumber for documentation.
template <typename CHAR, typename UCHAR>
CanonHostInfo::Family DoIPv4AddressToNumber(const CHAR* spec,
Component host,
unsigned char address[4],
int* num_ipv4_components) {
// Ignore terminal dot, if present.
if (host.is_nonempty() && spec[host.end() - 1] == '.')
--host.len;
// Do nothing if empty.
if (host.is_empty())
return CanonHostInfo::NEUTRAL;
// Read component values. The first `existing_components` of them are
// populated front to back, with the first one corresponding to the last
// component, which allows for early exit if the last component isn't a
// number.
uint32_t component_values[4];
int existing_components = 0;
int current_component_end = host.end();
int current_position = current_component_end;
while (true) {
// If this is not the first character of a component, go to the next
// component.
if (current_position != host.begin && spec[current_position - 1] != '.') {
--current_position;
continue;
}
CanonHostInfo::Family family = IPv4ComponentToNumber(
spec,
Component(current_position, current_component_end - current_position),
&component_values[existing_components]);
// If `family` is NEUTRAL and this is the last component, return NEUTRAL. If
// `family` is NEUTRAL but not the last component, this is considered a
// BROKEN IPv4 address, as opposed to a non-IPv4 hostname.
if (family == CanonHostInfo::NEUTRAL && existing_components == 0)
return CanonHostInfo::NEUTRAL;
if (family != CanonHostInfo::IPV4)
return CanonHostInfo::BROKEN;
++existing_components;
// If this is the final component, nothing else to do.
if (current_position == host.begin)
break;
// If there are more than 4 components, fail.
if (existing_components == 4)
return CanonHostInfo::BROKEN;
current_component_end = current_position - 1;
--current_position;
}
// Use `component_values` to fill out the 4-component IP address.
// First, process all components but the last, while making sure each fits
// within an 8-bit field.
for (int i = existing_components - 1; i > 0; i--) {
if (component_values[i] > std::numeric_limits<uint8_t>::max())
return CanonHostInfo::BROKEN;
address[existing_components - i - 1] =
static_cast<unsigned char>(component_values[i]);
}
uint32_t last_value = component_values[0];
for (int i = 3; i >= existing_components - 1; i--) {
address[i] = static_cast<unsigned char>(last_value);
last_value >>= 8;
}
// If the last component has residual bits, report overflow.
if (last_value != 0)
return CanonHostInfo::BROKEN;
// Tell the caller how many components we saw.
*num_ipv4_components = existing_components;
// Success!
return CanonHostInfo::IPV4;
}
// Return true if we've made a final IPV4/BROKEN decision, false if the result
// is NEUTRAL, and we could use a second opinion.
template<typename CHAR, typename UCHAR>
bool DoCanonicalizeIPv4Address(const CHAR* spec,
const Component& host,
CanonOutput* output,
CanonHostInfo* host_info) {
host_info->family = IPv4AddressToNumber(
spec, host, host_info->address, &host_info->num_ipv4_components);
switch (host_info->family) {
case CanonHostInfo::IPV4:
// Definitely an IPv4 address.
host_info->out_host.begin = output->length();
AppendIPv4Address(host_info->address, output);
host_info->out_host.len = output->length() - host_info->out_host.begin;
return true;
case CanonHostInfo::BROKEN:
// Definitely broken.
return true;
default:
// Could be IPv6 or a hostname.
return false;
}
}
// Helper class that describes the main components of an IPv6 input string.
// See the following examples to understand how it breaks up an input string:
//
// [Example 1]: input = "[::aa:bb]"
// ==> num_hex_components = 2
// ==> hex_components[0] = Component(3,2) "aa"
// ==> hex_components[1] = Component(6,2) "bb"
// ==> index_of_contraction = 0
// ==> ipv4_component = Component(0, -1)
//
// [Example 2]: input = "[1:2::3:4:5]"
// ==> num_hex_components = 5
// ==> hex_components[0] = Component(1,1) "1"
// ==> hex_components[1] = Component(3,1) "2"
// ==> hex_components[2] = Component(6,1) "3"
// ==> hex_components[3] = Component(8,1) "4"
// ==> hex_components[4] = Component(10,1) "5"
// ==> index_of_contraction = 2
// ==> ipv4_component = Component(0, -1)
//
// [Example 3]: input = "[::ffff:192.168.0.1]"
// ==> num_hex_components = 1
// ==> hex_components[0] = Component(3,4) "ffff"
// ==> index_of_contraction = 0
// ==> ipv4_component = Component(8, 11) "192.168.0.1"
//
// [Example 4]: input = "[1::]"
// ==> num_hex_components = 1
// ==> hex_components[0] = Component(1,1) "1"
// ==> index_of_contraction = 1
// ==> ipv4_component = Component(0, -1)
//
// [Example 5]: input = "[::192.168.0.1]"
// ==> num_hex_components = 0
// ==> index_of_contraction = 0
// ==> ipv4_component = Component(8, 11) "192.168.0.1"
//
struct IPv6Parsed {
// Zero-out the parse information.
void reset() {
num_hex_components = 0;
index_of_contraction = -1;
ipv4_component.reset();
}
// There can be up to 8 hex components (colon separated) in the literal.
Component hex_components[8];
// The count of hex components present. Ranges from [0,8].
int num_hex_components;
// The index of the hex component that the "::" contraction precedes, or
// -1 if there is no contraction.
int index_of_contraction;
// The range of characters which are an IPv4 literal.
Component ipv4_component;
};
// Parse the IPv6 input string. If parsing succeeded returns true and fills
// |parsed| with the information. If parsing failed (because the input is
// invalid) returns false.
template<typename CHAR, typename UCHAR>
bool DoParseIPv6(const CHAR* spec, const Component& host, IPv6Parsed* parsed) {
// Zero-out the info.
parsed->reset();
if (host.is_empty())
return false;
// The index for start and end of address range (no brackets).
int begin = host.begin;
int end = host.end();
int cur_component_begin = begin; // Start of the current component.
// Scan through the input, searching for hex components, "::" contractions,
// and IPv4 components.
for (int i = begin; /* i <= end */; i++) {
bool is_colon = spec[i] == ':';
bool is_contraction = is_colon && i < end - 1 && spec[i + 1] == ':';
// We reached the end of the current component if we encounter a colon
// (separator between hex components, or start of a contraction), or end of
// input.
if (is_colon || i == end) {
int component_len = i - cur_component_begin;
// A component should not have more than 4 hex digits.
if (component_len > 4)
return false;
// Don't allow empty components.
if (component_len == 0) {
// The exception is when contractions appear at beginning of the
// input or at the end of the input.
if (!((is_contraction && i == begin) || (i == end &&
parsed->index_of_contraction == parsed->num_hex_components)))
return false;
}
// Add the hex component we just found to running list.
if (component_len > 0) {
// Can't have more than 8 components!
if (parsed->num_hex_components >= 8)
return false;
parsed->hex_components[parsed->num_hex_components++] =
Component(cur_component_begin, component_len);
}
}
if (i == end)
break; // Reached the end of the input, DONE.
// We found a "::" contraction.
if (is_contraction) {
// There can be at most one contraction in the literal.
if (parsed->index_of_contraction != -1)
return false;
parsed->index_of_contraction = parsed->num_hex_components;
++i; // Consume the colon we peeked.
}
if (is_colon) {
// Colons are separators between components, keep track of where the
// current component started (after this colon).
cur_component_begin = i + 1;
} else {
if (static_cast<UCHAR>(spec[i]) >= 0x80)
return false; // Not ASCII.
if (!IsHexChar(static_cast<unsigned char>(spec[i]))) {
// Regular components are hex numbers. It is also possible for
// a component to be an IPv4 address in dotted form.
if (IsIPv4Char(static_cast<unsigned char>(spec[i]))) {
// Since IPv4 address can only appear at the end, assume the rest
// of the string is an IPv4 address. (We will parse this separately
// later).
parsed->ipv4_component =
Component(cur_component_begin, end - cur_component_begin);
break;
} else {
// The character was neither a hex digit, nor an IPv4 character.
return false;
}
}
}
}
return true;
}
// Verifies the parsed IPv6 information, checking that the various components
// add up to the right number of bits (hex components are 16 bits, while
// embedded IPv4 formats are 32 bits, and contractions are placeholdes for
// 16 or more bits). Returns true if sizes match up, false otherwise. On
// success writes the length of the contraction (if any) to
// |out_num_bytes_of_contraction|.
bool CheckIPv6ComponentsSize(const IPv6Parsed& parsed,
int* out_num_bytes_of_contraction) {
// Each group of four hex digits contributes 16 bits.
int num_bytes_without_contraction = parsed.num_hex_components * 2;
// If an IPv4 address was embedded at the end, it contributes 32 bits.
if (parsed.ipv4_component.is_valid())
num_bytes_without_contraction += 4;
// If there was a "::" contraction, its size is going to be:
// MAX([16bits], [128bits] - num_bytes_without_contraction).
int num_bytes_of_contraction = 0;
if (parsed.index_of_contraction != -1) {
num_bytes_of_contraction = 16 - num_bytes_without_contraction;
if (num_bytes_of_contraction < 2)
num_bytes_of_contraction = 2;
}
// Check that the numbers add up.
if (num_bytes_without_contraction + num_bytes_of_contraction != 16)
return false;
*out_num_bytes_of_contraction = num_bytes_of_contraction;
return true;
}
// Converts a hex component into a number. This cannot fail since the caller has
// already verified that each character in the string was a hex digit, and
// that there were no more than 4 characters.
template <typename CHAR>
uint16_t IPv6HexComponentToNumber(const CHAR* spec,
const Component& component) {
DCHECK(component.len <= 4);
// Copy the hex string into a C-string.
char buf[5];
for (int i = 0; i < component.len; ++i)
buf[i] = static_cast<char>(spec[component.begin + i]);
buf[component.len] = '\0';
// Convert it to a number (overflow is not possible, since with 4 hex
// characters we can at most have a 16 bit number).
return static_cast<uint16_t>(_strtoui64(buf, NULL, 16));
}
// Converts an IPv6 address to a 128-bit number (network byte order), returning
// true on success. False means that the input was not a valid IPv6 address.
template<typename CHAR, typename UCHAR>
bool DoIPv6AddressToNumber(const CHAR* spec,
const Component& host,
unsigned char address[16]) {
// Make sure the component is bounded by '[' and ']'.
int end = host.end();
if (host.is_empty() || spec[host.begin] != '[' || spec[end - 1] != ']')
return false;
// Exclude the square brackets.
Component ipv6_comp(host.begin + 1, host.len - 2);
// Parse the IPv6 address -- identify where all the colon separated hex
// components are, the "::" contraction, and the embedded IPv4 address.
IPv6Parsed ipv6_parsed;
if (!DoParseIPv6<CHAR, UCHAR>(spec, ipv6_comp, &ipv6_parsed))
return false;
// Do some basic size checks to make sure that the address doesn't
// specify more than 128 bits or fewer than 128 bits. This also resolves
// how may zero bytes the "::" contraction represents.
int num_bytes_of_contraction;
if (!CheckIPv6ComponentsSize(ipv6_parsed, &num_bytes_of_contraction))
return false;
int cur_index_in_address = 0;
// Loop through each hex components, and contraction in order.
for (int i = 0; i <= ipv6_parsed.num_hex_components; ++i) {
// Append the contraction if it appears before this component.
if (i == ipv6_parsed.index_of_contraction) {
for (int j = 0; j < num_bytes_of_contraction; ++j)
address[cur_index_in_address++] = 0;
}
// Append the hex component's value.
if (i != ipv6_parsed.num_hex_components) {
// Get the 16-bit value for this hex component.
uint16_t number = IPv6HexComponentToNumber<CHAR>(
spec, ipv6_parsed.hex_components[i]);
// Append to |address|, in network byte order.
address[cur_index_in_address++] = (number & 0xFF00) >> 8;
address[cur_index_in_address++] = (number & 0x00FF);
}
}
// If there was an IPv4 section, convert it into a 32-bit number and append
// it to |address|.
if (ipv6_parsed.ipv4_component.is_valid()) {
// Append the 32-bit number to |address|.
int num_ipv4_components = 0;
// IPv4AddressToNumber will remove the trailing dot from the component.
bool trailing_dot = ipv6_parsed.ipv4_component.is_nonempty() &&
spec[ipv6_parsed.ipv4_component.end() - 1] == '.';
// The URL standard requires the embedded IPv4 address to be concisely
// composed of 4 parts and disallows terminal dots.
// See https://url.spec.whatwg.org/#concept-ipv6-parser
if (CanonHostInfo::IPV4 !=
IPv4AddressToNumber(spec, ipv6_parsed.ipv4_component,
&address[cur_index_in_address],
&num_ipv4_components)) {
return false;
}
if ((num_ipv4_components != 4 || trailing_dot) &&
base::FeatureList::IsEnabled(
url::kStrictIPv4EmbeddedIPv6AddressParsing)) {
return false;
}
}
return true;
}
// Searches for the longest sequence of zeros in |address|, and writes the
// range into |contraction_range|. The run of zeros must be at least 16 bits,
// and if there is a tie the first is chosen.
void ChooseIPv6ContractionRange(const unsigned char address[16],
Component* contraction_range) {
// The longest run of zeros in |address| seen so far.
Component max_range;
// The current run of zeros in |address| being iterated over.
Component cur_range;
for (int i = 0; i < 16; i += 2) {
// Test for 16 bits worth of zero.
bool is_zero = (address[i] == 0 && address[i + 1] == 0);
if (is_zero) {
// Add the zero to the current range (or start a new one).
if (!cur_range.is_valid())
cur_range = Component(i, 0);
cur_range.len += 2;
}
if (!is_zero || i == 14) {
// Just completed a run of zeros. If the run is greater than 16 bits,
// it is a candidate for the contraction.
if (cur_range.len > 2 && cur_range.len > max_range.len) {
max_range = cur_range;
}
cur_range.reset();
}
}
*contraction_range = max_range;
}
// Return true if we've made a final IPV6/BROKEN decision, false if the result
// is NEUTRAL, and we could use a second opinion.
template<typename CHAR, typename UCHAR>
bool DoCanonicalizeIPv6Address(const CHAR* spec,
const Component& host,
CanonOutput* output,
CanonHostInfo* host_info) {
// Turn the IP address into a 128 bit number.
if (!IPv6AddressToNumber(spec, host, host_info->address)) {
// If it's not an IPv6 address, scan for characters that should *only*
// exist in an IPv6 address.
for (int i = host.begin; i < host.end(); i++) {
switch (spec[i]) {
case '[':
case ']':
case ':':
host_info->family = CanonHostInfo::BROKEN;
return true;
}
}
// No invalid characters. Could still be IPv4 or a hostname.
host_info->family = CanonHostInfo::NEUTRAL;
return false;
}
host_info->out_host.begin = output->length();
output->push_back('[');
AppendIPv6Address(host_info->address, output);
output->push_back(']');
host_info->out_host.len = output->length() - host_info->out_host.begin;
host_info->family = CanonHostInfo::IPV6;
return true;
}
} // namespace
void AppendIPv4Address(const unsigned char address[4], CanonOutput* output) {
for (int i = 0; i < 4; i++) {
char str[16];
_itoa_s(address[i], str, 10);
for (int ch = 0; str[ch] != 0; ch++)
output->push_back(str[ch]);
if (i != 3)
output->push_back('.');
}
}
void AppendIPv6Address(const unsigned char address[16], CanonOutput* output) {
// We will output the address according to the rules in:
// http://tools.ietf.org/html/draft-kawamura-ipv6-text-representation-01#section-4
// Start by finding where to place the "::" contraction (if any).
Component contraction_range;
ChooseIPv6ContractionRange(address, &contraction_range);
for (int i = 0; i <= 14;) {
// We check 2 bytes at a time, from bytes (0, 1) to (14, 15), inclusive.
DCHECK(i % 2 == 0);
if (i == contraction_range.begin && contraction_range.len > 0) {
// Jump over the contraction.
if (i == 0)
output->push_back(':');
output->push_back(':');
i = contraction_range.end();
} else {
// Consume the next 16 bits from |address|.
int x = address[i] << 8 | address[i + 1];
i += 2;
// Stringify the 16 bit number (at most requires 4 hex digits).
char str[5];
_itoa_s(x, str, 16);
for (int ch = 0; str[ch] != 0; ++ch)
output->push_back(str[ch]);
// Put a colon after each number, except the last.
if (i < 16)
output->push_back(':');
}
}
}
void CanonicalizeIPAddress(const char* spec,
const Component& host,
CanonOutput* output,
CanonHostInfo* host_info) {
if (DoCanonicalizeIPv4Address<char, unsigned char>(
spec, host, output, host_info))
return;
if (DoCanonicalizeIPv6Address<char, unsigned char>(
spec, host, output, host_info))
return;
}
void CanonicalizeIPAddress(const char16_t* spec,
const Component& host,
CanonOutput* output,
CanonHostInfo* host_info) {
if (DoCanonicalizeIPv4Address<char16_t, char16_t>(spec, host, output,
host_info))
return;
if (DoCanonicalizeIPv6Address<char16_t, char16_t>(spec, host, output,
host_info))
return;
}
CanonHostInfo::Family IPv4AddressToNumber(const char* spec,
const Component& host,
unsigned char address[4],
int* num_ipv4_components) {
return DoIPv4AddressToNumber<char, unsigned char>(spec, host, address,
num_ipv4_components);
}
CanonHostInfo::Family IPv4AddressToNumber(const char16_t* spec,
const Component& host,
unsigned char address[4],
int* num_ipv4_components) {
return DoIPv4AddressToNumber<char16_t, char16_t>(spec, host, address,
num_ipv4_components);
}
bool IPv6AddressToNumber(const char* spec,
const Component& host,
unsigned char address[16]) {
return DoIPv6AddressToNumber<char, unsigned char>(spec, host, address);
}
bool IPv6AddressToNumber(const char16_t* spec,
const Component& host,
unsigned char address[16]) {
return DoIPv6AddressToNumber<char16_t, char16_t>(spec, host, address);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_ip.cc | C++ | unknown | 24,306 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_CANON_IP_H_
#define URL_URL_CANON_IP_H_
#include "base/component_export.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_canon.h"
namespace url {
// Writes the given IPv4 address to |output|.
COMPONENT_EXPORT(URL)
void AppendIPv4Address(const unsigned char address[4], CanonOutput* output);
// Writes the given IPv6 address to |output|.
COMPONENT_EXPORT(URL)
void AppendIPv6Address(const unsigned char address[16], CanonOutput* output);
// Converts an IPv4 address to a 32-bit number (network byte order).
//
// Possible return values:
// IPV4 - IPv4 address was successfully parsed.
// BROKEN - Input was formatted like an IPv4 address, but overflow occurred
// during parsing.
// NEUTRAL - Input couldn't possibly be interpreted as an IPv4 address.
// It might be an IPv6 address, or a hostname.
//
// On success, |num_ipv4_components| will be populated with the number of
// components in the IPv4 address.
COMPONENT_EXPORT(URL)
CanonHostInfo::Family IPv4AddressToNumber(const char* spec,
const Component& host,
unsigned char address[4],
int* num_ipv4_components);
COMPONENT_EXPORT(URL)
CanonHostInfo::Family IPv4AddressToNumber(const char16_t* spec,
const Component& host,
unsigned char address[4],
int* num_ipv4_components);
// Converts an IPv6 address to a 128-bit number (network byte order), returning
// true on success. False means that the input was not a valid IPv6 address.
//
// NOTE that |host| is expected to be surrounded by square brackets.
// i.e. "[::1]" rather than "::1".
COMPONENT_EXPORT(URL)
bool IPv6AddressToNumber(const char* spec,
const Component& host,
unsigned char address[16]);
COMPONENT_EXPORT(URL)
bool IPv6AddressToNumber(const char16_t* spec,
const Component& host,
unsigned char address[16]);
} // namespace url
#endif // URL_URL_CANON_IP_H_
| Zhao-PengFei35/chromium_src_4 | url/url_canon_ip.h | C++ | unknown | 2,354 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Functions for canonicalizing "mailto:" URLs.
#include "url/url_canon.h"
#include "url/url_canon_internal.h"
#include "url/url_file.h"
#include "url/url_parse_internal.h"
namespace url {
namespace {
// Certain characters should be percent-encoded when they appear in the path
// component of a mailto URL, to improve compatibility and mitigate against
// command-injection attacks on mailto handlers. See https://crbug.com/711020.
template <typename UCHAR>
bool ShouldEncodeMailboxCharacter(UCHAR uch) {
if (uch < 0x21 || // space & control characters.
uch > 0x7e || // high-ascii characters.
uch == 0x22 || // quote.
uch == 0x3c || uch == 0x3e || // angle brackets.
uch == 0x60 || // backtick.
uch == 0x7b || uch == 0x7c || uch == 0x7d // braces and pipe.
) {
return true;
}
return false;
}
template <typename CHAR, typename UCHAR>
bool DoCanonicalizeMailtoURL(const URLComponentSource<CHAR>& source,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
// mailto: only uses {scheme, path, query} -- clear the rest.
new_parsed->username = Component();
new_parsed->password = Component();
new_parsed->host = Component();
new_parsed->port = Component();
new_parsed->ref = Component();
// Scheme (known, so we don't bother running it through the more
// complicated scheme canonicalizer).
new_parsed->scheme.begin = output->length();
output->Append("mailto:", 7);
new_parsed->scheme.len = 6;
bool success = true;
// Path
if (parsed.path.is_valid()) {
new_parsed->path.begin = output->length();
// Copy the path using path URL's more lax escaping rules.
// We convert to UTF-8 and escape non-ASCII, but leave most
// ASCII characters alone.
size_t end = static_cast<size_t>(parsed.path.end());
for (size_t i = static_cast<size_t>(parsed.path.begin); i < end; ++i) {
UCHAR uch = static_cast<UCHAR>(source.path[i]);
if (ShouldEncodeMailboxCharacter<UCHAR>(uch))
success &= AppendUTF8EscapedChar(source.path, &i, end, output);
else
output->push_back(static_cast<char>(uch));
}
new_parsed->path.len = output->length() - new_parsed->path.begin;
} else {
// No path at all
new_parsed->path.reset();
}
// Query -- always use the default UTF8 charset converter.
CanonicalizeQuery(source.query, parsed.query, NULL,
output, &new_parsed->query);
return success;
}
} // namespace
bool CanonicalizeMailtoURL(const char* spec,
int spec_len,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
return DoCanonicalizeMailtoURL<char, unsigned char>(
URLComponentSource<char>(spec), parsed, output, new_parsed);
}
bool CanonicalizeMailtoURL(const char16_t* spec,
int spec_len,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
return DoCanonicalizeMailtoURL<char16_t, char16_t>(
URLComponentSource<char16_t>(spec), parsed, output, new_parsed);
}
bool ReplaceMailtoURL(const char* base,
const Parsed& base_parsed,
const Replacements<char>& replacements,
CanonOutput* output,
Parsed* new_parsed) {
URLComponentSource<char> source(base);
Parsed parsed(base_parsed);
SetupOverrideComponents(base, replacements, &source, &parsed);
return DoCanonicalizeMailtoURL<char, unsigned char>(
source, parsed, output, new_parsed);
}
bool ReplaceMailtoURL(const char* base,
const Parsed& base_parsed,
const Replacements<char16_t>& replacements,
CanonOutput* output,
Parsed* new_parsed) {
RawCanonOutput<1024> utf8;
URLComponentSource<char> source(base);
Parsed parsed(base_parsed);
SetupUTF16OverrideComponents(base, replacements, &utf8, &source, &parsed);
return DoCanonicalizeMailtoURL<char, unsigned char>(
source, parsed, output, new_parsed);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_mailtourl.cc | C++ | unknown | 4,566 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits.h>
#include "base/check.h"
#include "base/check_op.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/url_canon.h"
#include "url/url_canon_internal.h"
#include "url/url_parse_internal.h"
namespace url {
namespace {
enum CharacterFlags {
// Pass through unchanged, whether escaped or unescaped. This doesn't
// actually set anything so you can't OR it to check, it's just to make the
// table below more clear when neither ESCAPE or UNESCAPE is set.
PASS = 0,
// This character requires special handling in DoPartialPathInternal. Doing
// this test
// first allows us to filter out the common cases of regular characters that
// can be directly copied.
SPECIAL = 1,
// This character must be escaped in the canonical output. Note that all
// escaped chars also have the "special" bit set so that the code that looks
// for this is triggered. Not valid with PASS or ESCAPE
ESCAPE_BIT = 2,
ESCAPE = ESCAPE_BIT | SPECIAL,
// This character must be unescaped in canonical output. Not valid with
// ESCAPE or PASS. We DON'T set the SPECIAL flag since if we encounter these
// characters unescaped, they should just be copied.
UNESCAPE = 4,
// This character is disallowed in URLs. Note that the "special" bit is also
// set to trigger handling.
INVALID_BIT = 8,
INVALID = INVALID_BIT | SPECIAL,
};
// This table contains one of the above flag values. Note some flags are more
// than one bits because they also turn on the "special" flag. Special is the
// only flag that may be combined with others.
//
// This table is designed to match exactly what IE does with the characters.
//
// Dot is even more special, and the escaped version is handled specially by
// IsDot. Therefore, we don't need the "escape" flag, and even the "unescape"
// bit is never handled (we just need the "special") bit.
const unsigned char kPathCharLookup[0x100] = {
// NULL control chars...
INVALID, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
// control chars...
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
// ' ' ! " # $ % & ' ( ) * + , - . /
ESCAPE, PASS, ESCAPE, ESCAPE, PASS, ESCAPE, PASS, PASS, PASS, PASS, PASS, PASS, PASS, UNESCAPE,SPECIAL, PASS,
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,PASS, PASS, ESCAPE, PASS, ESCAPE, ESCAPE,
// @ A B C D E F G H I J K L M N O
PASS, UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,
// P Q R S T U V W X Y Z [ \ ] ^ _
UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,PASS, ESCAPE, PASS, ESCAPE, UNESCAPE,
// ` a b c d e f g h i j k l m n o
ESCAPE, UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,
// p q r s t u v w x y z { | } ~ <NBSP>
UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,UNESCAPE,ESCAPE, ESCAPE, ESCAPE, UNESCAPE,ESCAPE,
// ...all the high-bit characters are escaped
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE,
ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE, ESCAPE};
enum DotDisposition {
// The given dot is just part of a filename and is not special.
NOT_A_DIRECTORY,
// The given dot is the current directory.
DIRECTORY_CUR,
// The given dot is the first of a double dot that should take us up one.
DIRECTORY_UP
};
// When the path resolver finds a dot, this function is called with the
// character following that dot to see what it is. The return value
// indicates what type this dot is (see above). This code handles the case
// where the dot is at the end of the input.
//
// |*consumed_len| will contain the number of characters in the input that
// express what we found.
//
// If the input is "../foo", |after_dot| = 1, |end| = 6, and
// at the end, |*consumed_len| = 2 for the "./" this function consumed. The
// original dot length should be handled by the caller.
template <typename CHAR>
DotDisposition ClassifyAfterDot(const CHAR* spec,
size_t after_dot,
size_t end,
size_t* consumed_len) {
if (after_dot == end) {
// Single dot at the end.
*consumed_len = 0;
return DIRECTORY_CUR;
}
if (IsURLSlash(spec[after_dot])) {
// Single dot followed by a slash.
*consumed_len = 1; // Consume the slash
return DIRECTORY_CUR;
}
size_t second_dot_len = IsDot(spec, after_dot, end);
if (second_dot_len) {
size_t after_second_dot = after_dot + second_dot_len;
if (after_second_dot == end) {
// Double dot at the end.
*consumed_len = second_dot_len;
return DIRECTORY_UP;
}
if (IsURLSlash(spec[after_second_dot])) {
// Double dot followed by a slash.
*consumed_len = second_dot_len + 1;
return DIRECTORY_UP;
}
}
// The dots are followed by something else, not a directory.
*consumed_len = 0;
return NOT_A_DIRECTORY;
}
// Rewinds the output to the previous slash. It is assumed that the output
// ends with a slash and this doesn't count (we call this when we are
// appending directory paths, so the previous path component has and ending
// slash).
//
// This will stop at the first slash (assumed to be at position
// |path_begin_in_output| and not go any higher than that. Some web pages
// do ".." too many times, so we need to handle that brokenness.
//
// It searches for a literal slash rather than including a backslash as well
// because it is run only on the canonical output.
//
// The output is guaranteed to end in a slash when this function completes.
void BackUpToPreviousSlash(size_t path_begin_in_output, CanonOutput* output) {
CHECK(output->length() > 0);
CHECK(path_begin_in_output < output->length());
size_t i = output->length() - 1;
DCHECK(output->at(i) == '/');
if (i == path_begin_in_output)
return; // We're at the first slash, nothing to do.
// Now back up (skipping the trailing slash) until we find another slash.
do {
--i;
} while (output->at(i) != '/' && i > path_begin_in_output);
// Now shrink the output to just include that last slash we found.
output->set_length(i + 1);
}
// Looks for problematic nested escape sequences and escapes the output as
// needed to ensure they can't be misinterpreted.
//
// Our concern is that in input escape sequence that's invalid because it
// contains nested escape sequences might look valid once those are unescaped.
// For example, "%%300" is not a valid escape sequence, but after unescaping the
// inner "%30" this becomes "%00" which is valid. Leaving this in the output
// string can result in callers re-canonicalizing the string and unescaping this
// sequence, thus resulting in something fundamentally different than the
// original input here. This can cause a variety of problems.
//
// This function is called after we've just unescaped a sequence that's within
// two output characters of a previous '%' that we know didn't begin a valid
// escape sequence in the input string. We look for whether the output is going
// to turn into a valid escape sequence, and if so, convert the initial '%' into
// an escaped "%25" so the output can't be misinterpreted.
//
// |spec| is the input string we're canonicalizing.
// |next_input_index| is the index of the next unprocessed character in |spec|.
// |input_len| is the length of |spec|.
// |last_invalid_percent_index| is the index in |output| of a previously-seen
// '%' character. The caller knows this '%' character isn't followed by a valid
// escape sequence in the input string.
// |output| is the canonicalized output thus far. The caller guarantees this
// ends with a '%' followed by one or two characters, and the '%' is the one
// pointed to by |last_invalid_percent_index|. The last character in the string
// was just unescaped.
template <typename CHAR>
void CheckForNestedEscapes(const CHAR* spec,
size_t next_input_index,
size_t input_len,
size_t last_invalid_percent_index,
CanonOutput* output) {
const size_t length = output->length();
const char last_unescaped_char = output->at(length - 1);
// If |output| currently looks like "%c", we need to try appending the next
// input character to see if this will result in a problematic escape
// sequence. Note that this won't trigger on the first nested escape of a
// two-escape sequence like "%%30%30" -- we'll allow the conversion to
// "%0%30" -- but the second nested escape will be caught by this function
// when it's called again in that case.
const bool append_next_char = last_invalid_percent_index == length - 2;
if (append_next_char) {
// If the input doesn't contain a 7-bit character next, this case won't be a
// problem.
if ((next_input_index == input_len) || (spec[next_input_index] >= 0x80))
return;
output->push_back(static_cast<char>(spec[next_input_index]));
}
// Now output ends like "%cc". Try to unescape this.
size_t begin = last_invalid_percent_index;
unsigned char temp;
if (DecodeEscaped(output->data(), &begin, output->length(), &temp)) {
// New escape sequence found. Overwrite the characters following the '%'
// with "25", and push_back() the one or two characters that were following
// the '%' when we were called.
if (!append_next_char)
output->push_back(output->at(last_invalid_percent_index + 1));
output->set(last_invalid_percent_index + 1, '2');
output->set(last_invalid_percent_index + 2, '5');
output->push_back(last_unescaped_char);
} else if (append_next_char) {
// Not a valid escape sequence, but we still need to undo appending the next
// source character so the caller can process it normally.
output->set_length(length);
}
}
// Canonicalizes and appends the given path to the output. It assumes that if
// the input path starts with a slash, it should be copied to the output.
//
// If there are already path components (this mode is used when appending
// relative paths for resolving), it assumes that the output already has
// a trailing slash and that if the input begins with a slash, it should be
// copied to the output.
//
// We do not collapse multiple slashes in a row to a single slash. It seems
// no web browsers do this, and we don't want incompatibilities, even though
// it would be correct for most systems.
template <typename CHAR, typename UCHAR>
bool DoPartialPathInternal(const CHAR* spec,
const Component& path,
size_t path_begin_in_output,
CanonOutput* output) {
if (path.is_empty())
return true;
size_t end = static_cast<size_t>(path.end());
// We use this variable to minimize the amount of work done when unescaping --
// we'll only call CheckForNestedEscapes() when this points at one of the last
// couple of characters in |output|.
absl::optional<size_t> last_invalid_percent_index;
bool success = true;
for (size_t i = static_cast<size_t>(path.begin); i < end; i++) {
UCHAR uch = static_cast<UCHAR>(spec[i]);
if (sizeof(CHAR) > 1 && uch >= 0x80) {
// We only need to test wide input for having non-ASCII characters. For
// narrow input, we'll always just use the lookup table. We don't try to
// do anything tricky with decoding/validating UTF-8. This function will
// read one or two UTF-16 characters and append the output as UTF-8. This
// call will be removed in 8-bit mode.
success &= AppendUTF8EscapedChar(spec, &i, end, output);
} else {
// Normal ASCII character or 8-bit input, use the lookup table.
unsigned char out_ch = static_cast<unsigned char>(uch);
unsigned char flags = kPathCharLookup[out_ch];
if (flags & SPECIAL) {
// Needs special handling of some sort.
size_t dotlen;
if ((dotlen = IsDot(spec, i, end)) > 0) {
// See if this dot was preceded by a slash in the output.
//
// Note that we check this in the case of dots so we don't have to
// special case slashes. Since slashes are much more common than
// dots, this actually increases performance measurably (though
// slightly).
if (output->length() > path_begin_in_output &&
output->at(output->length() - 1) == '/') {
// Slash followed by a dot, check to see if this is means relative
size_t consumed_len;
switch (ClassifyAfterDot<CHAR>(spec, i + dotlen, end,
&consumed_len)) {
case NOT_A_DIRECTORY:
// Copy the dot to the output, it means nothing special.
output->push_back('.');
i += dotlen - 1;
break;
case DIRECTORY_CUR: // Current directory, just skip the input.
i += dotlen + consumed_len - 1;
break;
case DIRECTORY_UP:
BackUpToPreviousSlash(path_begin_in_output, output);
if (last_invalid_percent_index >= output->length()) {
last_invalid_percent_index = absl::nullopt;
}
i += dotlen + consumed_len - 1;
break;
}
} else {
// This dot is not preceded by a slash, it is just part of some
// file name.
output->push_back('.');
i += dotlen - 1;
}
} else if (out_ch == '\\') {
// Convert backslashes to forward slashes
output->push_back('/');
} else if (out_ch == '%') {
// Handle escape sequences.
unsigned char unescaped_value;
if (DecodeEscaped(spec, &i, end, &unescaped_value)) {
// Valid escape sequence, see if we keep, reject, or unescape it.
// Note that at this point DecodeEscape() will have advanced |i| to
// the last character of the escape sequence.
char unescaped_flags = kPathCharLookup[unescaped_value];
if (unescaped_flags & UNESCAPE) {
// This escaped value shouldn't be escaped. Try to copy it.
output->push_back(unescaped_value);
// If we just unescaped a value within 2 output characters of the
// '%' from a previously-detected invalid escape sequence, we
// might have an input string with problematic nested escape
// sequences; detect and fix them.
if (last_invalid_percent_index.has_value() &&
((last_invalid_percent_index.value() + 3) >=
output->length())) {
CheckForNestedEscapes(spec, i + 1, end,
last_invalid_percent_index.value(),
output);
}
} else {
// Either this is an invalid escaped character, or it's a valid
// escaped character we should keep escaped. In the first case we
// should just copy it exactly and remember the error. In the
// second we also copy exactly in case the server is sensitive to
// changing the case of any hex letters.
output->push_back('%');
output->push_back(static_cast<char>(spec[i - 1]));
output->push_back(static_cast<char>(spec[i]));
if (unescaped_flags & INVALID_BIT)
success = false;
}
} else {
// Invalid escape sequence. IE7+ rejects any URLs with such
// sequences, while other browsers pass them through unchanged. We
// use the permissive behavior.
// TODO(brettw): Consider testing IE's strict behavior, which would
// allow removing the code to handle nested escapes above.
last_invalid_percent_index = output->length();
output->push_back('%');
}
} else if (flags & INVALID_BIT) {
// For NULLs, etc. fail.
AppendEscapedChar(out_ch, output);
success = false;
} else if (flags & ESCAPE_BIT) {
// This character should be escaped.
AppendEscapedChar(out_ch, output);
}
} else {
// Nothing special about this character, just append it.
output->push_back(out_ch);
}
}
}
return success;
}
// Perform the same logic as in DoPartialPathInternal(), but updates the
// publicly exposed CanonOutput structure similar to DoPath(). Returns
// true if successful.
template <typename CHAR, typename UCHAR>
bool DoPartialPath(const CHAR* spec,
const Component& path,
CanonOutput* output,
Component* out_path) {
out_path->begin = output->length();
bool success =
DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin, output);
out_path->len = output->length() - out_path->begin;
return success;
}
template<typename CHAR, typename UCHAR>
bool DoPath(const CHAR* spec,
const Component& path,
CanonOutput* output,
Component* out_path) {
bool success = true;
out_path->begin = output->length();
if (path.is_nonempty()) {
// Write out an initial slash if the input has none. If we just parse a URL
// and then canonicalize it, it will of course have a slash already. This
// check is for the replacement and relative URL resolving cases of file
// URLs.
if (!IsURLSlash(spec[path.begin]))
output->push_back('/');
success =
DoPartialPathInternal<CHAR, UCHAR>(spec, path, out_path->begin, output);
} else {
// No input, canonical path is a slash.
output->push_back('/');
}
out_path->len = output->length() - out_path->begin;
return success;
}
} // namespace
bool CanonicalizePath(const char* spec,
const Component& path,
CanonOutput* output,
Component* out_path) {
return DoPath<char, unsigned char>(spec, path, output, out_path);
}
bool CanonicalizePath(const char16_t* spec,
const Component& path,
CanonOutput* output,
Component* out_path) {
return DoPath<char16_t, char16_t>(spec, path, output, out_path);
}
bool CanonicalizePartialPath(const char* spec,
const Component& path,
CanonOutput* output,
Component* out_path) {
return DoPartialPath<char, unsigned char>(spec, path, output, out_path);
}
bool CanonicalizePartialPath(const char16_t* spec,
const Component& path,
CanonOutput* output,
Component* out_path) {
return DoPartialPath<char16_t, char16_t>(spec, path, output, out_path);
}
bool CanonicalizePartialPathInternal(const char* spec,
const Component& path,
size_t path_begin_in_output,
CanonOutput* output) {
return DoPartialPathInternal<char, unsigned char>(
spec, path, path_begin_in_output, output);
}
bool CanonicalizePartialPathInternal(const char16_t* spec,
const Component& path,
size_t path_begin_in_output,
CanonOutput* output) {
return DoPartialPathInternal<char16_t, char16_t>(
spec, path, path_begin_in_output, output);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_path.cc | C++ | unknown | 22,058 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Functions for canonicalizing "path" URLs. Not to be confused with the path
// of a URL, these are URLs that have no authority section, only a path. For
// example, "javascript:" and "data:".
#include "url/url_canon.h"
#include "url/url_canon_internal.h"
namespace url {
namespace {
// Canonicalize the given |component| from |source| into |output| and
// |new_component|. If |separator| is non-zero, it is pre-pended to |output|
// prior to the canonicalized component; i.e. for the '?' or '#' characters.
template <typename CHAR, typename UCHAR>
void DoCanonicalizePathComponent(const CHAR* source,
const Component& component,
char separator,
CanonOutput* output,
Component* new_component) {
if (component.is_valid()) {
if (separator)
output->push_back(separator);
// Copy the path using path URL's more lax escaping rules (think for
// javascript:). We convert to UTF-8 and escape characters from the
// C0 control percent-encode set, but leave all other characters alone.
// This helps readability of JavaScript.
// https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state
// https://url.spec.whatwg.org/#c0-control-percent-encode-set
new_component->begin = output->length();
size_t end = static_cast<size_t>(component.end());
for (size_t i = static_cast<size_t>(component.begin); i < end; i++) {
UCHAR uch = static_cast<UCHAR>(source[i]);
if (uch < 0x20 || uch > 0x7E)
AppendUTF8EscapedChar(source, &i, end, output);
else
output->push_back(static_cast<char>(uch));
}
new_component->len = output->length() - new_component->begin;
} else {
// Empty part.
new_component->reset();
}
}
template <typename CHAR, typename UCHAR>
bool DoCanonicalizePathURL(const URLComponentSource<CHAR>& source,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
// Scheme: this will append the colon.
bool success = CanonicalizeScheme(source.scheme, parsed.scheme,
output, &new_parsed->scheme);
// We assume there's no authority for path URLs. Note that hosts should never
// have -1 length.
new_parsed->username.reset();
new_parsed->password.reset();
new_parsed->host.reset();
new_parsed->port.reset();
// Canonicalize path via the weaker path URL rules.
//
// Note: parsing the path part should never cause a failure, see
// https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state
DoCanonicalizePathComponent<CHAR, UCHAR>(source.path, parsed.path, '\0',
output, &new_parsed->path);
// Similar to mailto:, always use the default UTF-8 charset converter for
// query.
CanonicalizeQuery(source.query, parsed.query, nullptr, output,
&new_parsed->query);
CanonicalizeRef(source.ref, parsed.ref, output, &new_parsed->ref);
return success;
}
} // namespace
bool CanonicalizePathURL(const char* spec,
int spec_len,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
return DoCanonicalizePathURL<char, unsigned char>(
URLComponentSource<char>(spec), parsed, output, new_parsed);
}
bool CanonicalizePathURL(const char16_t* spec,
int spec_len,
const Parsed& parsed,
CanonOutput* output,
Parsed* new_parsed) {
return DoCanonicalizePathURL<char16_t, char16_t>(
URLComponentSource<char16_t>(spec), parsed, output, new_parsed);
}
void CanonicalizePathURLPath(const char* source,
const Component& component,
CanonOutput* output,
Component* new_component) {
DoCanonicalizePathComponent<char, unsigned char>(source, component, '\0',
output, new_component);
}
void CanonicalizePathURLPath(const char16_t* source,
const Component& component,
CanonOutput* output,
Component* new_component) {
DoCanonicalizePathComponent<char16_t, char16_t>(source, component, '\0',
output, new_component);
}
bool ReplacePathURL(const char* base,
const Parsed& base_parsed,
const Replacements<char>& replacements,
CanonOutput* output,
Parsed* new_parsed) {
URLComponentSource<char> source(base);
Parsed parsed(base_parsed);
SetupOverrideComponents(base, replacements, &source, &parsed);
return DoCanonicalizePathURL<char, unsigned char>(
source, parsed, output, new_parsed);
}
bool ReplacePathURL(const char* base,
const Parsed& base_parsed,
const Replacements<char16_t>& replacements,
CanonOutput* output,
Parsed* new_parsed) {
RawCanonOutput<1024> utf8;
URLComponentSource<char> source(base);
Parsed parsed(base_parsed);
SetupUTF16OverrideComponents(base, replacements, &utf8, &source, &parsed);
return DoCanonicalizePathURL<char, unsigned char>(
source, parsed, output, new_parsed);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_pathurl.cc | C++ | unknown | 5,691 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_canon.h"
#include "url/url_canon_internal.h"
// Query canonicalization in IE
// ----------------------------
// IE is very permissive for query parameters specified in links on the page
// (in contrast to links that it constructs itself based on form data). It does
// not unescape any character. It does not reject any escape sequence (be they
// invalid like "%2y" or freaky like %00).
//
// IE only escapes spaces and nothing else. Embedded NULLs, tabs (0x09),
// LF (0x0a), and CR (0x0d) are removed (this probably happens at an earlier
// layer since they are removed from all portions of the URL). All other
// characters are passed unmodified. Invalid UTF-16 sequences are preserved as
// well, with each character in the input being converted to UTF-8. It is the
// server's job to make sense of this invalid query.
//
// Invalid multibyte sequences (for example, invalid UTF-8 on a UTF-8 page)
// are converted to the invalid character and sent as unescaped UTF-8 (0xef,
// 0xbf, 0xbd). This may not be canonicalization, the parser may generate these
// strings before the URL handler ever sees them.
//
// Our query canonicalization
// --------------------------
// We escape all non-ASCII characters and control characters, like Firefox.
// This is more conformant to the URL spec, and there do not seem to be many
// problems relating to Firefox's behavior.
//
// Like IE, we will never unescape (although the application may want to try
// unescaping to present the user with a more understandable URL). We will
// replace all invalid sequences (including invalid UTF-16 sequences, which IE
// doesn't) with the "invalid character," and we will escape it.
namespace url {
namespace {
// Appends the given string to the output, escaping characters that do not
// match the given |type| in SharedCharTypes. This version will accept 8 or 16
// bit characters, but assumes that they have only 7-bit values. It also assumes
// that all UTF-8 values are correct, so doesn't bother checking
template<typename CHAR>
void AppendRaw8BitQueryString(const CHAR* source, int length,
CanonOutput* output) {
for (int i = 0; i < length; i++) {
if (!IsQueryChar(static_cast<unsigned char>(source[i])))
AppendEscapedChar(static_cast<unsigned char>(source[i]), output);
else // Doesn't need escaping.
output->push_back(static_cast<char>(source[i]));
}
}
// Runs the converter on the given UTF-8 input. Since the converter expects
// UTF-16, we have to convert first. The converter must be non-NULL.
void RunConverter(const char* spec,
const Component& query,
CharsetConverter* converter,
CanonOutput* output) {
DCHECK(query.is_valid());
// This function will replace any misencoded values with the invalid
// character. This is what we want so we don't have to check for error.
RawCanonOutputW<1024> utf16;
ConvertUTF8ToUTF16(&spec[query.begin], static_cast<size_t>(query.len),
&utf16);
converter->ConvertFromUTF16(utf16.data(), utf16.length(), output);
}
// Runs the converter with the given UTF-16 input. We don't have to do
// anything, but this overridden function allows us to use the same code
// for both UTF-8 and UTF-16 input.
void RunConverter(const char16_t* spec,
const Component& query,
CharsetConverter* converter,
CanonOutput* output) {
DCHECK(query.is_valid());
converter->ConvertFromUTF16(&spec[query.begin],
static_cast<size_t>(query.len), output);
}
template <typename CHAR, typename UCHAR>
void DoConvertToQueryEncoding(const CHAR* spec,
const Component& query,
CharsetConverter* converter,
CanonOutput* output) {
if (converter) {
// Run the converter to get an 8-bit string, then append it, escaping
// necessary values.
RawCanonOutput<1024> eight_bit;
RunConverter(spec, query, converter, &eight_bit);
AppendRaw8BitQueryString(eight_bit.data(), eight_bit.length(), output);
} else {
// No converter, do our own UTF-8 conversion.
AppendStringOfType(&spec[query.begin], static_cast<size_t>(query.len),
CHAR_QUERY, output);
}
}
template<typename CHAR, typename UCHAR>
void DoCanonicalizeQuery(const CHAR* spec,
const Component& query,
CharsetConverter* converter,
CanonOutput* output,
Component* out_query) {
if (!query.is_valid()) {
*out_query = Component();
return;
}
output->push_back('?');
out_query->begin = output->length();
DoConvertToQueryEncoding<CHAR, UCHAR>(spec, query, converter, output);
out_query->len = output->length() - out_query->begin;
}
} // namespace
void CanonicalizeQuery(const char* spec,
const Component& query,
CharsetConverter* converter,
CanonOutput* output,
Component* out_query) {
DoCanonicalizeQuery<char, unsigned char>(spec, query, converter,
output, out_query);
}
void CanonicalizeQuery(const char16_t* spec,
const Component& query,
CharsetConverter* converter,
CanonOutput* output,
Component* out_query) {
DoCanonicalizeQuery<char16_t, char16_t>(spec, query, converter, output,
out_query);
}
void ConvertUTF16ToQueryEncoding(const char16_t* input,
const Component& query,
CharsetConverter* converter,
CanonOutput* output) {
DoConvertToQueryEncoding<char16_t, char16_t>(input, query, converter, output);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_query.cc | C++ | unknown | 6,125 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Canonicalizer functions for working with and resolving relative URLs.
#include <algorithm>
#include <ostream>
#include "base/check_op.h"
#include "base/strings/string_util.h"
#include "url/url_canon.h"
#include "url/url_canon_internal.h"
#include "url/url_constants.h"
#include "url/url_features.h"
#include "url/url_file.h"
#include "url/url_parse_internal.h"
#include "url/url_util.h"
#include "url/url_util_internal.h"
namespace url {
namespace {
// Firefox does a case-sensitive compare (which is probably wrong--Mozilla bug
// 379034), whereas IE is case-insensitive.
//
// We choose to be more permissive like IE. We don't need to worry about
// unescaping or anything here: neither IE or Firefox allow this. We also
// don't have to worry about invalid scheme characters since we are comparing
// against the canonical scheme of the base.
//
// The base URL should always be canonical, therefore it should be ASCII.
template<typename CHAR>
bool AreSchemesEqual(const char* base,
const Component& base_scheme,
const CHAR* cmp,
const Component& cmp_scheme) {
if (base_scheme.len != cmp_scheme.len)
return false;
for (int i = 0; i < base_scheme.len; i++) {
// We assume the base is already canonical, so we don't have to
// canonicalize it.
if (CanonicalSchemeChar(cmp[cmp_scheme.begin + i]) !=
base[base_scheme.begin + i])
return false;
}
return true;
}
#ifdef WIN32
// Here, we also allow Windows paths to be represented as "/C:/" so we can be
// consistent about URL paths beginning with slashes. This function is like
// DoesBeginWindowsDrivePath except that it also requires a slash at the
// beginning.
template<typename CHAR>
bool DoesBeginSlashWindowsDriveSpec(const CHAR* spec, int start_offset,
int spec_len) {
if (start_offset >= spec_len)
return false;
return IsURLSlash(spec[start_offset]) &&
DoesBeginWindowsDriveSpec(spec, start_offset + 1, spec_len);
}
#endif // WIN32
template <typename CHAR>
bool IsValidScheme(const CHAR* url, const Component& scheme) {
// Caller should ensure that the |scheme| is not empty.
DCHECK_NE(0, scheme.len);
// From https://url.spec.whatwg.org/#scheme-start-state:
// scheme start state:
// 1. If c is an ASCII alpha, append c, lowercased, to buffer, and set
// state to scheme state.
// 2. Otherwise, if state override is not given, set state to no scheme
// state, and decrease pointer by one.
// 3. Otherwise, validation error, return failure.
// Note that both step 2 and step 3 mean that the scheme was not valid.
if (!base::IsAsciiAlpha(url[scheme.begin]))
return false;
// From https://url.spec.whatwg.org/#scheme-state:
// scheme state:
// 1. If c is an ASCII alphanumeric, U+002B (+), U+002D (-), or U+002E
// (.), append c, lowercased, to buffer.
// 2. Otherwise, if c is U+003A (:), then [...]
//
// We begin at |scheme.begin + 1|, because the character at |scheme.begin| has
// already been checked by base::IsAsciiAlpha above.
int scheme_end = scheme.end();
for (int i = scheme.begin + 1; i < scheme_end; i++) {
if (!CanonicalSchemeChar(url[i]))
return false;
}
return true;
}
// See IsRelativeURL in the header file for usage.
template<typename CHAR>
bool DoIsRelativeURL(const char* base,
const Parsed& base_parsed,
const CHAR* url,
int url_len,
bool is_base_hierarchical,
bool* is_relative,
Component* relative_component) {
*is_relative = false; // So we can default later to not relative.
// Trim whitespace and construct a new range for the substring.
int begin = 0;
TrimURL(url, &begin, &url_len);
if (begin >= url_len) {
// Empty URLs are relative, but do nothing.
if (!is_base_hierarchical) {
// Don't allow relative URLs if the base scheme doesn't support it.
return false;
}
*relative_component = Component(begin, 0);
*is_relative = true;
return true;
}
#ifdef WIN32
// We special case paths like "C:\foo" so they can link directly to the
// file on Windows (IE compatibility). The security domain stuff should
// prevent a link like this from actually being followed if its on a
// web page.
//
// We treat "C:/foo" as an absolute URL. We can go ahead and treat "/c:/"
// as relative, as this will just replace the path when the base scheme
// is a file and the answer will still be correct.
//
// We require strict backslashes when detecting UNC since two forward
// slashes should be treated a a relative URL with a hostname.
if (DoesBeginWindowsDriveSpec(url, begin, url_len) ||
DoesBeginUNCPath(url, begin, url_len, true))
return true;
#endif // WIN32
// See if we've got a scheme, if not, we know this is a relative URL.
// BUT, just because we have a scheme, doesn't make it absolute.
// "http:foo.html" is a relative URL with path "foo.html". If the scheme is
// empty, we treat it as relative (":foo"), like IE does.
Component scheme;
const bool scheme_is_empty =
!ExtractScheme(url, url_len, &scheme) || scheme.len == 0;
if (scheme_is_empty) {
if (url[begin] == '#') {
// |url| is a bare fragment (e.g. "#foo"). This can be resolved against
// any base. Fall-through.
} else if (!is_base_hierarchical) {
// Don't allow relative URLs if the base scheme doesn't support it.
return false;
}
*relative_component = MakeRange(begin, url_len);
*is_relative = true;
return true;
}
// If the scheme isn't valid, then it's relative.
if (!IsValidScheme(url, scheme)) {
if (url[begin] == '#' &&
base::FeatureList::IsEnabled(
kResolveBareFragmentWithColonOnNonHierarchical)) {
// |url| is a bare fragment (e.g. "#foo:bar"). This can be resolved
// against any base. Fall-through.
} else if (!is_base_hierarchical) {
// Don't allow relative URLs if the base scheme doesn't support it.
return false;
}
*relative_component = MakeRange(begin, url_len);
*is_relative = true;
return true;
}
// If the scheme is not the same, then we can't count it as relative.
if (!AreSchemesEqual(base, base_parsed.scheme, url, scheme))
return true;
// When the scheme that they both share is not hierarchical, treat the
// incoming scheme as absolute (this way with the base of "data:foo",
// "data:bar" will be reported as absolute.
if (!is_base_hierarchical)
return true;
int colon_offset = scheme.end();
// If it's a filesystem URL, the only valid way to make it relative is not to
// supply a scheme. There's no equivalent to e.g. http:index.html.
if (CompareSchemeComponent(url, scheme, kFileSystemScheme))
return true;
// ExtractScheme guarantees that the colon immediately follows what it
// considers to be the scheme. CountConsecutiveSlashes will handle the
// case where the begin offset is the end of the input.
int num_slashes = CountConsecutiveSlashes(url, colon_offset + 1, url_len);
if (num_slashes == 0 || num_slashes == 1) {
// No slashes means it's a relative path like "http:foo.html". One slash
// is an absolute path. "http:/home/foo.html"
*is_relative = true;
*relative_component = MakeRange(colon_offset + 1, url_len);
return true;
}
// Two or more slashes after the scheme we treat as absolute.
return true;
}
// Copies all characters in the range [begin, end) of |spec| to the output,
// up until and including the last slash. There should be a slash in the
// range, if not, nothing will be copied.
//
// For stardard URLs the input should be canonical, but when resolving relative
// URLs on a non-standard base (like "data:") the input can be anything.
void CopyToLastSlash(const char* spec,
int begin,
int end,
CanonOutput* output) {
// Find the last slash.
int last_slash = -1;
for (int i = end - 1; i >= begin; i--) {
if (spec[i] == '/' || spec[i] == '\\') {
last_slash = i;
break;
}
}
if (last_slash < 0)
return; // No slash.
// Copy.
for (int i = begin; i <= last_slash; i++)
output->push_back(spec[i]);
}
// Copies a single component from the source to the output. This is used
// when resolving relative URLs and a given component is unchanged. Since the
// source should already be canonical, we don't have to do anything special,
// and the input is ASCII.
void CopyOneComponent(const char* source,
const Component& source_component,
CanonOutput* output,
Component* output_component) {
if (!source_component.is_valid()) {
// This component is not present.
*output_component = Component();
return;
}
output_component->begin = output->length();
int source_end = source_component.end();
for (int i = source_component.begin; i < source_end; i++)
output->push_back(source[i]);
output_component->len = output->length() - output_component->begin;
}
#ifdef WIN32
// Called on Windows when the base URL is a file URL, this will copy the "C:"
// to the output, if there is a drive letter and if that drive letter is not
// being overridden by the relative URL. Otherwise, do nothing.
//
// It will return the index of the beginning of the next character in the
// base to be processed: if there is a "C:", the slash after it, or if
// there is no drive letter, the slash at the beginning of the path, or
// the end of the base. This can be used as the starting offset for further
// path processing.
template<typename CHAR>
int CopyBaseDriveSpecIfNecessary(const char* base_url,
int base_path_begin,
int base_path_end,
const CHAR* relative_url,
int path_start,
int relative_url_len,
CanonOutput* output) {
if (base_path_begin >= base_path_end)
return base_path_begin; // No path.
// If the relative begins with a drive spec, don't do anything. The existing
// drive spec in the base will be replaced.
if (DoesBeginWindowsDriveSpec(relative_url, path_start, relative_url_len)) {
return base_path_begin; // Relative URL path is "C:/foo"
}
// The path should begin with a slash (as all canonical paths do). We check
// if it is followed by a drive letter and copy it.
if (DoesBeginSlashWindowsDriveSpec(base_url,
base_path_begin,
base_path_end)) {
// Copy the two-character drive spec to the output. It will now look like
// "file:///C:" so the rest of it can be treated like a standard path.
output->push_back('/');
output->push_back(base_url[base_path_begin + 1]);
output->push_back(base_url[base_path_begin + 2]);
return base_path_begin + 3;
}
return base_path_begin;
}
#endif // WIN32
// A subroutine of DoResolveRelativeURL, this resolves the URL knowning that
// the input is a relative path or less (query or ref).
template<typename CHAR>
bool DoResolveRelativePath(const char* base_url,
const Parsed& base_parsed,
bool base_is_file,
const CHAR* relative_url,
const Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* out_parsed) {
bool success = true;
// We know the authority section didn't change, copy it to the output. We
// also know we have a path so can copy up to there.
Component path, query, ref;
ParsePathInternal(relative_url, relative_component, &path, &query, &ref);
// Canonical URLs always have a path, so we can use that offset. Reserve
// enough room for the base URL, the new path, and some extra bytes for
// possible escaped characters.
output->ReserveSizeIfNeeded(base_parsed.path.begin +
std::max({path.end(), query.end(), ref.end()}));
output->Append(base_url, base_parsed.path.begin);
if (path.is_nonempty()) {
// The path is replaced or modified.
int true_path_begin = output->length();
// For file: URLs on Windows, we don't want to treat the drive letter and
// colon as part of the path for relative file resolution when the
// incoming URL does not provide a drive spec. We save the true path
// beginning so we can fix it up after we are done.
int base_path_begin = base_parsed.path.begin;
#ifdef WIN32
if (base_is_file) {
base_path_begin = CopyBaseDriveSpecIfNecessary(
base_url, base_parsed.path.begin, base_parsed.path.end(),
relative_url, relative_component.begin, relative_component.end(),
output);
// Now the output looks like either "file://" or "file:///C:"
// and we can start appending the rest of the path. |base_path_begin|
// points to the character in the base that comes next.
}
#endif // WIN32
if (IsURLSlash(relative_url[path.begin])) {
// Easy case: the path is an absolute path on the server, so we can
// just replace everything from the path on with the new versions.
// Since the input should be canonical hierarchical URL, we should
// always have a path.
success &= CanonicalizePath(relative_url, path,
output, &out_parsed->path);
} else {
// Relative path, replace the query, and reference. We take the
// original path with the file part stripped, and append the new path.
// The canonicalizer will take care of resolving ".." and "."
size_t path_begin = output->length();
CopyToLastSlash(base_url, base_path_begin, base_parsed.path.end(),
output);
success &= CanonicalizePartialPathInternal(relative_url, path, path_begin,
output);
out_parsed->path = MakeRange(path_begin, output->length());
// Copy the rest of the stuff after the path from the relative path.
}
// Finish with the query and reference part (these can't fail).
CanonicalizeQuery(relative_url, query, query_converter,
output, &out_parsed->query);
CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
// Fix the path beginning to add back the "C:" we may have written above.
out_parsed->path = MakeRange(true_path_begin, out_parsed->path.end());
return success;
}
// If we get here, the path is unchanged: copy to output.
CopyOneComponent(base_url, base_parsed.path, output, &out_parsed->path);
if (query.is_valid()) {
// Just the query specified, replace the query and reference (ignore
// failures for refs)
CanonicalizeQuery(relative_url, query, query_converter,
output, &out_parsed->query);
CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
return success;
}
// If we get here, the query is unchanged: copy to output. Note that the
// range of the query parameter doesn't include the question mark, so we
// have to add it manually if there is a component.
if (base_parsed.query.is_valid())
output->push_back('?');
CopyOneComponent(base_url, base_parsed.query, output, &out_parsed->query);
if (ref.is_valid()) {
// Just the reference specified: replace it (ignoring failures).
CanonicalizeRef(relative_url, ref, output, &out_parsed->ref);
return success;
}
// We should always have something to do in this function, the caller checks
// that some component is being replaced.
DCHECK(false) << "Not reached";
return success;
}
// Resolves a relative URL that contains a host. Typically, these will
// be of the form "//www.google.com/foo/bar?baz#ref" and the only thing which
// should be kept from the original URL is the scheme.
template<typename CHAR>
bool DoResolveRelativeHost(const char* base_url,
const Parsed& base_parsed,
const CHAR* relative_url,
const Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* out_parsed) {
// Parse the relative URL, just like we would for anything following a
// scheme.
Parsed relative_parsed; // Everything but the scheme is valid.
ParseAfterScheme(relative_url, relative_component.end(),
relative_component.begin, &relative_parsed);
// Now we can just use the replacement function to replace all the necessary
// parts of the old URL with the new one.
Replacements<CHAR> replacements;
replacements.SetUsername(relative_url, relative_parsed.username);
replacements.SetPassword(relative_url, relative_parsed.password);
replacements.SetHost(relative_url, relative_parsed.host);
replacements.SetPort(relative_url, relative_parsed.port);
replacements.SetPath(relative_url, relative_parsed.path);
replacements.SetQuery(relative_url, relative_parsed.query);
replacements.SetRef(relative_url, relative_parsed.ref);
// Length() does not include the old scheme, so make sure to add it from the
// base URL.
output->ReserveSizeIfNeeded(
replacements.components().Length() +
base_parsed.CountCharactersBefore(Parsed::USERNAME, false));
SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
if (!GetStandardSchemeType(base_url, base_parsed.scheme, &scheme_type)) {
// A path with an authority section gets canonicalized under standard URL
// rules, even though the base was not known to be standard.
scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
}
return ReplaceStandardURL(base_url, base_parsed, replacements, scheme_type,
query_converter, output, out_parsed);
}
// Resolves a relative URL that happens to be an absolute file path. Examples
// include: "//hostname/path", "/c:/foo", and "//hostname/c:/foo".
template<typename CHAR>
bool DoResolveAbsoluteFile(const CHAR* relative_url,
const Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* out_parsed) {
// Parse the file URL. The file URl parsing function uses the same logic
// as we do for determining if the file is absolute, in which case it will
// not bother to look for a scheme.
Parsed relative_parsed;
ParseFileURL(&relative_url[relative_component.begin], relative_component.len,
&relative_parsed);
return CanonicalizeFileURL(&relative_url[relative_component.begin],
relative_component.len, relative_parsed,
query_converter, output, out_parsed);
}
// TODO(brettw) treat two slashes as root like Mozilla for FTP?
template<typename CHAR>
bool DoResolveRelativeURL(const char* base_url,
const Parsed& base_parsed,
bool base_is_file,
const CHAR* relative_url,
const Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* out_parsed) {
// |base_parsed| is the starting point for our output. Since we may have
// removed whitespace from |relative_url| before entering this method, we'll
// carry over the |potentially_dangling_markup| flag.
bool potentially_dangling_markup = out_parsed->potentially_dangling_markup;
*out_parsed = base_parsed;
if (potentially_dangling_markup)
out_parsed->potentially_dangling_markup = true;
// Sanity check: the input should have a host or we'll break badly below.
// We can only resolve relative URLs with base URLs that have hosts and
// paths (even the default path of "/" is OK).
//
// We allow hosts with no length so we can handle file URLs, for example.
if (base_parsed.path.is_empty()) {
// On error, return the input (resolving a relative URL on a non-relative
// base = the base).
int base_len = base_parsed.Length();
for (int i = 0; i < base_len; i++)
output->push_back(base_url[i]);
return false;
}
if (relative_component.is_empty()) {
// Empty relative URL, leave unchanged, only removing the ref component.
int base_len = base_parsed.Length();
base_len -= base_parsed.ref.len + 1;
out_parsed->ref.reset();
output->Append(base_url, base_len);
return true;
}
int num_slashes = CountConsecutiveSlashes(
relative_url, relative_component.begin, relative_component.end());
#ifdef WIN32
// On Windows, two slashes for a file path (regardless of which direction
// they are) means that it's UNC. Two backslashes on any base scheme mean
// that it's an absolute UNC path (we use the base_is_file flag to control
// how strict the UNC finder is).
//
// We also allow Windows absolute drive specs on any scheme (for example
// "c:\foo") like IE does. There must be no preceding slashes in this
// case (we reject anything like "/c:/foo") because that should be treated
// as a path. For file URLs, we allow any number of slashes since that would
// be setting the path.
//
// This assumes the absolute path resolver handles absolute URLs like this
// properly. DoCanonicalize does this.
int after_slashes = relative_component.begin + num_slashes;
if (DoesBeginUNCPath(relative_url, relative_component.begin,
relative_component.end(), !base_is_file) ||
((num_slashes == 0 || base_is_file) &&
DoesBeginWindowsDriveSpec(
relative_url, after_slashes, relative_component.end()))) {
return DoResolveAbsoluteFile(relative_url, relative_component,
query_converter, output, out_parsed);
}
#else
// Other platforms need explicit handling for file: URLs with multiple
// slashes because the generic scheme parsing always extracts a host, but a
// file: URL only has a host if it has exactly 2 slashes. Even if it does
// have a host, we want to use the special host detection logic for file
// URLs provided by DoResolveAbsoluteFile(), as opposed to the generic host
// detection logic, for consistency with parsing file URLs from scratch.
if (base_is_file && num_slashes >= 2) {
return DoResolveAbsoluteFile(relative_url, relative_component,
query_converter, output, out_parsed);
}
#endif
// Any other double-slashes mean that this is relative to the scheme.
if (num_slashes >= 2) {
return DoResolveRelativeHost(base_url, base_parsed,
relative_url, relative_component,
query_converter, output, out_parsed);
}
// When we get here, we know that the relative URL is on the same host.
return DoResolveRelativePath(base_url, base_parsed, base_is_file,
relative_url, relative_component,
query_converter, output, out_parsed);
}
} // namespace
bool IsRelativeURL(const char* base,
const Parsed& base_parsed,
const char* fragment,
int fragment_len,
bool is_base_hierarchical,
bool* is_relative,
Component* relative_component) {
return DoIsRelativeURL<char>(
base, base_parsed, fragment, fragment_len, is_base_hierarchical,
is_relative, relative_component);
}
bool IsRelativeURL(const char* base,
const Parsed& base_parsed,
const char16_t* fragment,
int fragment_len,
bool is_base_hierarchical,
bool* is_relative,
Component* relative_component) {
return DoIsRelativeURL<char16_t>(base, base_parsed, fragment, fragment_len,
is_base_hierarchical, is_relative,
relative_component);
}
bool ResolveRelativeURL(const char* base_url,
const Parsed& base_parsed,
bool base_is_file,
const char* relative_url,
const Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* out_parsed) {
return DoResolveRelativeURL<char>(
base_url, base_parsed, base_is_file, relative_url,
relative_component, query_converter, output, out_parsed);
}
bool ResolveRelativeURL(const char* base_url,
const Parsed& base_parsed,
bool base_is_file,
const char16_t* relative_url,
const Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* out_parsed) {
return DoResolveRelativeURL<char16_t>(base_url, base_parsed, base_is_file,
relative_url, relative_component,
query_converter, output, out_parsed);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_relative.cc | C++ | unknown | 25,883 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_canon_stdstring.h"
namespace url {
StdStringCanonOutput::StdStringCanonOutput(std::string* str) : str_(str) {
cur_len_ = str_->size(); // Append to existing data.
buffer_ = str_->empty() ? nullptr : &(*str_)[0];
buffer_len_ = str_->size();
}
StdStringCanonOutput::~StdStringCanonOutput() {
// Nothing to do, we don't own the string.
}
void StdStringCanonOutput::Complete() {
str_->resize(cur_len_);
buffer_len_ = cur_len_;
}
void StdStringCanonOutput::Resize(size_t sz) {
str_->resize(sz);
buffer_ = str_->empty() ? nullptr : &(*str_)[0];
buffer_len_ = sz;
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_stdstring.cc | C++ | unknown | 766 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_CANON_STDSTRING_H_
#define URL_URL_CANON_STDSTRING_H_
// This header file defines a canonicalizer output method class for STL
// strings. Because the canonicalizer tries not to be dependent on the STL,
// we have segregated it here.
#include <string>
#include "base/compiler_specific.h"
#include "base/component_export.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/strings/string_piece.h"
#include "url/url_canon.h"
namespace url {
// Write into a std::string given in the constructor. This object does not own
// the string itself, and the user must ensure that the string stays alive
// throughout the lifetime of this object.
//
// The given string will be appended to; any existing data in the string will
// be preserved.
//
// Note that when canonicalization is complete, the string will likely have
// unused space at the end because we make the string very big to start out
// with (by |initial_size|). This ends up being important because resize
// operations are slow, and because the base class needs to write directly
// into the buffer.
//
// Therefore, the user should call Complete() before using the string that
// this class wrote into.
class COMPONENT_EXPORT(URL) StdStringCanonOutput : public CanonOutput {
public:
StdStringCanonOutput(std::string* str);
StdStringCanonOutput(const StdStringCanonOutput&) = delete;
StdStringCanonOutput& operator=(const StdStringCanonOutput&) = delete;
~StdStringCanonOutput() override;
// Must be called after writing has completed but before the string is used.
void Complete();
void Resize(size_t sz) override;
protected:
// `str_` is not a raw_ptr<...> for performance reasons (based on analysis of
// sampling profiler data and tab_search:top100:2020).
RAW_PTR_EXCLUSION std::string* str_;
};
// An extension of the Replacements class that allows the setters to use
// StringPieces (implicitly allowing strings or char*s).
//
// The contents of the StringPieces are not copied and must remain valid until
// the StringPieceReplacements object goes out of scope.
//
// In order to make it harder to misuse the API the setters do not accept rvalue
// references to std::strings.
// Note: Extra const char* overloads are necessary to break ambiguities that
// would otherwise exist for char literals.
template <typename CharT>
class StringPieceReplacements : public Replacements<CharT> {
private:
using StringT = std::basic_string<CharT>;
using StringPieceT = base::BasicStringPiece<CharT>;
using ParentT = Replacements<CharT>;
using SetterFun = void (ParentT::*)(const CharT*, const Component&);
void SetImpl(SetterFun fun, StringPieceT str) {
(this->*fun)(str.data(), Component(0, static_cast<int>(str.size())));
}
public:
void SetSchemeStr(const CharT* str) { SetImpl(&ParentT::SetScheme, str); }
void SetSchemeStr(StringPieceT str) { SetImpl(&ParentT::SetScheme, str); }
void SetSchemeStr(const StringT&&) = delete;
void SetUsernameStr(const CharT* str) { SetImpl(&ParentT::SetUsername, str); }
void SetUsernameStr(StringPieceT str) { SetImpl(&ParentT::SetUsername, str); }
void SetUsernameStr(const StringT&&) = delete;
using ParentT::ClearUsername;
void SetPasswordStr(const CharT* str) { SetImpl(&ParentT::SetPassword, str); }
void SetPasswordStr(StringPieceT str) { SetImpl(&ParentT::SetPassword, str); }
void SetPasswordStr(const StringT&&) = delete;
using ParentT::ClearPassword;
void SetHostStr(const CharT* str) { SetImpl(&ParentT::SetHost, str); }
void SetHostStr(StringPieceT str) { SetImpl(&ParentT::SetHost, str); }
void SetHostStr(const StringT&&) = delete;
using ParentT::ClearHost;
void SetPortStr(const CharT* str) { SetImpl(&ParentT::SetPort, str); }
void SetPortStr(StringPieceT str) { SetImpl(&ParentT::SetPort, str); }
void SetPortStr(const StringT&&) = delete;
using ParentT::ClearPort;
void SetPathStr(const CharT* str) { SetImpl(&ParentT::SetPath, str); }
void SetPathStr(StringPieceT str) { SetImpl(&ParentT::SetPath, str); }
void SetPathStr(const StringT&&) = delete;
using ParentT::ClearPath;
void SetQueryStr(const CharT* str) { SetImpl(&ParentT::SetQuery, str); }
void SetQueryStr(StringPieceT str) { SetImpl(&ParentT::SetQuery, str); }
void SetQueryStr(const StringT&&) = delete;
using ParentT::ClearQuery;
void SetRefStr(const CharT* str) { SetImpl(&ParentT::SetRef, str); }
void SetRefStr(StringPieceT str) { SetImpl(&ParentT::SetRef, str); }
void SetRefStr(const StringT&&) = delete;
using ParentT::ClearRef;
private:
using ParentT::SetHost;
using ParentT::SetPassword;
using ParentT::SetPath;
using ParentT::SetPort;
using ParentT::SetQuery;
using ParentT::SetRef;
using ParentT::SetScheme;
using ParentT::SetUsername;
};
} // namespace url
#endif // URL_URL_CANON_STDSTRING_H_
| Zhao-PengFei35/chromium_src_4 | url/url_canon_stdstring.h | C++ | unknown | 4,988 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Functions to canonicalize "standard" URLs, which are ones that have an
// authority section including a host name.
#include "url/url_canon.h"
#include "url/url_canon_internal.h"
#include "url/url_constants.h"
namespace url {
namespace {
template <typename CHAR, typename UCHAR>
bool DoCanonicalizeStandardURL(const URLComponentSource<CHAR>& source,
const Parsed& parsed,
SchemeType scheme_type,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* new_parsed) {
// Scheme: this will append the colon.
bool success = CanonicalizeScheme(source.scheme, parsed.scheme,
output, &new_parsed->scheme);
bool scheme_supports_user_info =
(scheme_type == SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION);
bool scheme_supports_ports =
(scheme_type == SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION ||
scheme_type == SCHEME_WITH_HOST_AND_PORT);
// Authority (username, password, host, port)
bool have_authority;
if ((scheme_supports_user_info &&
(parsed.username.is_valid() || parsed.password.is_valid())) ||
parsed.host.is_nonempty() ||
(scheme_supports_ports && parsed.port.is_valid())) {
have_authority = true;
// Only write the authority separators when we have a scheme.
if (parsed.scheme.is_valid()) {
output->push_back('/');
output->push_back('/');
}
// User info: the canonicalizer will handle the : and @.
if (scheme_supports_user_info) {
success &= CanonicalizeUserInfo(
source.username, parsed.username, source.password, parsed.password,
output, &new_parsed->username, &new_parsed->password);
} else {
new_parsed->username.reset();
new_parsed->password.reset();
}
success &= CanonicalizeHost(source.host, parsed.host,
output, &new_parsed->host);
// Host must not be empty for standard URLs.
if (parsed.host.is_empty())
success = false;
// Port: the port canonicalizer will handle the colon.
if (scheme_supports_ports) {
int default_port = DefaultPortForScheme(
&output->data()[new_parsed->scheme.begin], new_parsed->scheme.len);
success &= CanonicalizePort(source.port, parsed.port, default_port,
output, &new_parsed->port);
} else {
new_parsed->port.reset();
}
} else {
// No authority, clear the components.
have_authority = false;
new_parsed->host.reset();
new_parsed->username.reset();
new_parsed->password.reset();
new_parsed->port.reset();
success = false; // Standard URLs must have an authority.
}
// Path
if (parsed.path.is_valid()) {
success &= CanonicalizePath(source.path, parsed.path,
output, &new_parsed->path);
} else if (have_authority ||
parsed.query.is_valid() || parsed.ref.is_valid()) {
// When we have an empty path, make up a path when we have an authority
// or something following the path. The only time we allow an empty
// output path is when there is nothing else.
new_parsed->path = Component(output->length(), 1);
output->push_back('/');
} else {
// No path at all
new_parsed->path.reset();
}
// Query
CanonicalizeQuery(source.query, parsed.query, query_converter,
output, &new_parsed->query);
// Ref: ignore failure for this, since the page can probably still be loaded.
CanonicalizeRef(source.ref, parsed.ref, output, &new_parsed->ref);
// Carry over the flag for potentially dangling markup:
if (parsed.potentially_dangling_markup)
new_parsed->potentially_dangling_markup = true;
return success;
}
} // namespace
// Returns the default port for the given canonical scheme, or PORT_UNSPECIFIED
// if the scheme is unknown.
//
// Please keep blink::DefaultPortForProtocol and url::DefaultPortForProtocol in
// sync.
int DefaultPortForScheme(const char* scheme, int scheme_len) {
int default_port = PORT_UNSPECIFIED;
switch (scheme_len) {
case 4:
if (!strncmp(scheme, kHttpScheme, scheme_len))
default_port = 80;
break;
case 5:
if (!strncmp(scheme, kHttpsScheme, scheme_len))
default_port = 443;
break;
case 3:
if (!strncmp(scheme, kFtpScheme, scheme_len))
default_port = 21;
else if (!strncmp(scheme, kWssScheme, scheme_len))
default_port = 443;
break;
case 2:
if (!strncmp(scheme, kWsScheme, scheme_len))
default_port = 80;
break;
}
return default_port;
}
bool CanonicalizeStandardURL(const char* spec,
int spec_len,
const Parsed& parsed,
SchemeType scheme_type,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* new_parsed) {
return DoCanonicalizeStandardURL<char, unsigned char>(
URLComponentSource<char>(spec), parsed, scheme_type, query_converter,
output, new_parsed);
}
bool CanonicalizeStandardURL(const char16_t* spec,
int spec_len,
const Parsed& parsed,
SchemeType scheme_type,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* new_parsed) {
return DoCanonicalizeStandardURL<char16_t, char16_t>(
URLComponentSource<char16_t>(spec), parsed, scheme_type, query_converter,
output, new_parsed);
}
// It might be nice in the future to optimize this so unchanged components don't
// need to be recanonicalized. This is especially true since the common case for
// ReplaceComponents is removing things we don't want, like reference fragments
// and usernames. These cases can become more efficient if we can assume the
// rest of the URL is OK with these removed (or only the modified parts
// recanonicalized). This would be much more complex to implement, however.
//
// You would also need to update DoReplaceComponents in url_util.cc which
// relies on this re-checking everything (see the comment there for why).
bool ReplaceStandardURL(const char* base,
const Parsed& base_parsed,
const Replacements<char>& replacements,
SchemeType scheme_type,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* new_parsed) {
URLComponentSource<char> source(base);
Parsed parsed(base_parsed);
SetupOverrideComponents(base, replacements, &source, &parsed);
return DoCanonicalizeStandardURL<char, unsigned char>(
source, parsed, scheme_type, query_converter, output, new_parsed);
}
// For 16-bit replacements, we turn all the replacements into UTF-8 so the
// regular code path can be used.
bool ReplaceStandardURL(const char* base,
const Parsed& base_parsed,
const Replacements<char16_t>& replacements,
SchemeType scheme_type,
CharsetConverter* query_converter,
CanonOutput* output,
Parsed* new_parsed) {
RawCanonOutput<1024> utf8;
URLComponentSource<char> source(base);
Parsed parsed(base_parsed);
SetupUTF16OverrideComponents(base, replacements, &utf8, &source, &parsed);
return DoCanonicalizeStandardURL<char, unsigned char>(
source, parsed, scheme_type, query_converter, output, new_parsed);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_stdurl.cc | C++ | unknown | 7,975 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_canon.h"
#include <errno.h>
#include <stddef.h>
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/gtest_util.h"
#include "base/test/scoped_feature_list.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_canon_internal.h"
#include "url/url_canon_stdstring.h"
#include "url/url_features.h"
#include "url/url_test_utils.h"
namespace url {
namespace {
struct ComponentCase {
const char* input;
const char* expected;
Component expected_component;
bool expected_success;
};
// ComponentCase but with dual 8-bit/16-bit input. Generally, the unit tests
// treat each input as optional, and will only try processing if non-NULL.
// The output is always 8-bit.
struct DualComponentCase {
const char* input8;
const wchar_t* input16;
const char* expected;
Component expected_component;
bool expected_success;
};
// Test cases for CanonicalizeIPAddress(). The inputs are identical to
// DualComponentCase, but the output has extra CanonHostInfo fields.
struct IPAddressCase {
const char* input8;
const wchar_t* input16;
const char* expected;
Component expected_component;
// CanonHostInfo fields, for verbose output.
CanonHostInfo::Family expected_family;
int expected_num_ipv4_components;
const char* expected_address_hex; // Two hex chars per IP address byte.
};
std::string BytesToHexString(unsigned char bytes[16], int length) {
EXPECT_TRUE(length == 0 || length == 4 || length == 16)
<< "Bad IP address length: " << length;
std::string result;
for (int i = 0; i < length; ++i) {
result.push_back(kHexCharLookup[(bytes[i] >> 4) & 0xf]);
result.push_back(kHexCharLookup[bytes[i] & 0xf]);
}
return result;
}
struct ReplaceCase {
const char* base;
const char* scheme;
const char* username;
const char* password;
const char* host;
const char* port;
const char* path;
const char* query;
const char* ref;
const char* expected;
};
// Magic string used in the replacements code that tells SetupReplComp to
// call the clear function.
const char kDeleteComp[] = "|";
// Sets up a replacement for a single component. This is given pointers to
// the set and clear function for the component being replaced, and will
// either set the component (if it exists) or clear it (if the replacement
// string matches kDeleteComp).
//
// This template is currently used only for the 8-bit case, and the strlen
// causes it to fail in other cases. It is left a template in case we have
// tests for wide replacements.
template<typename CHAR>
void SetupReplComp(
void (Replacements<CHAR>::*set)(const CHAR*, const Component&),
void (Replacements<CHAR>::*clear)(),
Replacements<CHAR>* rep,
const CHAR* str) {
if (str && str[0] == kDeleteComp[0]) {
(rep->*clear)();
} else if (str) {
(rep->*set)(str, Component(0, static_cast<int>(strlen(str))));
}
}
} // namespace
TEST(URLCanonTest, DoAppendUTF8) {
struct UTF8Case {
unsigned input;
const char* output;
} utf_cases[] = {
// Valid code points.
{0x24, "\x24"},
{0xA2, "\xC2\xA2"},
{0x20AC, "\xE2\x82\xAC"},
{0x24B62, "\xF0\xA4\xAD\xA2"},
{0x10FFFF, "\xF4\x8F\xBF\xBF"},
};
std::string out_str;
for (size_t i = 0; i < std::size(utf_cases); i++) {
out_str.clear();
StdStringCanonOutput output(&out_str);
AppendUTF8Value(utf_cases[i].input, &output);
output.Complete();
EXPECT_EQ(utf_cases[i].output, out_str);
}
}
TEST(URLCanonTest, DoAppendUTF8Invalid) {
std::string out_str;
StdStringCanonOutput output(&out_str);
// Invalid code point (too large).
EXPECT_DCHECK_DEATH({
AppendUTF8Value(0x110000, &output);
output.Complete();
});
}
TEST(URLCanonTest, UTF) {
// Low-level test that we handle reading, canonicalization, and writing
// UTF-8/UTF-16 strings properly.
struct UTFCase {
const char* input8;
const wchar_t* input16;
bool expected_success;
const char* output;
} utf_cases[] = {
// Valid canonical input should get passed through & escaped.
{"\xe4\xbd\xa0\xe5\xa5\xbd", L"\x4f60\x597d", true, "%E4%BD%A0%E5%A5%BD"},
// Test a character that takes > 16 bits (U+10300 = old italic letter A)
{"\xF0\x90\x8C\x80", L"\xd800\xdf00", true, "%F0%90%8C%80"},
// Non-shortest-form UTF-8 characters are invalid. The bad bytes should
// each be replaced with the invalid character (EF BF DB in UTF-8).
{"\xf0\x84\xbd\xa0\xe5\xa5\xbd", nullptr, false,
"%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%E5%A5%BD"},
// Invalid UTF-8 sequences should be marked as invalid (the first
// sequence is truncated).
{"\xe4\xa0\xe5\xa5\xbd", L"\xd800\x597d", false, "%EF%BF%BD%E5%A5%BD"},
// Character going off the end.
{"\xe4\xbd\xa0\xe5\xa5", L"\x4f60\xd800", false, "%E4%BD%A0%EF%BF%BD"},
// ...same with low surrogates with no high surrogate.
{nullptr, L"\xdc00", false, "%EF%BF%BD"},
// Test a UTF-8 encoded surrogate value is marked as invalid.
// ED A0 80 = U+D800
{"\xed\xa0\x80", nullptr, false, "%EF%BF%BD%EF%BF%BD%EF%BF%BD"},
// ...even when paired.
{"\xed\xa0\x80\xed\xb0\x80", nullptr, false,
"%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD"},
};
std::string out_str;
for (size_t i = 0; i < std::size(utf_cases); i++) {
if (utf_cases[i].input8) {
out_str.clear();
StdStringCanonOutput output(&out_str);
size_t input_len = strlen(utf_cases[i].input8);
bool success = true;
for (size_t ch = 0; ch < input_len; ch++) {
success &= AppendUTF8EscapedChar(utf_cases[i].input8, &ch, input_len,
&output);
}
output.Complete();
EXPECT_EQ(utf_cases[i].expected_success, success);
EXPECT_EQ(std::string(utf_cases[i].output), out_str);
}
if (utf_cases[i].input16) {
out_str.clear();
StdStringCanonOutput output(&out_str);
std::u16string input_str(
test_utils::TruncateWStringToUTF16(utf_cases[i].input16));
size_t input_len = input_str.length();
bool success = true;
for (size_t ch = 0; ch < input_len; ch++) {
success &= AppendUTF8EscapedChar(input_str.c_str(), &ch, input_len,
&output);
}
output.Complete();
EXPECT_EQ(utf_cases[i].expected_success, success);
EXPECT_EQ(std::string(utf_cases[i].output), out_str);
}
if (utf_cases[i].input8 && utf_cases[i].input16 &&
utf_cases[i].expected_success) {
// Check that the UTF-8 and UTF-16 inputs are equivalent.
// UTF-16 -> UTF-8
std::string input8_str(utf_cases[i].input8);
std::u16string input16_str(
test_utils::TruncateWStringToUTF16(utf_cases[i].input16));
EXPECT_EQ(input8_str, base::UTF16ToUTF8(input16_str));
// UTF-8 -> UTF-16
EXPECT_EQ(input16_str, base::UTF8ToUTF16(input8_str));
}
}
}
TEST(URLCanonTest, Scheme) {
// Here, we're mostly testing that unusual characters are handled properly.
// The canonicalizer doesn't do any parsing or whitespace detection. It will
// also do its best on error, and will escape funny sequences (these won't be
// valid schemes and it will return error).
//
// Note that the canonicalizer will append a colon to the output to separate
// out the rest of the URL, which is not present in the input. We check,
// however, that the output range includes everything but the colon.
ComponentCase scheme_cases[] = {
{"http", "http:", Component(0, 4), true},
{"HTTP", "http:", Component(0, 4), true},
{" HTTP ", "%20http%20:", Component(0, 10), false},
{"htt: ", "htt%3A%20:", Component(0, 9), false},
{"\xe4\xbd\xa0\xe5\xa5\xbdhttp", "%E4%BD%A0%E5%A5%BDhttp:", Component(0, 22), false},
// Don't re-escape something already escaped. Note that it will
// "canonicalize" the 'A' to 'a', but that's OK.
{"ht%3Atp", "ht%3atp:", Component(0, 7), false},
{"", ":", Component(0, 0), false},
};
std::string out_str;
for (size_t i = 0; i < std::size(scheme_cases); i++) {
int url_len = static_cast<int>(strlen(scheme_cases[i].input));
Component in_comp(0, url_len);
Component out_comp;
out_str.clear();
StdStringCanonOutput output1(&out_str);
bool success = CanonicalizeScheme(scheme_cases[i].input, in_comp, &output1,
&out_comp);
output1.Complete();
EXPECT_EQ(scheme_cases[i].expected_success, success);
EXPECT_EQ(std::string(scheme_cases[i].expected), out_str);
EXPECT_EQ(scheme_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(scheme_cases[i].expected_component.len, out_comp.len);
// Now try the wide version.
out_str.clear();
StdStringCanonOutput output2(&out_str);
std::u16string wide_input(base::UTF8ToUTF16(scheme_cases[i].input));
in_comp.len = static_cast<int>(wide_input.length());
success = CanonicalizeScheme(wide_input.c_str(), in_comp, &output2,
&out_comp);
output2.Complete();
EXPECT_EQ(scheme_cases[i].expected_success, success);
EXPECT_EQ(std::string(scheme_cases[i].expected), out_str);
EXPECT_EQ(scheme_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(scheme_cases[i].expected_component.len, out_comp.len);
}
// Test the case where the scheme is declared nonexistent, it should be
// converted into an empty scheme.
Component out_comp;
out_str.clear();
StdStringCanonOutput output(&out_str);
EXPECT_FALSE(CanonicalizeScheme("", Component(0, -1), &output, &out_comp));
output.Complete();
EXPECT_EQ(std::string(":"), out_str);
EXPECT_EQ(0, out_comp.begin);
EXPECT_EQ(0, out_comp.len);
}
// IDNA mode to use in CanonHost tests.
enum class IDNAMode { kTransitional, kNonTransitional };
class URLCanonHostTest
: public ::testing::Test,
public ::testing::WithParamInterface<IDNAMode> {
public:
URLCanonHostTest() {
if (GetParam() == IDNAMode::kNonTransitional) {
scoped_feature_list_.InitAndEnableFeature(kUseIDNA2008NonTransitional);
} else {
scoped_feature_list_.InitAndDisableFeature(kUseIDNA2008NonTransitional);
}
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
URLCanonHostTest,
::testing::Values(IDNAMode::kTransitional,
IDNAMode::kNonTransitional));
TEST_P(URLCanonHostTest, Host) {
bool use_idna_non_transitional = IsUsingIDNA2008NonTransitional();
IPAddressCase host_cases[] = {
// Basic canonicalization, uppercase should be converted to lowercase.
{"GoOgLe.CoM", L"GoOgLe.CoM", "google.com", Component(0, 10),
CanonHostInfo::NEUTRAL, -1, ""},
// Spaces and some other characters should be escaped.
{"Goo%20 goo%7C|.com", L"Goo%20 goo%7C|.com", "goo%20%20goo%7C%7C.com",
Component(0, 22), CanonHostInfo::NEUTRAL, -1, ""},
// Exciting different types of spaces!
{NULL, L"GOO\x00a0\x3000goo.com", "goo%20%20goo.com", Component(0, 16),
CanonHostInfo::NEUTRAL, -1, ""},
// Other types of space (no-break, zero-width, zero-width-no-break) are
// name-prepped away to nothing.
{NULL, L"GOO\x200b\x2060\xfeffgoo.com", "googoo.com", Component(0, 10),
CanonHostInfo::NEUTRAL, -1, ""},
// Ideographic full stop (full-width period for Chinese, etc.) should be
// treated as a dot.
{NULL,
L"www.foo\x3002"
L"bar.com",
"www.foo.bar.com", Component(0, 15), CanonHostInfo::NEUTRAL, -1, ""},
// Invalid unicode characters should fail...
// ...In wide input, ICU will barf and we'll end up with the input as
// escaped UTF-8 (the invalid character should be replaced with the
// replacement character).
{"\xef\xb7\x90zyx.com", L"\xfdd0zyx.com", "%EF%BF%BDzyx.com",
Component(0, 16), CanonHostInfo::BROKEN, -1, ""},
// ...This is the same as previous but with with escaped.
{"%ef%b7%90zyx.com", L"%ef%b7%90zyx.com", "%EF%BF%BDzyx.com",
Component(0, 16), CanonHostInfo::BROKEN, -1, ""},
// Test name prepping, fullwidth input should be converted to ASCII and
// NOT
// IDN-ized. This is "Go" in fullwidth UTF-8/UTF-16.
{"\xef\xbc\xa7\xef\xbd\x8f.com", L"\xff27\xff4f.com", "go.com",
Component(0, 6), CanonHostInfo::NEUTRAL, -1, ""},
// Test that fullwidth escaped values are properly name-prepped,
// then converted or rejected.
// ...%41 in fullwidth = 'A' (also as escaped UTF-8 input)
{"\xef\xbc\x85\xef\xbc\x94\xef\xbc\x91.com", L"\xff05\xff14\xff11.com",
"a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
{"%ef%bc%85%ef%bc%94%ef%bc%91.com", L"%ef%bc%85%ef%bc%94%ef%bc%91.com",
"a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
// ...%00 in fullwidth should fail (also as escaped UTF-8 input)
{"\xef\xbc\x85\xef\xbc\x90\xef\xbc\x90.com", L"\xff05\xff10\xff10.com",
"%00.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
{"%ef%bc%85%ef%bc%90%ef%bc%90.com", L"%ef%bc%85%ef%bc%90%ef%bc%90.com",
"%00.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
// ICU will convert weird percents into ASCII percents, but not unescape
// further. A weird percent is U+FE6A (EF B9 AA in UTF-8) which is a
// "small percent". At this point we should be within our rights to mark
// anything as invalid since the URL is corrupt or malicious. The code
// happens to allow ASCII characters (%41 = "A" -> 'a') to be unescaped
// and kept as valid, so we validate that behavior here, but this level
// of fixing the input shouldn't be seen as required. "%81" is invalid.
{"\xef\xb9\xaa"
"41.com",
L"\xfe6a"
L"41.com",
"a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
{"%ef%b9%aa"
"41.com",
L"\xfe6a"
L"41.com",
"a.com", Component(0, 5), CanonHostInfo::NEUTRAL, -1, ""},
{"\xef\xb9\xaa"
"81.com",
L"\xfe6a"
L"81.com",
"%81.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
{"%ef%b9%aa"
"81.com",
L"\xfe6a"
L"81.com",
"%81.com", Component(0, 7), CanonHostInfo::BROKEN, -1, ""},
// Basic IDN support, UTF-8 and UTF-16 input should be converted to IDN
{"\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xbd\xa0\xe5\xa5\xbd",
L"\x4f60\x597d\x4f60\x597d", "xn--6qqa088eba", Component(0, 14),
CanonHostInfo::NEUTRAL, -1, ""},
// See http://unicode.org/cldr/utility/idna.jsp for other
// examples/experiments and http://goo.gl/7yG11o
// for the full list of characters handled differently by
// IDNA 2003, UTS 46 (http://unicode.org/reports/tr46/ ) and IDNA 2008.
// 4 Deviation characters are mapped/ignored in UTS 46 transitional
// mechansm. UTS 46, table 4 row (g).
// Sharp-s is mapped to 'ss' in IDNA 2003, not in IDNA 2008 or UTF 46
// after transitional period.
// Previously, it'd be "fussball.de".
{"fu\xc3\x9f"
"ball.de",
L"fu\x00df"
L"ball.de",
use_idna_non_transitional ? "xn--fuball-cta.de" : "fussball.de",
use_idna_non_transitional ? Component(0, 17) : Component(0, 11),
CanonHostInfo::NEUTRAL, -1, ""},
// Final-sigma (U+03C3) was mapped to regular sigma (U+03C2).
// Previously, it'd be "xn--wxaikc9b".
{"\xcf\x83\xcf\x8c\xce\xbb\xce\xbf\xcf\x82", L"\x3c3\x3cc\x3bb\x3bf\x3c2",
use_idna_non_transitional ? "xn--wxaijb9b" : "xn--wxaikc6b",
Component(0, 12), CanonHostInfo::NEUTRAL, -1, ""},
// ZWNJ (U+200C) and ZWJ (U+200D) are mapped away in UTS 46 transitional
// handling as well as in IDNA 2003, but not thereafter.
{"a\xe2\x80\x8c"
"b\xe2\x80\x8d"
"c",
L"a\x200c"
L"b\x200d"
L"c",
use_idna_non_transitional ? "xn--abc-9m0ag" : "abc",
use_idna_non_transitional ? Component(0, 13) : Component(0, 3),
CanonHostInfo::NEUTRAL, -1, ""},
// ZWJ between Devanagari characters was still mapped away in UTS 46
// transitional handling. IDNA 2008 gives xn--11bo0mv54g.
// Previously "xn--11bo0m".
{"\xe0\xa4\x95\xe0\xa5\x8d\xe2\x80\x8d\xe0\xa4\x9c",
L"\x915\x94d\x200d\x91c",
use_idna_non_transitional ? "xn--11bo0mv54g" : "xn--11bo0m",
use_idna_non_transitional ? Component(0, 14) : Component(0, 10),
CanonHostInfo::NEUTRAL, -1, ""},
// Fullwidth exclamation mark is disallowed. UTS 46, table 4, row (b)
// However, we do allow this at the moment because we don't use
// STD3 rules and canonicalize full-width ASCII to ASCII.
{"wow\xef\xbc\x81", L"wow\xff01", "wow%21", Component(0, 6),
CanonHostInfo::NEUTRAL, -1, ""},
// U+2132 (turned capital F) is disallowed. UTS 46, table 4, row (c)
// Allowed in IDNA 2003, but the mapping changed after Unicode 3.2
{"\xe2\x84\xb2oo", L"\x2132oo", "%E2%84%B2oo", Component(0, 11),
CanonHostInfo::BROKEN, -1, ""},
// U+2F868 (CJK Comp) is disallowed. UTS 46, table 4, row (d)
// Allowed in IDNA 2003, but the mapping changed after Unicode 3.2
{"\xf0\xaf\xa1\xa8\xe5\xa7\xbb.cn", L"\xd87e\xdc68\x59fb.cn",
"%F0%AF%A1%A8%E5%A7%BB.cn", Component(0, 24), CanonHostInfo::BROKEN, -1,
""},
// Maps uppercase letters to lower case letters. UTS 46 table 4 row (e)
{"M\xc3\x9cNCHEN", L"M\xdcNCHEN", "xn--mnchen-3ya", Component(0, 14),
CanonHostInfo::NEUTRAL, -1, ""},
// An already-IDNA host is not modified.
{"xn--mnchen-3ya", L"xn--mnchen-3ya", "xn--mnchen-3ya", Component(0, 14),
CanonHostInfo::NEUTRAL, -1, ""},
// Symbol/punctuations are allowed in IDNA 2003/UTS46.
// Not allowed in IDNA 2008. UTS 46 table 4 row (f).
{"\xe2\x99\xa5ny.us", L"\x2665ny.us", "xn--ny-s0x.us", Component(0, 13),
CanonHostInfo::NEUTRAL, -1, ""},
// U+11013 is new in Unicode 6.0 and is allowed. UTS 46 table 4, row (h)
// We used to allow it because we passed through unassigned code points.
{"\xf0\x91\x80\x93.com", L"\xd804\xdc13.com", "xn--n00d.com",
Component(0, 12), CanonHostInfo::NEUTRAL, -1, ""},
// U+0602 is disallowed in UTS46/IDNA 2008. UTS 46 table 4, row(i)
// Used to be allowed in INDA 2003.
{"\xd8\x82.eg", L"\x602.eg", "%D8%82.eg", Component(0, 9),
CanonHostInfo::BROKEN, -1, ""},
// U+20B7 is new in Unicode 5.2 (not a part of IDNA 2003 based
// on Unicode 3.2). We did allow it in the past because we let unassigned
// code point pass. We continue to allow it even though it's a
// "punctuation and symbol" blocked in IDNA 2008.
// UTS 46 table 4, row (j)
{"\xe2\x82\xb7.com", L"\x20b7.com", "xn--wzg.com", Component(0, 11),
CanonHostInfo::NEUTRAL, -1, ""},
// Maps uppercase letters to lower case letters.
// In IDNA 2003, it's allowed without case-folding
// ( xn--bc-7cb.com ) because it's not defined in Unicode 3.2
// (added in Unicode 4.1). UTS 46 table 4 row (k)
{"bc\xc8\xba.com", L"bc\x23a.com", "xn--bc-is1a.com", Component(0, 15),
CanonHostInfo::NEUTRAL, -1, ""},
// Maps U+FF43 (Full Width Small Letter C) to 'c'.
{"ab\xef\xbd\x83.xyz", L"ab\xff43.xyz", "abc.xyz", Component(0, 7),
CanonHostInfo::NEUTRAL, -1, ""},
// Maps U+1D68C (Math Monospace Small C) to 'c'.
// U+1D68C = \xD835\xDE8C in UTF-16
{"ab\xf0\x9d\x9a\x8c.xyz", L"ab\xd835\xde8c.xyz", "abc.xyz",
Component(0, 7), CanonHostInfo::NEUTRAL, -1, ""},
// BiDi check test
// "Divehi" in Divehi (Thaana script) ends with BidiClass=NSM.
// Disallowed in IDNA 2003 but now allowed in UTS 46/IDNA 2008.
{"\xde\x8b\xde\xa8\xde\x88\xde\xac\xde\x80\xde\xa8",
L"\x78b\x7a8\x788\x7ac\x780\x7a8", "xn--hqbpi0jcw", Component(0, 13),
CanonHostInfo::NEUTRAL, -1, ""},
// Disallowed in both IDNA 2003 and 2008 with BiDi check.
// Labels starting with a RTL character cannot end with a LTR character.
{"\xd8\xac\xd8\xa7\xd8\xb1xyz", L"\x62c\x627\x631xyz",
"%D8%AC%D8%A7%D8%B1xyz", Component(0, 21), CanonHostInfo::BROKEN, -1,
""},
// Labels starting with a RTL character can end with BC=EN (European
// number). Disallowed in IDNA 2003 but now allowed.
{"\xd8\xac\xd8\xa7\xd8\xb1"
"2",
L"\x62c\x627\x631"
L"2",
"xn--2-ymcov", Component(0, 11), CanonHostInfo::NEUTRAL, -1, ""},
// Labels starting with a RTL character cannot have "L" characters
// even if it ends with an BC=EN. Disallowed in both IDNA 2003/2008.
{"\xd8\xac\xd8\xa7\xd8\xb1xy2", L"\x62c\x627\x631xy2",
"%D8%AC%D8%A7%D8%B1xy2", Component(0, 21), CanonHostInfo::BROKEN, -1,
""},
// Labels starting with a RTL character can end with BC=AN (Arabic number)
// Disallowed in IDNA 2003, but now allowed.
{"\xd8\xac\xd8\xa7\xd8\xb1\xd9\xa2", L"\x62c\x627\x631\x662",
"xn--mgbjq0r", Component(0, 11), CanonHostInfo::NEUTRAL, -1, ""},
// Labels starting with a RTL character cannot have "L" characters
// even if it ends with an BC=AN (Arabic number).
// Disallowed in both IDNA 2003/2008.
{"\xd8\xac\xd8\xa7\xd8\xb1xy\xd9\xa2", L"\x62c\x627\x631xy\x662",
"%D8%AC%D8%A7%D8%B1xy%D9%A2", Component(0, 26), CanonHostInfo::BROKEN,
-1, ""},
// Labels starting with a RTL character cannot mix BC=EN and BC=AN
{"\xd8\xac\xd8\xa7\xd8\xb1xy2\xd9\xa2", L"\x62c\x627\x631xy2\x662",
"%D8%AC%D8%A7%D8%B1xy2%D9%A2", Component(0, 27), CanonHostInfo::BROKEN,
-1, ""},
// As of Unicode 6.2, U+20CF is not assigned. We do not allow it.
{"\xe2\x83\x8f.com", L"\x20cf.com", "%E2%83%8F.com", Component(0, 13),
CanonHostInfo::BROKEN, -1, ""},
// U+0080 is not allowed.
{"\xc2\x80.com", L"\x80.com", "%C2%80.com", Component(0, 10),
CanonHostInfo::BROKEN, -1, ""},
// Mixed UTF-8 and escaped UTF-8 (narrow case) and UTF-16 and escaped
// Mixed UTF-8 and escaped UTF-8 (narrow case) and UTF-16 and escaped
// UTF-8 (wide case). The output should be equivalent to the true wide
// character input above).
{"%E4%BD%A0%E5%A5%BD\xe4\xbd\xa0\xe5\xa5\xbd",
L"%E4%BD%A0%E5%A5%BD\x4f60\x597d", "xn--6qqa088eba", Component(0, 14),
CanonHostInfo::NEUTRAL, -1, ""},
// Invalid escaped characters should fail and the percents should be
// escaped.
{"%zz%66%a", L"%zz%66%a", "%25zzf%25a", Component(0, 10),
CanonHostInfo::BROKEN, -1, ""},
// If we get an invalid character that has been escaped.
{"%25", L"%25", "%25", Component(0, 3), CanonHostInfo::BROKEN, -1, ""},
{"hello%00", L"hello%00", "hello%00", Component(0, 8),
CanonHostInfo::BROKEN, -1, ""},
// Escaped numbers should be treated like IP addresses if they are.
{"%30%78%63%30%2e%30%32%35%30.01", L"%30%78%63%30%2e%30%32%35%30.01",
"192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0A80001"},
{"%30%78%63%30%2e%30%32%35%30.01%2e",
L"%30%78%63%30%2e%30%32%35%30.01%2e", "192.168.0.1", Component(0, 11),
CanonHostInfo::IPV4, 3, "C0A80001"},
// Invalid escaping should trigger the regular host error handling.
{"%3g%78%63%30%2e%30%32%35%30%2E.01",
L"%3g%78%63%30%2e%30%32%35%30%2E.01", "%253gxc0.0250..01",
Component(0, 17), CanonHostInfo::BROKEN, -1, ""},
// Something that isn't exactly an IP should get treated as a host and
// spaces escaped.
{"192.168.0.1 hello", L"192.168.0.1 hello", "192.168.0.1%20hello",
Component(0, 19), CanonHostInfo::NEUTRAL, -1, ""},
// Fullwidth and escaped UTF-8 fullwidth should still be treated as IP.
// These are "0Xc0.0250.01" in fullwidth.
{"\xef\xbc\x90%Ef%bc\xb8%ef%Bd%83\xef\xbc\x90%EF%BC%"
"8E\xef\xbc\x90\xef\xbc\x92\xef\xbc\x95\xef\xbc\x90\xef\xbc%"
"8E\xef\xbc\x90\xef\xbc\x91",
L"\xff10\xff38\xff43\xff10\xff0e\xff10\xff12\xff15\xff10\xff0e\xff10"
L"\xff11",
"192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0A80001"},
// Broken IP addresses get marked as such.
{"192.168.0.257", L"192.168.0.257", "192.168.0.257", Component(0, 13),
CanonHostInfo::BROKEN, -1, ""},
{"[google.com]", L"[google.com]", "[google.com]", Component(0, 12),
CanonHostInfo::BROKEN, -1, ""},
// Cyrillic letter followed by '(' should return punycode for '(' escaped
// before punycode string was created. I.e.
// if '(' is escaped after punycode is created we would get xn--%28-8tb
// (incorrect).
{"\xd1\x82(", L"\x0442(", "xn--%28-7ed", Component(0, 11),
CanonHostInfo::NEUTRAL, -1, ""},
// Address with all hexadecimal characters with leading number of 1<<32
// or greater and should return NEUTRAL rather than BROKEN if not all
// components are numbers.
{"12345678912345.de", L"12345678912345.de", "12345678912345.de",
Component(0, 17), CanonHostInfo::NEUTRAL, -1, ""},
{"1.12345678912345.de", L"1.12345678912345.de", "1.12345678912345.de",
Component(0, 19), CanonHostInfo::NEUTRAL, -1, ""},
{"12345678912345.12345678912345.de", L"12345678912345.12345678912345.de",
"12345678912345.12345678912345.de", Component(0, 32),
CanonHostInfo::NEUTRAL, -1, ""},
{"1.2.0xB3A73CE5B59.de", L"1.2.0xB3A73CE5B59.de", "1.2.0xb3a73ce5b59.de",
Component(0, 20), CanonHostInfo::NEUTRAL, -1, ""},
{"12345678912345.0xde", L"12345678912345.0xde", "12345678912345.0xde",
Component(0, 19), CanonHostInfo::BROKEN, -1, ""},
// A label that starts with "xn--" but contains non-ASCII characters
// should
// be an error. Escape the invalid characters.
{"xn--m\xc3\xbcnchen", L"xn--m\xfcnchen", "xn--m%C3%BCnchen",
Component(0, 16), CanonHostInfo::BROKEN, -1, ""},
};
// CanonicalizeHost() non-verbose.
std::string out_str;
for (size_t i = 0; i < std::size(host_cases); i++) {
// Narrow version.
if (host_cases[i].input8) {
int host_len = static_cast<int>(strlen(host_cases[i].input8));
Component in_comp(0, host_len);
Component out_comp;
out_str.clear();
StdStringCanonOutput output(&out_str);
bool success = CanonicalizeHost(host_cases[i].input8, in_comp, &output,
&out_comp);
output.Complete();
EXPECT_EQ(host_cases[i].expected_family != CanonHostInfo::BROKEN,
success) << "for input: " << host_cases[i].input8;
EXPECT_EQ(std::string(host_cases[i].expected), out_str) <<
"for input: " << host_cases[i].input8;
EXPECT_EQ(host_cases[i].expected_component.begin, out_comp.begin) <<
"for input: " << host_cases[i].input8;
EXPECT_EQ(host_cases[i].expected_component.len, out_comp.len) <<
"for input: " << host_cases[i].input8;
}
// Wide version.
if (host_cases[i].input16) {
std::u16string input16(
test_utils::TruncateWStringToUTF16(host_cases[i].input16));
int host_len = static_cast<int>(input16.length());
Component in_comp(0, host_len);
Component out_comp;
out_str.clear();
StdStringCanonOutput output(&out_str);
bool success = CanonicalizeHost(input16.c_str(), in_comp, &output,
&out_comp);
output.Complete();
EXPECT_EQ(host_cases[i].expected_family != CanonHostInfo::BROKEN,
success);
EXPECT_EQ(std::string(host_cases[i].expected), out_str);
EXPECT_EQ(host_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(host_cases[i].expected_component.len, out_comp.len);
}
}
// CanonicalizeHostVerbose()
for (size_t i = 0; i < std::size(host_cases); i++) {
// Narrow version.
if (host_cases[i].input8) {
int host_len = static_cast<int>(strlen(host_cases[i].input8));
Component in_comp(0, host_len);
out_str.clear();
StdStringCanonOutput output(&out_str);
CanonHostInfo host_info;
CanonicalizeHostVerbose(host_cases[i].input8, in_comp, &output,
&host_info);
output.Complete();
EXPECT_EQ(host_cases[i].expected_family, host_info.family);
EXPECT_EQ(std::string(host_cases[i].expected), out_str);
EXPECT_EQ(host_cases[i].expected_component.begin,
host_info.out_host.begin);
EXPECT_EQ(host_cases[i].expected_component.len, host_info.out_host.len);
EXPECT_EQ(std::string(host_cases[i].expected_address_hex),
BytesToHexString(host_info.address, host_info.AddressLength()));
if (host_cases[i].expected_family == CanonHostInfo::IPV4) {
EXPECT_EQ(host_cases[i].expected_num_ipv4_components,
host_info.num_ipv4_components);
}
}
// Wide version.
if (host_cases[i].input16) {
std::u16string input16(
test_utils::TruncateWStringToUTF16(host_cases[i].input16));
int host_len = static_cast<int>(input16.length());
Component in_comp(0, host_len);
out_str.clear();
StdStringCanonOutput output(&out_str);
CanonHostInfo host_info;
CanonicalizeHostVerbose(input16.c_str(), in_comp, &output, &host_info);
output.Complete();
EXPECT_EQ(host_cases[i].expected_family, host_info.family);
EXPECT_EQ(std::string(host_cases[i].expected), out_str);
EXPECT_EQ(host_cases[i].expected_component.begin,
host_info.out_host.begin);
EXPECT_EQ(host_cases[i].expected_component.len, host_info.out_host.len);
EXPECT_EQ(std::string(host_cases[i].expected_address_hex),
BytesToHexString(host_info.address, host_info.AddressLength()));
if (host_cases[i].expected_family == CanonHostInfo::IPV4) {
EXPECT_EQ(host_cases[i].expected_num_ipv4_components,
host_info.num_ipv4_components);
}
}
}
}
TEST(URLCanonTest, IPv4) {
// clang-format off
IPAddressCase cases[] = {
// Empty is not an IP address.
{"", L"", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{".", L".", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Regular IP addresses in different bases.
{"192.168.0.1", L"192.168.0.1", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
{"0300.0250.00.01", L"0300.0250.00.01", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
{"0xC0.0Xa8.0x0.0x1", L"0xC0.0Xa8.0x0.0x1", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
// Non-IP addresses due to invalid characters.
{"192.168.9.com", L"192.168.9.com", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Hostnames with a numeric final component but other components that don't
// parse as numbers should be considered broken.
{"19a.168.0.1", L"19a.168.0.1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"19a.168.0.1.", L"19a.168.0.1.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0308.0250.00.01", L"0308.0250.00.01", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0308.0250.00.01.", L"0308.0250.00.01.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0xCG.0xA8.0x0.0x1", L"0xCG.0xA8.0x0.0x1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0xCG.0xA8.0x0.0x1.", L"0xCG.0xA8.0x0.0x1.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Non-numeric terminal compeonent should be considered not IPv4 hostnames, but valid.
{"19.168.0.1a", L"19.168.0.1a", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"0xC.0xA8.0x0.0x1G", L"0xC.0xA8.0x0.0x1G", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Hostnames that would be considered broken IPv4 hostnames should be considered valid non-IPv4 hostnames if they end with two dots instead of 0 or 1.
{"19a.168.0.1..", L"19a.168.0.1..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"0308.0250.00.01..", L"0308.0250.00.01..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"0xCG.0xA8.0x0.0x1..", L"0xCG.0xA8.0x0.0x1..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Hosts with components that aren't considered valid IPv4 numbers but are entirely numeric should be considered invalid.
{"1.2.3.08", L"1.2.3.08", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"1.2.3.08.", L"1.2.3.08.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// If there are not enough components, the last one should fill them out.
{"192", L"192", "0.0.0.192", Component(0, 9), CanonHostInfo::IPV4, 1, "000000C0"},
{"0xC0a80001", L"0xC0a80001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 1, "C0A80001"},
{"030052000001", L"030052000001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 1, "C0A80001"},
{"000030052000001", L"000030052000001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 1, "C0A80001"},
{"192.168", L"192.168", "192.0.0.168", Component(0, 11), CanonHostInfo::IPV4, 2, "C00000A8"},
{"192.0x00A80001", L"192.0x000A80001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 2, "C0A80001"},
{"0xc0.052000001", L"0xc0.052000001", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 2, "C0A80001"},
{"192.168.1", L"192.168.1", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0A80001"},
// Hostnames with too many components, but a numeric final numeric component are invalid.
{"192.168.0.0.1", L"192.168.0.0.1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// We allow a single trailing dot.
{"192.168.0.1.", L"192.168.0.1.", "192.168.0.1", Component(0, 11), CanonHostInfo::IPV4, 4, "C0A80001"},
{"192.168.0.1. hello", L"192.168.0.1. hello", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"192.168.0.1..", L"192.168.0.1..", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Hosts with two dots in a row with a final numeric component are considered invalid.
{"192.168..1", L"192.168..1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"192.168..1.", L"192.168..1.", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Any numerical overflow should be marked as BROKEN.
{"0x100.0", L"0x100.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0x100.0.0", L"0x100.0.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0x100.0.0.0", L"0x100.0.0.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0.0x100.0.0", L"0.0x100.0.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0.0.0x100.0", L"0.0.0x100.0", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0.0.0.0x100", L"0.0.0.0x100", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0.0.0x10000", L"0.0.0x10000", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0.0x1000000", L"0.0x1000000", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0x100000000", L"0x100000000", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Repeat the previous tests, minus 1, to verify boundaries.
{"0xFF.0", L"0xFF.0", "255.0.0.0", Component(0, 9), CanonHostInfo::IPV4, 2, "FF000000"},
{"0xFF.0.0", L"0xFF.0.0", "255.0.0.0", Component(0, 9), CanonHostInfo::IPV4, 3, "FF000000"},
{"0xFF.0.0.0", L"0xFF.0.0.0", "255.0.0.0", Component(0, 9), CanonHostInfo::IPV4, 4, "FF000000"},
{"0.0xFF.0.0", L"0.0xFF.0.0", "0.255.0.0", Component(0, 9), CanonHostInfo::IPV4, 4, "00FF0000"},
{"0.0.0xFF.0", L"0.0.0xFF.0", "0.0.255.0", Component(0, 9), CanonHostInfo::IPV4, 4, "0000FF00"},
{"0.0.0.0xFF", L"0.0.0.0xFF", "0.0.0.255", Component(0, 9), CanonHostInfo::IPV4, 4, "000000FF"},
{"0.0.0xFFFF", L"0.0.0xFFFF", "0.0.255.255", Component(0, 11), CanonHostInfo::IPV4, 3, "0000FFFF"},
{"0.0xFFFFFF", L"0.0xFFFFFF", "0.255.255.255", Component(0, 13), CanonHostInfo::IPV4, 2, "00FFFFFF"},
{"0xFFFFFFFF", L"0xFFFFFFFF", "255.255.255.255", Component(0, 15), CanonHostInfo::IPV4, 1, "FFFFFFFF"},
// Old trunctations tests. They're all "BROKEN" now.
{"276.256.0xf1a2.077777", L"276.256.0xf1a2.077777", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"192.168.0.257", L"192.168.0.257", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"192.168.0xa20001", L"192.168.0xa20001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"192.015052000001", L"192.015052000001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"0X12C0a80001", L"0X12C0a80001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"276.1.2", L"276.1.2", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Too many components should be rejected, in valid ranges or not.
{"255.255.255.255.255", L"255.255.255.255.255", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"256.256.256.256.256", L"256.256.256.256.256", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Spaces should be rejected.
{"192.168.0.1 hello", L"192.168.0.1 hello", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Very large numbers.
{"0000000000000300.0x00000000000000fF.00000000000000001", L"0000000000000300.0x00000000000000fF.00000000000000001", "192.255.0.1", Component(0, 11), CanonHostInfo::IPV4, 3, "C0FF0001"},
{"0000000000000300.0xffffffffFFFFFFFF.3022415481470977", L"0000000000000300.0xffffffffFFFFFFFF.3022415481470977", "", Component(0, 11), CanonHostInfo::BROKEN, -1, ""},
// A number has no length limit, but long numbers can still overflow.
{"00000000000000000001", L"00000000000000000001", "0.0.0.1", Component(0, 7), CanonHostInfo::IPV4, 1, "00000001"},
{"0000000000000000100000000000000001", L"0000000000000000100000000000000001", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// If a long component is non-numeric, it's a hostname, *not* a broken IP.
{"0.0.0.000000000000000000z", L"0.0.0.000000000000000000z", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"0.0.0.100000000000000000z", L"0.0.0.100000000000000000z", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Truncation of all zeros should still result in 0.
{"0.00.0x.0x0", L"0.00.0x.0x0", "0.0.0.0", Component(0, 7), CanonHostInfo::IPV4, 4, "00000000"},
// Non-ASCII characters in final component should return NEUTRAL.
{"1.2.3.\xF0\x9F\x92\xA9", L"1.2.3.\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"1.2.3.4\xF0\x9F\x92\xA9", L"1.2.3.4\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"1.2.3.0x\xF0\x9F\x92\xA9", L"1.2.3.0x\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
{"1.2.3.0\xF0\x9F\x92\xA9", L"1.2.3.0\xD83D\xDCA9", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Non-ASCII characters in other components should result in broken IPs when final component is numeric.
{"1.2.\xF0\x9F\x92\xA9.4", L"1.2.\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"1.2.3\xF0\x9F\x92\xA9.4", L"1.2.3\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"1.2.0x\xF0\x9F\x92\xA9.4", L"1.2.0x\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"1.2.0\xF0\x9F\x92\xA9.4", L"1.2.0\xD83D\xDCA9.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"\xF0\x9F\x92\xA9.2.3.4", L"\xD83D\xDCA9.2.3.4", "", Component(), CanonHostInfo::BROKEN, -1, ""},
};
// clang-format on
for (const auto& test_case : cases) {
SCOPED_TRACE(test_case.input8);
// 8-bit version.
Component component(0, static_cast<int>(strlen(test_case.input8)));
std::string out_str1;
StdStringCanonOutput output1(&out_str1);
CanonHostInfo host_info;
CanonicalizeIPAddress(test_case.input8, component, &output1, &host_info);
output1.Complete();
EXPECT_EQ(test_case.expected_family, host_info.family);
EXPECT_EQ(std::string(test_case.expected_address_hex),
BytesToHexString(host_info.address, host_info.AddressLength()));
if (host_info.family == CanonHostInfo::IPV4) {
EXPECT_STREQ(test_case.expected, out_str1.c_str());
EXPECT_EQ(test_case.expected_component.begin, host_info.out_host.begin);
EXPECT_EQ(test_case.expected_component.len, host_info.out_host.len);
EXPECT_EQ(test_case.expected_num_ipv4_components,
host_info.num_ipv4_components);
}
// 16-bit version.
std::u16string input16(
test_utils::TruncateWStringToUTF16(test_case.input16));
component = Component(0, static_cast<int>(input16.length()));
std::string out_str2;
StdStringCanonOutput output2(&out_str2);
CanonicalizeIPAddress(input16.c_str(), component, &output2, &host_info);
output2.Complete();
EXPECT_EQ(test_case.expected_family, host_info.family);
EXPECT_EQ(std::string(test_case.expected_address_hex),
BytesToHexString(host_info.address, host_info.AddressLength()));
if (host_info.family == CanonHostInfo::IPV4) {
EXPECT_STREQ(test_case.expected, out_str2.c_str());
EXPECT_EQ(test_case.expected_component.begin, host_info.out_host.begin);
EXPECT_EQ(test_case.expected_component.len, host_info.out_host.len);
EXPECT_EQ(test_case.expected_num_ipv4_components,
host_info.num_ipv4_components);
}
}
}
class URLCanonIPv6Test
: public ::testing::Test,
public ::testing::WithParamInterface<bool> {
public:
URLCanonIPv6Test() {
if (GetParam()) {
scoped_feature_list_.InitAndEnableFeature(kStrictIPv4EmbeddedIPv6AddressParsing);
} else {
scoped_feature_list_.InitAndDisableFeature(kStrictIPv4EmbeddedIPv6AddressParsing);
}
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
URLCanonIPv6Test,
::testing::Bool());
TEST_P(URLCanonIPv6Test, IPv6) {
bool strict_ipv4_embedded_ipv6_parsing =
base::FeatureList::IsEnabled(url::kStrictIPv4EmbeddedIPv6AddressParsing);
IPAddressCase cases[] = {
// Empty is not an IP address.
{"", L"", "", Component(), CanonHostInfo::NEUTRAL, -1, ""},
// Non-IPs with [:] characters are marked BROKEN.
{":", L":", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[", L"[", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[:", L"[:", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"]", L"]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{":]", L":]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[]", L"[]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[:]", L"[:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Regular IP address is invalid without bounding '[' and ']'.
{"2001:db8::1", L"2001:db8::1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[2001:db8::1", L"[2001:db8::1", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"2001:db8::1]", L"2001:db8::1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Regular IP addresses.
{"[::]", L"[::]", "[::]", Component(0,4), CanonHostInfo::IPV6, -1, "00000000000000000000000000000000"},
{"[::1]", L"[::1]", "[::1]", Component(0,5), CanonHostInfo::IPV6, -1, "00000000000000000000000000000001"},
{"[1::]", L"[1::]", "[1::]", Component(0,5), CanonHostInfo::IPV6, -1, "00010000000000000000000000000000"},
// Leading zeros should be stripped.
{"[000:01:02:003:004:5:6:007]", L"[000:01:02:003:004:5:6:007]", "[0:1:2:3:4:5:6:7]", Component(0,17), CanonHostInfo::IPV6, -1, "00000001000200030004000500060007"},
// Upper case letters should be lowercased.
{"[A:b:c:DE:fF:0:1:aC]", L"[A:b:c:DE:fF:0:1:aC]", "[a:b:c:de:ff:0:1:ac]", Component(0,20), CanonHostInfo::IPV6, -1, "000A000B000C00DE00FF0000000100AC"},
// The same address can be written with different contractions, but should
// get canonicalized to the same thing.
{"[1:0:0:2::3:0]", L"[1:0:0:2::3:0]", "[1::2:0:0:3:0]", Component(0,14), CanonHostInfo::IPV6, -1, "00010000000000020000000000030000"},
{"[1::2:0:0:3:0]", L"[1::2:0:0:3:0]", "[1::2:0:0:3:0]", Component(0,14), CanonHostInfo::IPV6, -1, "00010000000000020000000000030000"},
// Addresses with embedded IPv4.
{"[::192.168.0.1]", L"[::192.168.0.1]", "[::c0a8:1]", Component(0,10), CanonHostInfo::IPV6, -1, "000000000000000000000000C0A80001"},
{"[::ffff:192.168.0.1]", L"[::ffff:192.168.0.1]", "[::ffff:c0a8:1]", Component(0,15), CanonHostInfo::IPV6, -1, "00000000000000000000FFFFC0A80001"},
{"[::eeee:192.168.0.1]", L"[::eeee:192.168.0.1]", "[::eeee:c0a8:1]", Component(0, 15), CanonHostInfo::IPV6, -1, "00000000000000000000EEEEC0A80001"},
{"[2001::192.168.0.1]", L"[2001::192.168.0.1]", "[2001::c0a8:1]", Component(0, 14), CanonHostInfo::IPV6, -1, "200100000000000000000000C0A80001"},
{"[1:2:192.168.0.1:5:6]", L"[1:2:192.168.0.1:5:6]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// IPv4 embedded IPv6 addresses
{"[::ffff:192.1.2]",
L"[::ffff:192.1.2]",
"[::ffff:c001:2]",
strict_ipv4_embedded_ipv6_parsing ? Component() : Component(0,15),
strict_ipv4_embedded_ipv6_parsing ? CanonHostInfo::BROKEN : CanonHostInfo::IPV6,
-1,
(strict_ipv4_embedded_ipv6_parsing ? "" : "00000000000000000000FFFFC0010002")},
{"[::ffff:192.1]",
L"[::ffff:192.1]",
"[::ffff:c000:1]",
strict_ipv4_embedded_ipv6_parsing ? Component() : Component(0,15),
strict_ipv4_embedded_ipv6_parsing ? CanonHostInfo::BROKEN : CanonHostInfo::IPV6,
-1,
(strict_ipv4_embedded_ipv6_parsing ? "" : "00000000000000000000FFFFC0000001")},
{"[::ffff:192.1.2.3.4]",
L"[::ffff:192.1.2.3.4]",
"", Component(), CanonHostInfo::BROKEN, -1, ""},
// IPv4 using hex.
// TODO(eroman): Should this format be disallowed?
{"[::ffff:0xC0.0Xa8.0x0.0x1]", L"[::ffff:0xC0.0Xa8.0x0.0x1]", "[::ffff:c0a8:1]", Component(0,15), CanonHostInfo::IPV6, -1, "00000000000000000000FFFFC0A80001"},
// There may be zeros surrounding the "::" contraction.
{"[0:0::0:0:8]", L"[0:0::0:0:8]", "[::8]", Component(0,5), CanonHostInfo::IPV6, -1, "00000000000000000000000000000008"},
{"[2001:db8::1]", L"[2001:db8::1]", "[2001:db8::1]", Component(0,13), CanonHostInfo::IPV6, -1, "20010DB8000000000000000000000001"},
// Can only have one "::" contraction in an IPv6 string literal.
{"[2001::db8::1]", L"[2001::db8::1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// No more than 2 consecutive ':'s.
{"[2001:db8:::1]", L"[2001:db8:::1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[:::]", L"[:::]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Non-IP addresses due to invalid characters.
{"[2001::.com]", L"[2001::.com]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// If there are not enough components, the last one should fill them out.
// ... omitted at this time ...
// Too many components means not an IP address. Similarly, with too few
// if using IPv4 compat or mapped addresses.
{"[::192.168.0.0.1]", L"[::192.168.0.0.1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[::ffff:192.168.0.0.1]", L"[::ffff:192.168.0.0.1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[1:2:3:4:5:6:7:8:9]", L"[1:2:3:4:5:6:7:8:9]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Too many bits (even though 8 comonents, the last one holds 32 bits).
{"[0:0:0:0:0:0:0:192.168.0.1]", L"[0:0:0:0:0:0:0:192.168.0.1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Too many bits specified -- the contraction would have to be zero-length
// to not exceed 128 bits.
{"[1:2:3:4:5:6::192.168.0.1]", L"[1:2:3:4:5:6::192.168.0.1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// The contraction is for 16 bits of zero.
{"[1:2:3:4:5:6::8]", L"[1:2:3:4:5:6::8]", "[1:2:3:4:5:6:0:8]", Component(0,17), CanonHostInfo::IPV6, -1, "00010002000300040005000600000008"},
// Cannot have a trailing colon.
{"[1:2:3:4:5:6:7:8:]", L"[1:2:3:4:5:6:7:8:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[1:2:3:4:5:6:192.168.0.1:]", L"[1:2:3:4:5:6:192.168.0.1:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Cannot have negative numbers.
{"[-1:2:3:4:5:6:7:8]", L"[-1:2:3:4:5:6:7:8]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Scope ID -- the URL may contain an optional ["%" <scope_id>] section.
// The scope_id should be included in the canonicalized URL, and is an
// unsigned decimal number.
// Invalid because no ID was given after the percent.
// Don't allow scope-id
{"[1::%1]", L"[1::%1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[1::%eth0]", L"[1::%eth0]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[1::%]", L"[1::%]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[%]", L"[%]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[::%:]", L"[::%:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Don't allow leading or trailing colons.
{"[:0:0::0:0:8]", L"[:0:0::0:0:8]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[0:0::0:0:8:]", L"[0:0::0:0:8:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
{"[:0:0::0:0:8:]", L"[:0:0::0:0:8:]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// We allow a single trailing dot.
// ... omitted at this time ...
// Two dots in a row means not an IP address.
{"[::192.168..1]", L"[::192.168..1]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
// Any non-first components get truncated to one byte.
// ... omitted at this time ...
// Spaces should be rejected.
{"[::1 hello]", L"[::1 hello]", "", Component(), CanonHostInfo::BROKEN, -1, ""},
};
for (size_t i = 0; i < std::size(cases); i++) {
// 8-bit version.
Component component(0, static_cast<int>(strlen(cases[i].input8)));
std::string out_str1;
StdStringCanonOutput output1(&out_str1);
CanonHostInfo host_info;
CanonicalizeIPAddress(cases[i].input8, component, &output1, &host_info);
output1.Complete();
EXPECT_EQ(cases[i].expected_family, host_info.family);
EXPECT_EQ(std::string(cases[i].expected_address_hex),
BytesToHexString(host_info.address, host_info.AddressLength())) << "iter " << i << " host " << cases[i].input8;
if (host_info.family == CanonHostInfo::IPV6) {
EXPECT_STREQ(cases[i].expected, out_str1.c_str());
EXPECT_EQ(cases[i].expected_component.begin,
host_info.out_host.begin);
EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
}
// 16-bit version.
std::u16string input16(
test_utils::TruncateWStringToUTF16(cases[i].input16));
component = Component(0, static_cast<int>(input16.length()));
std::string out_str2;
StdStringCanonOutput output2(&out_str2);
CanonicalizeIPAddress(input16.c_str(), component, &output2, &host_info);
output2.Complete();
EXPECT_EQ(cases[i].expected_family, host_info.family);
EXPECT_EQ(std::string(cases[i].expected_address_hex),
BytesToHexString(host_info.address, host_info.AddressLength()));
if (host_info.family == CanonHostInfo::IPV6) {
EXPECT_STREQ(cases[i].expected, out_str2.c_str());
EXPECT_EQ(cases[i].expected_component.begin, host_info.out_host.begin);
EXPECT_EQ(cases[i].expected_component.len, host_info.out_host.len);
}
}
}
TEST(URLCanonTest, IPEmpty) {
std::string out_str1;
StdStringCanonOutput output1(&out_str1);
CanonHostInfo host_info;
// This tests tests.
const char spec[] = "192.168.0.1";
CanonicalizeIPAddress(spec, Component(), &output1, &host_info);
EXPECT_FALSE(host_info.IsIPAddress());
CanonicalizeIPAddress(spec, Component(0, 0), &output1, &host_info);
EXPECT_FALSE(host_info.IsIPAddress());
}
// Verifies that CanonicalizeHostSubstring produces the expected output and
// does not "fix" IP addresses. Because this code is a subset of
// CanonicalizeHost, the shared functionality is not tested.
TEST(URLCanonTest, CanonicalizeHostSubstring) {
// Basic sanity check.
{
std::string out_str;
StdStringCanonOutput output(&out_str);
EXPECT_TRUE(CanonicalizeHostSubstring("M\xc3\x9cNCHEN.com",
Component(0, 12), &output));
output.Complete();
EXPECT_EQ("xn--mnchen-3ya.com", out_str);
}
// Failure case.
{
std::string out_str;
StdStringCanonOutput output(&out_str);
EXPECT_FALSE(CanonicalizeHostSubstring(
test_utils::TruncateWStringToUTF16(L"\xfdd0zyx.com").c_str(),
Component(0, 8), &output));
output.Complete();
EXPECT_EQ("%EF%BF%BDzyx.com", out_str);
}
// Should return true for empty input strings.
{
std::string out_str;
StdStringCanonOutput output(&out_str);
EXPECT_TRUE(CanonicalizeHostSubstring("", Component(0, 0), &output));
output.Complete();
EXPECT_EQ(std::string(), out_str);
}
// Numbers that look like IP addresses should not be changed.
{
std::string out_str;
StdStringCanonOutput output(&out_str);
EXPECT_TRUE(
CanonicalizeHostSubstring("01.02.03.04", Component(0, 11), &output));
output.Complete();
EXPECT_EQ("01.02.03.04", out_str);
}
}
TEST(URLCanonTest, UserInfo) {
// Note that the canonicalizer should escape and treat empty components as
// not being there.
// We actually parse a full input URL so we can get the initial components.
struct UserComponentCase {
const char* input;
const char* expected;
Component expected_username;
Component expected_password;
bool expected_success;
} user_info_cases[] = {
{"http://user:pass@host.com/", "user:pass@", Component(0, 4), Component(5, 4), true},
{"http://@host.com/", "", Component(0, -1), Component(0, -1), true},
{"http://:@host.com/", "", Component(0, -1), Component(0, -1), true},
{"http://foo:@host.com/", "foo@", Component(0, 3), Component(0, -1), true},
{"http://:foo@host.com/", ":foo@", Component(0, 0), Component(1, 3), true},
{"http://^ :$\t@host.com/", "%5E%20:$%09@", Component(0, 6), Component(7, 4), true},
{"http://user:pass@/", "user:pass@", Component(0, 4), Component(5, 4), true},
{"http://%2540:bar@domain.com/", "%2540:bar@", Component(0, 5), Component(6, 3), true },
// IE7 compatibility: old versions allowed backslashes in usernames, but
// IE7 does not. We disallow it as well.
{"ftp://me\\mydomain:pass@foo.com/", "", Component(0, -1), Component(0, -1), true},
};
for (size_t i = 0; i < std::size(user_info_cases); i++) {
int url_len = static_cast<int>(strlen(user_info_cases[i].input));
Parsed parsed;
ParseStandardURL(user_info_cases[i].input, url_len, &parsed);
Component out_user, out_pass;
std::string out_str;
StdStringCanonOutput output1(&out_str);
bool success = CanonicalizeUserInfo(user_info_cases[i].input,
parsed.username,
user_info_cases[i].input,
parsed.password,
&output1,
&out_user,
&out_pass);
output1.Complete();
EXPECT_EQ(user_info_cases[i].expected_success, success);
EXPECT_EQ(std::string(user_info_cases[i].expected), out_str);
EXPECT_EQ(user_info_cases[i].expected_username.begin, out_user.begin);
EXPECT_EQ(user_info_cases[i].expected_username.len, out_user.len);
EXPECT_EQ(user_info_cases[i].expected_password.begin, out_pass.begin);
EXPECT_EQ(user_info_cases[i].expected_password.len, out_pass.len);
// Now try the wide version
out_str.clear();
StdStringCanonOutput output2(&out_str);
std::u16string wide_input(base::UTF8ToUTF16(user_info_cases[i].input));
success = CanonicalizeUserInfo(wide_input.c_str(),
parsed.username,
wide_input.c_str(),
parsed.password,
&output2,
&out_user,
&out_pass);
output2.Complete();
EXPECT_EQ(user_info_cases[i].expected_success, success);
EXPECT_EQ(std::string(user_info_cases[i].expected), out_str);
EXPECT_EQ(user_info_cases[i].expected_username.begin, out_user.begin);
EXPECT_EQ(user_info_cases[i].expected_username.len, out_user.len);
EXPECT_EQ(user_info_cases[i].expected_password.begin, out_pass.begin);
EXPECT_EQ(user_info_cases[i].expected_password.len, out_pass.len);
}
}
TEST(URLCanonTest, Port) {
// We only need to test that the number gets properly put into the output
// buffer. The parser unit tests will test scanning the number correctly.
//
// Note that the CanonicalizePort will always prepend a colon to the output
// to separate it from the colon that it assumes precedes it.
struct PortCase {
const char* input;
int default_port;
const char* expected;
Component expected_component;
bool expected_success;
} port_cases[] = {
// Invalid input should be copied w/ failure.
{"as df", 80, ":as%20df", Component(1, 7), false},
{"-2", 80, ":-2", Component(1, 2), false},
// Default port should be omitted.
{"80", 80, "", Component(0, -1), true},
{"8080", 80, ":8080", Component(1, 4), true},
// PORT_UNSPECIFIED should mean always keep the port.
{"80", PORT_UNSPECIFIED, ":80", Component(1, 2), true},
};
for (size_t i = 0; i < std::size(port_cases); i++) {
int url_len = static_cast<int>(strlen(port_cases[i].input));
Component in_comp(0, url_len);
Component out_comp;
std::string out_str;
StdStringCanonOutput output1(&out_str);
bool success = CanonicalizePort(port_cases[i].input,
in_comp,
port_cases[i].default_port,
&output1,
&out_comp);
output1.Complete();
EXPECT_EQ(port_cases[i].expected_success, success);
EXPECT_EQ(std::string(port_cases[i].expected), out_str);
EXPECT_EQ(port_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(port_cases[i].expected_component.len, out_comp.len);
// Now try the wide version
out_str.clear();
StdStringCanonOutput output2(&out_str);
std::u16string wide_input(base::UTF8ToUTF16(port_cases[i].input));
success = CanonicalizePort(wide_input.c_str(),
in_comp,
port_cases[i].default_port,
&output2,
&out_comp);
output2.Complete();
EXPECT_EQ(port_cases[i].expected_success, success);
EXPECT_EQ(std::string(port_cases[i].expected), out_str);
EXPECT_EQ(port_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(port_cases[i].expected_component.len, out_comp.len);
}
}
DualComponentCase kCommonPathCases[] = {
// ----- path collapsing tests -----
{"/././foo", L"/././foo", "/foo", Component(0, 4), true},
{"/./.foo", L"/./.foo", "/.foo", Component(0, 5), true},
{"/foo/.", L"/foo/.", "/foo/", Component(0, 5), true},
{"/foo/./", L"/foo/./", "/foo/", Component(0, 5), true},
// double dots followed by a slash or the end of the string count
{"/foo/bar/..", L"/foo/bar/..", "/foo/", Component(0, 5), true},
{"/foo/bar/../", L"/foo/bar/../", "/foo/", Component(0, 5), true},
// don't count double dots when they aren't followed by a slash
{"/foo/..bar", L"/foo/..bar", "/foo/..bar", Component(0, 10), true},
// some in the middle
{"/foo/bar/../ton", L"/foo/bar/../ton", "/foo/ton", Component(0, 8), true},
{"/foo/bar/../ton/../../a", L"/foo/bar/../ton/../../a", "/a",
Component(0, 2), true},
// we should not be able to go above the root
{"/foo/../../..", L"/foo/../../..", "/", Component(0, 1), true},
{"/foo/../../../ton", L"/foo/../../../ton", "/ton", Component(0, 4), true},
// escaped dots should be unescaped and treated the same as dots
{"/foo/%2e", L"/foo/%2e", "/foo/", Component(0, 5), true},
{"/foo/%2e%2", L"/foo/%2e%2", "/foo/.%2", Component(0, 8), true},
{"/foo/%2e./%2e%2e/.%2e/%2e.bar", L"/foo/%2e./%2e%2e/.%2e/%2e.bar",
"/..bar", Component(0, 6), true},
// Multiple slashes in a row should be preserved and treated like empty
// directory names.
{"////../..", L"////../..", "//", Component(0, 2), true},
// ----- escaping tests -----
{"/foo", L"/foo", "/foo", Component(0, 4), true},
// Valid escape sequence
{"/%20foo", L"/%20foo", "/%20foo", Component(0, 7), true},
// Invalid escape sequence we should pass through unchanged.
{"/foo%", L"/foo%", "/foo%", Component(0, 5), true},
{"/foo%2", L"/foo%2", "/foo%2", Component(0, 6), true},
// Invalid escape sequence: bad characters should be treated the same as
// the surrounding text, not as escaped (in this case, UTF-8).
{"/foo%2zbar", L"/foo%2zbar", "/foo%2zbar", Component(0, 10), true},
{"/foo%2\xc2\xa9zbar", nullptr, "/foo%2%C2%A9zbar", Component(0, 16), true},
{nullptr, L"/foo%2\xc2\xa9zbar", "/foo%2%C3%82%C2%A9zbar", Component(0, 22),
true},
// Regular characters that are escaped should be unescaped
{"/foo%41%7a", L"/foo%41%7a", "/fooAz", Component(0, 6), true},
// Funny characters that are unescaped should be escaped
{"/foo\x09\x91%91", nullptr, "/foo%09%91%91", Component(0, 13), true},
{nullptr, L"/foo\x09\x91%91", "/foo%09%C2%91%91", Component(0, 16), true},
// Invalid characters that are escaped should cause a failure.
{"/foo%00%51", L"/foo%00%51", "/foo%00Q", Component(0, 8), false},
// Some characters should be passed through unchanged regardless of esc.
{"/(%28:%3A%29)", L"/(%28:%3A%29)", "/(%28:%3A%29)", Component(0, 13),
true},
// Characters that are properly escaped should not have the case changed
// of hex letters.
{"/%3A%3a%3C%3c", L"/%3A%3a%3C%3c", "/%3A%3a%3C%3c", Component(0, 13),
true},
// Funny characters that are unescaped should be escaped
{"/foo\tbar", L"/foo\tbar", "/foo%09bar", Component(0, 10), true},
// Backslashes should get converted to forward slashes
{"\\foo\\bar", L"\\foo\\bar", "/foo/bar", Component(0, 8), true},
// Hashes found in paths (possibly only when the caller explicitly sets
// the path on an already-parsed URL) should be escaped.
{"/foo#bar", L"/foo#bar", "/foo%23bar", Component(0, 10), true},
// %7f should be allowed and %3D should not be unescaped (these were wrong
// in a previous version).
{"/%7Ffp3%3Eju%3Dduvgw%3Dd", L"/%7Ffp3%3Eju%3Dduvgw%3Dd",
"/%7Ffp3%3Eju%3Dduvgw%3Dd", Component(0, 24), true},
// @ should be passed through unchanged (escaped or unescaped).
{"/@asdf%40", L"/@asdf%40", "/@asdf%40", Component(0, 9), true},
// Nested escape sequences should result in escaping the leading '%' if
// unescaping would result in a new escape sequence.
{"/%A%42", L"/%A%42", "/%25AB", Component(0, 6), true},
{"/%%41B", L"/%%41B", "/%25AB", Component(0, 6), true},
{"/%%41%42", L"/%%41%42", "/%25AB", Component(0, 6), true},
// Make sure truncated "nested" escapes don't result in reading off the
// string end.
{"/%%41", L"/%%41", "/%A", Component(0, 3), true},
// Don't unescape the leading '%' if unescaping doesn't result in a valid
// new escape sequence.
{"/%%470", L"/%%470", "/%G0", Component(0, 4), true},
{"/%%2D%41", L"/%%2D%41", "/%-A", Component(0, 4), true},
// Don't erroneously downcast a UTF-16 character in a way that makes it
// look like part of an escape sequence.
{nullptr, L"/%%41\x0130", "/%A%C4%B0", Component(0, 9), true},
// ----- encoding tests -----
// Basic conversions
{"/\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xbd\xa0\xe5\xa5\xbd",
L"/\x4f60\x597d\x4f60\x597d", "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD",
Component(0, 37), true},
// Invalid unicode characters should fail. We only do validation on
// UTF-16 input, so this doesn't happen on 8-bit.
{"/\xef\xb7\x90zyx", nullptr, "/%EF%B7%90zyx", Component(0, 13), true},
{nullptr, L"/\xfdd0zyx", "/%EF%BF%BDzyx", Component(0, 13), false},
};
typedef bool (*CanonFunc8Bit)(const char*,
const Component&,
CanonOutput*,
Component*);
typedef bool (*CanonFunc16Bit)(const char16_t*,
const Component&,
CanonOutput*,
Component*);
void DoPathTest(const DualComponentCase* path_cases,
size_t num_cases,
CanonFunc8Bit canon_func_8,
CanonFunc16Bit canon_func_16) {
for (size_t i = 0; i < num_cases; i++) {
testing::Message scope_message;
scope_message << path_cases[i].input8 << "," << path_cases[i].input16;
SCOPED_TRACE(scope_message);
if (path_cases[i].input8) {
int len = static_cast<int>(strlen(path_cases[i].input8));
Component in_comp(0, len);
Component out_comp;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success =
canon_func_8(path_cases[i].input8, in_comp, &output, &out_comp);
output.Complete();
EXPECT_EQ(path_cases[i].expected_success, success);
EXPECT_EQ(path_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(path_cases[i].expected_component.len, out_comp.len);
EXPECT_EQ(path_cases[i].expected, out_str);
}
if (path_cases[i].input16) {
std::u16string input16(
test_utils::TruncateWStringToUTF16(path_cases[i].input16));
int len = static_cast<int>(input16.length());
Component in_comp(0, len);
Component out_comp;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success =
canon_func_16(input16.c_str(), in_comp, &output, &out_comp);
output.Complete();
EXPECT_EQ(path_cases[i].expected_success, success);
EXPECT_EQ(path_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(path_cases[i].expected_component.len, out_comp.len);
EXPECT_EQ(path_cases[i].expected, out_str);
}
}
}
TEST(URLCanonTest, Path) {
DoPathTest(kCommonPathCases, std::size(kCommonPathCases), CanonicalizePath,
CanonicalizePath);
// Manual test: embedded NULLs should be escaped and the URL should be marked
// as invalid.
const char path_with_null[] = "/ab\0c";
Component in_comp(0, 5);
Component out_comp;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success = CanonicalizePath(path_with_null, in_comp, &output, &out_comp);
output.Complete();
EXPECT_FALSE(success);
EXPECT_EQ("/ab%00c", out_str);
}
TEST(URLCanonTest, PartialPath) {
DualComponentCase partial_path_cases[] = {
{".html", L".html", ".html", Component(0, 5), true},
{"", L"", "", Component(0, 0), true},
};
DoPathTest(kCommonPathCases, std::size(kCommonPathCases),
CanonicalizePartialPath, CanonicalizePartialPath);
DoPathTest(partial_path_cases, std::size(partial_path_cases),
CanonicalizePartialPath, CanonicalizePartialPath);
}
TEST(URLCanonTest, Query) {
struct QueryCase {
const char* input8;
const wchar_t* input16;
const char* expected;
} query_cases[] = {
// Regular ASCII case.
{"foo=bar", L"foo=bar", "?foo=bar"},
// Allow question marks in the query without escaping
{"as?df", L"as?df", "?as?df"},
// Always escape '#' since it would mark the ref.
{"as#df", L"as#df", "?as%23df"},
// Escape some questionable 8-bit characters, but never unescape.
{"\x02hello\x7f bye", L"\x02hello\x7f bye", "?%02hello%7F%20bye"},
{"%40%41123", L"%40%41123", "?%40%41123"},
// Chinese input/output
{"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", "?q=%E4%BD%A0%E5%A5%BD"},
// Invalid UTF-8/16 input should be replaced with invalid characters.
{"q=\xed\xed", L"q=\xd800\xd800", "?q=%EF%BF%BD%EF%BF%BD"},
// Don't allow < or > because sometimes they are used for XSS if the
// URL is echoed in content. Firefox does this, IE doesn't.
{"q=<asdf>", L"q=<asdf>", "?q=%3Casdf%3E"},
// Escape double quotemarks in the query.
{"q=\"asdf\"", L"q=\"asdf\"", "?q=%22asdf%22"},
};
for (size_t i = 0; i < std::size(query_cases); i++) {
Component out_comp;
if (query_cases[i].input8) {
int len = static_cast<int>(strlen(query_cases[i].input8));
Component in_comp(0, len);
std::string out_str;
StdStringCanonOutput output(&out_str);
CanonicalizeQuery(query_cases[i].input8, in_comp, NULL, &output,
&out_comp);
output.Complete();
EXPECT_EQ(query_cases[i].expected, out_str);
}
if (query_cases[i].input16) {
std::u16string input16(
test_utils::TruncateWStringToUTF16(query_cases[i].input16));
int len = static_cast<int>(input16.length());
Component in_comp(0, len);
std::string out_str;
StdStringCanonOutput output(&out_str);
CanonicalizeQuery(input16.c_str(), in_comp, NULL, &output, &out_comp);
output.Complete();
EXPECT_EQ(query_cases[i].expected, out_str);
}
}
// Extra test for input with embedded NULL;
std::string out_str;
StdStringCanonOutput output(&out_str);
Component out_comp;
CanonicalizeQuery("a \x00z\x01", Component(0, 5), NULL, &output, &out_comp);
output.Complete();
EXPECT_EQ("?a%20%00z%01", out_str);
}
TEST(URLCanonTest, Ref) {
// Refs are trivial, it just checks the encoding.
DualComponentCase ref_cases[] = {
{"hello!", L"hello!", "#hello!", Component(1, 6), true},
// We should escape spaces, double-quotes, angled braces, and backtics.
{"hello, world", L"hello, world", "#hello,%20world", Component(1, 14),
true},
{"hello,\"world", L"hello,\"world", "#hello,%22world", Component(1, 14),
true},
{"hello,<world", L"hello,<world", "#hello,%3Cworld", Component(1, 14),
true},
{"hello,>world", L"hello,>world", "#hello,%3Eworld", Component(1, 14),
true},
{"hello,`world", L"hello,`world", "#hello,%60world", Component(1, 14),
true},
// UTF-8/wide input should be preserved
{"\xc2\xa9", L"\xa9", "#%C2%A9", Component(1, 6), true},
// Test a characer that takes > 16 bits (U+10300 = old italic letter A)
{"\xF0\x90\x8C\x80ss", L"\xd800\xdf00ss", "#%F0%90%8C%80ss",
Component(1, 14), true},
// Escaping should be preserved unchanged, even invalid ones
{"%41%a", L"%41%a", "#%41%a", Component(1, 5), true},
// Invalid UTF-8/16 input should be flagged and the input made valid
{"\xc2", nullptr, "#%EF%BF%BD", Component(1, 9), true},
{nullptr, L"\xd800\x597d", "#%EF%BF%BD%E5%A5%BD", Component(1, 18), true},
// Test a Unicode invalid character.
{"a\xef\xb7\x90", L"a\xfdd0", "#a%EF%BF%BD", Component(1, 10), true},
// Refs can have # signs and we should preserve them.
{"asdf#qwer", L"asdf#qwer", "#asdf#qwer", Component(1, 9), true},
{"#asdf", L"#asdf", "##asdf", Component(1, 5), true},
};
for (size_t i = 0; i < std::size(ref_cases); i++) {
// 8-bit input
if (ref_cases[i].input8) {
int len = static_cast<int>(strlen(ref_cases[i].input8));
Component in_comp(0, len);
Component out_comp;
std::string out_str;
StdStringCanonOutput output(&out_str);
CanonicalizeRef(ref_cases[i].input8, in_comp, &output, &out_comp);
output.Complete();
EXPECT_EQ(ref_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(ref_cases[i].expected_component.len, out_comp.len);
EXPECT_EQ(ref_cases[i].expected, out_str);
}
// 16-bit input
if (ref_cases[i].input16) {
std::u16string input16(
test_utils::TruncateWStringToUTF16(ref_cases[i].input16));
int len = static_cast<int>(input16.length());
Component in_comp(0, len);
Component out_comp;
std::string out_str;
StdStringCanonOutput output(&out_str);
CanonicalizeRef(input16.c_str(), in_comp, &output, &out_comp);
output.Complete();
EXPECT_EQ(ref_cases[i].expected_component.begin, out_comp.begin);
EXPECT_EQ(ref_cases[i].expected_component.len, out_comp.len);
EXPECT_EQ(ref_cases[i].expected, out_str);
}
}
// Try one with an embedded NULL. It should be stripped.
const char null_input[5] = "ab\x00z";
Component null_input_component(0, 4);
Component out_comp;
std::string out_str;
StdStringCanonOutput output(&out_str);
CanonicalizeRef(null_input, null_input_component, &output, &out_comp);
output.Complete();
EXPECT_EQ(1, out_comp.begin);
EXPECT_EQ(6, out_comp.len);
EXPECT_EQ("#ab%00z", out_str);
}
TEST(URLCanonTest, CanonicalizeStandardURL) {
// The individual component canonicalize tests should have caught the cases
// for each of those components. Here, we just need to test that the various
// parts are included or excluded properly, and have the correct separators.
struct URLCase {
const char* input;
const char* expected;
bool expected_success;
} cases[] = {
{"http://www.google.com/foo?bar=baz#",
"http://www.google.com/foo?bar=baz#", true},
{"http://[www.google.com]/", "http://[www.google.com]/", false},
{"ht\ttp:@www.google.com:80/;p?#", "ht%09tp://www.google.com:80/;p?#",
false},
{"http:////////user:@google.com:99?foo", "http://user@google.com:99/?foo",
true},
{"www.google.com", ":www.google.com/", false},
{"http://192.0x00A80001", "http://192.168.0.1/", true},
{"http://www/foo%2Ehtml", "http://www/foo.html", true},
{"http://user:pass@/", "http://user:pass@/", false},
{"http://%25DOMAIN:foobar@foodomain.com/",
"http://%25DOMAIN:foobar@foodomain.com/", true},
// Backslashes should get converted to forward slashes.
{"http:\\\\www.google.com\\foo", "http://www.google.com/foo", true},
// Busted refs shouldn't make the whole thing fail.
{"http://www.google.com/asdf#\xc2",
"http://www.google.com/asdf#%EF%BF%BD", true},
// Basic port tests.
{"http://foo:80/", "http://foo/", true},
{"http://foo:81/", "http://foo:81/", true},
{"httpa://foo:80/", "httpa://foo:80/", true},
{"http://foo:-80/", "http://foo:-80/", false},
{"https://foo:443/", "https://foo/", true},
{"https://foo:80/", "https://foo:80/", true},
{"ftp://foo:21/", "ftp://foo/", true},
{"ftp://foo:80/", "ftp://foo:80/", true},
{"gopher://foo:70/", "gopher://foo:70/", true},
{"gopher://foo:443/", "gopher://foo:443/", true},
{"ws://foo:80/", "ws://foo/", true},
{"ws://foo:81/", "ws://foo:81/", true},
{"ws://foo:443/", "ws://foo:443/", true},
{"ws://foo:815/", "ws://foo:815/", true},
{"wss://foo:80/", "wss://foo:80/", true},
{"wss://foo:81/", "wss://foo:81/", true},
{"wss://foo:443/", "wss://foo/", true},
{"wss://foo:815/", "wss://foo:815/", true},
// This particular code path ends up "backing up" to replace an invalid
// host ICU generated with an escaped version. Test that in the context
// of a full URL to make sure the backing up doesn't mess up the non-host
// parts of the URL. "EF B9 AA" is U+FE6A which is a type of percent that
// ICU will convert to an ASCII one, generating "%81".
{"ws:)W\x1eW\xef\xb9\xaa"
"81:80/",
"ws://%29w%1ew%81/", false},
// Regression test for the last_invalid_percent_index bug described in
// https://crbug.com/1080890#c10.
{R"(HTTP:S/5%\../>%41)", "http://s/%3EA", true},
};
for (size_t i = 0; i < std::size(cases); i++) {
int url_len = static_cast<int>(strlen(cases[i].input));
Parsed parsed;
ParseStandardURL(cases[i].input, url_len, &parsed);
Parsed out_parsed;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success = CanonicalizeStandardURL(
cases[i].input, url_len, parsed,
SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, NULL, &output, &out_parsed);
output.Complete();
EXPECT_EQ(cases[i].expected_success, success);
EXPECT_EQ(cases[i].expected, out_str);
}
}
// The codepath here is the same as for regular canonicalization, so we just
// need to test that things are replaced or not correctly.
TEST(URLCanonTest, ReplaceStandardURL) {
ReplaceCase replace_cases[] = {
// Common case of truncating the path.
{"http://www.google.com/foo?bar=baz#ref", nullptr, nullptr, nullptr,
nullptr, nullptr, "/", kDeleteComp, kDeleteComp,
"http://www.google.com/"},
// Replace everything
{"http://a:b@google.com:22/foo;bar?baz@cat", "https", "me", "pw",
"host.com", "99", "/path", "query", "ref",
"https://me:pw@host.com:99/path?query#ref"},
// Replace nothing
{"http://a:b@google.com:22/foo?baz@cat", nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr,
"http://a:b@google.com:22/foo?baz@cat"},
// Replace scheme with filesystem. The result is garbage, but you asked
// for it.
{"http://a:b@google.com:22/foo?baz@cat", "filesystem", nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr,
"filesystem://a:b@google.com:22/foo?baz@cat"},
};
for (size_t i = 0; i < std::size(replace_cases); i++) {
const ReplaceCase& cur = replace_cases[i];
int base_len = static_cast<int>(strlen(cur.base));
Parsed parsed;
ParseStandardURL(cur.base, base_len, &parsed);
Replacements<char> r;
typedef Replacements<char> R; // Clean up syntax.
// Note that for the scheme we pass in a different clear function since
// there is no function to clear the scheme.
SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
std::string out_str;
StdStringCanonOutput output(&out_str);
Parsed out_parsed;
ReplaceStandardURL(replace_cases[i].base, parsed, r,
SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, NULL,
&output, &out_parsed);
output.Complete();
EXPECT_EQ(replace_cases[i].expected, out_str);
}
// The path pointer should be ignored if the address is invalid.
{
const char src[] = "http://www.google.com/here_is_the_path";
int src_len = static_cast<int>(strlen(src));
Parsed parsed;
ParseStandardURL(src, src_len, &parsed);
// Replace the path to 0 length string. By using 1 as the string address,
// the test should get an access violation if it tries to dereference it.
Replacements<char> r;
r.SetPath(reinterpret_cast<char*>(0x00000001), Component(0, 0));
std::string out_str1;
StdStringCanonOutput output1(&out_str1);
Parsed new_parsed;
ReplaceStandardURL(src, parsed, r,
SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, NULL,
&output1, &new_parsed);
output1.Complete();
EXPECT_STREQ("http://www.google.com/", out_str1.c_str());
// Same with an "invalid" path.
r.SetPath(reinterpret_cast<char*>(0x00000001), Component());
std::string out_str2;
StdStringCanonOutput output2(&out_str2);
ReplaceStandardURL(src, parsed, r,
SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, NULL,
&output2, &new_parsed);
output2.Complete();
EXPECT_STREQ("http://www.google.com/", out_str2.c_str());
}
}
TEST(URLCanonTest, ReplaceFileURL) {
ReplaceCase replace_cases[] = {
// Replace everything
{"file:///C:/gaba?query#ref", nullptr, nullptr, nullptr, "filer", nullptr,
"/foo", "b", "c", "file://filer/foo?b#c"},
// Replace nothing
{"file:///C:/gaba?query#ref", nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, "file:///C:/gaba?query#ref"},
{"file:///Y:", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, "file:///Y:"},
{"file:///Y:/", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, "file:///Y:/"},
{"file:///./Y", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, "file:///Y"},
{"file:///./Y:", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, "file:///Y:"},
// Clear non-path components (common)
{"file:///C:/gaba?query#ref", nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, kDeleteComp, kDeleteComp, "file:///C:/gaba"},
// Replace path with something that doesn't begin with a slash and make
// sure it gets added properly.
{"file:///C:/gaba", nullptr, nullptr, nullptr, nullptr, nullptr,
"interesting/", nullptr, nullptr, "file:///interesting/"},
{"file:///home/gaba?query#ref", nullptr, nullptr, nullptr, "filer",
nullptr, "/foo", "b", "c", "file://filer/foo?b#c"},
{"file:///home/gaba?query#ref", nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, "file:///home/gaba?query#ref"},
{"file:///home/gaba?query#ref", nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, kDeleteComp, kDeleteComp, "file:///home/gaba"},
{"file:///home/gaba", nullptr, nullptr, nullptr, nullptr, nullptr,
"interesting/", nullptr, nullptr, "file:///interesting/"},
// Replace scheme -- shouldn't do anything.
{"file:///C:/gaba?query#ref", "http", nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, "file:///C:/gaba?query#ref"},
};
for (size_t i = 0; i < std::size(replace_cases); i++) {
const ReplaceCase& cur = replace_cases[i];
SCOPED_TRACE(cur.base);
int base_len = static_cast<int>(strlen(cur.base));
Parsed parsed;
ParseFileURL(cur.base, base_len, &parsed);
Replacements<char> r;
typedef Replacements<char> R; // Clean up syntax.
SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
std::string out_str;
StdStringCanonOutput output(&out_str);
Parsed out_parsed;
ReplaceFileURL(cur.base, parsed, r, NULL, &output, &out_parsed);
output.Complete();
EXPECT_EQ(replace_cases[i].expected, out_str);
}
}
TEST(URLCanonTest, ReplaceFileSystemURL) {
ReplaceCase replace_cases[] = {
// Replace everything in the outer URL.
{"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
nullptr, nullptr, "/foo", "b", "c",
"filesystem:file:///temporary/foo?b#c"},
// Replace nothing
{"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr,
"filesystem:file:///temporary/gaba?query#ref"},
// Clear non-path components (common)
{"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, kDeleteComp, kDeleteComp,
"filesystem:file:///temporary/gaba"},
// Replace path with something that doesn't begin with a slash and make
// sure it gets added properly.
{"filesystem:file:///temporary/gaba?query#ref", nullptr, nullptr, nullptr,
nullptr, nullptr, "interesting/", nullptr, nullptr,
"filesystem:file:///temporary/interesting/?query#ref"},
// Replace scheme -- shouldn't do anything except canonicalize.
{"filesystem:http://u:p@bar.com/t/gaba?query#ref", "http", nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
"filesystem:http://bar.com/t/gaba?query#ref"},
// Replace username -- shouldn't do anything except canonicalize.
{"filesystem:http://u:p@bar.com/t/gaba?query#ref", nullptr, "u2", nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr,
"filesystem:http://bar.com/t/gaba?query#ref"},
// Replace password -- shouldn't do anything except canonicalize.
{"filesystem:http://u:p@bar.com/t/gaba?query#ref", nullptr, nullptr,
"pw2", nullptr, nullptr, nullptr, nullptr, nullptr,
"filesystem:http://bar.com/t/gaba?query#ref"},
// Replace host -- shouldn't do anything except canonicalize.
{"filesystem:http://u:p@bar.com:80/t/gaba?query#ref", nullptr, nullptr,
nullptr, "foo.com", nullptr, nullptr, nullptr, nullptr,
"filesystem:http://bar.com/t/gaba?query#ref"},
// Replace port -- shouldn't do anything except canonicalize.
{"filesystem:http://u:p@bar.com:40/t/gaba?query#ref", nullptr, nullptr,
nullptr, nullptr, "41", nullptr, nullptr, nullptr,
"filesystem:http://bar.com:40/t/gaba?query#ref"},
};
for (size_t i = 0; i < std::size(replace_cases); i++) {
const ReplaceCase& cur = replace_cases[i];
int base_len = static_cast<int>(strlen(cur.base));
Parsed parsed;
ParseFileSystemURL(cur.base, base_len, &parsed);
Replacements<char> r;
typedef Replacements<char> R; // Clean up syntax.
SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
std::string out_str;
StdStringCanonOutput output(&out_str);
Parsed out_parsed;
ReplaceFileSystemURL(cur.base, parsed, r, NULL, &output, &out_parsed);
output.Complete();
EXPECT_EQ(replace_cases[i].expected, out_str);
}
}
TEST(URLCanonTest, ReplacePathURL) {
ReplaceCase replace_cases[] = {
// Replace everything
{"data:foo", "javascript", nullptr, nullptr, nullptr, nullptr,
"alert('foo?');", nullptr, nullptr, "javascript:alert('foo?');"},
// Replace nothing
{"data:foo", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, "data:foo"},
// Replace one or the other
{"data:foo", "javascript", nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, "javascript:foo"},
{"data:foo", nullptr, nullptr, nullptr, nullptr, nullptr, "bar", nullptr,
nullptr, "data:bar"},
{"data:foo", nullptr, nullptr, nullptr, nullptr, nullptr, kDeleteComp,
nullptr, nullptr, "data:"},
};
for (size_t i = 0; i < std::size(replace_cases); i++) {
const ReplaceCase& cur = replace_cases[i];
int base_len = static_cast<int>(strlen(cur.base));
Parsed parsed;
ParsePathURL(cur.base, base_len, false, &parsed);
Replacements<char> r;
typedef Replacements<char> R; // Clean up syntax.
SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
std::string out_str;
StdStringCanonOutput output(&out_str);
Parsed out_parsed;
ReplacePathURL(cur.base, parsed, r, &output, &out_parsed);
output.Complete();
EXPECT_EQ(replace_cases[i].expected, out_str);
}
}
TEST(URLCanonTest, ReplaceMailtoURL) {
ReplaceCase replace_cases[] = {
// Replace everything
{"mailto:jon@foo.com?body=sup", "mailto", NULL, NULL, NULL, NULL, "addr1", "to=tony", NULL, "mailto:addr1?to=tony"},
// Replace nothing
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "mailto:jon@foo.com?body=sup"},
// Replace the path
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, "jason", NULL, NULL, "mailto:jason?body=sup"},
// Replace the query
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, "custom=1", NULL, "mailto:jon@foo.com?custom=1"},
// Replace the path and query
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, "jason", "custom=1", NULL, "mailto:jason?custom=1"},
// Set the query to empty (should leave trailing question mark)
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, "", NULL, "mailto:jon@foo.com?"},
// Clear the query
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, NULL, "|", NULL, "mailto:jon@foo.com"},
// Clear the path
{"mailto:jon@foo.com?body=sup", NULL, NULL, NULL, NULL, NULL, "|", NULL, NULL, "mailto:?body=sup"},
// Clear the path + query
{"mailto:", NULL, NULL, NULL, NULL, NULL, "|", "|", NULL, "mailto:"},
// Setting the ref should have no effect
{"mailto:addr1", NULL, NULL, NULL, NULL, NULL, NULL, NULL, "BLAH", "mailto:addr1"},
};
for (size_t i = 0; i < std::size(replace_cases); i++) {
const ReplaceCase& cur = replace_cases[i];
int base_len = static_cast<int>(strlen(cur.base));
Parsed parsed;
ParseMailtoURL(cur.base, base_len, &parsed);
Replacements<char> r;
typedef Replacements<char> R;
SetupReplComp(&R::SetScheme, &R::ClearRef, &r, cur.scheme);
SetupReplComp(&R::SetUsername, &R::ClearUsername, &r, cur.username);
SetupReplComp(&R::SetPassword, &R::ClearPassword, &r, cur.password);
SetupReplComp(&R::SetHost, &R::ClearHost, &r, cur.host);
SetupReplComp(&R::SetPort, &R::ClearPort, &r, cur.port);
SetupReplComp(&R::SetPath, &R::ClearPath, &r, cur.path);
SetupReplComp(&R::SetQuery, &R::ClearQuery, &r, cur.query);
SetupReplComp(&R::SetRef, &R::ClearRef, &r, cur.ref);
std::string out_str;
StdStringCanonOutput output(&out_str);
Parsed out_parsed;
ReplaceMailtoURL(cur.base, parsed, r, &output, &out_parsed);
output.Complete();
EXPECT_EQ(replace_cases[i].expected, out_str);
}
}
TEST(URLCanonTest, CanonicalizeFileURL) {
struct URLCase {
const char* input;
const char* expected;
bool expected_success;
Component expected_host;
Component expected_path;
} cases[] = {
#ifdef _WIN32
// Windows-style paths
{"file:c:\\foo\\bar.html", "file:///C:/foo/bar.html", true, Component(),
Component(7, 16)},
{" File:c|////foo\\bar.html", "file:///C:////foo/bar.html", true,
Component(), Component(7, 19)},
{"file:", "file:///", true, Component(), Component(7, 1)},
{"file:UNChost/path", "file://unchost/path", true, Component(7, 7),
Component(14, 5)},
// CanonicalizeFileURL supports absolute Windows style paths for IE
// compatibility. Note that the caller must decide that this is a file
// URL itself so it can call the file canonicalizer. This is usually
// done automatically as part of relative URL resolving.
{"c:\\foo\\bar", "file:///C:/foo/bar", true, Component(),
Component(7, 11)},
{"C|/foo/bar", "file:///C:/foo/bar", true, Component(), Component(7, 11)},
{"/C|\\foo\\bar", "file:///C:/foo/bar", true, Component(),
Component(7, 11)},
{"//C|/foo/bar", "file:///C:/foo/bar", true, Component(),
Component(7, 11)},
{"//server/file", "file://server/file", true, Component(7, 6),
Component(13, 5)},
{"\\\\server\\file", "file://server/file", true, Component(7, 6),
Component(13, 5)},
{"/\\server/file", "file://server/file", true, Component(7, 6),
Component(13, 5)},
// We should preserve the number of slashes after the colon for IE
// compatibility, except when there is none, in which case we should
// add one.
{"file:c:foo/bar.html", "file:///C:/foo/bar.html", true, Component(),
Component(7, 16)},
{"file:/\\/\\C:\\\\//foo\\bar.html", "file:///C:////foo/bar.html", true,
Component(), Component(7, 19)},
// Three slashes should be non-UNC, even if there is no drive spec (IE
// does this, which makes the resulting request invalid).
{"file:///foo/bar.txt", "file:///foo/bar.txt", true, Component(),
Component(7, 12)},
// TODO(brettw) we should probably fail for invalid host names, which
// would change the expected result on this test. We also currently allow
// colon even though it's probably invalid, because its currently the
// "natural" result of the way the canonicalizer is written. There doesn't
// seem to be a strong argument for why allowing it here would be bad, so
// we just tolerate it and the load will fail later.
{"FILE:/\\/\\7:\\\\//foo\\bar.html", "file://7:////foo/bar.html", false,
Component(7, 2), Component(9, 16)},
{"file:filer/home\\me", "file://filer/home/me", true, Component(7, 5),
Component(12, 8)},
// Make sure relative paths can't go above the "C:"
{"file:///C:/foo/../../../bar.html", "file:///C:/bar.html", true,
Component(), Component(7, 12)},
// Busted refs shouldn't make the whole thing fail.
{"file:///C:/asdf#\xc2", "file:///C:/asdf#%EF%BF%BD", true, Component(),
Component(7, 8)},
{"file:///./s:", "file:///S:", true, Component(), Component(7, 3)},
#else
// Unix-style paths
{"file:///home/me", "file:///home/me", true, Component(),
Component(7, 8)},
// Windowsy ones should get still treated as Unix-style.
{"file:c:\\foo\\bar.html", "file:///c:/foo/bar.html", true, Component(),
Component(7, 16)},
{"file:c|//foo\\bar.html", "file:///c%7C//foo/bar.html", true,
Component(), Component(7, 19)},
{"file:///./s:", "file:///s:", true, Component(), Component(7, 3)},
// file: tests from WebKit (LayoutTests/fast/loader/url-parse-1.html)
{"//", "file:///", true, Component(), Component(7, 1)},
{"///", "file:///", true, Component(), Component(7, 1)},
{"///test", "file:///test", true, Component(), Component(7, 5)},
{"file://test", "file://test/", true, Component(7, 4), Component(11, 1)},
{"file://localhost", "file://localhost/", true, Component(7, 9),
Component(16, 1)},
{"file://localhost/", "file://localhost/", true, Component(7, 9),
Component(16, 1)},
{"file://localhost/test", "file://localhost/test", true, Component(7, 9),
Component(16, 5)},
#endif // _WIN32
};
for (size_t i = 0; i < std::size(cases); i++) {
int url_len = static_cast<int>(strlen(cases[i].input));
Parsed parsed;
ParseFileURL(cases[i].input, url_len, &parsed);
Parsed out_parsed;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success = CanonicalizeFileURL(cases[i].input, url_len, parsed, NULL,
&output, &out_parsed);
output.Complete();
EXPECT_EQ(cases[i].expected_success, success);
EXPECT_EQ(cases[i].expected, out_str);
// Make sure the spec was properly identified, the file canonicalizer has
// different code for writing the spec.
EXPECT_EQ(0, out_parsed.scheme.begin);
EXPECT_EQ(4, out_parsed.scheme.len);
EXPECT_EQ(cases[i].expected_host.begin, out_parsed.host.begin);
EXPECT_EQ(cases[i].expected_host.len, out_parsed.host.len);
EXPECT_EQ(cases[i].expected_path.begin, out_parsed.path.begin);
EXPECT_EQ(cases[i].expected_path.len, out_parsed.path.len);
}
}
TEST(URLCanonTest, CanonicalizeFileSystemURL) {
struct URLCase {
const char* input;
const char* expected;
bool expected_success;
} cases[] = {
{"Filesystem:htTp://www.Foo.com:80/tempoRary",
"filesystem:http://www.foo.com/tempoRary/", true},
{"filesystem:httpS://www.foo.com/temporary/",
"filesystem:https://www.foo.com/temporary/", true},
{"filesystem:http://www.foo.com//", "filesystem:http://www.foo.com//",
false},
{"filesystem:http://www.foo.com/persistent/bob?query#ref",
"filesystem:http://www.foo.com/persistent/bob?query#ref", true},
{"filesystem:fIle://\\temporary/", "filesystem:file:///temporary/", true},
{"filesystem:fiLe:///temporary", "filesystem:file:///temporary/", true},
{"filesystem:File:///temporary/Bob?qUery#reF",
"filesystem:file:///temporary/Bob?qUery#reF", true},
{"FilEsysteM:htTp:E=/.", "filesystem:http://e%3D//", false},
};
for (size_t i = 0; i < std::size(cases); i++) {
int url_len = static_cast<int>(strlen(cases[i].input));
Parsed parsed;
ParseFileSystemURL(cases[i].input, url_len, &parsed);
Parsed out_parsed;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success = CanonicalizeFileSystemURL(cases[i].input, url_len, parsed,
NULL, &output, &out_parsed);
output.Complete();
EXPECT_EQ(cases[i].expected_success, success);
EXPECT_EQ(cases[i].expected, out_str);
// Make sure the spec was properly identified, the filesystem canonicalizer
// has different code for writing the spec.
EXPECT_EQ(0, out_parsed.scheme.begin);
EXPECT_EQ(10, out_parsed.scheme.len);
if (success)
EXPECT_GT(out_parsed.path.len, 0);
}
}
TEST(URLCanonTest, CanonicalizePathURL) {
// Path URLs should get canonicalized schemes but nothing else.
struct PathCase {
const char* input;
const char* expected;
} path_cases[] = {
{"javascript:", "javascript:"},
{"JavaScript:Foo", "javascript:Foo"},
{"Foo:\":This /is interesting;?#", "foo:\":This /is interesting;?#"},
// Validation errors should not cause failure. See
// https://crbug.com/925614.
{"javascript:\uFFFF", "javascript:%EF%BF%BD"},
};
for (size_t i = 0; i < std::size(path_cases); i++) {
int url_len = static_cast<int>(strlen(path_cases[i].input));
Parsed parsed;
ParsePathURL(path_cases[i].input, url_len, true, &parsed);
Parsed out_parsed;
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success = CanonicalizePathURL(path_cases[i].input, url_len, parsed,
&output, &out_parsed);
output.Complete();
EXPECT_TRUE(success);
EXPECT_EQ(path_cases[i].expected, out_str);
EXPECT_EQ(0, out_parsed.host.begin);
EXPECT_EQ(-1, out_parsed.host.len);
// When we end with a colon at the end, there should be no path.
if (path_cases[i].input[url_len - 1] == ':') {
EXPECT_EQ(0, out_parsed.GetContent().begin);
EXPECT_EQ(-1, out_parsed.GetContent().len);
}
}
}
TEST(URLCanonTest, CanonicalizePathURLPath) {
struct PathCase {
std::string input;
std::wstring input16;
std::string expected;
} path_cases[] = {
{"Foo", L"Foo", "Foo"},
{"\":This /is interesting;?#", L"\":This /is interesting;?#",
"\":This /is interesting;?#"},
{"\uFFFF", L"\uFFFF", "%EF%BF%BD"},
};
for (size_t i = 0; i < std::size(path_cases); i++) {
// 8-bit string input
std::string out_str;
StdStringCanonOutput output(&out_str);
url::Component out_component;
CanonicalizePathURLPath(path_cases[i].input.data(),
Component(0, path_cases[i].input.size()), &output,
&out_component);
output.Complete();
EXPECT_EQ(path_cases[i].expected, out_str);
EXPECT_EQ(0, out_component.begin);
EXPECT_EQ(path_cases[i].expected.size(),
static_cast<size_t>(out_component.len));
// 16-bit string input
std::string out_str16;
StdStringCanonOutput output16(&out_str16);
url::Component out_component16;
std::u16string input16(
test_utils::TruncateWStringToUTF16(path_cases[i].input16.data()));
CanonicalizePathURLPath(input16.c_str(),
Component(0, path_cases[i].input16.size()),
&output16, &out_component16);
output16.Complete();
EXPECT_EQ(path_cases[i].expected, out_str16);
EXPECT_EQ(0, out_component16.begin);
EXPECT_EQ(path_cases[i].expected.size(),
static_cast<size_t>(out_component16.len));
}
}
TEST(URLCanonTest, CanonicalizeMailtoURL) {
struct URLCase {
const char* input;
const char* expected;
bool expected_success;
Component expected_path;
Component expected_query;
} cases[] = {
// Null character should be escaped to %00.
// Keep this test first in the list as it is handled specially below.
{"mailto:addr1\0addr2?foo",
"mailto:addr1%00addr2?foo",
true, Component(7, 13), Component(21, 3)},
{"mailto:addr1",
"mailto:addr1",
true, Component(7, 5), Component()},
{"mailto:addr1@foo.com",
"mailto:addr1@foo.com",
true, Component(7, 13), Component()},
// Trailing whitespace is stripped.
{"MaIlTo:addr1 \t ",
"mailto:addr1",
true, Component(7, 5), Component()},
{"MaIlTo:addr1?to=jon",
"mailto:addr1?to=jon",
true, Component(7, 5), Component(13,6)},
{"mailto:addr1,addr2",
"mailto:addr1,addr2",
true, Component(7, 11), Component()},
// Embedded spaces must be encoded.
{"mailto:addr1, addr2",
"mailto:addr1,%20addr2",
true, Component(7, 14), Component()},
{"mailto:addr1, addr2?subject=one two ",
"mailto:addr1,%20addr2?subject=one%20two",
true, Component(7, 14), Component(22, 17)},
{"mailto:addr1%2caddr2",
"mailto:addr1%2caddr2",
true, Component(7, 13), Component()},
{"mailto:\xF0\x90\x8C\x80",
"mailto:%F0%90%8C%80",
true, Component(7, 12), Component()},
// Invalid -- UTF-8 encoded surrogate value.
{"mailto:\xed\xa0\x80",
"mailto:%EF%BF%BD%EF%BF%BD%EF%BF%BD",
false, Component(7, 27), Component()},
{"mailto:addr1?",
"mailto:addr1?",
true, Component(7, 5), Component(13, 0)},
// Certain characters have special meanings and must be encoded.
{"mailto:! \x22$&()+,-./09:;<=>@AZ[\\]&_`az{|}~\x7f?Query! \x22$&()+,-./09:;<=>@AZ[\\]&_`az{|}~",
"mailto:!%20%22$&()+,-./09:;%3C=%3E@AZ[\\]&_%60az%7B%7C%7D~%7F?Query!%20%22$&()+,-./09:;%3C=%3E@AZ[\\]&_`az{|}~",
true, Component(7, 53), Component(61, 47)},
};
// Define outside of loop to catch bugs where components aren't reset
Parsed parsed;
Parsed out_parsed;
for (size_t i = 0; i < std::size(cases); i++) {
int url_len = static_cast<int>(strlen(cases[i].input));
if (i == 0) {
// The first test case purposely has a '\0' in it -- don't count it
// as the string terminator.
url_len = 22;
}
ParseMailtoURL(cases[i].input, url_len, &parsed);
std::string out_str;
StdStringCanonOutput output(&out_str);
bool success = CanonicalizeMailtoURL(cases[i].input, url_len, parsed,
&output, &out_parsed);
output.Complete();
EXPECT_EQ(cases[i].expected_success, success);
EXPECT_EQ(cases[i].expected, out_str);
// Make sure the spec was properly identified
EXPECT_EQ(0, out_parsed.scheme.begin);
EXPECT_EQ(6, out_parsed.scheme.len);
EXPECT_EQ(cases[i].expected_path.begin, out_parsed.path.begin);
EXPECT_EQ(cases[i].expected_path.len, out_parsed.path.len);
EXPECT_EQ(cases[i].expected_query.begin, out_parsed.query.begin);
EXPECT_EQ(cases[i].expected_query.len, out_parsed.query.len);
}
}
#ifndef WIN32
TEST(URLCanonTest, _itoa_s) {
// We fill the buffer with 0xff to ensure that it's getting properly
// null-terminated. We also allocate one byte more than what we tell
// _itoa_s about, and ensure that the extra byte is untouched.
char buf[6];
memset(buf, 0xff, sizeof(buf));
EXPECT_EQ(0, _itoa_s(12, buf, sizeof(buf) - 1, 10));
EXPECT_STREQ("12", buf);
EXPECT_EQ('\xFF', buf[3]);
// Test the edge cases - exactly the buffer size and one over
memset(buf, 0xff, sizeof(buf));
EXPECT_EQ(0, _itoa_s(1234, buf, sizeof(buf) - 1, 10));
EXPECT_STREQ("1234", buf);
EXPECT_EQ('\xFF', buf[5]);
memset(buf, 0xff, sizeof(buf));
EXPECT_EQ(EINVAL, _itoa_s(12345, buf, sizeof(buf) - 1, 10));
EXPECT_EQ('\xFF', buf[5]); // should never write to this location
// Test the template overload (note that this will see the full buffer)
memset(buf, 0xff, sizeof(buf));
EXPECT_EQ(0, _itoa_s(12, buf, 10));
EXPECT_STREQ("12", buf);
EXPECT_EQ('\xFF', buf[3]);
memset(buf, 0xff, sizeof(buf));
EXPECT_EQ(0, _itoa_s(12345, buf, 10));
EXPECT_STREQ("12345", buf);
EXPECT_EQ(EINVAL, _itoa_s(123456, buf, 10));
// Test that radix 16 is supported.
memset(buf, 0xff, sizeof(buf));
EXPECT_EQ(0, _itoa_s(1234, buf, sizeof(buf) - 1, 16));
EXPECT_STREQ("4d2", buf);
EXPECT_EQ('\xFF', buf[5]);
}
TEST(URLCanonTest, _itow_s) {
// We fill the buffer with 0xff to ensure that it's getting properly
// null-terminated. We also allocate one byte more than what we tell
// _itoa_s about, and ensure that the extra byte is untouched.
char16_t buf[6];
const char fill_mem = 0xff;
const char16_t fill_char = 0xffff;
memset(buf, fill_mem, sizeof(buf));
EXPECT_EQ(0, _itow_s(12, buf, sizeof(buf) / 2 - 1, 10));
EXPECT_EQ(u"12", std::u16string(buf));
EXPECT_EQ(fill_char, buf[3]);
// Test the edge cases - exactly the buffer size and one over
EXPECT_EQ(0, _itow_s(1234, buf, sizeof(buf) / 2 - 1, 10));
EXPECT_EQ(u"1234", std::u16string(buf));
EXPECT_EQ(fill_char, buf[5]);
memset(buf, fill_mem, sizeof(buf));
EXPECT_EQ(EINVAL, _itow_s(12345, buf, sizeof(buf) / 2 - 1, 10));
EXPECT_EQ(fill_char, buf[5]); // should never write to this location
// Test the template overload (note that this will see the full buffer)
memset(buf, fill_mem, sizeof(buf));
EXPECT_EQ(0, _itow_s(12, buf, 10));
EXPECT_EQ(u"12", std::u16string(buf));
EXPECT_EQ(fill_char, buf[3]);
memset(buf, fill_mem, sizeof(buf));
EXPECT_EQ(0, _itow_s(12345, buf, 10));
EXPECT_EQ(u"12345", std::u16string(buf));
EXPECT_EQ(EINVAL, _itow_s(123456, buf, 10));
}
#endif // !WIN32
// Returns true if the given two structures are the same.
static bool ParsedIsEqual(const Parsed& a, const Parsed& b) {
return a.scheme.begin == b.scheme.begin && a.scheme.len == b.scheme.len &&
a.username.begin == b.username.begin && a.username.len == b.username.len &&
a.password.begin == b.password.begin && a.password.len == b.password.len &&
a.host.begin == b.host.begin && a.host.len == b.host.len &&
a.port.begin == b.port.begin && a.port.len == b.port.len &&
a.path.begin == b.path.begin && a.path.len == b.path.len &&
a.query.begin == b.query.begin && a.query.len == b.query.len &&
a.ref.begin == b.ref.begin && a.ref.len == b.ref.len;
}
TEST(URLCanonTest, ResolveRelativeURL) {
struct RelativeCase {
const char* base; // Input base URL: MUST BE CANONICAL
bool is_base_hier; // Is the base URL hierarchical
bool is_base_file; // Tells us if the base is a file URL.
const char* test; // Input URL to test against.
bool succeed_relative; // Whether we expect IsRelativeURL to succeed
bool is_rel; // Whether we expect |test| to be relative or not.
bool succeed_resolve; // Whether we expect ResolveRelativeURL to succeed.
const char* resolved; // What we expect in the result when resolving.
} rel_cases[] = {
// Basic absolute input.
{"http://host/a", true, false, "http://another/", true, false, false, NULL},
{"http://host/a", true, false, "http:////another/", true, false, false, NULL},
// Empty relative URLs should only remove the ref part of the URL,
// leaving the rest unchanged.
{"http://foo/bar", true, false, "", true, true, true, "http://foo/bar"},
{"http://foo/bar#ref", true, false, "", true, true, true, "http://foo/bar"},
{"http://foo/bar#", true, false, "", true, true, true, "http://foo/bar"},
// Spaces at the ends of the relative path should be ignored.
{"http://foo/bar", true, false, " another ", true, true, true, "http://foo/another"},
{"http://foo/bar", true, false, " . ", true, true, true, "http://foo/"},
{"http://foo/bar", true, false, " \t ", true, true, true, "http://foo/bar"},
// Matching schemes without two slashes are treated as relative.
{"http://host/a", true, false, "http:path", true, true, true, "http://host/path"},
{"http://host/a/", true, false, "http:path", true, true, true, "http://host/a/path"},
{"http://host/a", true, false, "http:/path", true, true, true, "http://host/path"},
{"http://host/a", true, false, "HTTP:/path", true, true, true, "http://host/path"},
// Nonmatching schemes are absolute.
{"http://host/a", true, false, "https:host2", true, false, false, NULL},
{"http://host/a", true, false, "htto:/host2", true, false, false, NULL},
// Absolute path input
{"http://host/a", true, false, "/b/c/d", true, true, true, "http://host/b/c/d"},
{"http://host/a", true, false, "\\b\\c\\d", true, true, true, "http://host/b/c/d"},
{"http://host/a", true, false, "/b/../c", true, true, true, "http://host/c"},
{"http://host/a?b#c", true, false, "/b/../c", true, true, true, "http://host/c"},
{"http://host/a", true, false, "\\b/../c?x#y", true, true, true, "http://host/c?x#y"},
{"http://host/a?b#c", true, false, "/b/../c?x#y", true, true, true, "http://host/c?x#y"},
// Relative path input
{"http://host/a", true, false, "b", true, true, true, "http://host/b"},
{"http://host/a", true, false, "bc/de", true, true, true, "http://host/bc/de"},
{"http://host/a/", true, false, "bc/de?query#ref", true, true, true, "http://host/a/bc/de?query#ref"},
{"http://host/a/", true, false, ".", true, true, true, "http://host/a/"},
{"http://host/a/", true, false, "..", true, true, true, "http://host/"},
{"http://host/a/", true, false, "./..", true, true, true, "http://host/"},
{"http://host/a/", true, false, "../.", true, true, true, "http://host/"},
{"http://host/a/", true, false, "././.", true, true, true, "http://host/a/"},
{"http://host/a?query#ref", true, false, "../../../foo", true, true, true, "http://host/foo"},
// Query input
{"http://host/a", true, false, "?foo=bar", true, true, true, "http://host/a?foo=bar"},
{"http://host/a?x=y#z", true, false, "?", true, true, true, "http://host/a?"},
{"http://host/a?x=y#z", true, false, "?foo=bar#com", true, true, true, "http://host/a?foo=bar#com"},
// Ref input
{"http://host/a", true, false, "#ref", true, true, true, "http://host/a#ref"},
{"http://host/a#b", true, false, "#", true, true, true, "http://host/a#"},
{"http://host/a?foo=bar#hello", true, false, "#bye", true, true, true, "http://host/a?foo=bar#bye"},
// Non-hierarchical base: no relative handling. Relative input should
// error, and if a scheme is present, it should be treated as absolute.
{"data:foobar", false, false, "baz.html", false, false, false, NULL},
{"data:foobar", false, false, "data:baz", true, false, false, NULL},
{"data:foobar", false, false, "data:/base", true, false, false, NULL},
// Non-hierarchical base: absolute input should succeed.
{"data:foobar", false, false, "http://host/", true, false, false, NULL},
{"data:foobar", false, false, "http:host", true, false, false, NULL},
// Non-hierarchical base: empty URL should give error.
{"data:foobar", false, false, "", false, false, false, NULL},
// Invalid schemes should be treated as relative.
{"http://foo/bar", true, false, "./asd:fgh", true, true, true, "http://foo/asd:fgh"},
{"http://foo/bar", true, false, ":foo", true, true, true, "http://foo/:foo"},
{"http://foo/bar", true, false, " hello world", true, true, true, "http://foo/hello%20world"},
{"data:asdf", false, false, ":foo", false, false, false, NULL},
{"data:asdf", false, false, "bad(':foo')", false, false, false, NULL},
// We should treat semicolons like any other character in URL resolving
{"http://host/a", true, false, ";foo", true, true, true, "http://host/;foo"},
{"http://host/a;", true, false, ";foo", true, true, true, "http://host/;foo"},
{"http://host/a", true, false, ";/../bar", true, true, true, "http://host/bar"},
// Relative URLs can also be written as "//foo/bar" which is relative to
// the scheme. In this case, it would take the old scheme, so for http
// the example would resolve to "http://foo/bar".
{"http://host/a", true, false, "//another", true, true, true, "http://another/"},
{"http://host/a", true, false, "//another/path?query#ref", true, true, true, "http://another/path?query#ref"},
{"http://host/a", true, false, "///another/path", true, true, true, "http://another/path"},
{"http://host/a", true, false, "//Another\\path", true, true, true, "http://another/path"},
{"http://host/a", true, false, "//", true, true, false, "http:"},
// IE will also allow one or the other to be a backslash to get the same
// behavior.
{"http://host/a", true, false, "\\/another/path", true, true, true, "http://another/path"},
{"http://host/a", true, false, "/\\Another\\path", true, true, true, "http://another/path"},
#ifdef WIN32
// Resolving against Windows file base URLs.
{"file:///C:/foo", true, true, "http://host/", true, false, false, NULL},
{"file:///C:/foo", true, true, "bar", true, true, true, "file:///C:/bar"},
{"file:///C:/foo", true, true, "../../../bar.html", true, true, true, "file:///C:/bar.html"},
{"file:///C:/foo", true, true, "/../bar.html", true, true, true, "file:///C:/bar.html"},
// But two backslashes on Windows should be UNC so should be treated
// as absolute.
{"http://host/a", true, false, "\\\\another\\path", true, false, false, NULL},
// IE doesn't support drive specs starting with two slashes. It fails
// immediately and doesn't even try to load. We fix it up to either
// an absolute path or UNC depending on what it looks like.
{"file:///C:/something", true, true, "//c:/foo", true, true, true, "file:///C:/foo"},
{"file:///C:/something", true, true, "//localhost/c:/foo", true, true, true, "file:///C:/foo"},
// Windows drive specs should be allowed and treated as absolute.
{"file:///C:/foo", true, true, "c:", true, false, false, NULL},
{"file:///C:/foo", true, true, "c:/foo", true, false, false, NULL},
{"http://host/a", true, false, "c:\\foo", true, false, false, NULL},
// Relative paths with drive letters should be allowed when the base is
// also a file.
{"file:///C:/foo", true, true, "/z:/bar", true, true, true, "file:///Z:/bar"},
// Treat absolute paths as being off of the drive.
{"file:///C:/foo", true, true, "/bar", true, true, true, "file:///C:/bar"},
{"file://localhost/C:/foo", true, true, "/bar", true, true, true, "file://localhost/C:/bar"},
{"file:///C:/foo/com/", true, true, "/bar", true, true, true, "file:///C:/bar"},
// On Windows, two slashes without a drive letter when the base is a file
// means that the path is UNC.
{"file:///C:/something", true, true, "//somehost/path", true, true, true, "file://somehost/path"},
{"file:///C:/something", true, true, "/\\//somehost/path", true, true, true, "file://somehost/path"},
#else
// On Unix we fall back to relative behavior since there's nothing else
// reasonable to do.
{"http://host/a", true, false, "\\\\Another\\path", true, true, true, "http://another/path"},
#endif
// Even on Windows, we don't allow relative drive specs when the base
// is not file.
{"http://host/a", true, false, "/c:\\foo", true, true, true, "http://host/c:/foo"},
{"http://host/a", true, false, "//c:\\foo", true, true, true, "http://c/foo"},
// Cross-platform relative file: resolution behavior.
{"file://host/a", true, true, "/", true, true, true, "file://host/"},
{"file://host/a", true, true, "//", true, true, true, "file:///"},
{"file://host/a", true, true, "/b", true, true, true, "file://host/b"},
{"file://host/a", true, true, "//b", true, true, true, "file://b/"},
// Ensure that ports aren't allowed for hosts relative to a file url.
// Although the result string shows a host:port portion, the call to
// resolve the relative URL returns false, indicating parse failure,
// which is what is required.
{"file:///foo.txt", true, true, "//host:80/bar.txt", true, true, false, "file://host:80/bar.txt"},
// Filesystem URL tests; filesystem URLs are only valid and relative if
// they have no scheme, e.g. "./index.html". There's no valid equivalent
// to http:index.html.
{"filesystem:http://host/t/path", true, false, "filesystem:http://host/t/path2", true, false, false, NULL},
{"filesystem:http://host/t/path", true, false, "filesystem:https://host/t/path2", true, false, false, NULL},
{"filesystem:http://host/t/path", true, false, "http://host/t/path2", true, false, false, NULL},
{"http://host/t/path", true, false, "filesystem:http://host/t/path2", true, false, false, NULL},
{"filesystem:http://host/t/path", true, false, "./path2", true, true, true, "filesystem:http://host/t/path2"},
{"filesystem:http://host/t/path/", true, false, "path2", true, true, true, "filesystem:http://host/t/path/path2"},
{"filesystem:http://host/t/path", true, false, "filesystem:http:path2", true, false, false, NULL},
// Absolute URLs are still not relative to a non-standard base URL.
{"about:blank", false, false, "http://X/A", true, false, true, ""},
{"about:blank", false, false, "content://content.Provider/", true, false, true, ""},
};
for (size_t i = 0; i < std::size(rel_cases); i++) {
const RelativeCase& cur_case = rel_cases[i];
Parsed parsed;
int base_len = static_cast<int>(strlen(cur_case.base));
if (cur_case.is_base_file)
ParseFileURL(cur_case.base, base_len, &parsed);
else if (cur_case.is_base_hier)
ParseStandardURL(cur_case.base, base_len, &parsed);
else
ParsePathURL(cur_case.base, base_len, false, &parsed);
// First see if it is relative.
int test_len = static_cast<int>(strlen(cur_case.test));
bool is_relative;
Component relative_component;
bool succeed_is_rel = IsRelativeURL(
cur_case.base, parsed, cur_case.test, test_len, cur_case.is_base_hier,
&is_relative, &relative_component);
EXPECT_EQ(cur_case.succeed_relative, succeed_is_rel) <<
"succeed is rel failure on " << cur_case.test;
EXPECT_EQ(cur_case.is_rel, is_relative) <<
"is rel failure on " << cur_case.test;
// Now resolve it.
if (succeed_is_rel && is_relative && cur_case.is_rel) {
std::string resolved;
StdStringCanonOutput output(&resolved);
Parsed resolved_parsed;
bool succeed_resolve = ResolveRelativeURL(
cur_case.base, parsed, cur_case.is_base_file, cur_case.test,
relative_component, NULL, &output, &resolved_parsed);
output.Complete();
EXPECT_EQ(cur_case.succeed_resolve, succeed_resolve);
EXPECT_EQ(cur_case.resolved, resolved) << " on " << cur_case.test;
// Verify that the output parsed structure is the same as parsing a
// the URL freshly.
Parsed ref_parsed;
int resolved_len = static_cast<int>(resolved.size());
if (cur_case.is_base_file) {
ParseFileURL(resolved.c_str(), resolved_len, &ref_parsed);
} else if (cur_case.is_base_hier) {
ParseStandardURL(resolved.c_str(), resolved_len, &ref_parsed);
} else {
ParsePathURL(resolved.c_str(), resolved_len, false, &ref_parsed);
}
EXPECT_TRUE(ParsedIsEqual(ref_parsed, resolved_parsed));
}
}
}
// It used to be the case that when we did a replacement with a long buffer of
// UTF-16 characters, we would get invalid data in the URL. This is because the
// buffer that it used to hold the UTF-8 data was resized, while some pointers
// were still kept to the old buffer that was removed.
TEST(URLCanonTest, ReplacementOverflow) {
const char src[] = "file:///C:/foo/bar";
int src_len = static_cast<int>(strlen(src));
Parsed parsed;
ParseFileURL(src, src_len, &parsed);
// Override two components, the path with something short, and the query with
// something long enough to trigger the bug.
Replacements<char16_t> repl;
std::u16string new_query;
for (int i = 0; i < 4800; i++)
new_query.push_back('a');
std::u16string new_path(test_utils::TruncateWStringToUTF16(L"/foo"));
repl.SetPath(new_path.c_str(), Component(0, 4));
repl.SetQuery(new_query.c_str(),
Component(0, static_cast<int>(new_query.length())));
// Call ReplaceComponents on the string. It doesn't matter if we call it for
// standard URLs, file URLs, etc, since they will go to the same replacement
// function that was buggy.
Parsed repl_parsed;
std::string repl_str;
StdStringCanonOutput repl_output(&repl_str);
ReplaceFileURL(src, parsed, repl, NULL, &repl_output, &repl_parsed);
repl_output.Complete();
// Generate the expected string and check.
std::string expected("file:///foo?");
for (size_t i = 0; i < new_query.length(); i++)
expected.push_back('a');
EXPECT_TRUE(expected == repl_str);
}
TEST(URLCanonTest, DefaultPortForScheme) {
struct TestCases {
const char* scheme;
const int expected_port;
} cases[]{
{"http", 80},
{"https", 443},
{"ftp", 21},
{"ws", 80},
{"wss", 443},
{"fake-scheme", PORT_UNSPECIFIED},
{"HTTP", PORT_UNSPECIFIED},
{"HTTPS", PORT_UNSPECIFIED},
{"FTP", PORT_UNSPECIFIED},
{"WS", PORT_UNSPECIFIED},
{"WSS", PORT_UNSPECIFIED},
};
for (auto& test_case : cases) {
SCOPED_TRACE(test_case.scheme);
EXPECT_EQ(test_case.expected_port,
DefaultPortForScheme(test_case.scheme, strlen(test_case.scheme)));
}
}
TEST(URLCanonTest, FindWindowsDriveLetter) {
struct TestCase {
base::StringPiece spec;
int begin;
int end; // -1 for end of spec
int expected_drive_letter_pos;
} cases[] = {
{"/", 0, -1, -1},
{"c:/foo", 0, -1, 0},
{"/c:/foo", 0, -1, 1},
{"//c:/foo", 0, -1, -1}, // "//" does not canonicalize to "/"
{"\\C|\\foo", 0, -1, 1},
{"/cd:/foo", 0, -1, -1}, // "/c" does not canonicalize to "/"
{"/./c:/foo", 0, -1, 3},
{"/.//c:/foo", 0, -1, -1}, // "/.//" does not canonicalize to "/"
{"/././c:/foo", 0, -1, 5},
{"/abc/c:/foo", 0, -1, -1}, // "/abc/" does not canonicalize to "/"
{"/abc/./../c:/foo", 0, -1, 10},
{"/c:/c:/foo", 3, -1, 4}, // actual input is "/c:/foo"
{"/c:/foo", 3, -1, -1}, // actual input is "/foo"
{"/c:/foo", 0, 1, -1}, // actual input is "/"
};
for (const auto& c : cases) {
int end = c.end;
if (end == -1)
end = c.spec.size();
EXPECT_EQ(c.expected_drive_letter_pos,
FindWindowsDriveLetter(c.spec.data(), c.begin, end))
<< "for " << c.spec << "[" << c.begin << ":" << end << "] (UTF-8)";
std::u16string spec16 = base::ASCIIToUTF16(c.spec);
EXPECT_EQ(c.expected_drive_letter_pos,
FindWindowsDriveLetter(spec16.data(), c.begin, end))
<< "for " << c.spec << "[" << c.begin << ":" << end << "] (UTF-16)";
}
}
TEST(URLCanonTest, IDNToASCII) {
RawCanonOutputW<1024> output;
// Basic ASCII test.
std::u16string str = u"hello";
EXPECT_TRUE(IDNToASCII(str.data(), str.length(), &output));
EXPECT_EQ(u"hello", std::u16string(output.data()));
output.set_length(0);
// Mixed ASCII/non-ASCII.
str = u"hellö";
EXPECT_TRUE(IDNToASCII(str.data(), str.length(), &output));
EXPECT_EQ(u"xn--hell-8qa", std::u16string(output.data()));
output.set_length(0);
// All non-ASCII.
str = u"你好";
EXPECT_TRUE(IDNToASCII(str.data(), str.length(), &output));
EXPECT_EQ(u"xn--6qq79v", std::u16string(output.data()));
output.set_length(0);
// Characters that need mapping (the resulting Punycode is the encoding for
// "1⁄4").
str = u"¼";
EXPECT_TRUE(IDNToASCII(str.data(), str.length(), &output));
EXPECT_EQ(u"xn--14-c6t", std::u16string(output.data()));
output.set_length(0);
// String to encode already starts with "xn--", and all ASCII. Should not
// modify the string.
str = u"xn--hell-8qa";
EXPECT_TRUE(IDNToASCII(str.data(), str.length(), &output));
EXPECT_EQ(u"xn--hell-8qa", std::u16string(output.data()));
output.set_length(0);
// String to encode already starts with "xn--", and mixed ASCII/non-ASCII.
// Should fail, due to a special case: if the label starts with "xn--", it
// should be parsed as Punycode, which must be all ASCII.
str = u"xn--hellö";
EXPECT_FALSE(IDNToASCII(str.data(), str.length(), &output));
output.set_length(0);
// String to encode already starts with "xn--", and mixed ASCII/non-ASCII.
// This tests that there is still an error for the character '⁄' (U+2044),
// which would be a valid ASCII character, U+0044, if the high byte were
// ignored.
str = u"xn--1⁄4";
EXPECT_FALSE(IDNToASCII(str.data(), str.length(), &output));
output.set_length(0);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_canon_unittest.cc | C++ | unknown | 126,962 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_constants.h"
namespace url {
const char kAboutBlankURL[] = "about:blank";
const char16_t kAboutBlankURL16[] = u"about:blank";
const char kAboutSrcdocURL[] = "about:srcdoc";
const char16_t kAboutSrcdocURL16[] = u"about:srcdoc";
const char kAboutBlankPath[] = "blank";
const char16_t kAboutBlankPath16[] = u"blank";
const char kAboutSrcdocPath[] = "srcdoc";
const char16_t kAboutSrcdocPath16[] = u"srcdoc";
const char kAboutScheme[] = "about";
const char16_t kAboutScheme16[] = u"about";
const char kBlobScheme[] = "blob";
const char16_t kBlobScheme16[] = u"blob";
const char kContentScheme[] = "content";
const char16_t kContentScheme16[] = u"content";
const char kContentIDScheme[] = "cid";
const char16_t kContentIDScheme16[] = u"cid";
const char kDataScheme[] = "data";
const char16_t kDataScheme16[] = u"data";
const char kFileScheme[] = "file";
const char16_t kFileScheme16[] = u"file";
const char kFileSystemScheme[] = "filesystem";
const char16_t kFileSystemScheme16[] = u"filesystem";
const char kFtpScheme[] = "ftp";
const char16_t kFtpScheme16[] = u"ftp";
const char kHttpScheme[] = "http";
const char16_t kHttpScheme16[] = u"http";
const char kHttpsScheme[] = "https";
const char16_t kHttpsScheme16[] = u"https";
const char kJavaScriptScheme[] = "javascript";
const char16_t kJavaScriptScheme16[] = u"javascript";
const char kMailToScheme[] = "mailto";
const char16_t kMailToScheme16[] = u"mailto";
const char kTelScheme[] = "tel";
const char16_t kTelScheme16[] = u"tel";
const char kUrnScheme[] = "urn";
const char16_t kUrnScheme16[] = u"urn";
const char kUuidInPackageScheme[] = "uuid-in-package";
const char16_t kUuidInPackageScheme16[] = u"uuid-in-package";
const char kWebcalScheme[] = "webcal";
const char16_t kWebcalScheme16[] = u"webcal";
const char kWsScheme[] = "ws";
const char16_t kWsScheme16[] = u"ws";
const char kWssScheme[] = "wss";
const char16_t kWssScheme16[] = u"wss";
const char kStandardSchemeSeparator[] = "://";
const char16_t kStandardSchemeSeparator16[] = u"://";
#ifdef OHOS_HAP_DECOMPRESSED
const char kResourcesScheme[] = "resource";
const char16_t kResourcesScheme16[] = u"resource";
#endif
#ifdef OHOS_FILE_UPLOAD
const char kDataabilityScheme[] = "dataability";
const char kDatashareScheme[] = "datashare";
#endif // OHOS_FILE_UPLOAD
const size_t kMaxURLChars = 2 * 1024 * 1024;
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_constants.cc | C++ | unknown | 2,511 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_CONSTANTS_H_
#define URL_URL_CONSTANTS_H_
#include <stddef.h>
#include "base/component_export.h"
#include "build/build_config.h"
namespace url {
COMPONENT_EXPORT(URL) extern const char kAboutBlankURL[];
COMPONENT_EXPORT(URL) extern const char16_t kAboutBlankURL16[];
COMPONENT_EXPORT(URL) extern const char kAboutSrcdocURL[];
COMPONENT_EXPORT(URL) extern const char16_t kAboutSrcdocURL16[];
COMPONENT_EXPORT(URL) extern const char kAboutBlankPath[];
COMPONENT_EXPORT(URL) extern const char16_t kAboutBlankPath16[];
COMPONENT_EXPORT(URL) extern const char kAboutSrcdocPath[];
COMPONENT_EXPORT(URL) extern const char16_t kAboutSrcdocPath16[];
COMPONENT_EXPORT(URL) extern const char kAboutScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kAboutScheme16[];
COMPONENT_EXPORT(URL) extern const char kBlobScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kBlobScheme16[];
// The content scheme is specific to Android for identifying a stored file.
COMPONENT_EXPORT(URL) extern const char kContentScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kContentScheme16[];
COMPONENT_EXPORT(URL) extern const char kContentIDScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kContentIDScheme16[];
COMPONENT_EXPORT(URL) extern const char kDataScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kDataScheme16[];
COMPONENT_EXPORT(URL) extern const char kFileScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kFileScheme16[];
COMPONENT_EXPORT(URL) extern const char kFileSystemScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kFileSystemScheme16[];
COMPONENT_EXPORT(URL) extern const char kFtpScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kFtpScheme16[];
COMPONENT_EXPORT(URL) extern const char kHttpScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kHttpScheme16[];
COMPONENT_EXPORT(URL) extern const char kHttpsScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kHttpsScheme16[];
COMPONENT_EXPORT(URL) extern const char kJavaScriptScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kJavaScriptScheme16[];
COMPONENT_EXPORT(URL) extern const char kMailToScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kMailToScheme16[];
COMPONENT_EXPORT(URL) extern const char kTelScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kTelScheme16[];
COMPONENT_EXPORT(URL) extern const char kUrnScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kUrnScheme16[];
COMPONENT_EXPORT(URL) extern const char kUuidInPackageScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kUuidInPackageScheme16[];
COMPONENT_EXPORT(URL) extern const char kWebcalScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kWebcalScheme16[];
COMPONENT_EXPORT(URL) extern const char kWsScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kWsScheme16[];
COMPONENT_EXPORT(URL) extern const char kWssScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kWssScheme16[];
#if BUILDFLAG(IS_OHOS)
COMPONENT_EXPORT(URL) extern const char kResourcesScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kResourcesScheme16[];
#endif // #if BUILDFLAG(IS_OHOS)
// Used to separate a standard scheme and the hostname: "://".
COMPONENT_EXPORT(URL) extern const char kStandardSchemeSeparator[];
COMPONENT_EXPORT(URL) extern const char16_t kStandardSchemeSeparator16[];
COMPONENT_EXPORT(URL) extern const size_t kMaxURLChars;
#ifdef OHOS_HAP_DECOMPRESSED
COMPONENT_EXPORT(URL) extern const char kResourcesScheme[];
COMPONENT_EXPORT(URL) extern const char16_t kResourcesScheme16[];
#endif
#ifdef OHOS_FILE_UPLOAD
COMPONENT_EXPORT(URL) extern const char kDatashareScheme[];
COMPONENT_EXPORT(URL) extern const char kDataabilityScheme[];
#endif // OHOS_FILE_UPLOAD
} // namespace url
#endif // URL_URL_CONSTANTS_H_
| Zhao-PengFei35/chromium_src_4 | url/url_constants.h | C++ | unknown | 3,866 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_features.h"
namespace url {
BASE_FEATURE(kUseIDNA2008NonTransitional,
"UseIDNA2008NonTransitional",
base::FEATURE_ENABLED_BY_DEFAULT);
// Kill switch for crbug.com/1362507.
BASE_FEATURE(kRecordIDNA2008Metrics,
"RecordIDNA2008Metrics",
base::FEATURE_ENABLED_BY_DEFAULT);
BASE_FEATURE(kStrictIPv4EmbeddedIPv6AddressParsing,
"StrictIPv4EmbeddedIPv6AddressParsing",
base::FEATURE_DISABLED_BY_DEFAULT);
// Kill switch for crbug.com/1220361.
BASE_FEATURE(kResolveBareFragmentWithColonOnNonHierarchical,
"ResolveBareFragmentWithColonOnNonHierarchical",
base::FEATURE_ENABLED_BY_DEFAULT);
bool IsUsingIDNA2008NonTransitional() {
return base::FeatureList::IsEnabled(kUseIDNA2008NonTransitional);
}
bool IsRecordingIDNA2008Metrics() {
return base::FeatureList::IsEnabled(kRecordIDNA2008Metrics);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_features.cc | C++ | unknown | 1,086 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_FEATURES_H_
#define URL_URL_FEATURES_H_
#include "base/component_export.h"
#include "base/feature_list.h"
namespace url {
COMPONENT_EXPORT(URL) BASE_DECLARE_FEATURE(kUseIDNA2008NonTransitional);
// Returns true if Chrome is using IDNA 2008 in Non-Transitional mode.
COMPONENT_EXPORT(URL) bool IsUsingIDNA2008NonTransitional();
// Returns true if Chrome is recording IDNA 2008 related metrics.
COMPONENT_EXPORT(URL) bool IsRecordingIDNA2008Metrics();
// Returns true if Chrome is enforcing the 4 part check for IPv4 embedded IPv6
// addresses.
COMPONENT_EXPORT(URL)
BASE_DECLARE_FEATURE(kStrictIPv4EmbeddedIPv6AddressParsing);
// When enabled, allows resolving of a bare fragment containing a colon against
// a non-hierarchical URL. (For example '#foo:bar' against 'about:blank'.)
COMPONENT_EXPORT(URL)
BASE_DECLARE_FEATURE(kResolveBareFragmentWithColonOnNonHierarchical);
} // namespace url
#endif // URL_URL_FEATURES_H_
| Zhao-PengFei35/chromium_src_4 | url/url_features.h | C++ | unknown | 1,093 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_FILE_H_
#define URL_URL_FILE_H_
// Provides shared functions used by the internals of the parser and
// canonicalizer for file URLs. Do not use outside of these modules.
#include "base/strings/string_util.h"
#include "url/url_parse_internal.h"
namespace url {
// We allow both "c:" and "c|" as drive identifiers.
inline bool IsWindowsDriveSeparator(char16_t ch) {
return ch == ':' || ch == '|';
}
inline bool IsWindowsDriveSeparator(char ch) {
return IsWindowsDriveSeparator(static_cast<char16_t>(ch));
}
// Returns the index of the next slash in the input after the given index, or
// spec_len if the end of the input is reached.
template<typename CHAR>
inline int FindNextSlash(const CHAR* spec, int begin_index, int spec_len) {
int idx = begin_index;
while (idx < spec_len && !IsURLSlash(spec[idx]))
idx++;
return idx;
}
// DoesContainWindowsDriveSpecUntil returns the least number between
// start_offset and max_offset such that the spec has a valid drive
// specification starting at that offset. Otherwise it returns -1. This function
// gracefully handles, by returning -1, start_offset values that are equal to or
// larger than the spec_len, and caps max_offset appropriately to simplify
// callers. max_offset must be at least start_offset.
template <typename CHAR>
inline int DoesContainWindowsDriveSpecUntil(const CHAR* spec,
int start_offset,
int max_offset,
int spec_len) {
CHECK_LE(start_offset, max_offset);
if (start_offset > spec_len - 2)
return -1; // Not enough room.
if (max_offset > spec_len - 2)
max_offset = spec_len - 2;
for (int offset = start_offset; offset <= max_offset; ++offset) {
if (!base::IsAsciiAlpha(spec[offset]))
continue; // Doesn't contain a valid drive letter.
if (!IsWindowsDriveSeparator(spec[offset + 1]))
continue; // Isn't followed with a drive separator.
return offset;
}
return -1;
}
// Returns true if the start_offset in the given spec looks like it begins a
// drive spec, for example "c:". This function explicitly handles start_offset
// values that are equal to or larger than the spec_len to simplify callers.
//
// If this returns true, the spec is guaranteed to have a valid drive letter
// plus a drive letter separator (a colon or a pipe) starting at |start_offset|.
template <typename CHAR>
inline bool DoesBeginWindowsDriveSpec(const CHAR* spec,
int start_offset,
int spec_len) {
return DoesContainWindowsDriveSpecUntil(spec, start_offset, start_offset,
spec_len) == start_offset;
}
#ifdef WIN32
// Returns true if the start_offset in the given text looks like it begins a
// UNC path, for example "\\". This function explicitly handles start_offset
// values that are equal to or larger than the spec_len to simplify callers.
//
// When strict_slashes is set, this function will only accept backslashes as is
// standard for Windows. Otherwise, it will accept forward slashes as well
// which we use for a lot of URL handling.
template<typename CHAR>
inline bool DoesBeginUNCPath(const CHAR* text,
int start_offset,
int len,
bool strict_slashes) {
int remaining_len = len - start_offset;
if (remaining_len < 2)
return false;
if (strict_slashes)
return text[start_offset] == '\\' && text[start_offset + 1] == '\\';
return IsURLSlash(text[start_offset]) && IsURLSlash(text[start_offset + 1]);
}
#endif // WIN32
} // namespace url
#endif // URL_URL_FILE_H_
| Zhao-PengFei35/chromium_src_4 | url/url_file.h | C++ | unknown | 3,909 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ICU-based IDNA converter.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ostream>
#include "base/check_op.h"
#include "third_party/icu/source/common/unicode/uidna.h"
#include "third_party/icu/source/common/unicode/utypes.h"
#include "url/url_canon_icu.h"
#include "url/url_canon_internal.h" // for _itoa_s
#include "url/url_features.h"
namespace url {
namespace {
// Use UIDNA, a C pointer to a UTS46/IDNA 2008 handling object opened with
// uidna_openUTS46().
//
// We use UTS46 with BiDiCheck to migrate from IDNA 2003 (with unassigned
// code points allowed) to IDNA 2008 with the backward compatibility in mind.
// What it does:
//
// 1. Use the up-to-date Unicode data.
// 2. Define a case folding/mapping with the up-to-date Unicode data as
// in IDNA 2003.
// 3. If `use_idna_non_transitional` is true, use non-transitional mechanism for
// 4 deviation characters (sharp-s, final sigma, ZWJ and ZWNJ) per
// url.spec.whatwg.org.
// 4. Continue to allow symbols and punctuations.
// 5. Apply new BiDi check rules more permissive than the IDNA 2003 BiDI rules.
// 6. Do not apply STD3 rules
// 7. Do not allow unassigned code points.
//
// It also closely matches what IE 10 does except for the BiDi check (
// http://goo.gl/3XBhqw ).
// See http://http://unicode.org/reports/tr46/ and references therein
// for more details.
UIDNA* CreateIDNA(bool use_idna_non_transitional) {
uint32_t options = UIDNA_CHECK_BIDI;
if (use_idna_non_transitional) {
// Use non-transitional processing if enabled. See
// https://url.spec.whatwg.org/#idna for details.
options |=
UIDNA_NONTRANSITIONAL_TO_ASCII | UIDNA_NONTRANSITIONAL_TO_UNICODE;
}
UErrorCode err = U_ZERO_ERROR;
UIDNA* idna = uidna_openUTS46(options, &err);
if (U_FAILURE(err)) {
CHECK(false) << "failed to open UTS46 data with error: " << u_errorName(err)
<< ". If you see this error message in a test environment "
<< "your test environment likely lacks the required data "
<< "tables for libicu. See https://crbug.com/778929.";
idna = nullptr;
}
return idna;
}
UIDNA* GetUIDNA() {
// This logic results in having two UIDNA instances in tests. This is okay.
if (IsUsingIDNA2008NonTransitional()) {
static UIDNA* uidna = CreateIDNA(/*use_idna_non_transitional=*/true);
return uidna;
} else {
static UIDNA* uidna = CreateIDNA(/*use_idna_non_transitional=*/false);
return uidna;
}
}
} // namespace
// Converts the Unicode input representing a hostname to ASCII using IDN rules.
// The output must be ASCII, but is represented as wide characters.
//
// On success, the output will be filled with the ASCII host name and it will
// return true. Unlike most other canonicalization functions, this assumes that
// the output is empty. The beginning of the host will be at offset 0, and
// the length of the output will be set to the length of the new host name.
//
// On error, this will return false. The output in this case is undefined.
// TODO(jungshik): use UTF-8/ASCII version of nameToASCII.
// Change the function signature and callers accordingly to avoid unnecessary
// conversions in our code. In addition, consider using icu::IDNA's UTF-8/ASCII
// version with StringByteSink. That way, we can avoid C wrappers and additional
// string conversion.
bool IDNToASCII(const char16_t* src, int src_len, CanonOutputW* output) {
DCHECK(output->length() == 0); // Output buffer is assumed empty.
UIDNA* uidna = GetUIDNA();
DCHECK(uidna != nullptr);
while (true) {
UErrorCode err = U_ZERO_ERROR;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
int output_length = uidna_nameToASCII(uidna, src, src_len, output->data(),
output->capacity(), &info, &err);
// Ignore various errors for web compatibility. The options are specified
// by the WHATWG URL Standard. See
// - https://unicode.org/reports/tr46/
// - https://url.spec.whatwg.org/#concept-domain-to-ascii
// (we set beStrict to false)
// Disable the "CheckHyphens" option in UTS #46. See
// - https://crbug.com/804688
// - https://github.com/whatwg/url/issues/267
info.errors &= ~UIDNA_ERROR_HYPHEN_3_4;
info.errors &= ~UIDNA_ERROR_LEADING_HYPHEN;
info.errors &= ~UIDNA_ERROR_TRAILING_HYPHEN;
// Disable the "VerifyDnsLength" option in UTS #46.
info.errors &= ~UIDNA_ERROR_EMPTY_LABEL;
info.errors &= ~UIDNA_ERROR_LABEL_TOO_LONG;
info.errors &= ~UIDNA_ERROR_DOMAIN_NAME_TOO_LONG;
if (U_SUCCESS(err) && info.errors == 0) {
// Per WHATWG URL, it is a failure if the ToASCII output is empty.
//
// ICU would usually return UIDNA_ERROR_EMPTY_LABEL in this case, but we
// want to continue allowing http://abc..def/ while forbidding http:///.
//
if (output_length == 0) {
return false;
}
output->set_length(output_length);
return true;
}
if (err != U_BUFFER_OVERFLOW_ERROR || info.errors != 0)
return false; // Unknown error, give up.
// Not enough room in our buffer, expand.
output->Resize(output_length);
}
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_idna_icu.cc | C++ | unknown | 5,364 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include <string>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/strings/string_piece.h"
#include "url/url_canon_internal.h"
#include "url/url_jni_headers/IDNStringUtil_jni.h"
using base::android::ScopedJavaLocalRef;
namespace url {
// This uses the JDK's conversion function, which uses IDNA 2003, unlike the
// ICU implementation.
bool IDNToASCII(const char16_t* src, int src_len, CanonOutputW* output) {
DCHECK_EQ(0u, output->length()); // Output buffer is assumed empty.
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jstring> java_src =
base::android::ConvertUTF16ToJavaString(
env, base::StringPiece16(src, src_len));
ScopedJavaLocalRef<jstring> java_result =
android::Java_IDNStringUtil_idnToASCII(env, java_src);
// NULL indicates failure.
if (java_result.is_null())
return false;
std::u16string utf16_result =
base::android::ConvertJavaStringToUTF16(java_result);
output->Append(utf16_result.data(), utf16_result.size());
return true;
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_idna_icu_alternatives_android.cc | C++ | unknown | 1,271 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include <ostream>
#include <string>
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "url/url_canon_internal.h"
namespace url {
// Only allow ASCII to avoid ICU dependency. Use NSString+IDN
// to convert non-ASCII URL prior to passing to API.
bool IDNToASCII(const char16_t* src, int src_len, CanonOutputW* output) {
if (base::IsStringASCII(base::StringPiece16(src, src_len))) {
output->Append(src, src_len);
return true;
}
DCHECK(false) << "IDN URL support is not available.";
return false;
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_idna_icu_alternatives_ios.mm | Objective-C++ | unknown | 786 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/check.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_file.h"
#include "url/url_parse_internal.h"
// Interesting IE file:isms...
//
// INPUT OUTPUT
// ========================= ==============================
// file:/foo/bar file:///foo/bar
// The result here seems totally invalid!?!? This isn't UNC.
//
// file:/
// file:// or any other number of slashes
// IE6 doesn't do anything at all if you click on this link. No error:
// nothing. IE6's history system seems to always color this link, so I'm
// guessing that it maps internally to the empty URL.
//
// C:\ file:///C:/
// When on a file: URL source page, this link will work. When over HTTP,
// the file: URL will appear in the status bar but the link will not work
// (security restriction for all file URLs).
//
// file:foo/ file:foo/ (invalid?!?!?)
// file:/foo/ file:///foo/ (invalid?!?!?)
// file://foo/ file://foo/ (UNC to server "foo")
// file:///foo/ file:///foo/ (invalid, seems to be a file)
// file:////foo/ file://foo/ (UNC to server "foo")
// Any more than four slashes is also treated as UNC.
//
// file:C:/ file://C:/
// file:/C:/ file://C:/
// The number of slashes after "file:" don't matter if the thing following
// it looks like an absolute drive path. Also, slashes and backslashes are
// equally valid here.
namespace url {
namespace {
// A subcomponent of DoParseFileURL, the input of this function should be a UNC
// path name, with the index of the first character after the slashes following
// the scheme given in |after_slashes|. This will initialize the host, path,
// query, and ref, and leave the other output components untouched
// (DoParseFileURL handles these for us).
template <typename CHAR>
void DoParseUNC(const CHAR* spec,
int after_slashes,
int spec_len,
Parsed* parsed) {
int next_slash = FindNextSlash(spec, after_slashes, spec_len);
// Everything up until that first slash we found (or end of string) is the
// host name, which will end up being the UNC host. For example,
// "file://foo/bar.txt" will get a server name of "foo" and a path of "/bar".
// Later, on Windows, this should be treated as the filename "\\foo\bar.txt"
// in proper UNC notation.
if (after_slashes < next_slash)
parsed->host = MakeRange(after_slashes, next_slash);
else
parsed->host.reset();
if (next_slash < spec_len) {
ParsePathInternal(spec, MakeRange(next_slash, spec_len),
&parsed->path, &parsed->query, &parsed->ref);
} else {
parsed->path.reset();
}
}
// A subcomponent of DoParseFileURL, the input should be a local file, with the
// beginning of the path indicated by the index in |path_begin|. This will
// initialize the host, path, query, and ref, and leave the other output
// components untouched (DoParseFileURL handles these for us).
template<typename CHAR>
void DoParseLocalFile(const CHAR* spec,
int path_begin,
int spec_len,
Parsed* parsed) {
parsed->host.reset();
ParsePathInternal(spec, MakeRange(path_begin, spec_len),
&parsed->path, &parsed->query, &parsed->ref);
}
// Backend for the external functions that operates on either char type.
// Handles cases where there is a scheme, but also when handed the first
// character following the "file:" at the beginning of the spec. If so,
// this is usually a slash, but needn't be; we allow paths like "file:c:\foo".
template<typename CHAR>
void DoParseFileURL(const CHAR* spec, int spec_len, Parsed* parsed) {
DCHECK(spec_len >= 0);
// Get the parts we never use for file URLs out of the way.
parsed->username.reset();
parsed->password.reset();
parsed->port.reset();
// Many of the code paths don't set these, so it's convenient to just clear
// them. We'll write them in those cases we need them.
parsed->query.reset();
parsed->ref.reset();
// Strip leading & trailing spaces and control characters.
int begin = 0;
TrimURL(spec, &begin, &spec_len);
// Find the scheme, if any.
int num_slashes = CountConsecutiveSlashes(spec, begin, spec_len);
int after_scheme;
int after_slashes;
#ifdef WIN32
// See how many slashes there are. We want to handle cases like UNC but also
// "/c:/foo". This is when there is no scheme, so we can allow pages to do
// links like "c:/foo/bar" or "//foo/bar". This is also called by the
// relative URL resolver when it determines there is an absolute URL, which
// may give us input like "/c:/foo".
after_slashes = begin + num_slashes;
if (DoesBeginWindowsDriveSpec(spec, after_slashes, spec_len)) {
// Windows path, don't try to extract the scheme (for example, "c:\foo").
parsed->scheme.reset();
after_scheme = after_slashes;
} else if (DoesBeginUNCPath(spec, begin, spec_len, false)) {
// Windows UNC path: don't try to extract the scheme, but keep the slashes.
parsed->scheme.reset();
after_scheme = begin;
} else
#endif
{
// ExtractScheme doesn't understand the possibility of filenames with
// colons in them, in which case it returns the entire spec up to the
// colon as the scheme. So handle /foo.c:5 as a file but foo.c:5 as
// the foo.c: scheme.
if (!num_slashes &&
ExtractScheme(&spec[begin], spec_len - begin, &parsed->scheme)) {
// Offset the results since we gave ExtractScheme a substring.
parsed->scheme.begin += begin;
after_scheme = parsed->scheme.end() + 1;
} else {
// No scheme found, remember that.
parsed->scheme.reset();
after_scheme = begin;
}
}
// Handle empty specs ones that contain only whitespace or control chars,
// or that are just the scheme (for example "file:").
if (after_scheme == spec_len) {
parsed->host.reset();
parsed->path.reset();
return;
}
num_slashes = CountConsecutiveSlashes(spec, after_scheme, spec_len);
after_slashes = after_scheme + num_slashes;
#ifdef WIN32
// Check whether the input is a drive again. We checked above for windows
// drive specs, but that's only at the very beginning to see if we have a
// scheme at all. This test will be duplicated in that case, but will
// additionally handle all cases with a real scheme such as "file:///C:/".
if (!DoesBeginWindowsDriveSpec(spec, after_slashes, spec_len) &&
num_slashes != 3) {
// Anything not beginning with a drive spec ("c:\") on Windows is treated
// as UNC, with the exception of three slashes which always means a file.
// Even IE7 treats file:///foo/bar as "/foo/bar", which then fails.
DoParseUNC(spec, after_slashes, spec_len, parsed);
return;
}
#else
// file: URL with exactly 2 slashes is considered to have a host component.
if (num_slashes == 2) {
DoParseUNC(spec, after_slashes, spec_len, parsed);
return;
}
#endif // WIN32
// Easy and common case, the full path immediately follows the scheme
// (modulo slashes), as in "file://c:/foo". Just treat everything from
// there to the end as the path. Empty hosts have 0 length instead of -1.
// We include the last slash as part of the path if there is one.
DoParseLocalFile(spec,
num_slashes > 0 ? after_scheme + num_slashes - 1 : after_scheme,
spec_len, parsed);
}
} // namespace
void ParseFileURL(const char* url, int url_len, Parsed* parsed) {
DoParseFileURL(url, url_len, parsed);
}
void ParseFileURL(const char16_t* url, int url_len, Parsed* parsed) {
DoParseFileURL(url, url_len, parsed);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_parse_file.cc | C++ | unknown | 7,963 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_PARSE_INTERNAL_H_
#define URL_URL_PARSE_INTERNAL_H_
// Contains common inline helper functions used by the URL parsing routines.
#include "url/third_party/mozilla/url_parse.h"
namespace url {
// We treat slashes and backslashes the same for IE compatibility.
inline bool IsURLSlash(char16_t ch) {
return ch == '/' || ch == '\\';
}
inline bool IsURLSlash(char ch) {
return IsURLSlash(static_cast<char16_t>(ch));
}
// Returns true if we should trim this character from the URL because it is a
// space or a control character.
inline bool ShouldTrimFromURL(char16_t ch) {
return ch <= ' ';
}
inline bool ShouldTrimFromURL(char ch) {
return ShouldTrimFromURL(static_cast<char16_t>(ch));
}
// Given an already-initialized begin index and length, this shrinks the range
// to eliminate "should-be-trimmed" characters. Note that the length does *not*
// indicate the length of untrimmed data from |*begin|, but rather the position
// in the input string (so the string starts at character |*begin| in the spec,
// and goes until |*len|).
template<typename CHAR>
inline void TrimURL(const CHAR* spec, int* begin, int* len,
bool trim_path_end = true) {
// Strip leading whitespace and control characters.
while (*begin < *len && ShouldTrimFromURL(spec[*begin]))
(*begin)++;
if (trim_path_end) {
// Strip trailing whitespace and control characters. We need the >i test
// for when the input string is all blanks; we don't want to back past the
// input.
while (*len > *begin && ShouldTrimFromURL(spec[*len - 1]))
(*len)--;
}
}
// Counts the number of consecutive slashes starting at the given offset
// in the given string of the given length.
template<typename CHAR>
inline int CountConsecutiveSlashes(const CHAR *str,
int begin_offset, int str_len) {
int count = 0;
while (begin_offset + count < str_len &&
IsURLSlash(str[begin_offset + count]))
++count;
return count;
}
// Internal functions in url_parse.cc that parse the path, that is, everything
// following the authority section. The input is the range of everything
// following the authority section, and the output is the identified ranges.
//
// This is designed for the file URL parser or other consumers who may do
// special stuff at the beginning, but want regular path parsing, it just
// maps to the internal parsing function for paths.
void ParsePathInternal(const char* spec,
const Component& path,
Component* filepath,
Component* query,
Component* ref);
void ParsePathInternal(const char16_t* spec,
const Component& path,
Component* filepath,
Component* query,
Component* ref);
// Given a spec and a pointer to the character after the colon following the
// scheme, this parses it and fills in the structure, Every item in the parsed
// structure is filled EXCEPT for the scheme, which is untouched.
void ParseAfterScheme(const char* spec,
int spec_len,
int after_scheme,
Parsed* parsed);
void ParseAfterScheme(const char16_t* spec,
int spec_len,
int after_scheme,
Parsed* parsed);
} // namespace url
#endif // URL_URL_PARSE_INTERNAL_H_
| Zhao-PengFei35/chromium_src_4 | url/url_parse_internal.h | C++ | unknown | 3,604 |
// Copyright 2006-2008 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/string_piece.h"
#include "base/test/perf_time_logger.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_canon.h"
#include "url/url_canon_stdstring.h"
namespace {
TEST(URLParse, FullURL) {
constexpr base::StringPiece kUrl =
"http://me:pass@host/foo/bar.html;param?query=yes#ref";
url::Parsed parsed;
base::PerfTimeLogger timer("Full_URL_Parse_AMillion");
for (int i = 0; i < 1000000; i++)
url::ParseStandardURL(kUrl.data(), kUrl.size(), &parsed);
timer.Done();
}
constexpr base::StringPiece kTypicalUrl1 =
"http://www.google.com/"
"search?q=url+parsing&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:"
"official&client=firefox-a";
constexpr base::StringPiece kTypicalUrl2 =
"http://www.amazon.com/Stephen-King-Thrillers-Horror-People/dp/0766012336/"
"ref=sr_1_2/133-4144931-4505264?ie=UTF8&s=books&qid=2144880915&sr=8-2";
constexpr base::StringPiece kTypicalUrl3 =
"http://store.apple.com/1-800-MY-APPLE/WebObjects/AppleStore.woa/wa/"
"RSLID?nnmm=browse&mco=578E9744&node=home/desktop/mac_pro";
TEST(URLParse, TypicalURLParse) {
url::Parsed parsed1;
url::Parsed parsed2;
url::Parsed parsed3;
// Do this 1/3 of a million times since we do 3 different URLs.
base::PerfTimeLogger parse_timer("Typical_URL_Parse_AMillion");
for (int i = 0; i < 333333; i++) {
url::ParseStandardURL(kTypicalUrl1.data(), kTypicalUrl1.size(), &parsed1);
url::ParseStandardURL(kTypicalUrl2.data(), kTypicalUrl2.size(), &parsed2);
url::ParseStandardURL(kTypicalUrl3.data(), kTypicalUrl3.size(), &parsed3);
}
parse_timer.Done();
}
// Includes both parsing and canonicalization with no mallocs.
TEST(URLParse, TypicalURLParseCanon) {
url::Parsed parsed1;
url::Parsed parsed2;
url::Parsed parsed3;
base::PerfTimeLogger canon_timer("Typical_Parse_Canon_AMillion");
url::Parsed out_parsed;
url::RawCanonOutput<1024> output;
for (int i = 0; i < 333333; i++) { // divide by 3 so we get 1M
url::ParseStandardURL(kTypicalUrl1.data(), kTypicalUrl1.size(), &parsed1);
output.set_length(0);
url::CanonicalizeStandardURL(
kTypicalUrl1.data(), kTypicalUrl1.size(), parsed1,
url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr, &output,
&out_parsed);
url::ParseStandardURL(kTypicalUrl2.data(), kTypicalUrl2.size(), &parsed2);
output.set_length(0);
url::CanonicalizeStandardURL(
kTypicalUrl2.data(), kTypicalUrl2.size(), parsed2,
url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr, &output,
&out_parsed);
url::ParseStandardURL(kTypicalUrl3.data(), kTypicalUrl3.size(), &parsed3);
output.set_length(0);
url::CanonicalizeStandardURL(
kTypicalUrl3.data(), kTypicalUrl3.size(), parsed3,
url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr, &output,
&out_parsed);
}
canon_timer.Done();
}
// Includes both parsing and canonicalization, and mallocs for the output.
TEST(URLParse, TypicalURLParseCanonStdString) {
url::Parsed parsed1;
url::Parsed parsed2;
url::Parsed parsed3;
base::PerfTimeLogger canon_timer("Typical_Parse_Canon_AMillion");
url::Parsed out_parsed;
for (int i = 0; i < 333333; i++) { // divide by 3 so we get 1M
url::ParseStandardURL(kTypicalUrl1.data(), kTypicalUrl1.size(), &parsed1);
std::string out1;
url::StdStringCanonOutput output1(&out1);
url::CanonicalizeStandardURL(
kTypicalUrl1.data(), kTypicalUrl1.size(), parsed1,
url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr, &output1,
&out_parsed);
url::ParseStandardURL(kTypicalUrl2.data(), kTypicalUrl2.size(), &parsed2);
std::string out2;
url::StdStringCanonOutput output2(&out2);
url::CanonicalizeStandardURL(
kTypicalUrl2.data(), kTypicalUrl2.size(), parsed2,
url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr, &output2,
&out_parsed);
url::ParseStandardURL(kTypicalUrl3.data(), kTypicalUrl3.size(), &parsed3);
std::string out3;
url::StdStringCanonOutput output3(&out3);
url::CanonicalizeStandardURL(
kTypicalUrl3.data(), kTypicalUrl3.size(), parsed3,
url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, nullptr, &output3,
&out_parsed);
}
canon_timer.Done();
}
TEST(URLParse, GURL) {
base::PerfTimeLogger gurl_timer("Typical_GURL_AMillion");
for (int i = 0; i < 333333; i++) { // divide by 3 so we get 1M
GURL gurl1(kTypicalUrl1);
GURL gurl2(kTypicalUrl2);
GURL gurl3(kTypicalUrl3);
}
gurl_timer.Done();
}
} // namespace
| Zhao-PengFei35/chromium_src_4 | url/url_parse_perftest.cc | C++ | unknown | 4,810 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "testing/gtest/include/gtest/gtest.h"
#include "url/third_party/mozilla/url_parse.h"
// Interesting IE file:isms...
//
// file:/foo/bar file:///foo/bar
// The result here seems totally invalid!?!? This isn't UNC.
//
// file:/
// file:// or any other number of slashes
// IE6 doesn't do anything at all if you click on this link. No error:
// nothing. IE6's history system seems to always color this link, so I'm
// guessing that it maps internally to the empty URL.
//
// C:\ file:///C:/
// / file:///C:/
// /foo file:///C:/foo
// Interestingly, IE treats "/" as an alias for "c:\", which makes sense,
// but is weird to think about on Windows.
//
// file:foo/ file:foo/ (invalid?!?!?)
// file:/foo/ file:///foo/ (invalid?!?!?)
// file://foo/ file://foo/ (UNC to server "foo")
// file:///foo/ file:///foo/ (invalid)
// file:////foo/ file://foo/ (UNC to server "foo")
// Any more than four slashes is also treated as UNC.
//
// file:C:/ file://C:/
// file:/C:/ file://C:/
// The number of slashes after "file:" don't matter if the thing following
// it looks like an absolute drive path. Also, slashes and backslashes are
// equally valid here.
namespace url {
namespace {
// Used for regular URL parse cases.
struct URLParseCase {
const char* input;
const char* scheme;
const char* username;
const char* password;
const char* host;
int port;
const char* path;
const char* query;
const char* ref;
};
// Simpler version of URLParseCase for testing path URLs.
struct PathURLParseCase {
const char* input;
const char* scheme;
const char* path;
};
// Simpler version of URLParseCase for testing mailto URLs.
struct MailtoURLParseCase {
const char* input;
const char* scheme;
const char* path;
const char* query;
};
// More complicated version of URLParseCase for testing filesystem URLs.
struct FileSystemURLParseCase {
const char* input;
const char* inner_scheme;
const char* inner_username;
const char* inner_password;
const char* inner_host;
int inner_port;
const char* inner_path;
const char* path;
const char* query;
const char* ref;
};
bool ComponentMatches(const char* input,
const char* reference,
const Component& component) {
// Check that the -1 sentinel is the only allowed negative value.
EXPECT_TRUE(component.is_valid() || component.len == -1);
// Begin should be valid.
EXPECT_LE(0, component.begin);
// A NULL reference means the component should be nonexistent.
if (!reference)
return component.len == -1;
if (!component.is_valid())
return false; // Reference is not NULL but we don't have anything
if (strlen(reference) != static_cast<size_t>(component.len))
return false; // Lengths don't match
// Now check the actual characters.
return strncmp(reference, &input[component.begin], component.len) == 0;
}
void ExpectInvalidComponent(const Component& component) {
EXPECT_EQ(0, component.begin);
EXPECT_EQ(-1, component.len);
}
// Parsed ----------------------------------------------------------------------
TEST(URLParser, Length) {
const char* length_cases[] = {
// One with everything in it.
"http://user:pass@host:99/foo?bar#baz",
// One with nothing in it.
"",
// Working backwards, let's start taking off stuff from the full one.
"http://user:pass@host:99/foo?bar#",
"http://user:pass@host:99/foo?bar",
"http://user:pass@host:99/foo?",
"http://user:pass@host:99/foo",
"http://user:pass@host:99/",
"http://user:pass@host:99",
"http://user:pass@host:",
"http://user:pass@host",
"http://host",
"http://user@",
"http:",
};
for (size_t i = 0; i < std::size(length_cases); i++) {
int true_length = static_cast<int>(strlen(length_cases[i]));
Parsed parsed;
ParseStandardURL(length_cases[i], true_length, &parsed);
EXPECT_EQ(true_length, parsed.Length());
}
}
TEST(URLParser, CountCharactersBefore) {
struct CountCase {
const char* url;
Parsed::ComponentType component;
bool include_delimiter;
int expected_count;
} count_cases[] = {
// Test each possibility in the case where all components are present.
// 0 1 2
// 0123456789012345678901
{"http://u:p@h:8/p?q#r", Parsed::SCHEME, true, 0},
{"http://u:p@h:8/p?q#r", Parsed::SCHEME, false, 0},
{"http://u:p@h:8/p?q#r", Parsed::USERNAME, true, 7},
{"http://u:p@h:8/p?q#r", Parsed::USERNAME, false, 7},
{"http://u:p@h:8/p?q#r", Parsed::PASSWORD, true, 9},
{"http://u:p@h:8/p?q#r", Parsed::PASSWORD, false, 9},
{"http://u:p@h:8/p?q#r", Parsed::HOST, true, 11},
{"http://u:p@h:8/p?q#r", Parsed::HOST, false, 11},
{"http://u:p@h:8/p?q#r", Parsed::PORT, true, 12},
{"http://u:p@h:8/p?q#r", Parsed::PORT, false, 13},
{"http://u:p@h:8/p?q#r", Parsed::PATH, false, 14},
{"http://u:p@h:8/p?q#r", Parsed::PATH, true, 14},
{"http://u:p@h:8/p?q#r", Parsed::QUERY, true, 16},
{"http://u:p@h:8/p?q#r", Parsed::QUERY, false, 17},
{"http://u:p@h:8/p?q#r", Parsed::REF, true, 18},
{"http://u:p@h:8/p?q#r", Parsed::REF, false, 19},
// Now test when the requested component is missing.
{"http://u:p@h:8/p?", Parsed::REF, true, 17},
{"http://u:p@h:8/p?q", Parsed::REF, true, 18},
{"http://u:p@h:8/p#r", Parsed::QUERY, true, 16},
{"http://u:p@h:8#r", Parsed::PATH, true, 14},
{"http://u:p@h/", Parsed::PORT, true, 12},
{"http://u:p@/", Parsed::HOST, true, 11},
// This case is a little weird. It will report that the password would
// start where the host begins. This is arguably correct, although you
// could also argue that it should start at the '@' sign. Doing it
// starting with the '@' sign is actually harder, so we don't bother.
{"http://u@h/", Parsed::PASSWORD, true, 9},
{"http://h/", Parsed::USERNAME, true, 7},
{"http:", Parsed::USERNAME, true, 5},
{"", Parsed::SCHEME, true, 0},
// Make sure a random component still works when there's nothing there.
{"", Parsed::REF, true, 0},
// File URLs are special with no host, so we test those.
{"file:///c:/foo", Parsed::USERNAME, true, 7},
{"file:///c:/foo", Parsed::PASSWORD, true, 7},
{"file:///c:/foo", Parsed::HOST, true, 7},
{"file:///c:/foo", Parsed::PATH, true, 7},
};
for (size_t i = 0; i < std::size(count_cases); i++) {
int length = static_cast<int>(strlen(count_cases[i].url));
// Simple test to distinguish file and standard URLs.
Parsed parsed;
if (length > 0 && count_cases[i].url[0] == 'f')
ParseFileURL(count_cases[i].url, length, &parsed);
else
ParseStandardURL(count_cases[i].url, length, &parsed);
int chars_before = parsed.CountCharactersBefore(
count_cases[i].component, count_cases[i].include_delimiter);
EXPECT_EQ(count_cases[i].expected_count, chars_before);
}
}
// Standard --------------------------------------------------------------------
// Input Scheme Usrname Passwd Host Port Path Query Ref
// ------------------------------------ ------- ------- ---------- ------------ --- ---------- ------------ -----
static URLParseCase cases[] = {
// Regular URL with all the parts
{"http://user:pass@foo:21/bar;par?b#c", "http", "user", "pass", "foo", 21, "/bar;par","b", "c"},
// Known schemes should lean towards authority identification
{"http:foo.com", "http", NULL, NULL, "foo.com", -1, NULL, NULL, NULL},
// Spaces!
{"\t :foo.com \n", "", NULL, NULL, "foo.com", -1, NULL, NULL, NULL},
{" foo.com ", NULL, NULL, NULL, "foo.com", -1, NULL, NULL, NULL},
{"a:\t foo.com", "a", NULL, NULL, "\t foo.com", -1, NULL, NULL, NULL},
{"http://f:21/ b ? d # e ", "http", NULL, NULL, "f", 21, "/ b ", " d ", " e"},
// Invalid port numbers should be identified and turned into -2, empty port
// numbers should be -1. Spaces aren't allowed in port numbers
{"http://f:/c", "http", NULL, NULL, "f", -1, "/c", NULL, NULL},
{"http://f:0/c", "http", NULL, NULL, "f", 0, "/c", NULL, NULL},
{"http://f:00000000000000/c", "http", NULL, NULL, "f", 0, "/c", NULL, NULL},
{"http://f:00000000000000000000080/c", "http", NULL, NULL, "f", 80, "/c", NULL, NULL},
{"http://f:b/c", "http", NULL, NULL, "f", -2, "/c", NULL, NULL},
{"http://f: /c", "http", NULL, NULL, "f", -2, "/c", NULL, NULL},
{"http://f:\n/c", "http", NULL, NULL, "f", -2, "/c", NULL, NULL},
{"http://f:fifty-two/c", "http", NULL, NULL, "f", -2, "/c", NULL, NULL},
{"http://f:999999/c", "http", NULL, NULL, "f", -2, "/c", NULL, NULL},
{"http://f: 21 / b ? d # e ", "http", NULL, NULL, "f", -2, "/ b ", " d ", " e"},
// Creative URLs missing key elements
{"", NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL},
{" \t", NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL},
{":foo.com/", "", NULL, NULL, "foo.com", -1, "/", NULL, NULL},
{":foo.com\\", "", NULL, NULL, "foo.com", -1, "\\", NULL, NULL},
{":", "", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{":a", "", NULL, NULL, "a", -1, NULL, NULL, NULL},
{":/", "", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{":\\", "", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{":#", "", NULL, NULL, NULL, -1, NULL, NULL, ""},
{"#", NULL, NULL, NULL, NULL, -1, NULL, NULL, ""},
{"#/", NULL, NULL, NULL, NULL, -1, NULL, NULL, "/"},
{"#\\", NULL, NULL, NULL, NULL, -1, NULL, NULL, "\\"},
{"#;?", NULL, NULL, NULL, NULL, -1, NULL, NULL, ";?"},
{"?", NULL, NULL, NULL, NULL, -1, NULL, "", NULL},
{"/", NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL},
{":23", "", NULL, NULL, "23", -1, NULL, NULL, NULL},
{"/:23", "/", NULL, NULL, "23", -1, NULL, NULL, NULL},
{"//", NULL, NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"::", "", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"::23", "", NULL, NULL, NULL, 23, NULL, NULL, NULL},
{"foo://", "foo", NULL, NULL, NULL, -1, NULL, NULL, NULL},
// Username/passwords and things that look like them
{"http://a:b@c:29/d", "http", "a", "b", "c", 29, "/d", NULL, NULL},
{"http::@c:29", "http", "", "", "c", 29, NULL, NULL, NULL},
// ... "]" in the password field isn't allowed, but we tolerate it here...
{"http://&a:foo(b]c@d:2/", "http", "&a", "foo(b]c", "d", 2, "/", NULL, NULL},
{"http://::@c@d:2", "http", "", ":@c", "d", 2, NULL, NULL, NULL},
{"http://foo.com:b@d/", "http", "foo.com", "b", "d", -1, "/", NULL, NULL},
{"http://foo.com/\\@", "http", NULL, NULL, "foo.com", -1, "/\\@", NULL, NULL},
{"http:\\\\foo.com\\", "http", NULL, NULL, "foo.com", -1, "\\", NULL, NULL},
{"http:\\\\a\\b:c\\d@foo.com\\", "http", NULL, NULL, "a", -1, "\\b:c\\d@foo.com\\", NULL, NULL},
// Tolerate different numbers of slashes.
{"foo:/", "foo", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"foo:/bar.com/", "foo", NULL, NULL, "bar.com", -1, "/", NULL, NULL},
{"foo://///////", "foo", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"foo://///////bar.com/", "foo", NULL, NULL, "bar.com", -1, "/", NULL, NULL},
{"foo:////://///", "foo", NULL, NULL, NULL, -1, "/////", NULL, NULL},
// Raw file paths on Windows aren't handled by the parser.
{"c:/foo", "c", NULL, NULL, "foo", -1, NULL, NULL, NULL},
{"//foo/bar", NULL, NULL, NULL, "foo", -1, "/bar", NULL, NULL},
// Use the first question mark for the query and the ref.
{"http://foo/path;a??e#f#g", "http", NULL, NULL, "foo", -1, "/path;a", "?e", "f#g"},
{"http://foo/abcd?efgh?ijkl", "http", NULL, NULL, "foo", -1, "/abcd", "efgh?ijkl", NULL},
{"http://foo/abcd#foo?bar", "http", NULL, NULL, "foo", -1, "/abcd", NULL, "foo?bar"},
// IPv6, check also interesting uses of colons.
{"[61:24:74]:98", "[61", NULL, NULL, "24:74]", 98, NULL, NULL, NULL},
{"http://[61:27]:98", "http", NULL, NULL, "[61:27]", 98, NULL, NULL, NULL},
{"http:[61:27]/:foo", "http", NULL, NULL, "[61:27]", -1, "/:foo", NULL, NULL},
{"http://[1::2]:3:4", "http", NULL, NULL, "[1::2]:3", 4, NULL, NULL, NULL},
// Partially-complete IPv6 literals, and related cases.
{"http://2001::1", "http", NULL, NULL, "2001:", 1, NULL, NULL, NULL},
{"http://[2001::1", "http", NULL, NULL, "[2001::1", -1, NULL, NULL, NULL},
{"http://2001::1]", "http", NULL, NULL, "2001::1]", -1, NULL, NULL, NULL},
{"http://2001::1]:80", "http", NULL, NULL, "2001::1]", 80, NULL, NULL, NULL},
{"http://[2001::1]", "http", NULL, NULL, "[2001::1]", -1, NULL, NULL, NULL},
{"http://[2001::1]:80", "http", NULL, NULL, "[2001::1]", 80, NULL, NULL, NULL},
{"http://[[::]]", "http", NULL, NULL, "[[::]]", -1, NULL, NULL, NULL},
};
TEST(URLParser, Standard) {
// Declared outside for loop to try to catch cases in init() where we forget
// to reset something that is reset by the constructor.
Parsed parsed;
for (size_t i = 0; i < std::size(cases); i++) {
const char* url = cases[i].input;
ParseStandardURL(url, static_cast<int>(strlen(url)), &parsed);
int port = ParsePort(url, parsed.port);
EXPECT_TRUE(ComponentMatches(url, cases[i].scheme, parsed.scheme));
EXPECT_TRUE(ComponentMatches(url, cases[i].username, parsed.username));
EXPECT_TRUE(ComponentMatches(url, cases[i].password, parsed.password));
EXPECT_TRUE(ComponentMatches(url, cases[i].host, parsed.host));
EXPECT_EQ(cases[i].port, port);
EXPECT_TRUE(ComponentMatches(url, cases[i].path, parsed.path));
EXPECT_TRUE(ComponentMatches(url, cases[i].query, parsed.query));
EXPECT_TRUE(ComponentMatches(url, cases[i].ref, parsed.ref));
}
}
// PathURL --------------------------------------------------------------------
// Various incarnations of path URLs.
static PathURLParseCase path_cases[] = {
{"", NULL, NULL},
{":", "", NULL},
{":/", "", "/"},
{"/", NULL, "/"},
{" This is \\interesting// \t", NULL, "This is \\interesting// \t"},
{"about:", "about", NULL},
{"about:blank", "about", "blank"},
{" about: blank ", "about", " blank "},
{"javascript :alert(\"He:/l\\l#o?foo\"); ", "javascript ", "alert(\"He:/l\\l#o?foo\"); "},
};
TEST(URLParser, PathURL) {
// Declared outside for loop to try to catch cases in init() where we forget
// to reset something that is reset by the constructor.
Parsed parsed;
for (size_t i = 0; i < std::size(path_cases); i++) {
const char* url = path_cases[i].input;
ParsePathURL(url, static_cast<int>(strlen(url)), false, &parsed);
EXPECT_TRUE(ComponentMatches(url, path_cases[i].scheme, parsed.scheme))
<< i;
EXPECT_TRUE(ComponentMatches(url, path_cases[i].path, parsed.GetContent()))
<< i;
// The remaining components are never used for path URLs.
ExpectInvalidComponent(parsed.username);
ExpectInvalidComponent(parsed.password);
ExpectInvalidComponent(parsed.host);
ExpectInvalidComponent(parsed.port);
}
}
// Various incarnations of file URLs.
static URLParseCase file_cases[] = {
#ifdef WIN32
{"file:server", "file", NULL, NULL, "server", -1, NULL, NULL, NULL},
{" file: server \t", "file", NULL, NULL, " server",-1, NULL, NULL, NULL},
{"FiLe:c|", "FiLe", NULL, NULL, NULL, -1, "c|", NULL, NULL},
{"FILE:/\\\\/server/file", "FILE", NULL, NULL, "server", -1, "/file", NULL, NULL},
{"file://server/", "file", NULL, NULL, "server", -1, "/", NULL, NULL},
{"file://localhost/c:/", "file", NULL, NULL, "localhost", -1, "/c:/", NULL, NULL},
{"file://127.0.0.1/c|\\", "file", NULL, NULL, "127.0.0.1", -1, "/c|\\", NULL, NULL},
{"file:/", "file", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"file:", "file", NULL, NULL, NULL, -1, NULL, NULL, NULL},
// If there is a Windows drive letter, treat any number of slashes as the
// path part.
{"file:c:\\fo\\b", "file", NULL, NULL, NULL, -1, "c:\\fo\\b", NULL, NULL},
{"file:/c:\\foo/bar", "file", NULL, NULL, NULL, -1, "/c:\\foo/bar",NULL, NULL},
{"file://c:/f\\b", "file", NULL, NULL, NULL, -1, "/c:/f\\b", NULL, NULL},
{"file:///C:/foo", "file", NULL, NULL, NULL, -1, "/C:/foo", NULL, NULL},
{"file://///\\/\\/c:\\f\\b", "file", NULL, NULL, NULL, -1, "/c:\\f\\b", NULL, NULL},
// If there is not a drive letter, we should treat is as UNC EXCEPT for
// three slashes, which we treat as a Unix style path.
{"file:server/file", "file", NULL, NULL, "server", -1, "/file", NULL, NULL},
{"file:/server/file", "file", NULL, NULL, "server", -1, "/file", NULL, NULL},
{"file://server/file", "file", NULL, NULL, "server", -1, "/file", NULL, NULL},
{"file:///server/file", "file", NULL, NULL, NULL, -1, "/server/file",NULL, NULL},
{"file://\\server/file", "file", NULL, NULL, NULL, -1, "\\server/file",NULL, NULL},
{"file:////server/file", "file", NULL, NULL, "server", -1, "/file", NULL, NULL},
// Queries and refs are valid for file URLs as well.
{"file:///C:/foo.html?#", "file", NULL, NULL, NULL, -1, "/C:/foo.html", "", ""},
{"file:///C:/foo.html?query=yes#ref", "file", NULL, NULL, NULL, -1, "/C:/foo.html", "query=yes", "ref"},
#else // WIN32
// No slashes.
{"file:", "file", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"file:path", "file", NULL, NULL, NULL, -1, "path", NULL, NULL},
{"file:path/", "file", NULL, NULL, NULL, -1, "path/", NULL, NULL},
{"file:path/f.txt", "file", NULL, NULL, NULL, -1, "path/f.txt", NULL, NULL},
// One slash.
{"file:/", "file", NULL, NULL, NULL, -1, "/", NULL, NULL},
{"file:/path", "file", NULL, NULL, NULL, -1, "/path", NULL, NULL},
{"file:/path/", "file", NULL, NULL, NULL, -1, "/path/", NULL, NULL},
{"file:/path/f.txt", "file", NULL, NULL, NULL, -1, "/path/f.txt", NULL, NULL},
// Two slashes.
{"file://", "file", NULL, NULL, NULL, -1, NULL, NULL, NULL},
{"file://server", "file", NULL, NULL, "server", -1, NULL, NULL, NULL},
{"file://server/", "file", NULL, NULL, "server", -1, "/", NULL, NULL},
{"file://server/f.txt", "file", NULL, NULL, "server", -1, "/f.txt", NULL, NULL},
// Three slashes.
{"file:///", "file", NULL, NULL, NULL, -1, "/", NULL, NULL},
{"file:///path", "file", NULL, NULL, NULL, -1, "/path", NULL, NULL},
{"file:///path/", "file", NULL, NULL, NULL, -1, "/path/", NULL, NULL},
{"file:///path/f.txt", "file", NULL, NULL, NULL, -1, "/path/f.txt", NULL, NULL},
// More than three slashes.
{"file:////", "file", NULL, NULL, NULL, -1, "/", NULL, NULL},
{"file:////path", "file", NULL, NULL, NULL, -1, "/path", NULL, NULL},
{"file:////path/", "file", NULL, NULL, NULL, -1, "/path/", NULL, NULL},
{"file:////path/f.txt", "file", NULL, NULL, NULL, -1, "/path/f.txt", NULL, NULL},
// Schemeless URLs
{"path/f.txt", NULL, NULL, NULL, NULL, -1, "path/f.txt", NULL, NULL},
{"path:80/f.txt", "path", NULL, NULL, NULL, -1, "80/f.txt", NULL, NULL},
{"path/f.txt:80", "path/f.txt",NULL, NULL, NULL, -1, "80", NULL, NULL}, // Wrong.
{"/path/f.txt", NULL, NULL, NULL, NULL, -1, "/path/f.txt", NULL, NULL},
{"/path:80/f.txt", NULL, NULL, NULL, NULL, -1, "/path:80/f.txt",NULL, NULL},
{"/path/f.txt:80", NULL, NULL, NULL, NULL, -1, "/path/f.txt:80",NULL, NULL},
{"//server/f.txt", NULL, NULL, NULL, "server", -1, "/f.txt", NULL, NULL},
{"//server:80/f.txt", NULL, NULL, NULL, "server:80",-1, "/f.txt", NULL, NULL},
{"//server/f.txt:80", NULL, NULL, NULL, "server", -1, "/f.txt:80", NULL, NULL},
{"///path/f.txt", NULL, NULL, NULL, NULL, -1, "/path/f.txt", NULL, NULL},
{"///path:80/f.txt", NULL, NULL, NULL, NULL, -1, "/path:80/f.txt",NULL, NULL},
{"///path/f.txt:80", NULL, NULL, NULL, NULL, -1, "/path/f.txt:80",NULL, NULL},
{"////path/f.txt", NULL, NULL, NULL, NULL, -1, "/path/f.txt", NULL, NULL},
{"////path:80/f.txt", NULL, NULL, NULL, NULL, -1, "/path:80/f.txt",NULL, NULL},
{"////path/f.txt:80", NULL, NULL, NULL, NULL, -1, "/path/f.txt:80",NULL, NULL},
// Queries and refs are valid for file URLs as well.
{"file:///foo.html?#", "file", NULL, NULL, NULL, -1, "/foo.html", "", ""},
{"file:///foo.html?q=y#ref", "file", NULL, NULL, NULL, -1, "/foo.html", "q=y", "ref"},
#endif // WIN32
};
TEST(URLParser, ParseFileURL) {
// Declared outside for loop to try to catch cases in init() where we forget
// to reset something that is reset by the construtor.
Parsed parsed;
for (size_t i = 0; i < std::size(file_cases); i++) {
const char* url = file_cases[i].input;
ParseFileURL(url, static_cast<int>(strlen(url)), &parsed);
int port = ParsePort(url, parsed.port);
EXPECT_TRUE(ComponentMatches(url, file_cases[i].scheme, parsed.scheme))
<< " for case #" << i << " [" << url << "] "
<< parsed.scheme.begin << ", " << parsed.scheme.len;
EXPECT_TRUE(ComponentMatches(url, file_cases[i].username, parsed.username))
<< " for case #" << i << " [" << url << "] "
<< parsed.username.begin << ", " << parsed.username.len;
EXPECT_TRUE(ComponentMatches(url, file_cases[i].password, parsed.password))
<< " for case #" << i << " [" << url << "] "
<< parsed.password.begin << ", " << parsed.password.len;
EXPECT_TRUE(ComponentMatches(url, file_cases[i].host, parsed.host))
<< " for case #" << i << " [" << url << "] "
<< parsed.host.begin << ", " << parsed.host.len;
EXPECT_EQ(file_cases[i].port, port)
<< " for case #" << i << " [ " << url << "] " << port;
EXPECT_TRUE(ComponentMatches(url, file_cases[i].path, parsed.path))
<< " for case #" << i << " [" << url << "] "
<< parsed.path.begin << ", " << parsed.path.len;
EXPECT_TRUE(ComponentMatches(url, file_cases[i].query, parsed.query))
<< " for case #" << i << " [" << url << "] "
<< parsed.query.begin << ", " << parsed.query.len;
EXPECT_TRUE(ComponentMatches(url, file_cases[i].ref, parsed.ref))
<< " for case #" << i << " [ "<< url << "] "
<< parsed.query.begin << ", " << parsed.scheme.len;
}
}
TEST(URLParser, ExtractFileName) {
struct FileCase {
const char* input;
const char* expected;
} extract_cases[] = {
{"http://www.google.com", nullptr},
{"http://www.google.com/", ""},
{"http://www.google.com/search", "search"},
{"http://www.google.com/search/", ""},
{"http://www.google.com/foo/bar.html?baz=22", "bar.html"},
{"http://www.google.com/foo/bar.html#ref", "bar.html"},
{"http://www.google.com/search/;param", ""},
{"http://www.google.com/foo/bar.html;param#ref", "bar.html"},
{"http://www.google.com/foo/bar.html;foo;param#ref", "bar.html"},
{"http://www.google.com/foo/bar.html?query#ref", "bar.html"},
{"http://www.google.com/foo;/bar.html", "bar.html"},
{"http://www.google.com/foo;/", ""},
{"http://www.google.com/foo;", "foo"},
{"http://www.google.com/;", ""},
{"http://www.google.com/foo;bar;html", "foo"},
};
for (size_t i = 0; i < std::size(extract_cases); i++) {
const char* url = extract_cases[i].input;
int len = static_cast<int>(strlen(url));
Parsed parsed;
ParseStandardURL(url, len, &parsed);
Component file_name;
ExtractFileName(url, parsed.path, &file_name);
EXPECT_TRUE(ComponentMatches(url, extract_cases[i].expected, file_name));
}
}
// Returns true if the parameter with index |parameter| in the given URL's
// query string. The expected key can be NULL to indicate no such key index
// should exist. The parameter number is 1-based.
static bool NthParameterIs(const char* url,
int parameter,
const char* expected_key,
const char* expected_value) {
Parsed parsed;
ParseStandardURL(url, static_cast<int>(strlen(url)), &parsed);
Component query = parsed.query;
for (int i = 1; i <= parameter; i++) {
Component key, value;
if (!ExtractQueryKeyValue(url, &query, &key, &value)) {
if (parameter >= i && !expected_key)
return true; // Expected nonexistent key, got one.
return false; // Not enough keys.
}
if (i == parameter) {
if (!expected_key)
return false;
if (strncmp(&url[key.begin], expected_key, key.len) != 0)
return false;
if (strncmp(&url[value.begin], expected_value, value.len) != 0)
return false;
return true;
}
}
return expected_key == NULL; // We didn't find that many parameters.
}
TEST(URLParser, ExtractQueryKeyValue) {
EXPECT_TRUE(NthParameterIs("http://www.google.com", 1, NULL, NULL));
// Basic case.
char a[] = "http://www.google.com?arg1=1&arg2=2&bar";
EXPECT_TRUE(NthParameterIs(a, 1, "arg1", "1"));
EXPECT_TRUE(NthParameterIs(a, 2, "arg2", "2"));
EXPECT_TRUE(NthParameterIs(a, 3, "bar", ""));
EXPECT_TRUE(NthParameterIs(a, 4, NULL, NULL));
// Empty param at the end.
char b[] = "http://www.google.com?foo=bar&";
EXPECT_TRUE(NthParameterIs(b, 1, "foo", "bar"));
EXPECT_TRUE(NthParameterIs(b, 2, NULL, NULL));
// Empty param at the beginning.
char c[] = "http://www.google.com?&foo=bar";
EXPECT_TRUE(NthParameterIs(c, 1, "", ""));
EXPECT_TRUE(NthParameterIs(c, 2, "foo", "bar"));
EXPECT_TRUE(NthParameterIs(c, 3, NULL, NULL));
// Empty key with value.
char d[] = "http://www.google.com?=foo";
EXPECT_TRUE(NthParameterIs(d, 1, "", "foo"));
EXPECT_TRUE(NthParameterIs(d, 2, NULL, NULL));
// Empty value with key.
char e[] = "http://www.google.com?foo=";
EXPECT_TRUE(NthParameterIs(e, 1, "foo", ""));
EXPECT_TRUE(NthParameterIs(e, 2, NULL, NULL));
// Empty key and values.
char f[] = "http://www.google.com?&&==&=";
EXPECT_TRUE(NthParameterIs(f, 1, "", ""));
EXPECT_TRUE(NthParameterIs(f, 2, "", ""));
EXPECT_TRUE(NthParameterIs(f, 3, "", "="));
EXPECT_TRUE(NthParameterIs(f, 4, "", ""));
EXPECT_TRUE(NthParameterIs(f, 5, NULL, NULL));
}
// MailtoURL --------------------------------------------------------------------
static MailtoURLParseCase mailto_cases[] = {
//|input |scheme |path |query
{"mailto:foo@gmail.com", "mailto", "foo@gmail.com", NULL},
{" mailto: to \t", "mailto", " to", NULL},
{"mailto:addr1%2C%20addr2 ", "mailto", "addr1%2C%20addr2", NULL},
{"Mailto:addr1, addr2 ", "Mailto", "addr1, addr2", NULL},
{"mailto:addr1:addr2 ", "mailto", "addr1:addr2", NULL},
{"mailto:?to=addr1,addr2", "mailto", NULL, "to=addr1,addr2"},
{"mailto:?to=addr1%2C%20addr2", "mailto", NULL, "to=addr1%2C%20addr2"},
{"mailto:addr1?to=addr2", "mailto", "addr1", "to=addr2"},
{"mailto:?body=#foobar#", "mailto", NULL, "body=#foobar#",},
{"mailto:#?body=#foobar#", "mailto", "#", "body=#foobar#"},
};
TEST(URLParser, MailtoUrl) {
// Declared outside for loop to try to catch cases in init() where we forget
// to reset something that is reset by the constructor.
Parsed parsed;
for (size_t i = 0; i < std::size(mailto_cases); ++i) {
const char* url = mailto_cases[i].input;
ParseMailtoURL(url, static_cast<int>(strlen(url)), &parsed);
int port = ParsePort(url, parsed.port);
EXPECT_TRUE(ComponentMatches(url, mailto_cases[i].scheme, parsed.scheme));
EXPECT_TRUE(ComponentMatches(url, mailto_cases[i].path, parsed.path));
EXPECT_TRUE(ComponentMatches(url, mailto_cases[i].query, parsed.query));
EXPECT_EQ(PORT_UNSPECIFIED, port);
// The remaining components are never used for mailto URLs.
ExpectInvalidComponent(parsed.username);
ExpectInvalidComponent(parsed.password);
ExpectInvalidComponent(parsed.port);
ExpectInvalidComponent(parsed.ref);
}
}
// Various incarnations of filesystem URLs.
static FileSystemURLParseCase filesystem_cases[] = {
// Regular URL with all the parts
{"filesystem:http://user:pass@foo:21/temporary/bar;par?b#c", "http", "user", "pass", "foo", 21, "/temporary", "/bar;par", "b", "c"},
{"filesystem:https://foo/persistent/bar;par/", "https", NULL, NULL, "foo", -1, "/persistent", "/bar;par/", NULL, NULL},
{"filesystem:file:///persistent/bar;par/", "file", NULL, NULL, NULL, -1, "/persistent", "/bar;par/", NULL, NULL},
{"filesystem:file:///persistent/bar;par/?query#ref", "file", NULL, NULL, NULL, -1, "/persistent", "/bar;par/", "query", "ref"},
{"filesystem:file:///persistent", "file", NULL, NULL, NULL, -1, "/persistent", "", NULL, NULL},
};
TEST(URLParser, FileSystemURL) {
// Declared outside for loop to try to catch cases in init() where we forget
// to reset something that is reset by the constructor.
Parsed parsed;
for (size_t i = 0; i < std::size(filesystem_cases); i++) {
const FileSystemURLParseCase* parsecase = &filesystem_cases[i];
const char* url = parsecase->input;
ParseFileSystemURL(url, static_cast<int>(strlen(url)), &parsed);
EXPECT_TRUE(ComponentMatches(url, "filesystem", parsed.scheme));
EXPECT_EQ(!parsecase->inner_scheme, !parsed.inner_parsed());
// Only check the inner_parsed if there is one.
if (parsed.inner_parsed()) {
EXPECT_TRUE(ComponentMatches(url, parsecase->inner_scheme,
parsed.inner_parsed()->scheme));
EXPECT_TRUE(ComponentMatches(url, parsecase->inner_username,
parsed.inner_parsed()->username));
EXPECT_TRUE(ComponentMatches(url, parsecase->inner_password,
parsed.inner_parsed()->password));
EXPECT_TRUE(ComponentMatches(url, parsecase->inner_host,
parsed.inner_parsed()->host));
int port = ParsePort(url, parsed.inner_parsed()->port);
EXPECT_EQ(parsecase->inner_port, port);
// The remaining components are never used for filesystem URLs.
ExpectInvalidComponent(parsed.inner_parsed()->query);
ExpectInvalidComponent(parsed.inner_parsed()->ref);
}
EXPECT_TRUE(ComponentMatches(url, parsecase->path, parsed.path));
EXPECT_TRUE(ComponentMatches(url, parsecase->query, parsed.query));
EXPECT_TRUE(ComponentMatches(url, parsecase->ref, parsed.ref));
// The remaining components are never used for filesystem URLs.
ExpectInvalidComponent(parsed.username);
ExpectInvalidComponent(parsed.password);
ExpectInvalidComponent(parsed.host);
ExpectInvalidComponent(parsed.port);
}
}
} // namespace
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_parse_unittest.cc | C++ | unknown | 34,985 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_TEST_UTILS_H_
#define URL_URL_TEST_UTILS_H_
// Convenience functions for string conversions.
// These are mostly intended for use in unit tests.
#include <string>
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/url_canon_internal.h"
namespace url {
namespace test_utils {
// Converts a UTF-16 string from native wchar_t format to char16 by
// truncating the high 32 bits. This is different than the conversion function
// in base bacause it passes invalid UTF-16 characters which is important for
// test purposes. As a result, this is not meant to handle true UTF-32 encoded
// strings.
inline std::u16string TruncateWStringToUTF16(const wchar_t* src) {
std::u16string str;
int length = static_cast<int>(wcslen(src));
for (int i = 0; i < length; ++i) {
str.push_back(static_cast<char16_t>(src[i]));
}
return str;
}
} // namespace test_utils
} // namespace url
#endif // URL_URL_TEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | url/url_test_utils.h | C++ | unknown | 1,141 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_util.h"
#include <stddef.h>
#include <string.h>
#include <atomic>
#include <ostream>
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/containers/contains.h"
#include "base/no_destructor.h"
#include "base/strings/string_util.h"
#include "url/url_canon_internal.h"
#include "url/url_constants.h"
#include "url/url_file.h"
#include "url/url_util_internal.h"
namespace url {
namespace {
// A pair for representing a standard scheme name and the SchemeType for it.
struct SchemeWithType {
std::string scheme;
SchemeType type;
};
// A pair for representing a scheme and a custom protocol handler for it.
//
// This pair of strings must be normalized protocol handler parameters as
// described in the Custom Handler specification.
// https://html.spec.whatwg.org/multipage/system-state.html#normalize-protocol-handler-parameters
struct SchemeWithHandler {
std::string scheme;
std::string handler;
};
// List of currently registered schemes and associated properties.
struct SchemeRegistry {
// Standard format schemes (see header for details).
std::vector<SchemeWithType> standard_schemes = {
{kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
{kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
// Yes, file URLs can have a hostname, so file URLs should be handled as
// "standard". File URLs never have a port as specified by the SchemeType
// field. Unlike other SCHEME_WITH_HOST schemes, the 'host' in a file
// URL may be empty, a behavior which is special-cased during
// canonicalization.
{kFileScheme, SCHEME_WITH_HOST},
{kFtpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
{kWssScheme,
SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // WebSocket secure.
{kWsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // WebSocket.
{kFileSystemScheme, SCHEME_WITHOUT_AUTHORITY},
#ifdef OHOS_HAP_DECOMPRESSED
{kResourcesScheme, SCHEME_WITH_HOST},
#endif
};
// Schemes that are allowed for referrers.
//
// WARNING: Adding (1) a non-"standard" scheme or (2) a scheme whose URLs have
// opaque origins could lead to surprising behavior in some of the referrer
// generation logic. In order to avoid surprises, be sure to have adequate
// test coverage in each of the multiple code locations that compute
// referrers.
std::vector<SchemeWithType> referrer_schemes = {
{kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
{kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION},
};
// Schemes that do not trigger mixed content warning.
std::vector<std::string> secure_schemes = {
kHttpsScheme,
kWssScheme,
kDataScheme,
kAboutScheme,
};
// Schemes that normal pages cannot link to or access (i.e., with the same
// security rules as those applied to "file" URLs).
std::vector<std::string> local_schemes = {
kFileScheme,
#ifdef OHOS_HAP_DECOMPRESSED
kResourcesScheme,
#endif
};
// Schemes that cause pages loaded with them to not have access to pages
// loaded with any other URL scheme.
std::vector<std::string> no_access_schemes = {
kAboutScheme,
kJavaScriptScheme,
kDataScheme,
};
// Schemes that can be sent CORS requests.
std::vector<std::string> cors_enabled_schemes = {
kHttpsScheme,
kHttpScheme,
kDataScheme,
};
// Schemes that can be used by web to store data (local storage, etc).
std::vector<std::string> web_storage_schemes = {
kHttpsScheme, kHttpScheme, kFileScheme,
kFtpScheme, kWssScheme, kWsScheme,
#ifdef OHOS_HAP_DECOMPRESSED
kResourcesScheme,
#endif
};
// Schemes that can bypass the Content-Security-Policy (CSP) checks.
std::vector<std::string> csp_bypassing_schemes = {};
// Schemes that are strictly empty documents, allowing them to commit
// synchronously.
std::vector<std::string> empty_document_schemes = {
kAboutScheme,
};
// Schemes with a predefined default custom handler.
std::vector<SchemeWithHandler> predefined_handler_schemes;
#ifdef OHOS_NETWORK_LOAD
std::vector<std::string> custom_schemes = {};
#endif
#if BUILDFLAG(IS_OHOS)
std::vector<std::string> code_cache_enabled_schemes = {};
#endif
bool allow_non_standard_schemes = false;
};
// See the LockSchemeRegistries declaration in the header.
bool scheme_registries_locked = false;
// Ensure that the schemes aren't modified after first use.
static std::atomic<bool> g_scheme_registries_used{false};
// Gets the scheme registry without locking the schemes. This should *only* be
// used for adding schemes to the registry.
SchemeRegistry* GetSchemeRegistryWithoutLocking() {
static base::NoDestructor<SchemeRegistry> registry;
return registry.get();
}
const SchemeRegistry& GetSchemeRegistry() {
#if DCHECK_IS_ON()
g_scheme_registries_used.store(true);
#endif
return *GetSchemeRegistryWithoutLocking();
}
// Pass this enum through for methods which would like to know if whitespace
// removal is necessary.
enum WhitespaceRemovalPolicy {
REMOVE_WHITESPACE,
DO_NOT_REMOVE_WHITESPACE,
};
// This template converts a given character type to the corresponding
// StringPiece type.
template<typename CHAR> struct CharToStringPiece {
};
template<> struct CharToStringPiece<char> {
typedef base::StringPiece Piece;
};
template <>
struct CharToStringPiece<char16_t> {
typedef base::StringPiece16 Piece;
};
// Given a string and a range inside the string, compares it to the given
// lower-case |compare_to| buffer.
template<typename CHAR>
inline bool DoCompareSchemeComponent(const CHAR* spec,
const Component& component,
const char* compare_to) {
if (component.is_empty())
return compare_to[0] == 0; // When component is empty, match empty scheme.
return base::EqualsCaseInsensitiveASCII(
typename CharToStringPiece<CHAR>::Piece(&spec[component.begin],
component.len),
compare_to);
}
// Returns true and sets |type| to the SchemeType of the given scheme
// identified by |scheme| within |spec| if in |schemes|.
template<typename CHAR>
bool DoIsInSchemes(const CHAR* spec,
const Component& scheme,
SchemeType* type,
const std::vector<SchemeWithType>& schemes) {
if (scheme.is_empty())
return false; // Empty or invalid schemes are non-standard.
for (const SchemeWithType& scheme_with_type : schemes) {
if (base::EqualsCaseInsensitiveASCII(
typename CharToStringPiece<CHAR>::Piece(&spec[scheme.begin],
scheme.len),
scheme_with_type.scheme)) {
*type = scheme_with_type.type;
return true;
}
}
return false;
}
template<typename CHAR>
bool DoIsStandard(const CHAR* spec, const Component& scheme, SchemeType* type) {
return DoIsInSchemes(spec, scheme, type,
GetSchemeRegistry().standard_schemes);
}
template<typename CHAR>
bool DoFindAndCompareScheme(const CHAR* str,
int str_len,
const char* compare,
Component* found_scheme) {
// Before extracting scheme, canonicalize the URL to remove any whitespace.
// This matches the canonicalization done in DoCanonicalize function.
STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
int spec_len;
const CHAR* spec =
RemoveURLWhitespace(str, str_len, &whitespace_buffer, &spec_len, nullptr);
Component our_scheme;
if (!ExtractScheme(spec, spec_len, &our_scheme)) {
// No scheme.
if (found_scheme)
*found_scheme = Component();
return false;
}
if (found_scheme)
*found_scheme = our_scheme;
return DoCompareSchemeComponent(spec, our_scheme, compare);
}
template <typename CHAR>
bool DoCanonicalize(const CHAR* spec,
int spec_len,
bool trim_path_end,
WhitespaceRemovalPolicy whitespace_policy,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed) {
// Trim leading C0 control characters and spaces.
int begin = 0;
TrimURL(spec, &begin, &spec_len, trim_path_end);
DCHECK(0 <= begin && begin <= spec_len);
spec += begin;
spec_len -= begin;
output->ReserveSizeIfNeeded(spec_len);
// Remove any whitespace from the middle of the relative URL if necessary.
// Possibly this will result in copying to the new buffer.
STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
if (whitespace_policy == REMOVE_WHITESPACE) {
spec = RemoveURLWhitespace(spec, spec_len, &whitespace_buffer, &spec_len,
&output_parsed->potentially_dangling_markup);
}
Parsed parsed_input;
#ifdef WIN32
// For Windows, we allow things that look like absolute Windows paths to be
// fixed up magically to file URLs. This is done for IE compatibility. For
// example, this will change "c:/foo" into a file URL rather than treating
// it as a URL with the protocol "c". It also works for UNC ("\\foo\bar.txt").
// There is similar logic in url_canon_relative.cc for
//
// For Max & Unix, we don't do this (the equivalent would be "/foo/bar" which
// has no meaning as an absolute path name. This is because browsers on Mac
// & Unix don't generally do this, so there is no compatibility reason for
// doing so.
if (DoesBeginUNCPath(spec, 0, spec_len, false) ||
DoesBeginWindowsDriveSpec(spec, 0, spec_len)) {
ParseFileURL(spec, spec_len, &parsed_input);
return CanonicalizeFileURL(spec, spec_len, parsed_input, charset_converter,
output, output_parsed);
}
#endif
Component scheme;
if (!ExtractScheme(spec, spec_len, &scheme))
return false;
// This is the parsed version of the input URL, we have to canonicalize it
// before storing it in our object.
bool success;
SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
if (DoCompareSchemeComponent(spec, scheme, url::kFileScheme)) {
// File URLs are special.
ParseFileURL(spec, spec_len, &parsed_input);
success = CanonicalizeFileURL(spec, spec_len, parsed_input,
charset_converter, output, output_parsed);
} else if (DoCompareSchemeComponent(spec, scheme, url::kFileSystemScheme)) {
// Filesystem URLs are special.
ParseFileSystemURL(spec, spec_len, &parsed_input);
success = CanonicalizeFileSystemURL(spec, spec_len, parsed_input,
charset_converter, output,
output_parsed);
} else if (DoIsStandard(spec, scheme, &scheme_type)) {
// All "normal" URLs.
ParseStandardURL(spec, spec_len, &parsed_input);
success = CanonicalizeStandardURL(spec, spec_len, parsed_input, scheme_type,
charset_converter, output, output_parsed);
} else if (DoCompareSchemeComponent(spec, scheme, url::kMailToScheme)) {
// Mailto URLs are treated like standard URLs, with only a scheme, path,
// and query.
ParseMailtoURL(spec, spec_len, &parsed_input);
success = CanonicalizeMailtoURL(spec, spec_len, parsed_input, output,
output_parsed);
} else {
// "Weird" URLs like data: and javascript:.
ParsePathURL(spec, spec_len, trim_path_end, &parsed_input);
success = CanonicalizePathURL(spec, spec_len, parsed_input, output,
output_parsed);
}
return success;
}
template<typename CHAR>
bool DoResolveRelative(const char* base_spec,
int base_spec_len,
const Parsed& base_parsed,
const CHAR* in_relative,
int in_relative_length,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed) {
// Remove any whitespace from the middle of the relative URL, possibly
// copying to the new buffer.
STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer;
int relative_length;
const CHAR* relative = RemoveURLWhitespace(
in_relative, in_relative_length, &whitespace_buffer, &relative_length,
&output_parsed->potentially_dangling_markup);
bool base_is_authority_based = false;
bool base_is_hierarchical = false;
if (base_spec &&
base_parsed.scheme.is_nonempty()) {
int after_scheme = base_parsed.scheme.end() + 1; // Skip past the colon.
int num_slashes = CountConsecutiveSlashes(base_spec, after_scheme,
base_spec_len);
base_is_authority_based = num_slashes > 1;
base_is_hierarchical = num_slashes > 0;
}
SchemeType unused_scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
bool standard_base_scheme =
base_parsed.scheme.is_nonempty() &&
DoIsStandard(base_spec, base_parsed.scheme, &unused_scheme_type);
bool is_relative;
Component relative_component;
if (!IsRelativeURL(base_spec, base_parsed, relative, relative_length,
(base_is_hierarchical || standard_base_scheme),
&is_relative, &relative_component)) {
// Error resolving.
return false;
}
// Don't reserve buffer space here. Instead, reserve in DoCanonicalize and
// ReserveRelativeURL, to enable more accurate buffer sizes.
// Pretend for a moment that |base_spec| is a standard URL. Normally
// non-standard URLs are treated as PathURLs, but if the base has an
// authority we would like to preserve it.
if (is_relative && base_is_authority_based && !standard_base_scheme) {
Parsed base_parsed_authority;
ParseStandardURL(base_spec, base_spec_len, &base_parsed_authority);
if (base_parsed_authority.host.is_nonempty()) {
STACK_UNINITIALIZED RawCanonOutputT<char> temporary_output;
bool did_resolve_succeed =
ResolveRelativeURL(base_spec, base_parsed_authority, false, relative,
relative_component, charset_converter,
&temporary_output, output_parsed);
// The output_parsed is incorrect at this point (because it was built
// based on base_parsed_authority instead of base_parsed) and needs to be
// re-created.
DoCanonicalize(temporary_output.data(), temporary_output.length(), true,
REMOVE_WHITESPACE, charset_converter, output,
output_parsed);
return did_resolve_succeed;
}
} else if (is_relative) {
// Relative, resolve and canonicalize.
bool file_base_scheme = base_parsed.scheme.is_nonempty() &&
DoCompareSchemeComponent(base_spec, base_parsed.scheme, kFileScheme);
return ResolveRelativeURL(base_spec, base_parsed, file_base_scheme, relative,
relative_component, charset_converter, output,
output_parsed);
}
// Not relative, canonicalize the input.
return DoCanonicalize(relative, relative_length, true,
DO_NOT_REMOVE_WHITESPACE, charset_converter, output,
output_parsed);
}
template<typename CHAR>
bool DoReplaceComponents(const char* spec,
int spec_len,
const Parsed& parsed,
const Replacements<CHAR>& replacements,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* out_parsed) {
// If the scheme is overridden, just do a simple string substitution and
// re-parse the whole thing. There are lots of edge cases that we really don't
// want to deal with. Like what happens if I replace "http://e:8080/foo"
// with a file. Does it become "file:///E:/8080/foo" where the port number
// becomes part of the path? Parsing that string as a file URL says "yes"
// but almost no sane rule for dealing with the components individually would
// come up with that.
//
// Why allow these crazy cases at all? Programatically, there is almost no
// case for replacing the scheme. The most common case for hitting this is
// in JS when building up a URL using the location object. In this case, the
// JS code expects the string substitution behavior:
// http://www.w3.org/TR/2008/WD-html5-20080610/structured.html#common3
if (replacements.IsSchemeOverridden()) {
// Canonicalize the new scheme so it is 8-bit and can be concatenated with
// the existing spec.
STACK_UNINITIALIZED RawCanonOutput<128> scheme_replaced;
Component scheme_replaced_parsed;
CanonicalizeScheme(replacements.sources().scheme,
replacements.components().scheme,
&scheme_replaced, &scheme_replaced_parsed);
// We can assume that the input is canonicalized, which means it always has
// a colon after the scheme (or where the scheme would be).
int spec_after_colon = parsed.scheme.is_valid() ? parsed.scheme.end() + 1
: 1;
if (spec_len - spec_after_colon > 0) {
scheme_replaced.Append(&spec[spec_after_colon],
spec_len - spec_after_colon);
}
// We now need to completely re-parse the resulting string since its meaning
// may have changed with the different scheme.
STACK_UNINITIALIZED RawCanonOutput<128> recanonicalized;
Parsed recanonicalized_parsed;
DoCanonicalize(scheme_replaced.data(), scheme_replaced.length(), true,
REMOVE_WHITESPACE, charset_converter, &recanonicalized,
&recanonicalized_parsed);
// Recurse using the version with the scheme already replaced. This will now
// use the replacement rules for the new scheme.
//
// Warning: this code assumes that ReplaceComponents will re-check all
// components for validity. This is because we can't fail if DoCanonicalize
// failed above since theoretically the thing making it fail could be
// getting replaced here. If ReplaceComponents didn't re-check everything,
// we wouldn't know if something *not* getting replaced is a problem.
// If the scheme-specific replacers are made more intelligent so they don't
// re-check everything, we should instead re-canonicalize the whole thing
// after this call to check validity (this assumes replacing the scheme is
// much much less common than other types of replacements, like clearing the
// ref).
Replacements<CHAR> replacements_no_scheme = replacements;
replacements_no_scheme.SetScheme(NULL, Component());
// If the input URL has potentially dangling markup, set the flag on the
// output too. Note that in some cases the replacement gets rid of the
// potentially dangling markup, but this ok since the check will fail
// closed.
if (parsed.potentially_dangling_markup) {
out_parsed->potentially_dangling_markup = true;
}
return DoReplaceComponents(recanonicalized.data(), recanonicalized.length(),
recanonicalized_parsed, replacements_no_scheme,
charset_converter, output, out_parsed);
}
// TODO(csharrison): We could be smarter about size to reserve if this is done
// in callers below, and the code checks to see which components are being
// replaced, and with what length. If this ends up being a hot spot it should
// be changed.
output->ReserveSizeIfNeeded(spec_len);
// If we get here, then we know the scheme doesn't need to be replaced, so can
// just key off the scheme in the spec to know how to do the replacements.
if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileScheme)) {
return ReplaceFileURL(spec, parsed, replacements, charset_converter, output,
out_parsed);
}
if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileSystemScheme)) {
return ReplaceFileSystemURL(spec, parsed, replacements, charset_converter,
output, out_parsed);
}
SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
if (DoIsStandard(spec, parsed.scheme, &scheme_type)) {
return ReplaceStandardURL(spec, parsed, replacements, scheme_type,
charset_converter, output, out_parsed);
}
if (DoCompareSchemeComponent(spec, parsed.scheme, url::kMailToScheme)) {
return ReplaceMailtoURL(spec, parsed, replacements, output, out_parsed);
}
// Default is a path URL.
return ReplacePathURL(spec, parsed, replacements, output, out_parsed);
}
void DoSchemeModificationPreamble() {
// If this assert triggers, it means you've called Add*Scheme after
// the SchemeRegistry has been used.
//
// This normally means you're trying to set up a new scheme too late or using
// the SchemeRegistry too early in your application's init process.
DCHECK(!g_scheme_registries_used.load())
<< "Trying to add a scheme after the lists have been used. "
"Make sure that you haven't added any static GURL initializers in tests.";
// If this assert triggers, it means you've called Add*Scheme after
// LockSchemeRegistries has been called (see the header file for
// LockSchemeRegistries for more).
//
// This normally means you're trying to set up a new scheme too late in your
// application's init process. Locate where your app does this initialization
// and calls LockSchemeRegistries, and add your new scheme there.
DCHECK(!scheme_registries_locked)
<< "Trying to add a scheme after the lists have been locked.";
}
void DoAddSchemeWithHandler(const char* new_scheme,
const char* handler,
std::vector<SchemeWithHandler>* schemes) {
DoSchemeModificationPreamble();
DCHECK(schemes);
DCHECK(strlen(new_scheme) > 0);
DCHECK(strlen(handler) > 0);
DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
DCHECK(!base::Contains(*schemes, new_scheme, &SchemeWithHandler::scheme));
schemes->push_back({new_scheme, handler});
}
void DoAddScheme(const char* new_scheme, std::vector<std::string>* schemes) {
DoSchemeModificationPreamble();
DCHECK(schemes);
DCHECK(strlen(new_scheme) > 0);
DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
DCHECK(!base::Contains(*schemes, new_scheme));
schemes->push_back(new_scheme);
}
void DoAddSchemeWithType(const char* new_scheme,
SchemeType type,
std::vector<SchemeWithType>* schemes) {
DoSchemeModificationPreamble();
DCHECK(schemes);
DCHECK(strlen(new_scheme) > 0);
DCHECK_EQ(base::ToLowerASCII(new_scheme), new_scheme);
DCHECK(!base::Contains(*schemes, new_scheme, &SchemeWithType::scheme));
schemes->push_back({new_scheme, type});
}
} // namespace
void ClearSchemesForTests() {
DCHECK(!g_scheme_registries_used.load())
<< "Schemes already used "
<< "(use ScopedSchemeRegistryForTests to relax for tests).";
DCHECK(!scheme_registries_locked)
<< "Schemes already locked "
<< "(use ScopedSchemeRegistryForTests to relax for tests).";
*GetSchemeRegistryWithoutLocking() = SchemeRegistry();
}
class ScopedSchemeRegistryInternal {
public:
ScopedSchemeRegistryInternal()
: registry_(std::make_unique<SchemeRegistry>(
*GetSchemeRegistryWithoutLocking())) {
g_scheme_registries_used.store(false);
scheme_registries_locked = false;
}
~ScopedSchemeRegistryInternal() {
*GetSchemeRegistryWithoutLocking() = *registry_;
g_scheme_registries_used.store(true);
scheme_registries_locked = true;
}
private:
std::unique_ptr<SchemeRegistry> registry_;
};
ScopedSchemeRegistryForTests::ScopedSchemeRegistryForTests()
: internal_(std::make_unique<ScopedSchemeRegistryInternal>()) {}
ScopedSchemeRegistryForTests::~ScopedSchemeRegistryForTests() = default;
void EnableNonStandardSchemesForAndroidWebView() {
DoSchemeModificationPreamble();
GetSchemeRegistryWithoutLocking()->allow_non_standard_schemes = true;
}
bool AllowNonStandardSchemesForAndroidWebView() {
#ifdef OHOS_NETWORK_LOAD
return true;
#else
return GetSchemeRegistry().allow_non_standard_schemes;
#endif
}
void AddStandardScheme(const char* new_scheme, SchemeType type) {
DoAddSchemeWithType(new_scheme, type,
&GetSchemeRegistryWithoutLocking()->standard_schemes);
}
std::vector<std::string> GetStandardSchemes() {
std::vector<std::string> result;
result.reserve(GetSchemeRegistry().standard_schemes.size());
for (const auto& entry : GetSchemeRegistry().standard_schemes) {
result.push_back(entry.scheme);
}
return result;
}
void AddReferrerScheme(const char* new_scheme, SchemeType type) {
DoAddSchemeWithType(new_scheme, type,
&GetSchemeRegistryWithoutLocking()->referrer_schemes);
}
void AddSecureScheme(const char* new_scheme) {
DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->secure_schemes);
}
const std::vector<std::string>& GetSecureSchemes() {
return GetSchemeRegistry().secure_schemes;
}
void AddLocalScheme(const char* new_scheme) {
DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->local_schemes);
}
const std::vector<std::string>& GetLocalSchemes() {
return GetSchemeRegistry().local_schemes;
}
void AddNoAccessScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->no_access_schemes);
}
const std::vector<std::string>& GetNoAccessSchemes() {
return GetSchemeRegistry().no_access_schemes;
}
void AddCorsEnabledScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->cors_enabled_schemes);
}
const std::vector<std::string>& GetCorsEnabledSchemes() {
return GetSchemeRegistry().cors_enabled_schemes;
}
void AddWebStorageScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->web_storage_schemes);
}
const std::vector<std::string>& GetWebStorageSchemes() {
return GetSchemeRegistry().web_storage_schemes;
}
void AddCSPBypassingScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->csp_bypassing_schemes);
}
const std::vector<std::string>& GetCSPBypassingSchemes() {
return GetSchemeRegistry().csp_bypassing_schemes;
}
void AddEmptyDocumentScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->empty_document_schemes);
}
const std::vector<std::string>& GetEmptyDocumentSchemes() {
return GetSchemeRegistry().empty_document_schemes;
}
#ifdef OHOS_NETWORK_LOAD
void AddCustomScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->custom_schemes);
}
const std::vector<std::string>& GetCustomScheme() {
return GetSchemeRegistry().custom_schemes;
}
#endif
#if BUILDFLAG(IS_OHOS)
void AddCodeCacheEnabledScheme(const char* new_scheme) {
DoAddScheme(new_scheme,
&GetSchemeRegistryWithoutLocking()->code_cache_enabled_schemes);
}
bool IsCodeCacheEnabledScheme(const std::string& scheme) {
for (const std::string& it : GetSchemeRegistry().code_cache_enabled_schemes) {
if (it == scheme) {
return true;
}
}
return false;
}
#endif
void AddPredefinedHandlerScheme(const char* new_scheme, const char* handler) {
DoAddSchemeWithHandler(
new_scheme, handler,
&GetSchemeRegistryWithoutLocking()->predefined_handler_schemes);
}
std::vector<std::pair<std::string, std::string>> GetPredefinedHandlerSchemes() {
std::vector<std::pair<std::string, std::string>> result;
result.reserve(GetSchemeRegistry().predefined_handler_schemes.size());
for (const SchemeWithHandler& entry :
GetSchemeRegistry().predefined_handler_schemes) {
result.emplace_back(entry.scheme, entry.handler);
}
return result;
}
void LockSchemeRegistries() {
scheme_registries_locked = true;
}
bool IsStandard(const char* spec, const Component& scheme) {
SchemeType unused_scheme_type;
return DoIsStandard(spec, scheme, &unused_scheme_type);
}
bool GetStandardSchemeType(const char* spec,
const Component& scheme,
SchemeType* type) {
return DoIsStandard(spec, scheme, type);
}
bool GetStandardSchemeType(const char16_t* spec,
const Component& scheme,
SchemeType* type) {
return DoIsStandard(spec, scheme, type);
}
bool IsStandard(const char16_t* spec, const Component& scheme) {
SchemeType unused_scheme_type;
return DoIsStandard(spec, scheme, &unused_scheme_type);
}
bool IsReferrerScheme(const char* spec, const Component& scheme) {
SchemeType unused_scheme_type;
return DoIsInSchemes(spec, scheme, &unused_scheme_type,
GetSchemeRegistry().referrer_schemes);
}
bool FindAndCompareScheme(const char* str,
int str_len,
const char* compare,
Component* found_scheme) {
return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
}
bool FindAndCompareScheme(const char16_t* str,
int str_len,
const char* compare,
Component* found_scheme) {
return DoFindAndCompareScheme(str, str_len, compare, found_scheme);
}
bool DomainIs(base::StringPiece canonical_host,
base::StringPiece canonical_domain) {
if (canonical_host.empty() || canonical_domain.empty())
return false;
// If the host name ends with a dot but the input domain doesn't, then we
// ignore the dot in the host name.
size_t host_len = canonical_host.length();
if (canonical_host.back() == '.' && canonical_domain.back() != '.')
--host_len;
if (host_len < canonical_domain.length())
return false;
// |host_first_pos| is the start of the compared part of the host name, not
// start of the whole host name.
const char* host_first_pos =
canonical_host.data() + host_len - canonical_domain.length();
if (base::StringPiece(host_first_pos, canonical_domain.length()) !=
canonical_domain) {
return false;
}
// Make sure there aren't extra characters in host before the compared part;
// if the host name is longer than the input domain name, then the character
// immediately before the compared part should be a dot. For example,
// www.google.com has domain "google.com", but www.iamnotgoogle.com does not.
if (canonical_domain[0] != '.' && host_len > canonical_domain.length() &&
*(host_first_pos - 1) != '.') {
return false;
}
return true;
}
bool HostIsIPAddress(base::StringPiece host) {
STACK_UNINITIALIZED url::RawCanonOutputT<char, 128> ignored_output;
url::CanonHostInfo host_info;
url::CanonicalizeIPAddress(host.data(), Component(0, host.length()),
&ignored_output, &host_info);
return host_info.IsIPAddress();
}
bool Canonicalize(const char* spec,
int spec_len,
bool trim_path_end,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed) {
return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
charset_converter, output, output_parsed);
}
bool Canonicalize(const char16_t* spec,
int spec_len,
bool trim_path_end,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed) {
return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE,
charset_converter, output, output_parsed);
}
bool ResolveRelative(const char* base_spec,
int base_spec_len,
const Parsed& base_parsed,
const char* relative,
int relative_length,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed) {
return DoResolveRelative(base_spec, base_spec_len, base_parsed,
relative, relative_length,
charset_converter, output, output_parsed);
}
bool ResolveRelative(const char* base_spec,
int base_spec_len,
const Parsed& base_parsed,
const char16_t* relative,
int relative_length,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed) {
return DoResolveRelative(base_spec, base_spec_len, base_parsed,
relative, relative_length,
charset_converter, output, output_parsed);
}
bool ReplaceComponents(const char* spec,
int spec_len,
const Parsed& parsed,
const Replacements<char>& replacements,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* out_parsed) {
return DoReplaceComponents(spec, spec_len, parsed, replacements,
charset_converter, output, out_parsed);
}
bool ReplaceComponents(const char* spec,
int spec_len,
const Parsed& parsed,
const Replacements<char16_t>& replacements,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* out_parsed) {
return DoReplaceComponents(spec, spec_len, parsed, replacements,
charset_converter, output, out_parsed);
}
void DecodeURLEscapeSequences(const char* input,
int length,
DecodeURLMode mode,
CanonOutputW* output) {
if (length <= 0)
return;
STACK_UNINITIALIZED RawCanonOutputT<char> unescaped_chars;
size_t length_size_t = static_cast<size_t>(length);
for (size_t i = 0; i < length_size_t; i++) {
if (input[i] == '%') {
unsigned char ch;
if (DecodeEscaped(input, &i, length_size_t, &ch)) {
unescaped_chars.push_back(ch);
} else {
// Invalid escape sequence, copy the percent literal.
unescaped_chars.push_back('%');
}
} else {
// Regular non-escaped 8-bit character.
unescaped_chars.push_back(input[i]);
}
}
int output_initial_length = output->length();
// Convert that 8-bit to UTF-16. It's not clear IE does this at all to
// JavaScript URLs, but Firefox and Safari do.
size_t unescaped_length = unescaped_chars.length();
for (size_t i = 0; i < unescaped_length; i++) {
unsigned char uch = static_cast<unsigned char>(unescaped_chars.at(i));
if (uch < 0x80) {
// Non-UTF-8, just append directly
output->push_back(uch);
} else {
// next_ch will point to the last character of the decoded
// character.
size_t next_character = i;
base_icu::UChar32 code_point;
if (ReadUTFChar(unescaped_chars.data(), &next_character, unescaped_length,
&code_point)) {
// Valid UTF-8 character, convert to UTF-16.
AppendUTF16Value(code_point, output);
i = next_character;
} else if (mode == DecodeURLMode::kUTF8) {
DCHECK_EQ(code_point, 0xFFFD);
AppendUTF16Value(code_point, output);
i = next_character;
} else {
// If there are any sequences that are not valid UTF-8, we
// revert |output| changes, and promote any bytes to UTF-16. We
// copy all characters from the beginning to the end of the
// identified sequence.
output->set_length(output_initial_length);
for (size_t j = 0; j < unescaped_chars.length(); ++j)
output->push_back(static_cast<unsigned char>(unescaped_chars.at(j)));
break;
}
}
}
}
void EncodeURIComponent(const char* input, int length, CanonOutput* output) {
for (int i = 0; i < length; ++i) {
unsigned char c = static_cast<unsigned char>(input[i]);
if (IsComponentChar(c))
output->push_back(c);
else
AppendEscapedChar(c, output);
}
}
bool CompareSchemeComponent(const char* spec,
const Component& component,
const char* compare_to) {
return DoCompareSchemeComponent(spec, component, compare_to);
}
bool CompareSchemeComponent(const char16_t* spec,
const Component& component,
const char* compare_to) {
return DoCompareSchemeComponent(spec, component, compare_to);
}
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_util.cc | C++ | unknown | 37,346 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_UTIL_H_
#define URL_URL_UTIL_H_
#include <memory>
#include <string>
#include <vector>
#include "base/component_export.h"
#include "base/strings/string_piece.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_canon.h"
#include "url/url_constants.h"
namespace url {
// Init ------------------------------------------------------------------------
// Used for tests that need to reset schemes. Note that this can only be used
// in conjunction with ScopedSchemeRegistryForTests.
COMPONENT_EXPORT(URL) void ClearSchemesForTests();
class ScopedSchemeRegistryInternal;
// Stores the SchemeRegistry upon creation, allowing tests to modify a copy of
// it, and restores the original SchemeRegistry when deleted.
class COMPONENT_EXPORT(URL) ScopedSchemeRegistryForTests {
public:
ScopedSchemeRegistryForTests();
~ScopedSchemeRegistryForTests();
private:
std::unique_ptr<ScopedSchemeRegistryInternal> internal_;
};
// Schemes ---------------------------------------------------------------------
// Changes the behavior of SchemeHostPort / Origin to allow non-standard schemes
// to be specified, instead of canonicalizing them to an invalid SchemeHostPort
// or opaque Origin, respectively. This is used for Android WebView backwards
// compatibility, which allows the use of custom schemes: content hosted in
// Android WebView assumes that one URL with a non-standard scheme will be
// same-origin to another URL with the same non-standard scheme.
//
// Not thread-safe.
COMPONENT_EXPORT(URL) void EnableNonStandardSchemesForAndroidWebView();
// Whether or not SchemeHostPort and Origin allow non-standard schemes.
COMPONENT_EXPORT(URL) bool AllowNonStandardSchemesForAndroidWebView();
// The following Add*Scheme method are not threadsafe and can not be called
// concurrently with any other url_util function. They will assert if the lists
// of schemes have been locked (see LockSchemeRegistries), or used.
// Adds an application-defined scheme to the internal list of "standard-format"
// URL schemes. A standard-format scheme adheres to what RFC 3986 calls "generic
// URI syntax" (https://tools.ietf.org/html/rfc3986#section-3).
COMPONENT_EXPORT(URL)
void AddStandardScheme(const char* new_scheme, SchemeType scheme_type);
// Returns the list of schemes registered for "standard" URLs. Note, this
// should not be used if you just need to check if your protocol is standard
// or not. Instead use the IsStandard() function above as its much more
// efficient. This function should only be used where you need to perform
// other operations against the standard scheme list.
COMPONENT_EXPORT(URL)
std::vector<std::string> GetStandardSchemes();
// Adds an application-defined scheme to the internal list of schemes allowed
// for referrers.
COMPONENT_EXPORT(URL)
void AddReferrerScheme(const char* new_scheme, SchemeType scheme_type);
// Adds an application-defined scheme to the list of schemes that do not trigger
// mixed content warnings.
COMPONENT_EXPORT(URL) void AddSecureScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetSecureSchemes();
// Adds an application-defined scheme to the list of schemes that normal pages
// cannot link to or access (i.e., with the same security rules as those applied
// to "file" URLs).
COMPONENT_EXPORT(URL) void AddLocalScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetLocalSchemes();
// Adds an application-defined scheme to the list of schemes that cause pages
// loaded with them to not have access to pages loaded with any other URL
// scheme.
COMPONENT_EXPORT(URL) void AddNoAccessScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetNoAccessSchemes();
// Adds an application-defined scheme to the list of schemes that can be sent
// CORS requests.
COMPONENT_EXPORT(URL) void AddCorsEnabledScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetCorsEnabledSchemes();
// Adds an application-defined scheme to the list of web schemes that can be
// used by web to store data (e.g. cookies, local storage, ...). This is
// to differentiate them from schemes that can store data but are not used on
// web (e.g. application's internal schemes) or schemes that are used on web but
// cannot store data.
COMPONENT_EXPORT(URL) void AddWebStorageScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetWebStorageSchemes();
// Adds an application-defined scheme to the list of schemes that can bypass the
// Content-Security-Policy (CSP) checks.
COMPONENT_EXPORT(URL) void AddCSPBypassingScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetCSPBypassingSchemes();
// Adds an application-defined scheme to the list of schemes that are strictly
// empty documents, allowing them to commit synchronously.
COMPONENT_EXPORT(URL) void AddEmptyDocumentScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetEmptyDocumentSchemes();
#ifdef OHOS_NETWORK_LOAD
// Adds an custom scheme
COMPONENT_EXPORT(URL) void AddCustomScheme(const char* new_scheme);
COMPONENT_EXPORT(URL) const std::vector<std::string>& GetCustomScheme();
#endif
#if BUILDFLAG(IS_OHOS)
// Adds an application-defined scheme that the js of this scheme supports code cache.
COMPONENT_EXPORT(URL) void AddCodeCacheEnabledScheme(const char* new_scheme);
// Returns true if the given scheme identified by |scheme| within |spec| is in
// the list of allowed schemes for code cache (see AddCodeCacheEnabledScheme).
COMPONENT_EXPORT(URL) bool IsCodeCacheEnabledScheme(const std::string& scheme);
#endif
// Adds a scheme with a predefined default handler.
//
// This pair of strings must be normalized protocol handler parameters as
// described in the Custom Handler specification.
// https://html.spec.whatwg.org/multipage/system-state.html#normalize-protocol-handler-parameters
COMPONENT_EXPORT(URL)
void AddPredefinedHandlerScheme(const char* new_scheme, const char* handler);
COMPONENT_EXPORT(URL)
std::vector<std::pair<std::string, std::string>> GetPredefinedHandlerSchemes();
// Sets a flag to prevent future calls to Add*Scheme from succeeding.
//
// This is designed to help prevent errors for multithreaded applications.
// Normal usage would be to call Add*Scheme for your custom schemes at
// the beginning of program initialization, and then LockSchemeRegistries. This
// prevents future callers from mistakenly calling Add*Scheme when the
// program is running with multiple threads, where such usage would be
// dangerous.
//
// We could have had Add*Scheme use a lock instead, but that would add
// some platform-specific dependencies we don't otherwise have now, and is
// overkill considering the normal usage is so simple.
COMPONENT_EXPORT(URL) void LockSchemeRegistries();
// Locates the scheme in the given string and places it into |found_scheme|,
// which may be NULL to indicate the caller does not care about the range.
//
// Returns whether the given |compare| scheme matches the scheme found in the
// input (if any). The |compare| scheme must be a valid canonical scheme or
// the result of the comparison is undefined.
COMPONENT_EXPORT(URL)
bool FindAndCompareScheme(const char* str,
int str_len,
const char* compare,
Component* found_scheme);
COMPONENT_EXPORT(URL)
bool FindAndCompareScheme(const char16_t* str,
int str_len,
const char* compare,
Component* found_scheme);
inline bool FindAndCompareScheme(const std::string& str,
const char* compare,
Component* found_scheme) {
return FindAndCompareScheme(str.data(), static_cast<int>(str.size()),
compare, found_scheme);
}
inline bool FindAndCompareScheme(const std::u16string& str,
const char* compare,
Component* found_scheme) {
return FindAndCompareScheme(str.data(), static_cast<int>(str.size()),
compare, found_scheme);
}
// Returns true if the given scheme identified by |scheme| within |spec| is in
// the list of known standard-format schemes (see AddStandardScheme).
COMPONENT_EXPORT(URL)
bool IsStandard(const char* spec, const Component& scheme);
COMPONENT_EXPORT(URL)
bool IsStandard(const char16_t* spec, const Component& scheme);
// Returns true if the given scheme identified by |scheme| within |spec| is in
// the list of allowed schemes for referrers (see AddReferrerScheme).
COMPONENT_EXPORT(URL)
bool IsReferrerScheme(const char* spec, const Component& scheme);
// Returns true and sets |type| to the SchemeType of the given scheme
// identified by |scheme| within |spec| if the scheme is in the list of known
// standard-format schemes (see AddStandardScheme).
COMPONENT_EXPORT(URL)
bool GetStandardSchemeType(const char* spec,
const Component& scheme,
SchemeType* type);
COMPONENT_EXPORT(URL)
bool GetStandardSchemeType(const char16_t* spec,
const Component& scheme,
SchemeType* type);
// Hosts ----------------------------------------------------------------------
// Returns true if the |canonical_host| matches or is in the same domain as the
// given |canonical_domain| string. For example, if the canonicalized hostname
// is "www.google.com", this will return true for "com", "google.com", and
// "www.google.com" domains.
//
// If either of the input StringPieces is empty, the return value is false. The
// input domain should match host canonicalization rules. i.e. it should be
// lowercase except for escape chars.
COMPONENT_EXPORT(URL)
bool DomainIs(base::StringPiece canonical_host,
base::StringPiece canonical_domain);
// Returns true if the hostname is an IP address. Note: this function isn't very
// cheap, as it must re-parse the host to verify.
COMPONENT_EXPORT(URL) bool HostIsIPAddress(base::StringPiece host);
// URL library wrappers --------------------------------------------------------
// Parses the given spec according to the extracted scheme type. Normal users
// should use the URL object, although this may be useful if performance is
// critical and you don't want to do the heap allocation for the std::string.
//
// As with the Canonicalize* functions, the charset converter can
// be NULL to use UTF-8 (it will be faster in this case).
//
// Returns true if a valid URL was produced, false if not. On failure, the
// output and parsed structures will still be filled and will be consistent,
// but they will not represent a loadable URL.
COMPONENT_EXPORT(URL)
bool Canonicalize(const char* spec,
int spec_len,
bool trim_path_end,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed);
COMPONENT_EXPORT(URL)
bool Canonicalize(const char16_t* spec,
int spec_len,
bool trim_path_end,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed);
// Resolves a potentially relative URL relative to the given parsed base URL.
// The base MUST be valid. The resulting canonical URL and parsed information
// will be placed in to the given out variables.
//
// The relative need not be relative. If we discover that it's absolute, this
// will produce a canonical version of that URL. See Canonicalize() for more
// about the charset_converter.
//
// Returns true if the output is valid, false if the input could not produce
// a valid URL.
COMPONENT_EXPORT(URL)
bool ResolveRelative(const char* base_spec,
int base_spec_len,
const Parsed& base_parsed,
const char* relative,
int relative_length,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed);
COMPONENT_EXPORT(URL)
bool ResolveRelative(const char* base_spec,
int base_spec_len,
const Parsed& base_parsed,
const char16_t* relative,
int relative_length,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* output_parsed);
// Replaces components in the given VALID input URL. The new canonical URL info
// is written to output and out_parsed.
//
// Returns true if the resulting URL is valid.
COMPONENT_EXPORT(URL)
bool ReplaceComponents(const char* spec,
int spec_len,
const Parsed& parsed,
const Replacements<char>& replacements,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* out_parsed);
COMPONENT_EXPORT(URL)
bool ReplaceComponents(const char* spec,
int spec_len,
const Parsed& parsed,
const Replacements<char16_t>& replacements,
CharsetConverter* charset_converter,
CanonOutput* output,
Parsed* out_parsed);
// String helper functions -----------------------------------------------------
enum class DecodeURLMode {
// UTF-8 decode only. Invalid byte sequences are replaced with U+FFFD.
kUTF8,
// Try UTF-8 decoding. If the input contains byte sequences invalid
// for UTF-8, apply byte to Unicode mapping.
kUTF8OrIsomorphic,
};
// Unescapes the given string using URL escaping rules.
COMPONENT_EXPORT(URL)
void DecodeURLEscapeSequences(const char* input,
int length,
DecodeURLMode mode,
CanonOutputW* output);
// Escapes the given string as defined by the JS method encodeURIComponent. See
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
COMPONENT_EXPORT(URL)
void EncodeURIComponent(const char* input, int length, CanonOutput* output);
} // namespace url
#endif // URL_URL_UTIL_H_
| Zhao-PengFei35/chromium_src_4 | url/url_util.h | C++ | unknown | 14,620 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef URL_URL_UTIL_INTERNAL_H_
#define URL_URL_UTIL_INTERNAL_H_
#include "url/third_party/mozilla/url_parse.h"
namespace url {
// Given a string and a range inside the string, compares it to the given
// lower-case |compare_to| buffer.
bool CompareSchemeComponent(const char* spec,
const Component& component,
const char* compare_to);
bool CompareSchemeComponent(const char16_t* spec,
const Component& component,
const char* compare_to);
} // namespace url
#endif // URL_URL_UTIL_INTERNAL_H_
| Zhao-PengFei35/chromium_src_4 | url/url_util_internal.h | C++ | unknown | 757 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "url/url_util.h"
#include <stddef.h>
#include "base/strings/string_piece.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest-message.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_canon.h"
#include "url/url_canon_stdstring.h"
#include "url/url_test_utils.h"
namespace url {
class URLUtilTest : public testing::Test {
public:
URLUtilTest() = default;
URLUtilTest(const URLUtilTest&) = delete;
URLUtilTest& operator=(const URLUtilTest&) = delete;
~URLUtilTest() override = default;
private:
ScopedSchemeRegistryForTests scoped_registry_;
};
TEST_F(URLUtilTest, FindAndCompareScheme) {
Component found_scheme;
// Simple case where the scheme is found and matches.
const char kStr1[] = "http://www.com/";
EXPECT_TRUE(FindAndCompareScheme(
kStr1, static_cast<int>(strlen(kStr1)), "http", NULL));
EXPECT_TRUE(FindAndCompareScheme(
kStr1, static_cast<int>(strlen(kStr1)), "http", &found_scheme));
EXPECT_TRUE(found_scheme == Component(0, 4));
// A case where the scheme is found and doesn't match.
EXPECT_FALSE(FindAndCompareScheme(
kStr1, static_cast<int>(strlen(kStr1)), "https", &found_scheme));
EXPECT_TRUE(found_scheme == Component(0, 4));
// A case where there is no scheme.
const char kStr2[] = "httpfoobar";
EXPECT_FALSE(FindAndCompareScheme(
kStr2, static_cast<int>(strlen(kStr2)), "http", &found_scheme));
EXPECT_TRUE(found_scheme == Component());
// When there is an empty scheme, it should match the empty scheme.
const char kStr3[] = ":foo.com/";
EXPECT_TRUE(FindAndCompareScheme(
kStr3, static_cast<int>(strlen(kStr3)), "", &found_scheme));
EXPECT_TRUE(found_scheme == Component(0, 0));
// But when there is no scheme, it should fail.
EXPECT_FALSE(FindAndCompareScheme("", 0, "", &found_scheme));
EXPECT_TRUE(found_scheme == Component());
// When there is a whitespace char in scheme, it should canonicalize the URL
// before comparison.
const char whtspc_str[] = " \r\n\tjav\ra\nscri\tpt:alert(1)";
EXPECT_TRUE(FindAndCompareScheme(whtspc_str,
static_cast<int>(strlen(whtspc_str)),
"javascript", &found_scheme));
EXPECT_TRUE(found_scheme == Component(1, 10));
// Control characters should be stripped out on the ends, and kept in the
// middle.
const char ctrl_str[] = "\02jav\02scr\03ipt:alert(1)";
EXPECT_FALSE(FindAndCompareScheme(ctrl_str,
static_cast<int>(strlen(ctrl_str)),
"javascript", &found_scheme));
EXPECT_TRUE(found_scheme == Component(1, 11));
}
TEST_F(URLUtilTest, IsStandard) {
const char kHTTPScheme[] = "http";
EXPECT_TRUE(IsStandard(kHTTPScheme, Component(0, strlen(kHTTPScheme))));
const char kFooScheme[] = "foo";
EXPECT_FALSE(IsStandard(kFooScheme, Component(0, strlen(kFooScheme))));
}
TEST_F(URLUtilTest, IsReferrerScheme) {
const char kHTTPScheme[] = "http";
EXPECT_TRUE(IsReferrerScheme(kHTTPScheme, Component(0, strlen(kHTTPScheme))));
const char kFooScheme[] = "foo";
EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
}
TEST_F(URLUtilTest, AddReferrerScheme) {
static const char kFooScheme[] = "foo";
EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
url::ScopedSchemeRegistryForTests scoped_registry;
AddReferrerScheme(kFooScheme, url::SCHEME_WITH_HOST);
EXPECT_TRUE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
}
TEST_F(URLUtilTest, ShutdownCleansUpSchemes) {
static const char kFooScheme[] = "foo";
EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
{
url::ScopedSchemeRegistryForTests scoped_registry;
AddReferrerScheme(kFooScheme, url::SCHEME_WITH_HOST);
EXPECT_TRUE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
}
EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
}
TEST_F(URLUtilTest, GetStandardSchemeType) {
url::SchemeType scheme_type;
const char kHTTPScheme[] = "http";
scheme_type = url::SCHEME_WITHOUT_AUTHORITY;
EXPECT_TRUE(GetStandardSchemeType(kHTTPScheme,
Component(0, strlen(kHTTPScheme)),
&scheme_type));
EXPECT_EQ(url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, scheme_type);
const char kFilesystemScheme[] = "filesystem";
scheme_type = url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
EXPECT_TRUE(GetStandardSchemeType(kFilesystemScheme,
Component(0, strlen(kFilesystemScheme)),
&scheme_type));
EXPECT_EQ(url::SCHEME_WITHOUT_AUTHORITY, scheme_type);
const char kFooScheme[] = "foo";
scheme_type = url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
EXPECT_FALSE(GetStandardSchemeType(kFooScheme,
Component(0, strlen(kFooScheme)),
&scheme_type));
}
TEST_F(URLUtilTest, GetStandardSchemes) {
std::vector<std::string> expected = {
kHttpsScheme, kHttpScheme, kFileScheme, kFtpScheme,
kWssScheme, kWsScheme, kFileSystemScheme,
#if defined(OHOS_HAP_DECOMPRESSED) && defined(OHOS_UNITTESTS)
kResourcesScheme,
#endif
"foo",
};
AddStandardScheme("foo", url::SCHEME_WITHOUT_AUTHORITY);
EXPECT_EQ(expected, GetStandardSchemes());
}
TEST_F(URLUtilTest, ReplaceComponents) {
Parsed parsed;
RawCanonOutputT<char> output;
Parsed new_parsed;
// Check that the following calls do not cause crash
Replacements<char> replacements;
replacements.SetRef("test", Component(0, 4));
ReplaceComponents(NULL, 0, parsed, replacements, NULL, &output, &new_parsed);
ReplaceComponents("", 0, parsed, replacements, NULL, &output, &new_parsed);
replacements.ClearRef();
replacements.SetHost("test", Component(0, 4));
ReplaceComponents(NULL, 0, parsed, replacements, NULL, &output, &new_parsed);
ReplaceComponents("", 0, parsed, replacements, NULL, &output, &new_parsed);
replacements.ClearHost();
ReplaceComponents(NULL, 0, parsed, replacements, NULL, &output, &new_parsed);
ReplaceComponents("", 0, parsed, replacements, NULL, &output, &new_parsed);
ReplaceComponents(NULL, 0, parsed, replacements, NULL, &output, &new_parsed);
ReplaceComponents("", 0, parsed, replacements, NULL, &output, &new_parsed);
}
static std::string CheckReplaceScheme(const char* base_url,
const char* scheme) {
// Make sure the input is canonicalized.
RawCanonOutput<32> original;
Parsed original_parsed;
Canonicalize(base_url, strlen(base_url), true, NULL, &original,
&original_parsed);
Replacements<char> replacements;
replacements.SetScheme(scheme, Component(0, strlen(scheme)));
std::string output_string;
StdStringCanonOutput output(&output_string);
Parsed output_parsed;
ReplaceComponents(original.data(), original.length(), original_parsed,
replacements, NULL, &output, &output_parsed);
output.Complete();
return output_string;
}
TEST_F(URLUtilTest, ReplaceScheme) {
EXPECT_EQ("https://google.com/",
CheckReplaceScheme("http://google.com/", "https"));
EXPECT_EQ("file://google.com/",
CheckReplaceScheme("http://google.com/", "file"));
EXPECT_EQ("http://home/Build",
CheckReplaceScheme("file:///Home/Build", "http"));
EXPECT_EQ("javascript:foo",
CheckReplaceScheme("about:foo", "javascript"));
EXPECT_EQ("://google.com/",
CheckReplaceScheme("http://google.com/", ""));
EXPECT_EQ("http://google.com/",
CheckReplaceScheme("about:google.com", "http"));
EXPECT_EQ("http:", CheckReplaceScheme("", "http"));
#ifdef WIN32
// Magic Windows drive letter behavior when converting to a file URL.
EXPECT_EQ("file:///E:/foo/",
CheckReplaceScheme("http://localhost/e:foo/", "file"));
#endif
// This will probably change to "about://google.com/" when we fix
// http://crbug.com/160 which should also be an acceptable result.
EXPECT_EQ("about://google.com/",
CheckReplaceScheme("http://google.com/", "about"));
EXPECT_EQ("http://example.com/%20hello%20#%20world",
CheckReplaceScheme("myscheme:example.com/ hello # world ", "http"));
}
TEST_F(URLUtilTest, DecodeURLEscapeSequences) {
struct DecodeCase {
const char* input;
const char* output;
} decode_cases[] = {
{"hello, world", "hello, world"},
{"%01%02%03%04%05%06%07%08%09%0a%0B%0C%0D%0e%0f/",
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0B\x0C\x0D\x0e\x0f/"},
{"%10%11%12%13%14%15%16%17%18%19%1a%1B%1C%1D%1e%1f/",
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1B\x1C\x1D\x1e\x1f/"},
{"%20%21%22%23%24%25%26%27%28%29%2a%2B%2C%2D%2e%2f/",
" !\"#$%&'()*+,-.//"},
{"%30%31%32%33%34%35%36%37%38%39%3a%3B%3C%3D%3e%3f/",
"0123456789:;<=>?/"},
{"%40%41%42%43%44%45%46%47%48%49%4a%4B%4C%4D%4e%4f/",
"@ABCDEFGHIJKLMNO/"},
{"%50%51%52%53%54%55%56%57%58%59%5a%5B%5C%5D%5e%5f/",
"PQRSTUVWXYZ[\\]^_/"},
{"%60%61%62%63%64%65%66%67%68%69%6a%6B%6C%6D%6e%6f/",
"`abcdefghijklmno/"},
{"%70%71%72%73%74%75%76%77%78%79%7a%7B%7C%7D%7e%7f/",
"pqrstuvwxyz{|}~\x7f/"},
{"%e4%bd%a0%e5%a5%bd", "\xe4\xbd\xa0\xe5\xa5\xbd"},
};
for (size_t i = 0; i < std::size(decode_cases); i++) {
const char* input = decode_cases[i].input;
RawCanonOutputT<char16_t> output;
DecodeURLEscapeSequences(input, strlen(input),
DecodeURLMode::kUTF8OrIsomorphic, &output);
EXPECT_EQ(decode_cases[i].output, base::UTF16ToUTF8(std::u16string(
output.data(), output.length())));
RawCanonOutputT<char16_t> output_utf8;
DecodeURLEscapeSequences(input, strlen(input), DecodeURLMode::kUTF8,
&output_utf8);
EXPECT_EQ(decode_cases[i].output,
base::UTF16ToUTF8(
std::u16string(output_utf8.data(), output_utf8.length())));
}
// Our decode should decode %00
const char zero_input[] = "%00";
RawCanonOutputT<char16_t> zero_output;
DecodeURLEscapeSequences(zero_input, strlen(zero_input), DecodeURLMode::kUTF8,
&zero_output);
EXPECT_NE("%00", base::UTF16ToUTF8(std::u16string(zero_output.data(),
zero_output.length())));
// Test the error behavior for invalid UTF-8.
struct Utf8DecodeCase {
const char* input;
std::vector<char16_t> expected_iso;
std::vector<char16_t> expected_utf8;
} utf8_decode_cases[] = {
// %e5%a5%bd is a valid UTF-8 sequence. U+597D
{"%e4%a0%e5%a5%bd",
{0x00e4, 0x00a0, 0x00e5, 0x00a5, 0x00bd, 0},
{0xfffd, 0x597d, 0}},
{"%e5%a5%bd%e4%a0",
{0x00e5, 0x00a5, 0x00bd, 0x00e4, 0x00a0, 0},
{0x597d, 0xfffd, 0}},
{"%e4%a0%e5%bd",
{0x00e4, 0x00a0, 0x00e5, 0x00bd, 0},
{0xfffd, 0xfffd, 0}},
};
for (const auto& test : utf8_decode_cases) {
const char* input = test.input;
RawCanonOutputT<char16_t> output_iso;
DecodeURLEscapeSequences(input, strlen(input),
DecodeURLMode::kUTF8OrIsomorphic, &output_iso);
EXPECT_EQ(std::u16string(test.expected_iso.data()),
std::u16string(output_iso.data(), output_iso.length()));
RawCanonOutputT<char16_t> output_utf8;
DecodeURLEscapeSequences(input, strlen(input), DecodeURLMode::kUTF8,
&output_utf8);
EXPECT_EQ(std::u16string(test.expected_utf8.data()),
std::u16string(output_utf8.data(), output_utf8.length()));
}
}
TEST_F(URLUtilTest, TestEncodeURIComponent) {
struct EncodeCase {
const char* input;
const char* output;
} encode_cases[] = {
{"hello, world", "hello%2C%20world"},
{"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
"%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F"},
{"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
"%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F"},
{" !\"#$%&'()*+,-./",
"%20!%22%23%24%25%26%27()*%2B%2C-.%2F"},
{"0123456789:;<=>?",
"0123456789%3A%3B%3C%3D%3E%3F"},
{"@ABCDEFGHIJKLMNO",
"%40ABCDEFGHIJKLMNO"},
{"PQRSTUVWXYZ[\\]^_",
"PQRSTUVWXYZ%5B%5C%5D%5E_"},
{"`abcdefghijklmno",
"%60abcdefghijklmno"},
{"pqrstuvwxyz{|}~\x7f",
"pqrstuvwxyz%7B%7C%7D~%7F"},
};
for (size_t i = 0; i < std::size(encode_cases); i++) {
const char* input = encode_cases[i].input;
RawCanonOutputT<char> buffer;
EncodeURIComponent(input, strlen(input), &buffer);
std::string output(buffer.data(), buffer.length());
EXPECT_EQ(encode_cases[i].output, output);
}
}
TEST_F(URLUtilTest, TestResolveRelativeWithNonStandardBase) {
// This tests non-standard (in the sense that IsStandard() == false)
// hierarchical schemes.
struct ResolveRelativeCase {
const char* base;
const char* rel;
bool is_valid;
const char* out;
} resolve_non_standard_cases[] = {
// Resolving a relative path against a non-hierarchical URL should fail.
{"scheme:opaque_data", "/path", false, ""},
// Resolving a relative path against a non-standard authority-based base
// URL doesn't alter the authority section.
{"scheme://Authority/", "../path", true, "scheme://Authority/path"},
// A non-standard hierarchical base is resolved with path URL
// canonicalization rules.
{"data:/Blah:Blah/", "file.html", true, "data:/Blah:Blah/file.html"},
{"data:/Path/../part/part2", "file.html", true,
"data:/Path/../part/file.html"},
{"data://text/html,payload", "//user:pass@host:33////payload22", true,
"data://user:pass@host:33////payload22"},
// Path URL canonicalization rules also apply to non-standard authority-
// based URLs.
{"custom://Authority/", "file.html", true,
"custom://Authority/file.html"},
{"custom://Authority/", "other://Auth/", true, "other://Auth/"},
{"custom://Authority/", "../../file.html", true,
"custom://Authority/file.html"},
{"custom://Authority/path/", "file.html", true,
"custom://Authority/path/file.html"},
{"custom://Authority:NoCanon/path/", "file.html", true,
"custom://Authority:NoCanon/path/file.html"},
// It's still possible to get an invalid path URL.
{"custom://Invalid:!#Auth/", "file.html", false, ""},
// A path with an authority section gets canonicalized under standard URL
// rules, even though the base was non-standard.
{"content://content.Provider/", "//other.Provider", true,
"content://other.provider/"},
// Resolving an absolute URL doesn't cause canonicalization of the
// result.
{"about:blank", "custom://Authority", true, "custom://Authority"},
// Fragment URLs can be resolved against a non-standard base.
{"scheme://Authority/path", "#fragment", true,
"scheme://Authority/path#fragment"},
{"scheme://Authority/", "#fragment", true,
"scheme://Authority/#fragment"},
// Resolving should fail if the base URL is authority-based but is
// missing a path component (the '/' at the end).
{"scheme://Authority", "path", false, ""},
// Test resolving a fragment (only) against any kind of base-URL.
{"about:blank", "#id42", true, "about:blank#id42"},
{"about:blank", " #id42", true, "about:blank#id42"},
{"about:blank#oldfrag", "#newfrag", true, "about:blank#newfrag"},
{"about:blank", " #id:42", true, "about:blank#id:42"},
// A surprising side effect of allowing fragments to resolve against
// any URL scheme is we might break javascript: URLs by doing so...
{"javascript:alert('foo#bar')", "#badfrag", true,
"javascript:alert('foo#badfrag"},
// In this case, the backslashes will not be canonicalized because it's a
// non-standard URL, but they will be treated as a path separators,
// giving the base URL here a path of "\".
//
// The result here is somewhat arbitrary. One could argue it should be
// either "aaa://a\" or "aaa://a/" since the path is being replaced with
// the "current directory". But in the context of resolving on data URLs,
// adding the requested dot doesn't seem wrong either.
{"aaa://a\\", "aaa:.", true, "aaa://a\\."}};
for (size_t i = 0; i < std::size(resolve_non_standard_cases); i++) {
const ResolveRelativeCase& test_data = resolve_non_standard_cases[i];
Parsed base_parsed;
ParsePathURL(test_data.base, strlen(test_data.base), false, &base_parsed);
std::string resolved;
StdStringCanonOutput output(&resolved);
Parsed resolved_parsed;
bool valid = ResolveRelative(test_data.base, strlen(test_data.base),
base_parsed, test_data.rel,
strlen(test_data.rel), NULL, &output,
&resolved_parsed);
output.Complete();
EXPECT_EQ(test_data.is_valid, valid) << i;
if (test_data.is_valid && valid)
EXPECT_EQ(test_data.out, resolved) << i;
}
}
TEST_F(URLUtilTest, TestNoRefComponent) {
// The hash-mark must be ignored when mailto: scheme is parsed,
// even if the URL has a base and relative part.
const char* base = "mailto://to/";
const char* rel = "any#body";
Parsed base_parsed;
ParsePathURL(base, strlen(base), false, &base_parsed);
std::string resolved;
StdStringCanonOutput output(&resolved);
Parsed resolved_parsed;
bool valid = ResolveRelative(base, strlen(base),
base_parsed, rel,
strlen(rel), NULL, &output,
&resolved_parsed);
EXPECT_TRUE(valid);
EXPECT_FALSE(resolved_parsed.ref.is_valid());
}
TEST_F(URLUtilTest, PotentiallyDanglingMarkup) {
struct ResolveRelativeCase {
const char* base;
const char* rel;
bool potentially_dangling_markup;
const char* out;
} cases[] = {
{"https://example.com/", "/path<", false, "https://example.com/path%3C"},
{"https://example.com/", "\n/path<", true, "https://example.com/path%3C"},
{"https://example.com/", "\r/path<", true, "https://example.com/path%3C"},
{"https://example.com/", "\t/path<", true, "https://example.com/path%3C"},
{"https://example.com/", "/pa\nth<", true, "https://example.com/path%3C"},
{"https://example.com/", "/pa\rth<", true, "https://example.com/path%3C"},
{"https://example.com/", "/pa\tth<", true, "https://example.com/path%3C"},
{"https://example.com/", "/path\n<", true, "https://example.com/path%3C"},
{"https://example.com/", "/path\r<", true, "https://example.com/path%3C"},
{"https://example.com/", "/path\r<", true, "https://example.com/path%3C"},
{"https://example.com/", "\n/<path", true, "https://example.com/%3Cpath"},
{"https://example.com/", "\r/<path", true, "https://example.com/%3Cpath"},
{"https://example.com/", "\t/<path", true, "https://example.com/%3Cpath"},
{"https://example.com/", "/<pa\nth", true, "https://example.com/%3Cpath"},
{"https://example.com/", "/<pa\rth", true, "https://example.com/%3Cpath"},
{"https://example.com/", "/<pa\tth", true, "https://example.com/%3Cpath"},
{"https://example.com/", "/<path\n", true, "https://example.com/%3Cpath"},
{"https://example.com/", "/<path\r", true, "https://example.com/%3Cpath"},
{"https://example.com/", "/<path\r", true, "https://example.com/%3Cpath"},
};
for (const auto& test : cases) {
SCOPED_TRACE(::testing::Message() << test.base << ", " << test.rel);
Parsed base_parsed;
ParseStandardURL(test.base, strlen(test.base), &base_parsed);
std::string resolved;
StdStringCanonOutput output(&resolved);
Parsed resolved_parsed;
bool valid =
ResolveRelative(test.base, strlen(test.base), base_parsed, test.rel,
strlen(test.rel), NULL, &output, &resolved_parsed);
ASSERT_TRUE(valid);
output.Complete();
EXPECT_EQ(test.potentially_dangling_markup,
resolved_parsed.potentially_dangling_markup);
EXPECT_EQ(test.out, resolved);
}
}
TEST_F(URLUtilTest, PotentiallyDanglingMarkupAfterReplacement) {
// Parse a URL with potentially dangling markup.
Parsed original_parsed;
RawCanonOutput<32> original;
const char* url = "htt\nps://example.com/<path";
Canonicalize(url, strlen(url), false, nullptr, &original, &original_parsed);
ASSERT_TRUE(original_parsed.potentially_dangling_markup);
// Perform a replacement, and validate that the potentially_dangling_markup
// flag carried over to the new Parsed object.
Replacements<char> replacements;
replacements.ClearRef();
Parsed replaced_parsed;
RawCanonOutput<32> replaced;
ReplaceComponents(original.data(), original.length(), original_parsed,
replacements, nullptr, &replaced, &replaced_parsed);
EXPECT_TRUE(replaced_parsed.potentially_dangling_markup);
}
TEST_F(URLUtilTest, PotentiallyDanglingMarkupAfterSchemeOnlyReplacement) {
// Parse a URL with potentially dangling markup.
Parsed original_parsed;
RawCanonOutput<32> original;
const char* url = "http://example.com/\n/<path";
Canonicalize(url, strlen(url), false, nullptr, &original, &original_parsed);
ASSERT_TRUE(original_parsed.potentially_dangling_markup);
// Perform a replacement, and validate that the potentially_dangling_markup
// flag carried over to the new Parsed object.
Replacements<char> replacements;
const char* new_scheme = "https";
replacements.SetScheme(new_scheme, Component(0, strlen(new_scheme)));
Parsed replaced_parsed;
RawCanonOutput<32> replaced;
ReplaceComponents(original.data(), original.length(), original_parsed,
replacements, nullptr, &replaced, &replaced_parsed);
EXPECT_TRUE(replaced_parsed.potentially_dangling_markup);
}
TEST_F(URLUtilTest, TestDomainIs) {
const struct {
const char* canonicalized_host;
const char* lower_ascii_domain;
bool expected_domain_is;
} kTestCases[] = {
{"google.com", "google.com", true},
{"www.google.com", "google.com", true}, // Subdomain is ignored.
{"www.google.com.cn", "google.com", false}, // Different TLD.
{"www.google.comm", "google.com", false},
{"www.iamnotgoogle.com", "google.com", false}, // Different hostname.
{"www.google.com", "Google.com", false}, // The input is not lower-cased.
// If the host ends with a dot, it matches domains with or without a dot.
{"www.google.com.", "google.com", true},
{"www.google.com.", "google.com.", true},
{"www.google.com.", ".com", true},
{"www.google.com.", ".com.", true},
// But, if the host doesn't end with a dot and the input domain does, then
// it's considered to not match.
{"www.google.com", "google.com.", false},
// If the host ends with two dots, it doesn't match.
{"www.google.com..", "google.com", false},
// Empty parameters.
{"www.google.com", "", false},
{"", "www.google.com", false},
{"", "", false},
};
for (const auto& test_case : kTestCases) {
SCOPED_TRACE(testing::Message() << "(host, domain): ("
<< test_case.canonicalized_host << ", "
<< test_case.lower_ascii_domain << ")");
EXPECT_EQ(
test_case.expected_domain_is,
DomainIs(test_case.canonicalized_host, test_case.lower_ascii_domain));
}
}
namespace {
absl::optional<std::string> CanonicalizeSpec(base::StringPiece spec,
bool trim_path_end) {
std::string canonicalized;
StdStringCanonOutput output(&canonicalized);
Parsed parsed;
if (!Canonicalize(spec.data(), spec.size(), trim_path_end,
/*charset_converter=*/nullptr, &output, &parsed)) {
return {};
}
output.Complete(); // Must be called before string is used.
return canonicalized;
}
} // namespace
#if BUILDFLAG(IS_WIN)
// Regression test for https://crbug.com/1252658.
TEST_F(URLUtilTest, TestCanonicalizeWindowsPathWithLeadingNUL) {
auto PrefixWithNUL = [](std::string&& s) -> std::string { return '\0' + s; };
EXPECT_EQ(CanonicalizeSpec(PrefixWithNUL("w:"), /*trim_path_end=*/false),
absl::make_optional("file:///W:"));
EXPECT_EQ(CanonicalizeSpec(PrefixWithNUL("\\\\server\\share"),
/*trim_path_end=*/false),
absl::make_optional("file://server/share"));
}
#endif
TEST_F(URLUtilTest, TestCanonicalizeIdempotencyWithLeadingControlCharacters) {
std::string spec = "_w:";
// Loop over all C0 control characters and the space character.
for (char c = '\0'; c <= ' '; c++) {
SCOPED_TRACE(testing::Message() << "c: " << c);
// Overwrite the first character of `spec`. Note that replacing the first
// character with NUL will not change the length!
spec[0] = c;
for (bool trim_path_end : {false, true}) {
SCOPED_TRACE(testing::Message() << "trim_path_end: " << trim_path_end);
absl::optional<std::string> canonicalized =
CanonicalizeSpec(spec, trim_path_end);
ASSERT_TRUE(canonicalized);
EXPECT_EQ(canonicalized, CanonicalizeSpec(*canonicalized, trim_path_end));
}
}
}
#if BUILDFLAG(IS_OHOS)
TEST_F(URLUtilTest, CodeCacheEnabledScheme) {
const char* kEmptyStringScheme = "";
const char* kStandardHttpScheme = "http";
const char* kCustomStringScheme = "abc";
const char* kSpecialStringScheme = "11\a113&@2";
EXPECT_FALSE(IsCodeCacheEnabledScheme(kEmptyStringScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kStandardHttpScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kCustomStringScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kSpecialStringScheme));
AddCodeCacheEnabledScheme(kEmptyStringScheme);
EXPECT_TRUE(IsCodeCacheEnabledScheme(kEmptyStringScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kStandardHttpScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kCustomStringScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kSpecialStringScheme));
AddCodeCacheEnabledScheme(kStandardHttpScheme);
EXPECT_TRUE(IsCodeCacheEnabledScheme(kEmptyStringScheme));
EXPECT_TRUE(IsCodeCacheEnabledScheme(kStandardHttpScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kCustomStringScheme));
EXPECT_FALSE(IsCodeCacheEnabledScheme(kSpecialStringScheme));
AddCodeCacheEnabledScheme(kCustomStringScheme);
AddCodeCacheEnabledScheme(kSpecialStringScheme);
EXPECT_TRUE(IsCodeCacheEnabledScheme(kEmptyStringScheme));
EXPECT_TRUE(IsCodeCacheEnabledScheme(kStandardHttpScheme));
EXPECT_TRUE(IsCodeCacheEnabledScheme(kCustomStringScheme));
EXPECT_TRUE(IsCodeCacheEnabledScheme(kSpecialStringScheme));
}
#endif
} // namespace url
| Zhao-PengFei35/chromium_src_4 | url/url_util_unittest.cc | C++ | unknown | 27,366 |
include_rules = [
"+components/content_settings/core/browser",
"+components/embedder_support/android/common",
"+components/js_injection",
"+components/omnibox/browser",
"+components/page_info/android",
"+components/payments/core",
"+components/security_state/core/security_state.h",
"+device/vr/buildflags",
"+third_party/metrics_proto/omnibox_input_type.pb.h",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/DEPS | Python | unknown | 382 |
include_rules = [
"+components/autofill/core/common",
"+components/content_capture/common",
"+components/startup_metric_utils",
"+components/variations",
"+components/version_info",
"+components/viz/common",
"+components/translate/core/common",
"+content/public",
"+device/base/features.h",
"+media/base/media_switches.h",
"+sandbox",
"+services/network/public/cpp",
"+third_party/blink/public",
"+ui/base",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/app/DEPS | Python | unknown | 438 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/app/content_main_delegate_impl.h"
#include <iostream>
#include <tuple>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/containers/flat_set.h"
#include "base/cpu.h"
#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/strings/string_split.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/content_capture/common/content_capture_features.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/translate/core/common/translate_util.h"
#include "components/variations/variations_ids_provider.h"
#include "content/public/app/initialize_mojo_core.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "media/base/media_switches.h"
#include "services/network/public/cpp/features.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_factory.h"
#include "weblayer/browser/content_browser_client_impl.h"
#include "weblayer/common/content_client_impl.h"
#include "weblayer/common/weblayer_paths.h"
#include "weblayer/public/common/switches.h"
#include "weblayer/renderer/content_renderer_client_impl.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/apk_assets.h"
#include "base/android/build_info.h"
#include "base/android/bundle_utils.h"
#include "base/android/java_exception_reporter.h"
#include "base/android/locale_utils.h"
#include "base/i18n/rtl.h"
#include "base/posix/global_descriptors.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/viz/common/features.h"
#include "content/public/browser/android/compositor.h"
#include "ui/base/resource/resource_bundle_android.h"
#include "ui/base/ui_base_switches.h"
#include "weblayer/browser/android/application_info_helper.h"
#include "weblayer/browser/android/exception_filter.h"
#include "weblayer/browser/android_descriptors.h"
#include "weblayer/common/crash_reporter/crash_keys.h"
#include "weblayer/common/crash_reporter/crash_reporter_client.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include <initguid.h>
#include "base/logging_win.h"
#endif
namespace weblayer {
namespace {
void InitLogging(MainParams* params) {
if (params->log_filename.empty())
return;
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_ALL;
settings.log_file_path = params->log_filename.value().c_str();
settings.delete_old = logging::DELETE_OLD_LOG_FILE;
logging::InitLogging(settings);
logging::SetLogItems(true /* Process ID */, true /* Thread ID */,
true /* Timestamp */, false /* Tick count */);
}
// Enables each feature in |features_to_enable| unless it is already set in the
// command line, and similarly disables each feature in |features_to_disable|
// unless it is already set in the command line.
void ConfigureFeaturesIfNotSet(
const std::vector<const base::Feature*>& features_to_enable,
const std::vector<const base::Feature*>& features_to_disable) {
auto* cl = base::CommandLine::ForCurrentProcess();
std::vector<std::string> enabled_features;
base::flat_set<std::string> feature_names_enabled_via_command_line;
std::string enabled_features_str =
cl->GetSwitchValueASCII(::switches::kEnableFeatures);
for (const auto& f :
base::FeatureList::SplitFeatureListString(enabled_features_str)) {
enabled_features.emplace_back(f);
// "<" is used as separator for field trial/groups.
std::vector<base::StringPiece> parts = base::SplitStringPiece(
f, "<", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
// Split with supplied params should always return at least one entry.
DCHECK(!parts.empty());
if (parts[0].length() > 0)
feature_names_enabled_via_command_line.insert(std::string(parts[0]));
}
std::vector<std::string> disabled_features;
std::string disabled_features_str =
cl->GetSwitchValueASCII(::switches::kDisableFeatures);
for (const auto& f :
base::FeatureList::SplitFeatureListString(disabled_features_str)) {
disabled_features.emplace_back(f);
}
for (const auto* feature : features_to_enable) {
if (!base::Contains(disabled_features, feature->name) &&
!base::Contains(feature_names_enabled_via_command_line,
feature->name)) {
enabled_features.push_back(feature->name);
}
}
cl->AppendSwitchASCII(::switches::kEnableFeatures,
base::JoinString(enabled_features, ","));
for (const auto* feature : features_to_disable) {
if (!base::Contains(disabled_features, feature->name) &&
!base::Contains(feature_names_enabled_via_command_line,
feature->name)) {
disabled_features.push_back(feature->name);
}
}
cl->AppendSwitchASCII(::switches::kDisableFeatures,
base::JoinString(disabled_features, ","));
}
} // namespace
ContentMainDelegateImpl::ContentMainDelegateImpl(MainParams params)
: params_(std::move(params)) {
#if !BUILDFLAG(IS_ANDROID)
// On non-Android, the application start time is recorded in this constructor,
// which runs early during application lifetime. On Android, the application
// start time is sampled when the Java code is entered, and it is retrieved
// from C++ after initializing the JNI (see
// BrowserMainPartsImpl::PreMainMessageLoopRun()).
startup_metric_utils::RecordApplicationStartTime(base::TimeTicks::Now());
#endif
}
ContentMainDelegateImpl::~ContentMainDelegateImpl() = default;
absl::optional<int> ContentMainDelegateImpl::BasicStartupComplete() {
// Disable features which are not currently supported in WebLayer. This allows
// sites to do feature detection, and prevents crashes in some not fully
// implemented features.
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
// TODO(crbug.com/1025610): make notifications work with WebLayer.
// This also turns off Push messaging.
cl->AppendSwitch(::switches::kDisableNotifications);
std::vector<const base::Feature*> enabled_features = {
#if BUILDFLAG(IS_ANDROID)
// Overlay promotion requires some guarantees we don't have on WebLayer
// (e.g. ensuring fullscreen, no movement of the parent view). Given that
// we're unsure about the benefits when used embedded in a parent app, we
// will only promote to overlays if needed for secure videos.
&media::kUseAndroidOverlayForSecureOnly,
#endif
};
std::vector<const base::Feature*> disabled_features = {
// TODO(crbug.com/1313771): Support Digital Goods API.
&::features::kDigitalGoodsApi,
// TODO(crbug.com/1091212): make Notification triggers work with
// WebLayer.
&::features::kNotificationTriggers,
// TODO(crbug.com/1091211): Support PeriodicBackgroundSync on WebLayer.
&::features::kPeriodicBackgroundSync,
// TODO(crbug.com/1174856): Support Portals.
&blink::features::kPortals,
// TODO(crbug.com/1144912): Support BackForwardCache on WebLayer.
&::features::kBackForwardCache,
// TODO(crbug.com/1247836): Enable TFLite/Optimization Guide on WebLayer.
&translate::kTFLiteLanguageDetectionEnabled,
// TODO(crbug.com/1338402): Add support for WebLayer. Disabling autofill is
// not yet supported.
&blink::features::kAnonymousIframeOriginTrial,
#if BUILDFLAG(IS_ANDROID)
&::features::kDynamicColorGamut,
#else
// WebOTP is supported only on Android in WebLayer.
&::features::kWebOTP,
#endif
};
#if BUILDFLAG(IS_ANDROID)
if (base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_OREO) {
enabled_features.push_back(
&autofill::features::kAutofillExtractAllDatalists);
enabled_features.push_back(
&autofill::features::kAutofillSkipComparingInferredLabels);
}
if (GetApplicationMetadataAsBoolean(
"org.chromium.weblayer.ENABLE_LOGGING_OF_JS_CONSOLE_MESSAGES",
/*default_value=*/false)) {
enabled_features.push_back(&features::kLogJsConsoleMessages);
}
#endif
ConfigureFeaturesIfNotSet(enabled_features, disabled_features);
// TODO(crbug.com/1338402): Add support for WebLayer. Disabling autofill is
// not yet supported.
blink::WebRuntimeFeatures::EnableAnonymousIframe(false);
#if BUILDFLAG(IS_ANDROID)
content::Compositor::Initialize();
#endif
InitLogging(¶ms_);
RegisterPathProvider();
return absl::nullopt;
}
bool ContentMainDelegateImpl::ShouldCreateFeatureList(InvokedIn invoked_in) {
#if BUILDFLAG(IS_ANDROID)
// On android WebLayer is in charge of creating its own FeatureList in the
// browser process.
return absl::holds_alternative<InvokedInChildProcess>(invoked_in);
#else
// TODO(weblayer-dev): Support feature lists on desktop.
return true;
#endif
}
bool ContentMainDelegateImpl::ShouldInitializeMojo(InvokedIn invoked_in) {
return ShouldCreateFeatureList(invoked_in);
}
variations::VariationsIdsProvider*
ContentMainDelegateImpl::CreateVariationsIdsProvider() {
// As the embedder supplies the set of ids, the signed-in state does not make
// sense and is ignored.
return variations::VariationsIdsProvider::Create(
variations::VariationsIdsProvider::Mode::kIgnoreSignedInState);
}
void ContentMainDelegateImpl::PreSandboxStartup() {
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if defined(ARCH_CPU_ARM_FAMILY) && \
(BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || \
BUILDFLAG(IS_CHROMEOS_LACROS))
// Create an instance of the CPU class to parse /proc/cpuinfo and cache
// cpu_brand info.
base::CPU cpu_info;
#endif
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
const bool is_browser_process =
command_line.GetSwitchValueASCII(::switches::kProcessType).empty();
if (is_browser_process &&
command_line.HasSwitch(switches::kWebEngineUserDataDir)) {
base::FilePath path =
command_line.GetSwitchValuePath(switches::kWebEngineUserDataDir);
if (base::DirectoryExists(path) || base::CreateDirectory(path)) {
// Profile needs an absolute path, which we would normally get via
// PathService. In this case, manually ensure the path is absolute.
if (!path.IsAbsolute())
path = base::MakeAbsoluteFilePath(path);
} else {
LOG(ERROR) << "Unable to create data-path directory: " << path.value();
}
CHECK(base::PathService::OverrideAndCreateIfNeeded(
DIR_USER_DATA, path, true /* is_absolute */, false /* create */));
}
InitializeResourceBundle();
#if BUILDFLAG(IS_ANDROID)
EnableCrashReporter(
command_line.GetSwitchValueASCII(::switches::kProcessType));
if (is_browser_process) {
base::android::SetJavaExceptionFilter(
base::BindRepeating(&WebLayerJavaExceptionFilter));
}
SetWebLayerCrashKeys();
#endif
}
absl::optional<int> ContentMainDelegateImpl::PostEarlyInitialization(
InvokedIn invoked_in) {
if (absl::holds_alternative<InvokedInBrowserProcess>(invoked_in)) {
browser_client_->CreateFeatureListAndFieldTrials();
}
if (!ShouldInitializeMojo(invoked_in)) {
// Since we've told Content not to initialize Mojo on its own, we must do it
// here manually.
content::InitializeMojoCore();
}
return absl::nullopt;
}
absl::variant<int, content::MainFunctionParams>
ContentMainDelegateImpl::RunProcess(
const std::string& process_type,
content::MainFunctionParams main_function_params) {
// For non-browser process, return and have the caller run the main loop.
if (!process_type.empty())
return std::move(main_function_params);
#if !BUILDFLAG(IS_ANDROID)
// On non-Android, we can return |main_function_params| back and have the
// caller run BrowserMain() normally.
return std::move(main_function_params);
#else
// On Android, we defer to the system message loop when the stack unwinds.
// So here we only create (and leak) a BrowserMainRunner. The shutdown
// of BrowserMainRunner doesn't happen in Chrome Android and doesn't work
// properly on Android at all.
auto main_runner = content::BrowserMainRunner::Create();
// In browser tests, the |main_function_params| contains a |ui_task| which
// will execute the testing. The task will be executed synchronously inside
// Initialize() so we don't depend on the BrowserMainRunner being Run().
int initialize_exit_code =
main_runner->Initialize(std::move(main_function_params));
DCHECK_LT(initialize_exit_code, 0)
<< "BrowserMainRunner::Initialize failed in MainDelegate";
std::ignore = main_runner.release();
// Return 0 as BrowserMain() should not be called after this, bounce up to
// the system message loop for ContentShell, and we're already done thanks
// to the |ui_task| for browser tests.
return 0;
#endif
}
void ContentMainDelegateImpl::InitializeResourceBundle() {
#if BUILDFLAG(IS_ANDROID)
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
bool is_browser_process =
command_line.GetSwitchValueASCII(::switches::kProcessType).empty();
if (is_browser_process) {
// If we're not being loaded from a bundle, locales will be loaded from the
// webview stored-locales directory. Otherwise, we are in Monochrome, and
// we load both chrome and webview's locale assets.
if (base::android::BundleUtils::IsBundle())
ui::SetLoadSecondaryLocalePaks(true);
else
ui::SetLocalePaksStoredInApk(true);
// Passing an empty |pref_locale| yields the system default locale.
std::string locale = ui::ResourceBundle::InitSharedInstanceWithLocale(
{} /*pref_locale*/, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
if (locale.empty()) {
LOG(WARNING) << "Failed to load locale .pak from apk.";
}
// Try to directly mmap the resources.pak from the apk. Fall back to load
// from file, using PATH_SERVICE, otherwise.
base::FilePath pak_file_path;
base::PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &pak_file_path);
pak_file_path = pak_file_path.AppendASCII("resources.pak");
ui::LoadMainAndroidPackFile("assets/resources.pak", pak_file_path);
// The English-only workaround is not needed for bundles, since bundles will
// contain assets for all locales.
if (!base::android::BundleUtils::IsBundle()) {
constexpr char kWebLayerLocalePath[] =
"assets/stored-locales/weblayer/en-US.pak";
base::MemoryMappedFile::Region region;
int fd = base::android::OpenApkAsset(kWebLayerLocalePath, ®ion);
CHECK_GE(fd, 0) << "Could not find " << kWebLayerLocalePath << " in APK.";
ui::ResourceBundle::GetSharedInstance()
.LoadSecondaryLocaleDataWithPakFileRegion(base::File(fd), region);
base::GlobalDescriptors::GetInstance()->Set(
kWebLayerSecondaryLocalePakDescriptor, fd, region);
}
} else {
base::i18n::SetICUDefaultLocale(
command_line.GetSwitchValueASCII(::switches::kLang));
auto* global_descriptors = base::GlobalDescriptors::GetInstance();
int pak_fd = global_descriptors->Get(kWebLayerLocalePakDescriptor);
base::MemoryMappedFile::Region pak_region =
global_descriptors->GetRegion(kWebLayerLocalePakDescriptor);
ui::ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd),
pak_region);
pak_fd = global_descriptors->Get(kWebLayerSecondaryLocalePakDescriptor);
pak_region =
global_descriptors->GetRegion(kWebLayerSecondaryLocalePakDescriptor);
ui::ResourceBundle::GetSharedInstance()
.LoadSecondaryLocaleDataWithPakFileRegion(base::File(pak_fd),
pak_region);
std::vector<std::pair<int, ui::ResourceScaleFactor>> extra_paks = {
{kWebLayerMainPakDescriptor, ui::kScaleFactorNone},
{kWebLayer100PercentPakDescriptor, ui::k100Percent}};
for (const auto& pak_info : extra_paks) {
pak_fd = global_descriptors->Get(pak_info.first);
pak_region = global_descriptors->GetRegion(pak_info.first);
ui::ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
base::File(pak_fd), pak_region, pak_info.second);
}
}
#else
base::FilePath pak_file;
bool r = base::PathService::Get(base::DIR_ASSETS, &pak_file);
DCHECK(r);
pak_file = pak_file.AppendASCII(params_.pak_name);
ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
#endif
}
content::ContentClient* ContentMainDelegateImpl::CreateContentClient() {
content_client_ = std::make_unique<ContentClientImpl>();
return content_client_.get();
}
content::ContentBrowserClient*
ContentMainDelegateImpl::CreateContentBrowserClient() {
browser_client_ = std::make_unique<ContentBrowserClientImpl>(¶ms_);
return browser_client_.get();
}
content::ContentRendererClient*
ContentMainDelegateImpl::CreateContentRendererClient() {
renderer_client_ = std::make_unique<ContentRendererClientImpl>();
return renderer_client_.get();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/app/content_main_delegate_impl.cc | C++ | unknown | 17,823 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_APP_CONTENT_MAIN_DELEGATE_IMPL_H_
#define WEBLAYER_APP_CONTENT_MAIN_DELEGATE_IMPL_H_
#include <memory>
#include "base/compiler_specific.h"
#include "build/build_config.h"
#include "content/public/app/content_main_delegate.h"
#include "weblayer/public/main.h"
namespace weblayer {
class ContentBrowserClientImpl;
class ContentClientImpl;
class ContentRendererClientImpl;
class ContentMainDelegateImpl : public content::ContentMainDelegate {
public:
explicit ContentMainDelegateImpl(MainParams params);
ContentMainDelegateImpl(const ContentMainDelegateImpl&) = delete;
ContentMainDelegateImpl& operator=(const ContentMainDelegateImpl&) = delete;
~ContentMainDelegateImpl() override;
// ContentMainDelegate implementation:
absl::optional<int> BasicStartupComplete() override;
bool ShouldCreateFeatureList(InvokedIn invoked_in) override;
bool ShouldInitializeMojo(InvokedIn invoked_in) override;
variations::VariationsIdsProvider* CreateVariationsIdsProvider() override;
void PreSandboxStartup() override;
absl::optional<int> PostEarlyInitialization(InvokedIn invoked_in) override;
absl::variant<int, content::MainFunctionParams> RunProcess(
const std::string& process_type,
content::MainFunctionParams main_function_params) override;
content::ContentClient* CreateContentClient() override;
content::ContentBrowserClient* CreateContentBrowserClient() override;
content::ContentRendererClient* CreateContentRendererClient() override;
private:
void InitializeResourceBundle();
MainParams params_;
std::unique_ptr<ContentBrowserClientImpl> browser_client_;
std::unique_ptr<ContentRendererClientImpl> renderer_client_;
std::unique_ptr<ContentClientImpl> content_client_;
};
} // namespace weblayer
#endif // WEBLAYER_APP_CONTENT_MAIN_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/app/content_main_delegate_impl.h | C++ | unknown | 1,971 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_android.h"
#include "base/android/library_loader/library_loader_hooks.h"
#include "weblayer/app/jni_onload.h"
namespace {
bool NativeInit(base::android::LibraryProcessType) {
return weblayer::OnJNIOnLoadInit();
}
} // namespace
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
base::android::InitVM(vm);
base::android::SetNativeInitializationHook(&NativeInit);
return JNI_VERSION_1_4;
}
| Zhao-PengFei35/chromium_src_4 | weblayer/app/entry_point.cc | C++ | unknown | 579 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/app/content_jni_onload.h"
#include "content/public/app/content_main.h"
#include "weblayer/app/content_main_delegate_impl.h"
namespace weblayer {
class MainDelegateImpl : public MainDelegate {
public:
void PreMainMessageLoopRun() override {}
void PostMainMessageLoopRun() override {}
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure) override {}
};
// This is called by the VM when the shared library is first loaded.
bool OnJNIOnLoadInit() {
if (!content::android::OnJNIOnLoadInit())
return false;
weblayer::MainParams params;
params.delegate = new weblayer::MainDelegateImpl;
content::SetContentMainDelegate(
new weblayer::ContentMainDelegateImpl(params));
return true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/app/jni_onload.cc | C++ | unknown | 917 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_APP_JNI_ONLOAD_H_
#define WEBLAYER_APP_JNI_ONLOAD_H_
namespace weblayer {
bool OnJNIOnLoadInit();
} // namespace weblayer
#endif // WEBLAYER_APP_JNI_ONLOAD_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/app/jni_onload.h | C++ | unknown | 326 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/public/main.h"
#include "build/build_config.h"
#include "content/public/app/content_main.h"
#include "weblayer/app/content_main_delegate_impl.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
#include "content/public/app/sandbox_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
#endif
namespace weblayer {
MainParams::MainParams() = default;
MainParams::MainParams(const MainParams& other) = default;
MainParams::~MainParams() = default;
#if !BUILDFLAG(IS_ANDROID)
int Main(MainParams params
#if BUILDFLAG(IS_WIN)
#if !defined(WIN_CONSOLE_APP)
,
HINSTANCE instance
#endif
#else
,
int argc,
const char** argv
#endif
) {
ContentMainDelegateImpl delegate(std::move(params));
content::ContentMainParams content_params(&delegate);
#if BUILDFLAG(IS_WIN)
#if defined(WIN_CONSOLE_APP)
HINSTANCE instance = GetModuleHandle(nullptr);
#endif
sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
content::InitializeSandboxInfo(&sandbox_info);
content_params.instance = instance;
content_params.sandbox_info = &sandbox_info;
#else
content_params.argc = argc;
content_params.argv = argv;
#endif
return content::ContentMain(std::move(content_params));
}
#endif // !BUILDFLAG(IS_ANDROID)
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/app/main.cc | C++ | unknown | 1,451 |
include_rules = [
"+cc",
"+components/android_autofill/browser",
"+components/autofill/content/browser",
"+components/autofill/content/common",
"+components/autofill/core/browser",
"+components/autofill/core/common",
"+components/background_fetch",
"+components/background_sync",
"+components/base32",
"+components/blocked_content",
"+components/browsing_data/content",
"+components/browser_ui",
"+components/captive_portal",
"+components/cdm/browser",
"+components/client_hints/browser",
"+components/component_updater/android",
"+components/content_capture/browser",
"+components/content_settings/browser",
"+components/content_settings/common",
"+components/content_settings/core/common",
"+components/crash/content/browser",
"+components/crash/core/common",
"+components/content_relationship_verification",
"+components/download/content/factory",
"+components/download/content/public",
"+components/download/public/background_service",
"+components/download/public/common",
"+components/download/public/task",
"+components/embedder_support",
"+components/error_page/common",
"+components/error_page/content/browser",
"+components/favicon_base",
"+components/favicon",
"+components/find_in_page",
"+components/heavy_ad_intervention",
"+components/infobars/android",
"+components/infobars/content",
"+components/infobars/core",
"+components/installedapp/android",
"+components/javascript_dialogs",
"+components/keep_alive_registry",
"+components/keyed_service/content",
"+components/keyed_service/core",
"+components/language/core/browser",
"+components/leveldb_proto/public",
"+components/media_router",
"+components/metrics",
"+components/navigation_interception",
"+components/net_log",
"+components/network_session_configurator",
"+components/network_time",
"+components/page_load_metrics/browser",
"+components/payments/content",
"+components/password_manager/content/browser",
"+components/performance_manager/embedder",
"+components/performance_manager/public",
"+components/origin_trials",
"+components/permissions",
"+components/pref_registry",
"+components/prefs",
"+components/profile_metrics",
"+components/no_state_prefetch/browser",
"+components/no_state_prefetch/common",
"+components/reduce_accept_language/browser",
"+components/resources/android",
"+components/safe_browsing/android",
"+components/safe_browsing/content/browser",
"+components/safe_browsing/core",
"+components/safe_browsing/core/common",
"+components/security_interstitials",
"+components/security_state/content/content_utils.h",
"+components/security_state/core/security_state.h",
"+components/sessions",
"+components/signin/core/browser",
"+components/signin/public",
"+components/site_engagement/content",
"+components/site_isolation",
"+components/spellcheck/browser",
"+components/ssl_errors",
"+components/startup_metric_utils",
"+components/strings",
"+components/subresource_filter/android",
"+components/subresource_filter/content/browser",
"+components/subresource_filter/core/browser",
"+components/subresource_filter/core/common",
"+components/subresource_filter/core/mojom",
"+components/translate/content/android",
"+components/translate/content/browser",
"+components/translate/core/browser",
"+components/translate/core/common",
"+components/ukm",
"+components/unified_consent/pref_names.h",
"+components/url_formatter",
"+components/user_prefs",
"+components/variations",
"+components/version_info",
"+components/web_cache/browser",
"+components/webdata_services",
"+components/webapps/browser",
"+components/webrtc",
"+components/webxr",
"+content/public",
"+device/vr/public",
"+google_apis",
"+mojo/public",
"+net",
"+sandbox",
"+services/cert_verifier/public/mojom",
"+services/metrics/public/cpp",
"+services/network/network_service.h",
"+services/network/public",
"+services/service_manager",
"+storage/browser/quota",
"+third_party/blink/public/common",
"+third_party/blink/public/mojom",
"+third_party/skia",
"+ui/aura",
"+ui/android",
"+ui/base",
"+ui/display",
"+ui/events",
"+ui/gfx",
"+ui/shell_dialogs",
"+ui/views",
"+ui/webui",
"+ui/wm",
]
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/DEPS | Python | unknown | 4,311 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/accept_languages_service_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/language/core/browser/accept_languages_service.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
namespace weblayer {
// static
language::AcceptLanguagesService*
AcceptLanguagesServiceFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<language::AcceptLanguagesService*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
AcceptLanguagesServiceFactory* AcceptLanguagesServiceFactory::GetInstance() {
static base::NoDestructor<AcceptLanguagesServiceFactory> factory;
return factory.get();
}
AcceptLanguagesServiceFactory::AcceptLanguagesServiceFactory()
: BrowserContextKeyedServiceFactory(
"AcceptLanguagesService",
BrowserContextDependencyManager::GetInstance()) {}
AcceptLanguagesServiceFactory::~AcceptLanguagesServiceFactory() = default;
KeyedService* AcceptLanguagesServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* browser_context) const {
return new language::AcceptLanguagesService(
user_prefs::UserPrefs::Get(browser_context),
language::prefs::kAcceptLanguages);
}
content::BrowserContext* AcceptLanguagesServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/accept_languages_service_factory.cc | C++ | unknown | 1,776 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ACCEPT_LANGUAGES_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_ACCEPT_LANGUAGES_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace language {
class AcceptLanguagesService;
}
namespace weblayer {
// AcceptLanguagesServiceFactory is a way to associate an
// AcceptLanguagesService instance to a BrowserContext.
class AcceptLanguagesServiceFactory : public BrowserContextKeyedServiceFactory {
public:
AcceptLanguagesServiceFactory(const AcceptLanguagesServiceFactory&) = delete;
AcceptLanguagesServiceFactory& operator=(
const AcceptLanguagesServiceFactory&) = delete;
static language::AcceptLanguagesService* GetForBrowserContext(
content::BrowserContext* browser_context);
static AcceptLanguagesServiceFactory* GetInstance();
private:
friend class base::NoDestructor<AcceptLanguagesServiceFactory>;
AcceptLanguagesServiceFactory();
~AcceptLanguagesServiceFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ACCEPT_LANGUAGES_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/accept_languages_service_factory.h | C++ | unknown | 1,509 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "build/build_config.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/subresource_filter/content/browser/ad_tagging_browser_test_utils.h"
#include "components/subresource_filter/content/browser/subresource_filter_observer_test_utils.h"
#include "components/subresource_filter/core/common/test_ruleset_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/test/subresource_filter_browser_test_harness.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
// Tests of ad tagging integration in WebLayer. A minimal port of //chrome's
// ad_tagging_browsertest.cc.
class AdTaggingBrowserTest : public SubresourceFilterBrowserTest {
public:
AdTaggingBrowserTest() = default;
~AdTaggingBrowserTest() override = default;
void SetUpOnMainThread() override {
SubresourceFilterBrowserTest::SetUpOnMainThread();
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("ad_script.js"),
subresource_filter::testing::CreateSuffixRule("ad=true")});
}
GURL GetURL(const std::string& page) {
return embedded_test_server()->GetURL("/ad_tagging/" + page);
}
};
IN_PROC_BROWSER_TEST_F(AdTaggingBrowserTest,
AdContentSettingAllowed_AdTaggingDisabled) {
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents()->GetBrowserContext())
->SetDefaultContentSetting(ContentSettingsType::ADS,
CONTENT_SETTING_ALLOW);
subresource_filter::TestSubresourceFilterObserver observer(web_contents());
NavigateAndWaitForCompletion(GetURL("frame_factory.html"), shell());
// Create an ad frame.
GURL ad_url = GetURL("frame_factory.html?2&ad=true");
content::RenderFrameHost* ad_frame =
subresource_filter::CreateSrcFrame(web_contents(), ad_url);
// Verify that we are not evaluating subframe loads.
EXPECT_FALSE(observer.GetChildFrameLoadPolicy(ad_url).has_value());
EXPECT_FALSE(observer.GetIsAdFrame(ad_frame->GetFrameTreeNodeId()));
// Child frame created by ad script.
content::RenderFrameHost* ad_frame_tagged_by_script =
subresource_filter::CreateSrcFrameFromAdScript(
web_contents(), GetURL("frame_factory.html?1"));
// No frames should be detected by script heuristics.
EXPECT_FALSE(
observer.GetIsAdFrame(ad_frame_tagged_by_script->GetFrameTreeNodeId()));
}
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdTaggingBrowserTest,
DISABLED_AdContentSettingBlocked_AdTaggingEnabled) {
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents()->GetBrowserContext())
->SetDefaultContentSetting(ContentSettingsType::ADS,
CONTENT_SETTING_BLOCK);
subresource_filter::TestSubresourceFilterObserver observer(web_contents());
NavigateAndWaitForCompletion(GetURL("frame_factory.html"), shell());
// Create an ad frame.
GURL ad_url = GetURL("frame_factory.html?2&ad=true");
content::RenderFrameHost* ad_frame =
subresource_filter::CreateSrcFrame(web_contents(), ad_url);
// Verify that we are evaluating subframe loads.
EXPECT_TRUE(observer.GetChildFrameLoadPolicy(ad_url).has_value());
EXPECT_TRUE(observer.GetIsAdFrame(ad_frame->GetFrameTreeNodeId()));
// Child frame created by ad script.
content::RenderFrameHost* ad_frame_tagged_by_script =
subresource_filter::CreateSrcFrameFromAdScript(
web_contents(), GetURL("frame_factory.html?1"));
// Frames should be detected by script heuristics.
EXPECT_TRUE(
observer.GetIsAdFrame(ad_frame_tagged_by_script->GetFrameTreeNodeId()));
}
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdTaggingBrowserTest, DISABLED_FramesByURL) {
subresource_filter::TestSubresourceFilterObserver observer(web_contents());
// Main frame.
NavigateAndWaitForCompletion(GetURL("frame_factory.html"), shell());
EXPECT_FALSE(observer.GetIsAdFrame(
web_contents()->GetPrimaryMainFrame()->GetFrameTreeNodeId()));
// (1) Vanilla child.
content::RenderFrameHost* vanilla_child = subresource_filter::CreateSrcFrame(
web_contents(), GetURL("frame_factory.html?1"));
EXPECT_FALSE(observer.GetIsAdFrame(vanilla_child->GetFrameTreeNodeId()));
// (2) Ad child.
content::RenderFrameHost* ad_child = subresource_filter::CreateSrcFrame(
web_contents(), GetURL("frame_factory.html?2&ad=true"));
EXPECT_TRUE(observer.GetIsAdFrame(ad_child->GetFrameTreeNodeId()));
EXPECT_TRUE(subresource_filter::EvidenceForFrameComprises(
ad_child, /*parent_is_ad=*/false,
blink::mojom::FilterListResult::kMatchedBlockingRule,
blink::mojom::FrameCreationStackEvidence::kNotCreatedByAdScript));
// (3) Ad child of 2.
content::RenderFrameHost* ad_child_2 = subresource_filter::CreateSrcFrame(
ad_child, GetURL("frame_factory.html?sub=1&3&ad=true"));
EXPECT_TRUE(observer.GetIsAdFrame(ad_child_2->GetFrameTreeNodeId()));
EXPECT_TRUE(subresource_filter::EvidenceForFrameComprises(
ad_child_2, /*parent_is_ad=*/true,
blink::mojom::FilterListResult::kMatchedBlockingRule,
blink::mojom::FrameCreationStackEvidence::kCreatedByAdScript));
// (4) Vanilla child of 2.
content::RenderFrameHost* vanilla_child_2 =
subresource_filter::CreateSrcFrame(ad_child,
GetURL("frame_factory.html?4"));
EXPECT_TRUE(observer.GetIsAdFrame(vanilla_child_2->GetFrameTreeNodeId()));
EXPECT_TRUE(subresource_filter::EvidenceForFrameComprises(
vanilla_child_2, /*parent_is_ad=*/true,
blink::mojom::FilterListResult::kMatchedNoRules,
blink::mojom::FrameCreationStackEvidence::kCreatedByAdScript));
// (5) Vanilla child of 1. This tests something subtle.
// frame_factory.html?ad=true loads the same script that frame_factory.html
// uses to load frames. This tests that even though the script is tagged as an
// ad in the ad iframe, it's not considered an ad in the main frame, hence
// it's able to create an iframe that's not labeled as an ad.
content::RenderFrameHost* vanilla_child_3 =
subresource_filter::CreateSrcFrame(vanilla_child,
GetURL("frame_factory.html?5"));
EXPECT_FALSE(observer.GetIsAdFrame(vanilla_child_3->GetFrameTreeNodeId()));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/ad_tagging_browsertest.cc | C++ | unknown | 6,811 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/heavy_ad_intervention/heavy_ad_features.h"
#include "components/heavy_ad_intervention/heavy_ad_service.h"
#include "components/page_load_metrics/browser/ads_page_load_metrics_test_waiter.h"
#include "components/page_load_metrics/browser/observers/ad_metrics/ad_intervention_browser_test_utils.h"
#include "components/page_load_metrics/browser/observers/ad_metrics/ads_page_load_metrics_observer.h"
#include "components/page_load_metrics/browser/observers/ad_metrics/frame_tree_data.h"
#include "components/page_load_metrics/browser/page_load_metrics_test_waiter.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
#include "components/subresource_filter/core/browser/subresource_filter_features.h"
#include "components/subresource_filter/core/common/common_features.h"
#include "components/subresource_filter/core/common/test_ruleset_utils.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/subresource_filter_browser_test_harness.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
const char kAdsInterventionRecordedHistogram[] =
"SubresourceFilter.PageLoad.AdsInterventionTriggered";
const char kCrossOriginHistogramId[] =
"PageLoad.Clients.Ads.FrameCounts.AdFrames.PerFrame."
"OriginStatus";
const char kHeavyAdInterventionTypeHistogramId[] =
"PageLoad.Clients.Ads.HeavyAds.InterventionType2";
} // namespace
class AdsPageLoadMetricsObserverBrowserTest
: public SubresourceFilterBrowserTest {
public:
AdsPageLoadMetricsObserverBrowserTest() {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{subresource_filter::kAdTagging, {}}}, {});
}
~AdsPageLoadMetricsObserverBrowserTest() override = default;
std::unique_ptr<page_load_metrics::PageLoadMetricsTestWaiter>
CreatePageLoadMetricsTestWaiter() {
return std::make_unique<page_load_metrics::PageLoadMetricsTestWaiter>(
web_contents());
}
void SetUpOnMainThread() override {
SubresourceFilterBrowserTest::SetUpOnMainThread();
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Test that an embedded ad is same origin.
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest,
DISABLED_OriginStatusMetricEmbedded) {
base::HistogramTester histogram_tester;
auto waiter = CreatePageLoadMetricsTestWaiter();
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/ads_observer/srcdoc_embedded_ad.html"),
shell());
// NOTE: The corresponding test in //chrome waits for 4 resources; the fourth
// resource waited for is a favicon fetch that doesn't happen in WebLayer.
waiter->AddMinimumCompleteResourcesExpectation(3);
waiter->Wait();
NavigateAndWaitForCompletion(GURL(url::kAboutBlankURL), shell());
histogram_tester.ExpectUniqueSample(
kCrossOriginHistogramId, page_load_metrics::OriginStatus::kSame, 1);
}
// Test that an empty embedded ad isn't reported at all.
// TODO(crbug.com/1226500): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest,
DISABLED_OriginStatusMetricEmbeddedEmpty) {
base::HistogramTester histogram_tester;
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL(
"/ads_observer/srcdoc_embedded_ad_empty.html"),
shell());
NavigateAndWaitForCompletion(GURL(url::kAboutBlankURL), shell());
histogram_tester.ExpectTotalCount(kCrossOriginHistogramId, 0);
}
// Test that an ad with the same origin as the main page is same origin.
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest,
DISABLED_OriginStatusMetricSame) {
// Set the frame's resource as a rule.
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("pixel.png")});
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto waiter = CreatePageLoadMetricsTestWaiter();
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/ads_observer/same_origin_ad.html"),
shell());
// NOTE: The corresponding test in //chrome waits for 4 resources; the fourth
// resource waited for is a favicon fetch that doesn't // happen in WebLayer.
waiter->AddMinimumCompleteResourcesExpectation(3);
waiter->Wait();
NavigateAndWaitForCompletion(GURL(url::kAboutBlankURL), shell());
histogram_tester.ExpectUniqueSample(
kCrossOriginHistogramId, page_load_metrics::OriginStatus::kSame, 1);
auto entries =
ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName);
EXPECT_EQ(1u, entries.size());
ukm_recorder.ExpectEntryMetric(
entries.front(), ukm::builders::AdFrameLoad::kStatus_CrossOriginName,
static_cast<int>(page_load_metrics::OriginStatus::kSame));
}
// Test that an ad with a different origin as the main page is cross origin.
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverBrowserTest,
DISABLED_OriginStatusMetricCross) {
// Note: Cannot navigate cross-origin without dynamically generating the URL.
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto waiter = CreatePageLoadMetricsTestWaiter();
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/iframe_blank.html"), shell());
// Note that the initial iframe is not an ad, so the metric doesn't observe
// it initially as same origin. However, on re-navigating to a cross
// origin site that has an ad at its origin, the ad on that page is cross
// origin from the original page.
NavigateIframeToURL(web_contents(), "test",
embedded_test_server()->GetURL(
"a.com", "/ads_observer/same_origin_ad.html"));
// Wait until all resource data updates are sent. Note that there is one more
// than in the tests above due to the navigation to same_origin_ad.html being
// itself made in an iframe.
waiter->AddMinimumCompleteResourcesExpectation(4);
waiter->Wait();
NavigateAndWaitForCompletion(GURL(url::kAboutBlankURL), shell());
histogram_tester.ExpectUniqueSample(
kCrossOriginHistogramId, page_load_metrics::OriginStatus::kCross, 1);
auto entries =
ukm_recorder.GetEntriesByName(ukm::builders::AdFrameLoad::kEntryName);
EXPECT_EQ(1u, entries.size());
ukm_recorder.ExpectEntryMetric(
entries.front(), ukm::builders::AdFrameLoad::kStatus_CrossOriginName,
static_cast<int>(page_load_metrics::OriginStatus::kCross));
}
// This test harness does not start the test server and allows
// ControllableHttpResponses to be declared.
class AdsPageLoadMetricsObserverResourceBrowserTest
: public SubresourceFilterBrowserTest {
public:
AdsPageLoadMetricsObserverResourceBrowserTest() {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{subresource_filter::kAdsInterventionsEnforced, {}},
{subresource_filter::kAdTagging, {}},
{heavy_ad_intervention::features::kHeavyAdIntervention, {}},
{heavy_ad_intervention::features::kHeavyAdPrivacyMitigations,
{{"host-threshold", "3"}}}},
{});
}
~AdsPageLoadMetricsObserverResourceBrowserTest() override = default;
void SetUpOnMainThread() override {
SubresourceFilterBrowserTest::SetUpOnMainThread();
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("ad_script.js"),
subresource_filter::testing::CreateSuffixRule("ad_script_2.js"),
subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")});
}
protected:
std::unique_ptr<page_load_metrics::AdsPageLoadMetricsTestWaiter>
CreateAdsPageLoadMetricsTestWaiter() {
return std::make_unique<page_load_metrics::AdsPageLoadMetricsTestWaiter>(
web_contents());
}
// This function loads a |large_resource| and if |will_block| is set, then
// checks to see the resource is blocked, otherwise, it uses the |waiter| to
// wait until the resource is loaded.
void LoadHeavyAdResourceAndWaitOrError(
net::test_server::ControllableHttpResponse* large_resource,
page_load_metrics::PageLoadMetricsTestWaiter* waiter,
bool will_block) {
// Create a frame for the large resource.
EXPECT_TRUE(ExecJs(web_contents(),
"createAdFrame('/ads_observer/"
"ad_with_incomplete_resource.html', '');"));
if (will_block) {
// If we expect the resource to be blocked, load a resource large enough
// to trigger the intervention and ensure that the navigation failed.
content::TestNavigationObserver error_observer(
web_contents(), net::ERR_BLOCKED_BY_CLIENT);
page_load_metrics::LoadLargeResource(
large_resource, page_load_metrics::kMaxHeavyAdNetworkSize);
error_observer.WaitForNavigationFinished();
EXPECT_FALSE(error_observer.last_navigation_succeeded());
} else {
// Otherwise load the resource, ensuring enough bytes were loaded.
int64_t current_network_bytes = waiter->current_network_bytes();
page_load_metrics::LoadLargeResource(
large_resource, page_load_metrics::kMaxHeavyAdNetworkSize);
waiter->AddMinimumNetworkBytesExpectation(
current_network_bytes + page_load_metrics::kMaxHeavyAdNetworkSize);
waiter->Wait();
}
}
private:
// SubresourceFilterBrowserTest:
bool StartEmbeddedTestServerAutomatically() override { return false; }
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest,
ReceivedAdResources) {
ASSERT_TRUE(embedded_test_server()->Start());
auto waiter = CreateAdsPageLoadMetricsTestWaiter();
NavigateAndWaitForCompletion(embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html"),
shell());
// Two subresources should have been reported as ads.
waiter->AddMinimumAdResourceExpectation(2);
waiter->Wait();
}
// Verifies that the frame is navigated to the intervention page when a
// heavy ad intervention triggers.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest,
HeavyAdInterventionEnabled_ErrorPageLoaded) {
base::HistogramTester histogram_tester;
auto incomplete_resource_response =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/ads_observer/incomplete_resource.js",
true /*relative_url_is_prefix*/);
ASSERT_TRUE(embedded_test_server()->Start());
// Create a navigation observer that will watch for the intervention to
// navigate the frame.
content::TestNavigationObserver error_observer(web_contents(),
net::ERR_BLOCKED_BY_CLIENT);
auto waiter = CreateAdsPageLoadMetricsTestWaiter();
GURL url = embedded_test_server()->GetURL(
"/ads_observer/ad_with_incomplete_resource.html");
NavigateAndWaitForCompletion(url, shell());
// Load a resource large enough to trigger the intervention.
page_load_metrics::LoadLargeResource(
incomplete_resource_response.get(),
page_load_metrics::kMaxHeavyAdNetworkSize);
// Wait for the intervention page navigation to finish on the frame.
error_observer.WaitForNavigationFinished();
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 1);
// Check that the ad frame was navigated to the intervention page.
EXPECT_FALSE(error_observer.last_navigation_succeeded());
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 1);
histogram_tester.ExpectBucketCount(
"Blink.UseCounter.Features",
blink::mojom::WebFeature::kHeavyAdIntervention, 1);
}
// Check that the Heavy Ad Intervention fires the correct number of times to
// protect privacy, and that after that limit is hit, the Ads Intervention
// Framework takes over for future navigations.
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(
AdsPageLoadMetricsObserverResourceBrowserTest,
DISABLED_HeavyAdInterventionBlocklistFull_InterventionBlocked) {
std::vector<std::unique_ptr<net::test_server::ControllableHttpResponse>>
http_responses(4);
for (auto& http_response : http_responses) {
http_response =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/ads_observer/incomplete_resource.js",
false /*relative_url_is_prefix*/);
}
base::HistogramTester histogram_tester;
ASSERT_TRUE(embedded_test_server()->Start());
// Create a waiter for the navigation and navigate.
auto waiter = CreateAdsPageLoadMetricsTestWaiter();
NavigateAndWaitForCompletion(embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html"),
shell());
// Load and block the resource. The ads intervention framework should not
// be triggered at this point.
LoadHeavyAdResourceAndWaitOrError(http_responses[0].get(), waiter.get(),
/*will_block=*/true);
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 1);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
// Block a second resource on the page. The ads intervention framework should
// not be triggered at this point.
LoadHeavyAdResourceAndWaitOrError(http_responses[1].get(), waiter.get(),
/*will_block=*/true);
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 2);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
// Create a new waiter for the next navigation and navigate.
waiter = CreateAdsPageLoadMetricsTestWaiter();
// Set query to ensure that it's not treated as a reload as preview metrics
// are not recorded for reloads.
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html?avoid_reload"),
shell());
// Load and block the resource. The ads intervention framework should
// be triggered at this point.
LoadHeavyAdResourceAndWaitOrError(http_responses[2].get(), waiter.get(),
/*will_block=*/true);
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 3);
histogram_tester.ExpectUniqueSample(
kAdsInterventionRecordedHistogram,
subresource_filter::mojom::AdsViolation::kHeavyAdsInterventionAtHostLimit,
1);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
// Reset the waiter and navigate again. Check we show the Ads Intervention UI.
waiter.reset();
NavigateAndWaitForCompletion(embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html"),
shell());
histogram_tester.ExpectUniqueSample(
kAdsInterventionRecordedHistogram,
subresource_filter::mojom::AdsViolation::kHeavyAdsInterventionAtHostLimit,
1);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 1);
}
// Check that clearing browsing data resets the number of times that the Heavy
// Ad Intervention has been triggered.
// TODO(crbug.com/1210190): This test is flaky.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceBrowserTest,
DISABLED_ClearBrowsingDataClearsHeavyAdBlocklist) {
std::vector<std::unique_ptr<net::test_server::ControllableHttpResponse>>
http_responses(4);
for (auto& http_response : http_responses) {
http_response =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/ads_observer/incomplete_resource.js",
false /*relative_url_is_prefix*/);
}
base::HistogramTester histogram_tester;
ASSERT_TRUE(embedded_test_server()->Start());
// Create a waiter for the navigation and navigate.
auto waiter = CreateAdsPageLoadMetricsTestWaiter();
NavigateAndWaitForCompletion(embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html"),
shell());
// Load and block the resource. The ads intervention framework should not
// be triggered at this point.
LoadHeavyAdResourceAndWaitOrError(http_responses[0].get(), waiter.get(),
/*will_block=*/true);
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 1);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
// Block a second resource on the page. The ads intervention framework should
// not be triggered at this point.
LoadHeavyAdResourceAndWaitOrError(http_responses[1].get(), waiter.get(),
/*will_block=*/true);
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 2);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
// Clear browsing data and wait for the heavy ad blocklist to be cleared and
// reloaded (note that waiting for the latter event is necessary as until the
// blocklist is loaded all hosts are treated as blocklisted, which
// interferes with the flow below).
auto* heavy_ad_service = HeavyAdServiceFactory::GetForBrowserContext(
web_contents()->GetBrowserContext());
base::RunLoop on_browsing_data_cleared_run_loop;
base::RunLoop on_blocklist_cleared_run_loop;
base::RunLoop on_blocklist_reloaded_run_loop;
// First clear browsing data and wait for the blocklist to be cleared.
heavy_ad_service->NotifyOnBlocklistCleared(
on_blocklist_cleared_run_loop.QuitClosure());
base::Time now = base::Time::Now();
GetProfile()->ClearBrowsingData(
{BrowsingDataType::COOKIES_AND_SITE_DATA}, now - base::Days(1), now,
on_browsing_data_cleared_run_loop.QuitClosure());
on_blocklist_cleared_run_loop.Run();
// Then wait for the blocklist to be reloaded before proceeding.
heavy_ad_service->NotifyOnBlocklistLoaded(
on_blocklist_reloaded_run_loop.QuitClosure());
on_blocklist_reloaded_run_loop.Run();
// Create a new waiter for the next navigation and navigate.
waiter = CreateAdsPageLoadMetricsTestWaiter();
// Set query to ensure that it's not treated as a reload as preview metrics
// are not recorded for reloads.
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html?avoid_reload"),
shell());
// Load and block the resource. The ads intervention framework should not be
// triggered at this point as the heavy ad blocklist was cleared as part of
// clearing browsing data.
LoadHeavyAdResourceAndWaitOrError(http_responses[2].get(), waiter.get(),
/*will_block=*/true);
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 3);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
// Reset the waiter and navigate again. Check we don't show the Ads
// Intervention UI.
waiter.reset();
NavigateAndWaitForCompletion(embedded_test_server()->GetURL(
"foo.com", "/ad_tagging/frame_factory.html"),
shell());
// Note that the below metric will not have been updated due to this
// navigation being trated as a reload.
histogram_tester.ExpectUniqueSample(
kHeavyAdInterventionTypeHistogramId,
page_load_metrics::HeavyAdStatus::kNetwork, 3);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
histogram_tester.ExpectBucketCount(
"SubresourceFilter.Actions2",
subresource_filter::SubresourceFilterAction::kUIShown, 0);
}
class AdsPageLoadMetricsObserverResourceIncognitoBrowserTest
: public AdsPageLoadMetricsObserverResourceBrowserTest {
public:
AdsPageLoadMetricsObserverResourceIncognitoBrowserTest() {
SetShellStartsInIncognitoMode();
}
};
// Verifies that the blocklist is setup correctly and the intervention triggers
// in incognito mode.
IN_PROC_BROWSER_TEST_F(AdsPageLoadMetricsObserverResourceIncognitoBrowserTest,
HeavyAdInterventionIncognitoMode_InterventionFired) {
base::HistogramTester histogram_tester;
auto incomplete_resource_response =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/ads_observer/incomplete_resource.js",
true /*relative_url_is_prefix*/);
ASSERT_TRUE(embedded_test_server()->Start());
// Create a navigation observer that will watch for the intervention to
// navigate the frame.
content::TestNavigationObserver error_observer(web_contents(),
net::ERR_BLOCKED_BY_CLIENT);
// Create a waiter for the incognito contents.
auto waiter = std::make_unique<page_load_metrics::PageLoadMetricsTestWaiter>(
web_contents());
GURL url = embedded_test_server()->GetURL(
"/ads_observer/ad_with_incomplete_resource.html");
NavigateAndWaitForCompletion(url, shell());
// Load a resource large enough to trigger the intervention.
page_load_metrics::LoadLargeResource(
incomplete_resource_response.get(),
page_load_metrics::kMaxHeavyAdNetworkSize);
// Wait for the intervention page navigation to finish on the frame.
error_observer.WaitForNavigationFinished();
// Check that the ad frame was navigated to the intervention page.
EXPECT_FALSE(error_observer.last_navigation_succeeded());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/ads_page_load_metrics_observer_browsertest.cc | C++ | unknown | 23,869 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/google_account_access_token_fetch_delegate.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browsertests_jni/AccessTokenFetchTestBridge_jni.h"
#include "weblayer/test/weblayer_browsertests_jni/GoogleAccountAccessTokenFetcherTestStub_jni.h"
namespace weblayer {
// Callback passed to GoogleAccountAccessTokenFetcherDelegate to be invoked on
// access token fetch completion.
void OnAccessTokenFetched(base::OnceClosure quit_closure,
std::string* target_token,
const std::string& received_token) {
*target_token = received_token;
std::move(quit_closure).Run();
}
// Utility to convert an array of Java strings to a set of std::string.
std::set<std::string> ConvertJavaStringArrayToStringSet(
const base::android::JavaRef<jobjectArray>& jstring_array) {
JNIEnv* env = base::android::AttachCurrentThread();
std::vector<std::string> string_array;
base::android::AppendJavaStringArrayToStringVector(env, jstring_array,
&string_array);
return std::set<std::string>(string_array.begin(), string_array.end());
}
// Utility to return the scopes from the most recent access token request to
// |java_client_stub|.
std::set<std::string> GetMostRecentRequestScopes(
base::android::ScopedJavaLocalRef<jobject> java_client_stub) {
JNIEnv* env = base::android::AttachCurrentThread();
return ConvertJavaStringArrayToStringSet(
Java_GoogleAccountAccessTokenFetcherTestStub_getMostRecentRequestScopes(
env, java_client_stub));
}
// Utility to return the scopes from the most recent invalid access token
// notification to |java_client_stub|.
std::set<std::string> GetScopesForMostRecentInvalidToken(
base::android::ScopedJavaLocalRef<jobject> java_client_stub) {
JNIEnv* env = base::android::AttachCurrentThread();
return ConvertJavaStringArrayToStringSet(
Java_GoogleAccountAccessTokenFetcherTestStub_getScopesForMostRecentInvalidToken(
env, java_client_stub));
}
// Utility to return the token from the most recent invalid access token
// notification to |java_client_stub|.
std::string GetMostRecentInvalidToken(
base::android::ScopedJavaLocalRef<jobject> java_client_stub) {
JNIEnv* env = base::android::AttachCurrentThread();
return base::android::ConvertJavaStringToUTF8(
env,
Java_GoogleAccountAccessTokenFetcherTestStub_getMostRecentInvalidToken(
env, java_client_stub));
}
// Tests proper operation of access token fetches initiated from C++ when the
// embedder has set a client for access token fetches in Java.
class AccessTokenFetchBrowserTest : public WebLayerBrowserTest {
public:
AccessTokenFetchBrowserTest() {}
~AccessTokenFetchBrowserTest() override = default;
protected:
ProfileImpl* profile() {
auto* tab_impl = static_cast<TabImpl*>(shell()->tab());
return tab_impl->profile();
}
GoogleAccountAccessTokenFetchDelegate* access_token_fetch_delegate() {
return profile()->access_token_fetch_delegate();
}
};
// Tests that when the embedder hasn't set a
// GoogleAccountAccessTokenFetcherClient instance in Java, access token fetches
// from C++ on Android result in the empty string being returned.
IN_PROC_BROWSER_TEST_F(AccessTokenFetchBrowserTest,
NoGoogleAccountAccessTokenFetcherClientSetInJava) {
base::RunLoop run_loop;
std::string access_token = "dummy";
access_token_fetch_delegate()->FetchAccessToken(
{"scope1"}, base::BindOnce(&OnAccessTokenFetched, run_loop.QuitClosure(),
&access_token));
run_loop.Run();
EXPECT_EQ("", access_token);
}
// Tests that when the embedder sets a Java client that returns a given access
// token, access token fetches initiated from C++ resolve to that token.
IN_PROC_BROWSER_TEST_F(AccessTokenFetchBrowserTest, SuccessfulFetch) {
base::RunLoop run_loop;
std::string access_token = "";
std::string kTokenFromResponse = "token";
std::set<std::string> kScopes = {"scope1", "scope2"};
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jobject> java_client_stub =
Java_AccessTokenFetchTestBridge_installGoogleAccountAccessTokenFetcherTestStub(
env, profile()->GetJavaProfile());
access_token_fetch_delegate()->FetchAccessToken(
kScopes, base::BindOnce(&OnAccessTokenFetched, run_loop.QuitClosure(),
&access_token));
EXPECT_EQ("", access_token);
EXPECT_EQ(
1, Java_GoogleAccountAccessTokenFetcherTestStub_getNumOutstandingRequests(
env, java_client_stub));
int request_id =
Java_GoogleAccountAccessTokenFetcherTestStub_getMostRecentRequestId(
env, java_client_stub);
auto most_recent_request_scopes =
GetMostRecentRequestScopes(java_client_stub);
EXPECT_EQ(kScopes, most_recent_request_scopes);
Java_GoogleAccountAccessTokenFetcherTestStub_respondWithTokenForRequest(
env, java_client_stub, request_id,
base::android::ConvertUTF8ToJavaString(env, kTokenFromResponse));
run_loop.Run();
EXPECT_EQ(kTokenFromResponse, access_token);
}
// Tests correct operation when there are multiple ongoing fetches.
IN_PROC_BROWSER_TEST_F(AccessTokenFetchBrowserTest, MultipleFetches) {
base::RunLoop run_loop1;
base::RunLoop run_loop2;
std::string access_token1 = "";
std::string access_token2 = "";
std::string kTokenFromResponse1 = "token1";
std::string kTokenFromResponse2 = "token2";
std::set<std::string> kScopes1 = {"scope1", "scope2"};
std::set<std::string> kScopes2 = {"scope3"};
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jobject> java_client_stub =
Java_AccessTokenFetchTestBridge_installGoogleAccountAccessTokenFetcherTestStub(
env, profile()->GetJavaProfile());
access_token_fetch_delegate()->FetchAccessToken(
kScopes1, base::BindOnce(&OnAccessTokenFetched, run_loop1.QuitClosure(),
&access_token1));
EXPECT_EQ(
1, Java_GoogleAccountAccessTokenFetcherTestStub_getNumOutstandingRequests(
env, java_client_stub));
int request_id1 =
Java_GoogleAccountAccessTokenFetcherTestStub_getMostRecentRequestId(
env, java_client_stub);
auto most_recent_request_scopes1 =
GetMostRecentRequestScopes(java_client_stub);
EXPECT_EQ(kScopes1, most_recent_request_scopes1);
EXPECT_EQ("", access_token1);
EXPECT_EQ("", access_token2);
access_token_fetch_delegate()->FetchAccessToken(
kScopes2, base::BindOnce(&OnAccessTokenFetched, run_loop2.QuitClosure(),
&access_token2));
EXPECT_EQ(
2, Java_GoogleAccountAccessTokenFetcherTestStub_getNumOutstandingRequests(
env, java_client_stub));
int request_id2 =
Java_GoogleAccountAccessTokenFetcherTestStub_getMostRecentRequestId(
env, java_client_stub);
auto most_recent_request_scopes2 =
GetMostRecentRequestScopes(java_client_stub);
EXPECT_EQ(kScopes2, most_recent_request_scopes2);
EXPECT_EQ("", access_token1);
EXPECT_EQ("", access_token2);
Java_GoogleAccountAccessTokenFetcherTestStub_respondWithTokenForRequest(
env, java_client_stub, request_id2,
base::android::ConvertUTF8ToJavaString(env, kTokenFromResponse2));
run_loop2.Run();
EXPECT_EQ("", access_token1);
EXPECT_EQ(kTokenFromResponse2, access_token2);
Java_GoogleAccountAccessTokenFetcherTestStub_respondWithTokenForRequest(
env, java_client_stub, request_id1,
base::android::ConvertUTF8ToJavaString(env, kTokenFromResponse1));
run_loop1.Run();
EXPECT_EQ(kTokenFromResponse1, access_token1);
EXPECT_EQ(kTokenFromResponse2, access_token2);
}
// Tests that when the C++ delegate is notified that an access token has been
// identified as invalid, that information is forwarded to the Java side.
IN_PROC_BROWSER_TEST_F(AccessTokenFetchBrowserTest,
AccessTokenIdentifiedAsInvalid) {
const std::string kInvalidToken = "token";
const std::set<std::string> kScopesForInvalidToken = {"scope1", "scope2"};
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jobject> java_client_stub =
Java_AccessTokenFetchTestBridge_installGoogleAccountAccessTokenFetcherTestStub(
env, profile()->GetJavaProfile());
EXPECT_EQ(std::set<std::string>(),
GetScopesForMostRecentInvalidToken(java_client_stub));
EXPECT_EQ("", GetMostRecentInvalidToken(java_client_stub));
access_token_fetch_delegate()->OnAccessTokenIdentifiedAsInvalid(
kScopesForInvalidToken, kInvalidToken);
EXPECT_EQ(kScopesForInvalidToken,
GetScopesForMostRecentInvalidToken(java_client_stub));
EXPECT_EQ(kInvalidToken, GetMostRecentInvalidToken(java_client_stub));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/access_token_fetch_browsertest.cc | C++ | unknown | 9,408 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "base/test/scoped_feature_list.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#include "components/infobars/core/infobar_delegate.h"
#include "components/infobars/core/infobar_manager.h"
#include "components/page_load_metrics/browser/observers/ad_metrics/ad_intervention_browser_test_utils.h"
#include "components/page_load_metrics/browser/page_load_metrics_test_waiter.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
#include "components/subresource_filter/core/browser/subresource_filter_features.h"
#include "components/subresource_filter/core/common/common_features.h"
#include "components/subresource_filter/core/common/test_ruleset_utils.h"
#include "components/subresource_filter/core/mojom/subresource_filter.mojom.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/display/screen_info.h"
#include "ui/gfx/geometry/rect.h"
#include "url/gurl.h"
#include "weblayer/test/subresource_filter_browser_test_harness.h"
namespace weblayer {
namespace {
const char kAdsInterventionRecordedHistogram[] =
"SubresourceFilter.PageLoad.AdsInterventionTriggered";
} // namespace
class AdDensityViolationBrowserTest : public SubresourceFilterBrowserTest {
public:
AdDensityViolationBrowserTest() = default;
void SetUp() override {
std::vector<base::test::FeatureRef> enabled = {
subresource_filter::kAdTagging,
subresource_filter::kAdsInterventionsEnforced};
std::vector<base::test::FeatureRef> disabled = {};
feature_list_.InitWithFeatures(enabled, disabled);
SubresourceFilterBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
SubresourceFilterBrowserTest::SetUpOnMainThread();
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")});
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(
AdDensityViolationBrowserTest,
MobilePageAdDensityByHeightAbove30_AdInterventionTriggered) {
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto waiter = std::make_unique<page_load_metrics::PageLoadMetricsTestWaiter>(
web_contents());
const GURL url(embedded_test_server()->GetURL(
"a.com", "/ads_observer/blank_with_adiframe_writer.html"));
waiter->SetMainFrameIntersectionExpectation();
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
waiter->Wait();
int document_height = page_load_metrics::GetDocumentHeight(web_contents());
int frame_width = 100; // Ad density by height is independent of frame width.
int frame_height = document_height * 0.45;
// Create the frame with b.com as origin to not get caught by
// restricted ad tagging.
page_load_metrics::CreateAndWaitForIframeAtRect(
web_contents(), waiter.get(),
embedded_test_server()->GetURL("b.com", "/ads_observer/pixel.png"),
gfx::Rect(0, 0, frame_width, frame_height));
// Delete the page load metrics test waiter instead of reinitializing it
// for the next page load.
waiter.reset();
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
// blank_with_adiframe_writer loads a script tagged as an ad, verify it is not
// loaded and the subresource filter UI for ad blocking is shown.
EXPECT_FALSE(
WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame()));
EXPECT_EQ(infobars::ContentInfoBarManager::FromWebContents(web_contents())
->infobar_count(),
1u);
EXPECT_EQ(infobars::ContentInfoBarManager::FromWebContents(web_contents())
->infobar_at(0)
->delegate()
->GetIdentifier(),
infobars::InfoBarDelegate::ADS_BLOCKED_INFOBAR_DELEGATE_ANDROID);
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
}
IN_PROC_BROWSER_TEST_F(
AdDensityViolationBrowserTest,
MobilePageAdDensityByHeightBelow30_AdInterventionNotTriggered) {
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto waiter = std::make_unique<page_load_metrics::PageLoadMetricsTestWaiter>(
web_contents());
const GURL url(embedded_test_server()->GetURL(
"a.com", "/ads_observer/blank_with_adiframe_writer.html"));
waiter->SetMainFrameIntersectionExpectation();
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
waiter->Wait();
int document_height = page_load_metrics::GetDocumentHeight(web_contents());
int frame_width = 100; // Ad density by height is independent of frame width.
int frame_height = document_height * 0.25;
// Create the frame with b.com as origin to not get caught by
// restricted ad tagging.
page_load_metrics::CreateAndWaitForIframeAtRect(
web_contents(), waiter.get(),
embedded_test_server()->GetURL("b.com", "/ads_observer/pixel.png"),
gfx::Rect(0, 0, frame_width, frame_height));
// Delete the page load metrics test waiter instead of reinitializing it
// for the next page load.
waiter.reset();
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
// blank_with_adiframe_writer loads a script tagged as an ad, verify it is
// loaded as ads are not blocked and the subresource filter UI is not
// shown.
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame()));
// No ads blocked infobar should be shown as we have not triggered the
// intervention.
EXPECT_EQ(infobars::ContentInfoBarManager::FromWebContents(web_contents())
->infobar_count(),
0u);
histogram_tester.ExpectTotalCount(kAdsInterventionRecordedHistogram, 0);
}
class AdDensityViolationBrowserTestWithoutEnforcement
: public SubresourceFilterBrowserTest {
public:
AdDensityViolationBrowserTestWithoutEnforcement() = default;
void SetUp() override {
std::vector<base::test::FeatureRef> enabled = {
subresource_filter::kAdTagging};
std::vector<base::test::FeatureRef> disabled = {
subresource_filter::kAdsInterventionsEnforced};
feature_list_.InitWithFeatures(enabled, disabled);
SubresourceFilterBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
SubresourceFilterBrowserTest::SetUpOnMainThread();
SetRulesetWithRules(
{subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js")});
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(
AdDensityViolationBrowserTestWithoutEnforcement,
MobilePageAdDensityByHeightAbove30_NoAdInterventionTriggered) {
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
auto waiter = std::make_unique<page_load_metrics::PageLoadMetricsTestWaiter>(
web_contents());
const GURL url(embedded_test_server()->GetURL(
"a.com", "/ads_observer/blank_with_adiframe_writer.html"));
waiter->SetMainFrameIntersectionExpectation();
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
waiter->Wait();
int document_height = page_load_metrics::GetDocumentHeight(web_contents());
int frame_width = 100; // Ad density by height is independent of frame width.
int frame_height = document_height * 0.45;
// Create the frame with b.com as origin to not get caught by
// restricted ad tagging.
page_load_metrics::CreateAndWaitForIframeAtRect(
web_contents(), waiter.get(),
embedded_test_server()->GetURL("b.com", "/ads_observer/pixel.png"),
gfx::Rect(0, 0, frame_width, frame_height));
// Delete the page load metrics test waiter instead of reinitializing it
// for the next page load.
waiter.reset();
EXPECT_TRUE(content::NavigateToURL(web_contents(), url));
// We are not enforcing ad blocking on ads violations, site should load
// as expected without subresource filter UI.
EXPECT_TRUE(
WasParsedScriptElementLoaded(web_contents()->GetPrimaryMainFrame()));
// No ads blocked infobar should be shown as we have not triggered the
// intervention.
EXPECT_EQ(infobars::ContentInfoBarManager::FromWebContents(web_contents())
->infobar_count(),
0u);
histogram_tester.ExpectBucketCount(
kAdsInterventionRecordedHistogram,
static_cast<int>(subresource_filter::mojom::AdsViolation::
kMobileAdDensityByHeightAbove30),
1);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/ad_density_intervention_browsertest.cc | C++ | unknown | 8,950 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/application_info_helper.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "weblayer/browser/java/jni/ApplicationInfoHelper_jni.h"
namespace weblayer {
// static
bool GetApplicationMetadataAsBoolean(const std::string& key,
bool default_value) {
auto* env = base::android::AttachCurrentThread();
return Java_ApplicationInfoHelper_getMetadataAsBoolean(
env, base::android::ConvertUTF8ToJavaString(env, key), default_value);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/application_info_helper.cc | C++ | unknown | 715 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_APPLICATION_INFO_HELPER_H_
#define WEBLAYER_BROWSER_ANDROID_APPLICATION_INFO_HELPER_H_
#include <string>
namespace weblayer {
// Looks for a metadata tag with name |key| in the application's manifest, and
// returns its value if found, or |default_value| otherwise.
bool GetApplicationMetadataAsBoolean(const std::string& key,
bool default_value);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_APPLICATION_INFO_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/application_info_helper.h | C++ | unknown | 655 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/exception_filter.h"
#include "weblayer/browser/java/jni/WebLayerExceptionFilter_jni.h"
namespace weblayer {
bool WebLayerJavaExceptionFilter(
const base::android::JavaRef<jthrowable>& throwable) {
return Java_WebLayerExceptionFilter_stackTraceContainsWebLayerCode(
base::android::AttachCurrentThread(), throwable);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/exception_filter.cc | C++ | unknown | 537 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_EXCEPTION_FILTER_H_
#define WEBLAYER_BROWSER_ANDROID_EXCEPTION_FILTER_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
namespace weblayer {
// Called when an uncaught exception is detected. A return value of true
// indicates the exception is likely relevant to WebLayer.
bool WebLayerJavaExceptionFilter(
const base::android::JavaRef<jthrowable>& throwable);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_EXCEPTION_FILTER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/exception_filter.h | C++ | unknown | 641 |
include_rules = [
"-content/public",
"+content/public/test",
# WebEngineJUnit4ClassRunner should be used for all tests since it has logic to
# make command line flags work in WebLayer.
"-base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java",
]
specific_include_rules = {
"WebEngineJUnit4ClassRunner.java": [
"+base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java",
]
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/DEPS | Python | unknown | 446 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test.instrumentation_test_apk;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.common.util.concurrent.ListenableFuture;
import org.chromium.webengine.WebFragment;
import org.chromium.webengine.WebSandbox;
import java.util.List;
/**
* Activity for running instrumentation tests.
*/
public class InstrumentationActivity extends AppCompatActivity {
private ListenableFuture<WebSandbox> mWebSandboxFuture;
private ListenableFuture<String> mWebSandboxVersionFuture;
private LifeCycleListener mLifeCycleListener;
/**
* Use this to listen for life cycle events in tests.
*/
public interface LifeCycleListener {
void onNewIntent(Intent intent);
}
public void setLifeCycleListener(LifeCycleListener lifeCycleListener) {
mLifeCycleListener = lifeCycleListener;
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebSandboxFuture = WebSandbox.create(getApplicationContext());
}
public ListenableFuture<WebSandbox> getWebSandboxFuture() {
return mWebSandboxFuture;
}
public void attachFragment(WebFragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container_view, fragment)
.commitNow();
}
public View getFragmentContainerView() {
return findViewById(R.id.fragment_container_view);
}
public void detachFragment(WebFragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setReorderingAllowed(true).remove(fragment).commitNow();
}
public WebFragment getAttachedFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments.size() != 1) {
throw new IllegalStateException("Expected to have exactly 1 WebFragment.");
}
return (WebFragment) fragments.get(0);
}
@Override
protected void onNewIntent(Intent intent) {
if (mLifeCycleListener != null) {
mLifeCycleListener.onNewIntent(intent);
}
super.onNewIntent(intent);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/instrumentation_test_apk/src/org/chromium/webengine/test/instrumentation_test_apk/InstrumentationActivity.java | Java | unknown | 2,769 |
# Copyright 2021 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
USE_PYTHON3 = True
import inspect
import os
import sys
EXPECTATIONS_FILE = 'expectations.txt'
def _MaybeAddTypToPath():
src_dir = os.path.join(
os.path.dirname(inspect.getfile(CheckChangeOnUpload)),
os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)
typ_dir = os.path.join(src_dir, 'third_party', 'catapult',
'third_party', 'typ')
if typ_dir not in sys.path:
sys.path.append(typ_dir)
def CheckChangeOnUpload(input_api, output_api):
results = []
if any(EXPECTATIONS_FILE in f.LocalPath()
for f in input_api.AffectedFiles() if f.Action() != 'D'):
_MaybeAddTypToPath()
from typ.expectations_parser import TestExpectations
test_expectations = TestExpectations()
with open(EXPECTATIONS_FILE, 'r') as exp:
ret, errors = test_expectations.parse_tagged_list(exp.read())
if ret:
results.append(output_api.PresubmitError(
'Expectations file had the following errors: \n' + errors))
return results
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/skew/PRESUBMIT.py | Python | unknown | 1,206 |
#!/usr/bin/env python3
#
# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Script to build a CIPD package for weblayer_instrumentation_test_apk from
# the current Chromium checkout.
#
# This should be run from the src directory of a release branch. This will
# take care of the build, you need not do that yourself. After the package is
# built run two cipd commands (printed at the end of script execution) to
# upload the package to the CIPD server and to update the ref for the
# corresponding milestone. Once the ref is updated, the version skew test will
# pick up the new package in successive runs.
import argparse
import contextlib
import os
import shutil
import subprocess
import sys
import re
import tempfile
import zipfile
SRC_DIR = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', '..')
# Run mb.py out of the current branch for simplicity.
MB_PATH = os.path.join('tools', 'mb', 'mb.py')
# Get the config specifying the gn args from the location of this script.
MB_CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'mb_config.pyl')
CHROMIUM_VERSION_REGEX = r'\d+\.\d+\.\d+\.\d+$'
# CIPD package path.
# https://chrome-infra-packages.appspot.com/p/chromium/testing/weblayer-x86/+/
CIPD_PKG_PATH='chromium/testing/weblayer-x86'
@contextlib.contextmanager
def temporarily_chdir_to_src(local_paths=None):
"""Change directories to chromium/src when entering with block and
then change back to current directory after exiting with block.
Args:
local_paths: List of paths to change into relative paths.
Returns:
List of paths relative to chromium/src.
"""
curr_dir = os.getcwd()
paths_rel_to_src = [
os.path.relpath(p, SRC_DIR) for p in local_paths or []]
try:
os.chdir(SRC_DIR)
yield paths_rel_to_src
finally:
os.chdir(curr_dir)
def zip_test_target(zip_filename):
"""Create zip of all deps for weblayer_instrumentation_test_apk.
Args:
zip_filename: destination zip filename.
"""
cmd = [MB_PATH,
'zip',
'--master=dummy.master',
'--builder=dummy.builder',
'--config-file=%s' % MB_CONFIG_PATH,
os.path.join('out', 'Release'),
'weblayer_instrumentation_test_apk',
zip_filename]
print(' '.join(cmd))
subprocess.check_call(cmd)
def build_cipd_pkg(input_path, cipd_filename):
"""Create a CIPD package file from the given input path.
Args:
input_path: input directory from which to build the package.
cipd_filename: output filename for resulting cipd archive.
"""
cmd = ['cipd',
'pkg-build',
'--in=%s' % input_path,
'--install-mode=copy',
'--name=%s' % CIPD_PKG_PATH,
'--out=%s' % cipd_filename]
print(' '.join(cmd))
subprocess.check_call(cmd)
def get_chromium_version():
with open(os.path.join(SRC_DIR, 'chrome', 'VERSION')) as f:
version = '.'.join(line[line.index('=') + 1:]
for line in f.read().splitlines())
if not re.match(CHROMIUM_VERSION_REGEX, version):
raise ValueError("Chromium version, '%s', is not in proper format" %
version)
return version
def main():
parser = argparse.ArgumentParser(
description='Package weblayer instrumentation tests for CIPD.')
parser.add_argument(
'--cipd_out',
required=True,
help="Output filename for resulting .cipd file.")
args = parser.parse_args()
chromium_version = get_chromium_version()
with tempfile.TemporaryDirectory() as tmp_dir, \
temporarily_chdir_to_src([args.cipd_out]) as cipd_out_src_rel_paths:
# Create zip archive of test target.
zip_filename = os.path.join(tmp_dir, 'file.zip')
zip_test_target(zip_filename)
# Extract zip archive.
extracted = os.path.join(tmp_dir, 'extracted')
os.mkdir(extracted)
with zipfile.ZipFile(zip_filename) as zip_file:
zip_file.extractall(path=extracted)
# Create CIPD archive.
tmp_cipd_filename = os.path.join(tmp_dir, 'file.cipd')
build_cipd_pkg(extracted, tmp_cipd_filename)
shutil.move(tmp_cipd_filename, cipd_out_src_rel_paths[0])
print(('Use "cipd pkg-register %s -verbose -tag \'version:%s\'" ' +
'to upload package to the cipd server.') %
(args.cipd_out, chromium_version))
print('Use "cipd set-ref chromium/testing/weblayer-x86 --version ' +
'<CIPD instance version> -ref m<milestone>" to update the ref.')
print('The CIPD instance version can be found on the "Instance" line ' +
'after "chromium/testing/weblayer-x86:".')
if __name__ == '__main__':
sys.exit(main())
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/skew/build_weblayer_instrumentation_test_cipd_pkg.py | Python | unknown | 4,740 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.Tab;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebEngineParams;
import org.chromium.webengine.WebSandbox;
import java.util.ArrayList;
/**
* Tests allowed origins. This can be provided as a WebEngine parameter.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class AllowedOriginsTest {
private static final int PORT = 3000;
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
WebSandbox mSandbox;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
// The origin needs to specify the port so instead of auto-assigning one, we need to choose
// an explicit port in our tests.
mTestServerRule.setServerPort(PORT);
mServer = mTestServerRule.getServer();
mSandbox = mActivityTestRule.getWebSandbox();
}
@After
public void shutdown() throws Exception {
if (mSandbox != null) {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
}
mActivityTestRule.finish();
}
@Test
@SmallTest
public void testLoadsUrls_whenAllowlistNotProvided() throws Exception {
tryNavigateUrls(null);
}
@Test
@SmallTest
public void testLoadsUrls_whenOriginsAllowlisted() throws Exception {
ArrayList<String> allowList = new ArrayList<>();
allowList.add("http://localhost:" + PORT);
allowList.add("http://127.0.0.1:" + PORT);
tryNavigateUrls(allowList);
}
@Test()
@SmallTest
public void testDoNotLoadUrl_whenOriginNotAllowlisted() throws Exception {
ArrayList<String> allowList = new ArrayList<>();
allowList.add("http://localhost:" + PORT);
// Not allowing 127.0.0.1
try {
tryNavigateUrls(allowList);
Assert.fail("Should have thrown exception");
} catch (InstrumentationActivityTestRule.NavigationFailureException e) {
Navigation failedNavigation = e.getNavigation();
// Status code is 0 when a navigation hasn't completed
Assert.assertEquals(failedNavigation.getStatusCode(), 0);
// We can verify this failed for 127.0.0.1
Assert.assertEquals(failedNavigation.getUri().toString(),
getTestDataURL("127.0.0.1", "simple_page.html"));
}
}
@Test(expected = InstrumentationActivityTestRule.NavigationFailureException.class)
@SmallTest()
public void testDoNotLoadUrl_whenPortNotAllowlisted() throws Exception {
ArrayList<String> allowList = new ArrayList<>();
allowList.add("http://localhost:" + PORT);
// This will fail because this is using a port that wasn't allowlisted
allowList.add("http://127.0.0.1:" + (PORT + 1));
tryNavigateUrls(allowList);
}
@Test(expected = InstrumentationActivityTestRule.NavigationFailureException.class)
@SmallTest()
public void testDoNotLoadUrl_whenSchemeNotAllowlisted() throws Exception {
ArrayList<String> allowList = new ArrayList<>();
allowList.add("http://localhost:" + PORT);
// Our test server uses http so this will fail.
allowList.add("https://127.0.0.1:" + PORT);
tryNavigateUrls(allowList);
}
private void tryNavigateUrls(ArrayList<String> allowList) throws Exception {
WebEngine webEngine = createWebEngine(allowList);
String url1 = getTestDataURL("localhost", "simple_page.html");
String url2 = getTestDataURL("127.0.0.1", "simple_page.html");
Tab activeTab = webEngine.getTabManager().getActiveTab();
mActivityTestRule.navigateAndWait(activeTab, url1);
mActivityTestRule.navigateAndWait(activeTab, url2);
}
private WebEngine createWebEngine(ArrayList<String> allowList) throws Exception {
WebEngineParams.Builder builder =
(new WebEngineParams.Builder()).setProfileName("DefaultProfile");
if (allowList != null) {
builder.setAllowedOrigins(allowList);
}
WebEngineParams params = builder.build();
return runOnUiThreadBlocking(() -> mSandbox.createWebEngine(params)).get();
}
private String getTestDataURL(String host, String path) {
return mServer.getURLWithHostName(host, "/weblayer/test/data/" + path);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/AllowedOriginsTest.java | Java | unknown | 5,293 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.core.content.ContextCompat;
import androidx.test.filters.SmallTest;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.util.TestWebServer;
import org.chromium.webengine.CookieManager;
import org.chromium.webengine.RestrictedAPIException;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabManager;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.concurrent.CountDownLatch;
/**
* Tests the CookieManager API.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class CookieManagerTest {
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
@Rule
public DigitalAssetLinksServerRule mDALServerRule = new DigitalAssetLinksServerRule();
private TestWebServer mServer;
private CookieManager mCookieManager;
private TabManager mTabManager;
private WebSandbox mSandbox;
@Before
public void setUp() throws Exception {
mServer = mDALServerRule.getServer();
mActivityTestRule.launchShell();
mSandbox = mActivityTestRule.getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
runOnUiThreadBlocking(() -> mActivityTestRule.attachFragment(webEngine.getFragment()));
mCookieManager = webEngine.getCookieManager();
mTabManager = webEngine.getTabManager();
}
@After
public void tearDown() {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
mActivityTestRule.finish();
}
@Test
@SmallTest
public void accessFailsWithoutVerification() throws Exception {
ListenableFuture<String> future =
runOnUiThreadBlocking(() -> mCookieManager.getCookie(mServer.getBaseUrl()));
CountDownLatch executeLatch = new CountDownLatch(1);
Futures.addCallback(future, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
Assert.fail("future resolved unexpectedly.");
}
@Override
public void onFailure(Throwable thrown) {
if (!(thrown instanceof RestrictedAPIException)) {
Assert.fail(
"expected future to fail due to RestrictedAPIException, instead got: "
+ thrown.getClass().getName());
}
executeLatch.countDown();
}
}, ContextCompat.getMainExecutor(mActivityTestRule.getContext()));
executeLatch.await();
}
@Test
@SmallTest
public void setAndGetCookies() throws Exception {
mDALServerRule.setUpDigitalAssetLinks();
String cookie =
runOnUiThreadBlocking(() -> mCookieManager.getCookie(mServer.getBaseUrl())).get();
Assert.assertEquals(cookie, "");
runOnUiThreadBlocking(() -> mCookieManager.setCookie(mServer.getBaseUrl(), "foo=bar"));
String setCookie =
runOnUiThreadBlocking(() -> mCookieManager.getCookie(mServer.getBaseUrl())).get();
Assert.assertEquals(setCookie, "foo=bar");
}
@Test
@SmallTest
public void getCookieCreatedByPage() throws Exception {
mDALServerRule.setUpDigitalAssetLinks();
String url = mDALServerRule.getServer().setResponse("/page.html",
"<html><script>document.cookie='foo=bar42'</script><body>contents!</body></html>",
null);
String cookie =
runOnUiThreadBlocking(() -> mCookieManager.getCookie(mServer.getBaseUrl())).get();
Assert.assertEquals(cookie, "");
Tab tab = mTabManager.getActiveTab();
mActivityTestRule.navigateAndWait(tab, url);
// Run JS to make sure the script had time to run before we actually check via the cookie
// manager.
Assert.assertEquals("\"foo=bar42\"",
runOnUiThreadBlocking(() -> tab.executeScript("document.cookie", false)).get());
String updatedCookie = runOnUiThreadBlocking(() -> mCookieManager.getCookie(url)).get();
Assert.assertEquals(updatedCookie, "foo=bar42");
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/CookieManagerTest.java | Java | unknown | 4,909 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.chromium.base.ContextUtils;
import org.chromium.base.PackageUtils;
import org.chromium.net.test.util.TestWebServer;
import java.util.List;
/**
* Gives an option to make DAL verification pass for the tests.
* Also exposes the TestWebServer instance for more customization.
*/
public class DigitalAssetLinksServerRule extends TestWatcher {
private static final String ASSETLINKS_PATH = "/.well-known/assetlinks.json";
private TestWebServer mServer;
@Override
protected void starting(Description desc) {
super.starting(desc);
// Try to start a server on any of the ports in the 8900s range.
// The 1P port ranges are defined in
// //weblayer/shell/android/webengine_shell_apk/res_template/values/strings.xml.
for (int port = 8900; port < 9000; port++) {
try {
mServer = TestWebServer.start(port);
} catch (Exception e) {
}
}
if (mServer == null) {
Assert.fail("Failed to start a TestWebServer.");
}
// By default, the asset links are not set up.
mServer.setResponseWithNotFoundStatus(ASSETLINKS_PATH, null);
}
@Override
protected void finished(Description desc) {
super.finished(desc);
mServer.shutdown();
}
// Returns the TestServer in case you want to add additional handlers.
public TestWebServer getServer() {
return mServer;
}
// Makes the DAL verification succeed.
public void setUpDigitalAssetLinks() {
String packageName = ContextUtils.getApplicationContext().getPackageName();
List<String> signatureFingerprints =
PackageUtils.getCertificateSHA256FingerprintForPackage(packageName);
mServer.setResponse(
ASSETLINKS_PATH, makeAssetFile(packageName, signatureFingerprints.get(0)), null);
}
private static String makeAssetFile(String packageName, String fingerprint) {
try {
return (new JSONArray().put(
new JSONObject()
.put("relation",
new JSONArray().put(
"delegate_permission/common.handle_all_urls"))
.put("target",
new JSONObject()
.put("namespace", "android_app")
.put("package_name", packageName)
.put("sha256_cert_fingerprints",
new JSONArray().put(fingerprint)))))
.toString();
} catch (JSONException e) {
}
return "";
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/DigitalAssetLinksServerRule.java | Java | unknown | 3,234 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.util.Pair;
import androidx.core.content.ContextCompat;
import androidx.test.filters.SmallTest;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.util.TestWebServer;
import org.chromium.webengine.RestrictedAPIException;
import org.chromium.webengine.Tab;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* Tests executing JavaScript in a Tab.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class ExecuteScriptTest {
private static final String sRequestPath = "/page.html";
private static final String sResponseString =
"<html><head></head><body>contents!</body><script>window.foo = 42;</script></html>";
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
@Rule
public DigitalAssetLinksServerRule mDALServerRule = new DigitalAssetLinksServerRule();
private Tab mTab;
private String mDefaultUrl;
private TestWebServer mServer;
@Before
public void setUp() throws Exception {
mServer = mDALServerRule.getServer();
mActivityTestRule.launchShell();
List<Pair<String, String>> embedderAncestorHeader = new ArrayList();
embedderAncestorHeader.add(new Pair("X-embedder-ancestors", "none"));
mDefaultUrl = mServer.setResponse(sRequestPath, sResponseString, embedderAncestorHeader);
}
@After
public void tearDown() {
mActivityTestRule.finish();
}
private Tab navigate() throws Exception {
mActivityTestRule.createWebEngineAttachThenNavigateAndWait(mDefaultUrl);
return mActivityTestRule.getFragment().getWebEngine().getTabManager().getActiveTab();
}
@Test
@SmallTest
public void executeScriptFailsWithoutVerification() throws Exception {
Tab activeTab = navigate();
CountDownLatch executeLatch = new CountDownLatch(1);
ListenableFuture<String> future =
runOnUiThreadBlocking(() -> activeTab.executeScript("1+1", true));
Futures.addCallback(future, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
Assert.fail("future resolved unexpectedly.");
}
@Override
public void onFailure(Throwable thrown) {
if (!(thrown instanceof RestrictedAPIException)) {
Assert.fail(
"expected future to fail due to RestrictedAPIException, instead got: "
+ thrown.getClass().getName());
}
executeLatch.countDown();
}
}, ContextCompat.getMainExecutor(mActivityTestRule.getContext()));
executeLatch.await();
}
@Test
@SmallTest
public void executeScriptSucceedsWithDALVerification() throws Exception {
mDALServerRule.setUpDigitalAssetLinks();
Tab activeTab = navigate();
ListenableFuture<String> future =
runOnUiThreadBlocking(() -> activeTab.executeScript("1+1", true));
Assert.assertEquals(future.get(), "2");
}
@Test
@SmallTest
public void executeScriptSucceedsWithHeaderVerification() throws Exception {
List<Pair<String, String>> embedderAncestorHeader = new ArrayList();
embedderAncestorHeader.add(
new Pair("X-embedder-ancestors", mActivityTestRule.getPackageName()));
mDefaultUrl = mServer.setResponse(sRequestPath, sResponseString, embedderAncestorHeader);
Tab activeTab = navigate();
ListenableFuture<String> future =
runOnUiThreadBlocking(() -> activeTab.executeScript("1+1", true));
Assert.assertEquals(future.get(), "2");
}
@Test
@SmallTest
public void executeScriptSucceedsWithoutHeader() throws Exception {
mDefaultUrl = mServer.setResponse(sRequestPath, sResponseString, null);
Tab activeTab = navigate();
ListenableFuture<String> future =
runOnUiThreadBlocking(() -> activeTab.executeScript("1+1", true));
Assert.assertEquals(future.get(), "2");
}
@Test
@SmallTest
public void useSeparateIsolate() throws Exception {
mDALServerRule.setUpDigitalAssetLinks();
Tab activeTab = navigate();
ListenableFuture<String> futureIsolated =
runOnUiThreadBlocking(() -> activeTab.executeScript("window.foo", true));
Assert.assertEquals(futureIsolated.get(), "null");
ListenableFuture<String> futureUnisolated =
runOnUiThreadBlocking(() -> activeTab.executeScript("window.foo", false));
Assert.assertEquals(futureUnisolated.get(), "42");
}
@Test
@SmallTest
public void modifyDOMSucceeds() throws Exception {
mDALServerRule.setUpDigitalAssetLinks();
Tab activeTab = navigate();
ListenableFuture<String> future1 = runOnUiThreadBlocking(
() -> activeTab.executeScript("document.body.innerText", false));
Assert.assertEquals(future1.get(), "\"contents!\"");
runOnUiThreadBlocking(
() -> activeTab.executeScript("document.body.innerText = 'foo'", false))
.get();
ListenableFuture<String> future2 = runOnUiThreadBlocking(
() -> activeTab.executeScript("document.body.innerText", false));
Assert.assertEquals(future2.get(), "\"foo\"");
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/ExecuteScriptTest.java | Java | unknown | 6,188 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.app.Instrumentation;
import android.content.Intent;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.LargeTest;
import com.google.common.util.concurrent.SettableFuture;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.content_public.browser.test.util.ClickUtils;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Tab;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebEngineParams;
import org.chromium.webengine.WebSandbox;
import org.chromium.webengine.test.instrumentation_test_apk.InstrumentationActivity;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Tests for launching external intents from deep links.
*/
@DoNotBatch(reason = "Tests are testing behaviour between activities that are single task")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class ExternalIntentsTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
// We need plenty time to load up a page, launch a new activity, and return.
// We need to be confident that those events also did not happen in the disabled
// case if this times out.
// The is quite a slow set of tests because we need this to be a large value to avoid flaking.
private static final int TEST_TIMEOUT_MS = 20_000;
private EmbeddedTestServer mServer;
private WebSandbox mSandbox;
private Instrumentation mInstrumentation;
private String mUrl;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
mUrl = getTestDataURL("external_intents.html#"
+ mActivityTestRule.getShellComponentName().flattenToString());
mSandbox = mActivityTestRule.getWebSandbox();
}
@After
public void shutdown() {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
mActivityTestRule.finish();
}
@Test
@LargeTest
@DisabledTest(message = "Flaky because this relies on waiting for an activity to launch")
public void testOpensExternalIntents_shouldLaunch() throws Exception {
// Awful hack heads up:
// The problem is that the application is a separate application from the
// activity running the tests so we can't use an ActivityMonitor.
// Chromium thinks that if you are opening a deeplink to the same package,
// it should act as a "tab" navigation and not send an external intent.
// We can't override apis like startActivity for the instrumentation activity
// because the component is starting the activity from the web engine context.
final SettableFuture<Boolean> launchedExternal = SettableFuture.create();
mActivityTestRule.getActivity().setLifeCycleListener(
new InstrumentationActivity.LifeCycleListener() {
@Override
public void onNewIntent(Intent intent) {
launchedExternal.set(intent.hasExtra("LAUNCHED_EXTERNAL"));
}
});
Tab currentTab = createWebEngineAndLoadPage(/* isExternalIntentsEnabled= */ true);
ClickUtils.mouseSingleClickView(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getFragmentContainerView(), 1, 1);
try {
Assert.assertTrue(launchedExternal.get(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS));
} catch (TimeoutException e) {
Assert.fail("Shouldn't have timed out");
}
}
@Test
@LargeTest
public void testDisableExternalIntents_shouldNotLaunch() throws Exception {
final SettableFuture<Boolean> launchedExternal = SettableFuture.create();
mActivityTestRule.getActivity().setLifeCycleListener(
new InstrumentationActivity.LifeCycleListener() {
@Override
public void onNewIntent(Intent intent) {
launchedExternal.set(intent.hasExtra("LAUNCHED_EXTERNAL"));
}
});
Tab currentTab = createWebEngineAndLoadPage(/* isExternalIntentsEnabled= */ false);
ClickUtils.mouseSingleClickView(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getFragmentContainerView(), 1, 1);
try {
Assert.assertFalse(launchedExternal.get(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS));
// If we get here it means the test resumed from the other activity
Assert.fail("The activity shouldn't have been resumed");
} catch (TimeoutException e) {
// Yay it was meant to timeout
}
}
/**
* Creates a new web engine and loads the test page.
*
* Will configure if we can launch external intents or not.
*/
private Tab createWebEngineAndLoadPage(boolean isExternalIntentsEnabled) throws Exception {
WebEngineParams params = new WebEngineParams.Builder()
.setProfileName("Default")
.setIsExternalIntentsEnabled(isExternalIntentsEnabled)
.build();
WebEngine webEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine(params)).get();
runOnUiThreadBlocking(() -> mActivityTestRule.attachFragment(webEngine.getFragment()));
Tab activeTab = webEngine.getTabManager().getActiveTab();
mActivityTestRule.navigateAndWait(activeTab, mUrl);
return activeTab;
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/ExternalIntentsTest.java | Java | unknown | 6,420 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.graphics.Bitmap;
import android.graphics.Color;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabObserver;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Tests that a tab's favicon is returned.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class FaviconTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
private Tab mTab;
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
WebSandbox sandbox = mActivityTestRule.getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> sandbox.createWebEngine()).get();
mTab = webEngine.getTabManager().getActiveTab();
}
@After
public void tearDown() {
mActivityTestRule.finish();
}
private static final class ResultHolder {
public Bitmap mResult;
}
private Bitmap waitForFaviconChange() throws Exception {
final ResultHolder holder = new ResultHolder();
CountDownLatch faviconLatch = new CountDownLatch(1);
TabObserver observer = new TabObserver() {
@Override
public void onFaviconChanged(Tab tab, Bitmap favicon) {
holder.mResult = favicon;
faviconLatch.countDown();
}
};
runOnUiThreadBlocking(() -> mTab.registerTabObserver(observer));
faviconLatch.await(10, TimeUnit.SECONDS);
runOnUiThreadBlocking(() -> mTab.unregisterTabObserver(observer));
return holder.mResult;
}
private void verifyFavicon(Bitmap favicon) {
Assert.assertNotNull(favicon);
Assert.assertEquals(favicon.getHeight(), 16);
Assert.assertEquals(favicon.getWidth(), 16);
Assert.assertEquals(favicon.getPixel(0, 0), Color.rgb(0, 72, 255));
}
@Test
@SmallTest
public void checkFaviconIsExposed() throws Exception {
runOnUiThreadBlocking(()
-> mTab.getNavigationController().navigate(
getTestDataURL("simple_page_with_favicon.html")));
Bitmap favicon = waitForFaviconChange();
verifyFavicon(favicon);
}
@Test
@SmallTest
public void checkDelayedFaviconsAreDelivered() throws Exception {
runOnUiThreadBlocking(()
-> mTab.getNavigationController().navigate(getTestDataURL(
"simple_page_with_delayed_favicon.html")));
Bitmap favicon = waitForFaviconChange();
Assert.assertNull(favicon);
// The page dynamically creates a favicon after receiving a post message.
runOnUiThreadBlocking(() -> mTab.postMessage("message", "*"));
favicon = waitForFaviconChange();
verifyFavicon(favicon);
}
@Test
@MediumTest
public void checkFaviconsCanBeDeleted() throws Exception {
runOnUiThreadBlocking(()
-> mTab.getNavigationController().navigate(getTestDataURL(
"simple_page_with_deleted_favicon.html")));
Bitmap favicon = waitForFaviconChange();
verifyFavicon(favicon);
// Favicon eventually gets deleted.
favicon = waitForFaviconChange();
Assert.assertNull(favicon);
}
@Test
@SmallTest
public void pageWithNoFaviconDeliversEvent() throws Exception {
runOnUiThreadBlocking(
() -> mTab.getNavigationController().navigate(getTestDataURL("simple_page.html")));
Bitmap favicon = waitForFaviconChange();
Assert.assertNull(favicon);
}
@Test
@SmallTest
public void multipleNavigationsDelieverEvents() throws Exception {
runOnUiThreadBlocking(()
-> mTab.getNavigationController().navigate(
getTestDataURL("simple_page_with_favicon.html")));
Bitmap favicon = waitForFaviconChange();
verifyFavicon(favicon);
runOnUiThreadBlocking(
() -> mTab.getNavigationController().navigate(getTestDataURL("simple_page.html")));
favicon = waitForFaviconChange();
Assert.assertNull(favicon);
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/FaviconTest.java | Java | unknown | 5,509 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.content_public.browser.test.util.ClickUtils;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.FullscreenCallback;
import org.chromium.webengine.FullscreenClient;
import org.chromium.webengine.Tab;
import org.chromium.webengine.WebEngine;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Tests Fullscreen callbacks.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class FullscreenCallbackTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
private WebEngine mWebEngine;
private Tab mTab;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
mWebEngine = mActivityTestRule.createWebEngineAttachThenNavigateAndWait(
getTestDataURL("fullscreen.html"));
mTab = mWebEngine.getTabManager().getActiveTab();
}
@After
public void shutdown() throws Exception {
mActivityTestRule.finish();
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Test
@SmallTest
public void fullscreenCallbacksAreCalled() throws Exception {
CountDownLatch enterFullscreenLatch = new CountDownLatch(1);
CountDownLatch exitFullscreenLatch = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mTab.setFullscreenCallback(new FullscreenCallback() {
@Override
public void onEnterFullscreen(
WebEngine webEngine, Tab tab, FullscreenClient fullscreenClient) {
Assert.assertEquals(mWebEngine, webEngine);
Assert.assertEquals(mTab, tab);
enterFullscreenLatch.countDown();
}
@Override
public void onExitFullscreen(WebEngine webEngine, Tab tab) {
Assert.assertEquals(mWebEngine, webEngine);
Assert.assertEquals(mTab, tab);
exitFullscreenLatch.countDown();
}
});
});
// requestFullscreen()-js function expects to be invoked by an actual click.
ClickUtils.mouseSingleClickView(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getFragmentContainerView(), 1, 1);
enterFullscreenLatch.await();
ClickUtils.mouseSingleClickView(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getFragmentContainerView(), 1, 1);
exitFullscreenLatch.await();
}
@Test
@SmallTest
public void fullscreenIsEndedWhenTabIsInactive() throws Exception {
CountDownLatch enterFullscreenLatch = new CountDownLatch(1);
CountDownLatch exitFullscreenLatch = new CountDownLatch(1);
CountDownLatch reenterFullscreenLatch = new CountDownLatch(2);
runOnUiThreadBlocking(() -> {
mTab.setFullscreenCallback(new FullscreenCallback() {
@Override
public void onEnterFullscreen(
WebEngine webEngine, Tab tab, FullscreenClient fullscreenClient) {
Assert.assertEquals(mWebEngine, webEngine);
Assert.assertEquals(mTab, tab);
enterFullscreenLatch.countDown();
reenterFullscreenLatch.countDown();
}
@Override
public void onExitFullscreen(WebEngine webEngine, Tab tab) {
Assert.assertEquals(mWebEngine, webEngine);
Assert.assertEquals(mTab, tab);
exitFullscreenLatch.countDown();
}
});
});
// requestFullscreen()-js function expects to be invoked by an actual click.
ClickUtils.mouseSingleClickView(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getFragmentContainerView(), 1, 1);
enterFullscreenLatch.await();
Tab secondTab = runOnUiThreadBlocking(() -> mWebEngine.getTabManager().createTab()).get();
mActivityTestRule.setTabActiveAndWait(mWebEngine, secondTab);
exitFullscreenLatch.await();
mActivityTestRule.setTabActiveAndWait(mWebEngine, mTab);
Assert.assertFalse(reenterFullscreenLatch.await(3L, TimeUnit.SECONDS));
}
@Test
@SmallTest
public void fullscreenCanBeExitedViaClient() throws Exception {
CountDownLatch enterFullscreenLatch = new CountDownLatch(1);
CountDownLatch exitFullscreenLatch = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mTab.setFullscreenCallback(new FullscreenCallback() {
@Override
public void onEnterFullscreen(
WebEngine webEngine, Tab tab, FullscreenClient fullscreenClient) {
Assert.assertEquals(mWebEngine, webEngine);
Assert.assertEquals(mTab, tab);
enterFullscreenLatch.countDown();
fullscreenClient.exitFullscreen();
}
@Override
public void onExitFullscreen(WebEngine webEngine, Tab tab) {
Assert.assertEquals(mWebEngine, webEngine);
Assert.assertEquals(mTab, tab);
exitFullscreenLatch.countDown();
}
});
});
// requestFullscreen()-js function expects to be invoked by an actual click.
ClickUtils.mouseSingleClickView(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getFragmentContainerView(), 1, 1);
enterFullscreenLatch.await();
exitFullscreenLatch.await();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/FullscreenCallbackTest.java | Java | unknown | 6,700 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.test.InstrumentationRegistry;
import org.junit.Assert;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebFragment;
import org.chromium.webengine.WebSandbox;
import org.chromium.webengine.test.instrumentation_test_apk.InstrumentationActivity;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
/**
* ActivityTestRule for InstrumentationActivity.
*
* Test can use this ActivityTestRule to launch or get InstrumentationActivity.
*/
public class InstrumentationActivityTestRule
extends WebEngineActivityTestRule<InstrumentationActivity> {
@Nullable
private WebFragment mFragment;
public InstrumentationActivityTestRule() {
super(InstrumentationActivity.class);
}
/**
* Starts the WebEngine Instrumentation activity.
*/
public void launchShell() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(getShellComponentName());
launchActivity(intent);
}
public ComponentName getShellComponentName() {
return new ComponentName(InstrumentationRegistry.getInstrumentation().getTargetContext(),
InstrumentationActivity.class);
}
public void finish() {
Assert.assertNotNull(getActivity());
getActivity().finish();
}
public WebSandbox getWebSandbox() throws Exception {
return getActivity().getWebSandboxFuture().get();
}
/**
* Attaches a fragment to the container in the activity. If a fragment is already present, it
* will detach it first.
*/
public void attachFragment(WebFragment fragment) {
if (mFragment != null) {
detachFragment(mFragment);
}
getActivity().attachFragment(fragment);
mFragment = fragment;
}
/**
* Return the current fragment attached to the fragment container in the activity.
*/
public WebFragment getFragment() {
Assert.assertNotNull(mFragment);
return mFragment;
}
public void detachFragment(WebFragment fragment) {
getActivity().detachFragment(fragment);
}
public Tab getActiveTab() throws Exception {
return getFragment().getWebEngine().getTabManager().getActiveTab();
}
public View getFragmentContainerView() {
return getActivity().getFragmentContainerView();
}
/**
* Creates a new WebEngine and attaches its Fragment before navigating.
*/
public WebEngine createWebEngineAttachThenNavigateAndWait(String path) throws Exception {
WebSandbox sandbox = getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> sandbox.createWebEngine()).get();
runOnUiThreadBlocking(() -> attachFragment(webEngine.getFragment()));
Tab activeTab = webEngine.getTabManager().getActiveTab();
navigateAndWait(activeTab, path);
return webEngine;
}
/**
* Navigates Tab to new path and waits for navigation to complete.
*/
public void navigateAndWait(Tab tab, String url) throws Exception {
CountDownLatch navigationCompleteLatch = new CountDownLatch(1);
AtomicReference<Navigation> navigationFailure = new AtomicReference();
runOnUiThreadBlocking(() -> {
tab.getNavigationController().registerNavigationObserver(new NavigationObserver() {
@Override
public void onNavigationCompleted(Tab tab, Navigation navigation) {
navigationCompleteLatch.countDown();
}
@Override
public void onNavigationFailed(Tab tab, Navigation navigation) {
navigationFailure.set(navigation);
navigationCompleteLatch.countDown();
}
});
tab.getNavigationController().navigate(url);
});
navigationCompleteLatch.await();
if (navigationFailure.get() != null) {
throw new NavigationFailureException(navigationFailure.get());
}
}
public void setTabActiveAndWait(WebEngine webEngine, Tab tab) throws Exception {
CountDownLatch setActiveLatch = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
webEngine.getTabManager().registerTabListObserver(new TabListObserver() {
@Override
public void onActiveTabChanged(WebEngine webEngine, Tab activeTab) {
setActiveLatch.countDown();
}
});
tab.setActive();
});
setActiveLatch.await();
}
public Context getContext() {
return getActivity();
}
public String getPackageName() {
return getActivity().getPackageName();
}
/**
* Thrown by navigateAndWait if the navigation failed.
*/
public class NavigationFailureException extends RuntimeException {
private final Navigation mNavigation;
NavigationFailureException(Navigation navigation) {
super("Navigation failed.");
mNavigation = navigation;
}
public Navigation getNavigation() {
return mNavigation;
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/InstrumentationActivityTestRule.java | Java | unknown | 5,959 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.MessageEventListener;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabObserver;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Tests the postMessage functionality.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class PostMessageTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
private Tab mTab;
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
WebSandbox sandbox = mActivityTestRule.getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> sandbox.createWebEngine()).get();
mTab = webEngine.getTabManager().getActiveTab();
// First title is the domain, second title is the one in the html title tag.
CountDownLatch titleUpdateLatch = new CountDownLatch(2);
TabObserver observer = new TabObserver() {
@Override
public void onTitleUpdated(Tab tab, String title) {
titleUpdateLatch.countDown();
}
};
runOnUiThreadBlocking(() -> mTab.registerTabObserver(observer));
mActivityTestRule.navigateAndWait(mTab, getTestDataURL("postmessage.html"));
titleUpdateLatch.await(10, TimeUnit.SECONDS);
runOnUiThreadBlocking(() -> mTab.unregisterTabObserver(observer));
}
private static final class ResultHolder {
public String mResult;
}
private String waitForTitleChange() throws Exception {
final ResultHolder holder = new ResultHolder();
CountDownLatch postMessageLatch = new CountDownLatch(1);
TabObserver observer = new TabObserver() {
@Override
public void onTitleUpdated(Tab tab, String title) {
holder.mResult = title;
postMessageLatch.countDown();
}
};
runOnUiThreadBlocking(() -> mTab.registerTabObserver(observer));
postMessageLatch.await(10, TimeUnit.SECONDS);
runOnUiThreadBlocking(() -> mTab.unregisterTabObserver(observer));
if (holder.mResult == null) {
throw new RuntimeException("Title was not updated");
}
return holder.mResult;
}
private String waitForPostMessage() throws Exception {
return waitForPostMessage(Arrays.asList("*"));
}
private String waitForPostMessage(List<String> allowedOrigins) throws Exception {
final ResultHolder holder = new ResultHolder();
CountDownLatch postMessageLatch = new CountDownLatch(1);
MessageEventListener listener = new MessageEventListener() {
@Override
public void onMessage(Tab source, String message) {
Assert.assertEquals(source, mTab);
holder.mResult = message;
postMessageLatch.countDown();
}
};
runOnUiThreadBlocking(() -> mTab.addMessageEventListener(listener, allowedOrigins));
postMessageLatch.await(10, TimeUnit.SECONDS);
runOnUiThreadBlocking(() -> mTab.removeMessageEventListener(listener));
if (holder.mResult == null) {
throw new RuntimeException("postMessage was not received");
}
return holder.mResult;
}
@Test
@SmallTest
public void pageReceivesPostMessage() throws Exception {
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("postMessage: 1", waitForTitleChange());
}
@Test
@SmallTest
public void pageCanPostMessageBack() throws Exception {
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("message: hello, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
}
@Test
@MediumTest
public void postMessageTargetOriginIsRespected() throws Exception {
runOnUiThreadBlocking(() -> mTab.postMessage("hello", mTestServerRule.getOrigin()));
Assert.assertEquals("postMessage: 1", waitForTitleChange());
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "https://example.com/"));
try {
waitForPostMessage();
Assert.fail("postMessage was delivered to the wrong origin");
} catch (Exception e) {
}
}
@Test
@SmallTest
public void canPostToPageMultipleTimes() throws Exception {
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("message: hello, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("message: hello, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("postMessage: 3", waitForTitleChange());
}
@Test
@MediumTest
public void onlyTargetedTabReceivesPostMessage() throws Exception {
WebSandbox sandbox = mActivityTestRule.getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> sandbox.createWebEngine()).get();
Tab tab2 = runOnUiThreadBlocking(() -> webEngine.getTabManager().createTab()).get();
mActivityTestRule.navigateAndWait(tab2, getTestDataURL("postmessage.html"));
runOnUiThreadBlocking(() -> tab2.postMessage("hello", "*"));
try {
waitForPostMessage();
Assert.fail("postMessage was delivered to the wrong origin");
} catch (Exception e) {
}
}
@Test
@MediumTest
public void postMessageFromTabRespectsAllowedOrigin() throws Exception {
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("message: hello, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
try {
waitForPostMessage(Arrays.asList("https://different.example.com"));
Assert.fail("postMessage was received from the wrong origin");
} catch (Exception e) {
}
}
@Test
@MediumTest
public void receivePostMessageFromSavedPort() throws Exception {
runOnUiThreadBlocking(() -> mTab.postMessage("hello - delayed", "*"));
Assert.assertEquals("message: hello - delayed, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
Assert.assertEquals("message: hello - delayed2, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
Assert.assertEquals("message: hello - delayed3, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
runOnUiThreadBlocking(() -> mTab.postMessage("hello", "*"));
Assert.assertEquals("message: hello, "
+ "source: app://org.chromium.webengine.test.instrumentation_test_apk",
waitForPostMessage());
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/PostMessageTest.java | Java | unknown | 8,655 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.net.Uri;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ContextUtils;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Tab;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebEngineParams;
import org.chromium.webengine.WebSandbox;
import java.util.Set;
/**
* Tests the persistence state of WebEngine.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class StatePersistenceTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
WebSandbox mSandbox;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
mSandbox = mActivityTestRule.getWebSandbox();
}
@After
public void shutdown() throws Exception {
if (mSandbox != null) {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
}
mActivityTestRule.finish();
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Test
@SmallTest
public void tabsPersistAcrossSessions() throws Exception {
WebEngineParams params = (new WebEngineParams.Builder())
.setPersistenceId("pid1234")
.setProfileName("pn12345")
.build();
WebEngine webEngine = runOnUiThreadBlocking(
() -> mActivityTestRule.getWebSandbox().createWebEngine(params))
.get();
Tab activeTab = webEngine.getTabManager().getActiveTab();
String url = getTestDataURL("simple_page.html");
mActivityTestRule.navigateAndWait(activeTab, url);
// Shutdown the sandbox.
runOnUiThreadBlocking(() -> {
try {
mActivityTestRule.getWebSandbox().shutdown();
} catch (Exception e) {
Assert.fail("Failed to shutdown sandbox");
}
});
WebSandbox sandbox =
runOnUiThreadBlocking(() -> WebSandbox.create(ContextUtils.getApplicationContext()))
.get();
// Recreate a WebEngine with the same params.
WebEngine webEngine2 = runOnUiThreadBlocking(() -> sandbox.createWebEngine(params)).get();
Tab newActiveTab = webEngine2.getTabManager().getActiveTab();
Assert.assertEquals(url, newActiveTab.getDisplayUri().toString());
Assert.assertEquals(newActiveTab.getGuid(), activeTab.getGuid());
Set<Tab> allTabs = webEngine2.getTabManager().getAllTabs();
Assert.assertEquals(1, allTabs.size());
Assert.assertEquals(newActiveTab, allTabs.iterator().next());
}
@Test
@SmallTest
public void incognitoModeNotInterferingWithPerisitenceState() throws Exception {
String perisistenceId = "pid1234";
String profileName = "pn12345";
WebEngineParams params = (new WebEngineParams.Builder())
.setPersistenceId(perisistenceId)
.setProfileName(profileName)
.build();
// Create an initial WebEngine state and associate it with a persistence ID.
WebEngine webEngine = runOnUiThreadBlocking(
() -> mActivityTestRule.getWebSandbox().createWebEngine(params))
.get();
String url = getTestDataURL("simple_page.html");
Tab activeTab = webEngine.getTabManager().getActiveTab();
mActivityTestRule.navigateAndWait(activeTab, url);
runOnUiThreadBlocking(() -> webEngine.close());
// Recreate a WebEngine in incognito mode.
WebEngineParams paramsIncognito = (new WebEngineParams.Builder())
.setPersistenceId(perisistenceId)
.setProfileName(profileName)
.setIsIncognito(true)
.build();
WebEngine webEngineIncognito = runOnUiThreadBlocking(
() -> mActivityTestRule.getWebSandbox().createWebEngine(paramsIncognito))
.get();
// Test that WebEngine did not recreate based on persistence ID.
Tab incognitoTab = webEngineIncognito.getTabManager().getActiveTab();
Assert.assertNotEquals(activeTab.getGuid(), incognitoTab.getGuid());
Assert.assertEquals(Uri.EMPTY, incognitoTab.getDisplayUri());
Assert.assertEquals(1, webEngineIncognito.getTabManager().getAllTabs().size());
runOnUiThreadBlocking(() -> webEngineIncognito.close());
// Recreate WebEngine with perisistence ID, and verify that state was not changed.
WebEngine webEngine2 = runOnUiThreadBlocking(
() -> mActivityTestRule.getWebSandbox().createWebEngine(params))
.get();
Assert.assertEquals(
url, webEngine2.getTabManager().getActiveTab().getDisplayUri().toString());
Assert.assertEquals(1, webEngine2.getTabManager().getAllTabs().size());
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/StatePersistenceTest.java | Java | unknown | 6,121 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static org.hamcrest.CoreMatchers.is;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.content.pm.ActivityInfo;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.TabManager;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
/**
* Tests various aspects of interacting with Tabs.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class TabManagerTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
WebSandbox mSandbox;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
mSandbox = mActivityTestRule.getWebSandbox();
}
@After
public void shutdown() throws Exception {
if (mSandbox != null) {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
}
mActivityTestRule.finish();
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Test
@SmallTest
public void tabGetsAddedAndActivatedOnStartup() throws Exception {
WebEngine webEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
Tab activeTab = webEngine.getTabManager().getActiveTab();
Assert.assertNotNull(activeTab);
Set<Tab> allTabs = webEngine.getTabManager().getAllTabs();
Assert.assertEquals(1, allTabs.size());
Assert.assertTrue(allTabs.contains(activeTab));
}
@Test
@SmallTest
public void tabsGetAddedToRegistry() throws Exception {
WebEngine webEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
Set<Tab> initialTabs = webEngine.getTabManager().getAllTabs();
Assert.assertEquals(1, initialTabs.size());
Tab addedTab = runOnUiThreadBlocking(() -> webEngine.getTabManager().createTab()).get();
Set<Tab> twoTabs = webEngine.getTabManager().getAllTabs();
Assert.assertEquals(2, twoTabs.size());
Assert.assertTrue(twoTabs.contains(addedTab));
}
@Test
@SmallTest
@DisabledTest(message = "Flaky")
public void tabsPersistAcrossRotations() throws Exception {
String url = getTestDataURL("simple_page.html");
WebEngine webEngine = mActivityTestRule.createWebEngineAttachThenNavigateAndWait(url);
// Rotate device.
mActivityTestRule.getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
CriteriaHelper.pollUiThread(() -> {
Criteria.checkThat(
mActivityTestRule.getActivity().getResources().getConfiguration().orientation,
is(ORIENTATION_LANDSCAPE));
});
Tab activeTab = webEngine.getTabManager().getActiveTab();
Assert.assertEquals(url, activeTab.getDisplayUri().toString());
}
private static final class TabHolder {
private Tab mAddedTab;
private Tab mActiveTab;
private Tab mRemovedTab;
}
@Test
@SmallTest
public void newTabCanBeActivatedAndRemoved() throws Exception {
// One count for the initial tab created and one for the tab we programmatically create.
CountDownLatch activeLatch = new CountDownLatch(1);
CountDownLatch removeLatch = new CountDownLatch(1);
final TabHolder holder = new TabHolder();
WebEngine webEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
runOnUiThreadBlocking(
() -> webEngine.getTabManager().registerTabListObserver(new TabListObserver() {
@Override
public void onTabAdded(WebEngine webEngine, Tab tab) {
holder.mAddedTab = tab;
}
@Override
public void onActiveTabChanged(WebEngine webEngine, Tab tab) {
holder.mActiveTab = tab;
activeLatch.countDown();
}
@Override
public void onTabRemoved(WebEngine webEngine, Tab tab) {
holder.mRemovedTab = tab;
removeLatch.countDown();
}
}));
runOnUiThreadBlocking(() -> mActivityTestRule.attachFragment(webEngine.getFragment()));
TabManager tabManager = webEngine.getTabManager();
Tab newTab = runOnUiThreadBlocking(() -> tabManager.createTab()).get();
Assert.assertEquals(newTab, holder.mAddedTab);
runOnUiThreadBlocking(() -> newTab.setActive());
activeLatch.await();
Assert.assertEquals(newTab, holder.mActiveTab);
runOnUiThreadBlocking(() -> newTab.close());
removeLatch.await();
Assert.assertEquals(newTab, holder.mRemovedTab);
Assert.assertNull(tabManager.getActiveTab());
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/TabManagerTest.java | Java | unknown | 6,106 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.annotation.NonNull;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabNavigationController;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.concurrent.CountDownLatch;
/**
* Tests various aspects of Navigations and NavigationObservers.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class TabNavigationControllerTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
private WebSandbox mSandbox;
private TabNavigationController mNavigationController;
private Tab mActiveTab;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
mSandbox = mActivityTestRule.getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
mActiveTab = webEngine.getTabManager().getActiveTab();
mNavigationController = mActiveTab.getNavigationController();
}
@After
public void shutdown() throws Exception {
if (mSandbox != null) {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
}
mActivityTestRule.finish();
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
private void navigateSync(String url) throws InterruptedException {
CountDownLatch navigationCompleted = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mNavigationController.registerNavigationObserver(new NavigationObserver() {
@Override
public void onNavigationCompleted(
@NonNull Tab tab, @NonNull Navigation navigation) {
navigationCompleted.countDown();
}
});
mNavigationController.navigate(url);
});
navigationCompleted.await();
}
@Test
@SmallTest
public void cannotGoBackOnFirstLoadedUrl() throws Exception {
Assert.assertFalse((runOnUiThreadBlocking(() -> mNavigationController.canGoBack())).get());
navigateSync(getTestDataURL("simple_page.html"));
Assert.assertFalse((runOnUiThreadBlocking(() -> mNavigationController.canGoBack())).get());
}
@Test
@SmallTest
public void canGoBackOnSecondLoadedUrl() throws Exception {
navigateSync(getTestDataURL("simple_page.html"));
navigateSync(getTestDataURL("simple_page2.html"));
Assert.assertTrue((runOnUiThreadBlocking(() -> mNavigationController.canGoBack())).get());
}
@Test
@SmallTest
public void cannotGoForwardWhenNotNavigatedBackBefore() throws Exception {
navigateSync(getTestDataURL("simple_page.html"));
Assert.assertFalse(
(runOnUiThreadBlocking(() -> mNavigationController.canGoForward())).get());
}
@Test
@SmallTest
public void backNavigationToFirstPage() throws Exception {
navigateSync(getTestDataURL("simple_page.html"));
navigateSync(getTestDataURL("simple_page2.html"));
// Synchronously go back.
CountDownLatch navigationCompleted = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mNavigationController.registerNavigationObserver(new NavigationObserver() {
@Override
public void onNavigationCompleted(
@NonNull Tab tab, @NonNull Navigation navigation) {
navigationCompleted.countDown();
}
});
mNavigationController.goBack();
});
navigationCompleted.await();
Assert.assertEquals(
getTestDataURL("simple_page.html"), mActiveTab.getDisplayUri().toString());
Assert.assertFalse((runOnUiThreadBlocking(() -> mNavigationController.canGoBack())).get());
Assert.assertTrue(
(runOnUiThreadBlocking(() -> mNavigationController.canGoForward())).get());
}
@Test
@SmallTest
public void forwardNavigationAfterBackNavigation() throws Exception {
navigateSync(getTestDataURL("simple_page.html"));
navigateSync(getTestDataURL("simple_page2.html"));
// Synchronously go back.
CountDownLatch backNavigationCompleted = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mNavigationController.registerNavigationObserver(new NavigationObserver() {
@Override
public void onNavigationCompleted(
@NonNull Tab tab, @NonNull Navigation navigation) {
backNavigationCompleted.countDown();
}
});
mNavigationController.goBack();
});
backNavigationCompleted.await();
Assert.assertEquals(
getTestDataURL("simple_page.html"), mActiveTab.getDisplayUri().toString());
// Synchronously go forward
CountDownLatch forwardNavigationCompleted = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mNavigationController.registerNavigationObserver(new NavigationObserver() {
@Override
public void onNavigationCompleted(
@NonNull Tab tab, @NonNull Navigation navigation) {
forwardNavigationCompleted.countDown();
}
});
mNavigationController.goForward();
});
forwardNavigationCompleted.await();
Assert.assertEquals(
getTestDataURL("simple_page2.html"), mActiveTab.getDisplayUri().toString());
}
@Test
@SmallTest
public void testAllNavigationEventsAreReceivedOnNavigate() throws Exception {
CountDownLatch navigationCompleted = new CountDownLatch(1);
CountDownLatch navigationStarted = new CountDownLatch(1);
CountDownLatch finishedLoadProgress = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mNavigationController.registerNavigationObserver(new NavigationObserver() {
@Override
public void onNavigationStarted(@NonNull Tab tab, @NonNull Navigation navigation) {
navigationStarted.countDown();
}
@Override
public void onNavigationCompleted(
@NonNull Tab tab, @NonNull Navigation navigation) {
navigationCompleted.countDown();
}
@Override
public void onLoadProgressChanged(@NonNull Tab tab, double progress) {
if (progress == 1.0) {
finishedLoadProgress.countDown();
}
}
});
mNavigationController.navigate(getTestDataURL("simple_page.html"));
});
navigationStarted.await();
navigationCompleted.await();
finishedLoadProgress.await();
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/TabNavigationControllerTest.java | Java | unknown | 7,987 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.hamcrest.CoreMatchers.is;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.test.filters.MediumTest;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.concurrent.CountDownLatch;
/**
* Tests prerendering when tab navigations happen before the UI is shown.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class TabPrerenderTest {
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
@Rule
public DigitalAssetLinksServerRule mDALServerRule = new DigitalAssetLinksServerRule();
private Tab mTab;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mDALServerRule.setUpDigitalAssetLinks();
WebSandbox sandbox = mActivityTestRule.getWebSandbox();
WebEngine webEngine = runOnUiThreadBlocking(() -> sandbox.createWebEngine()).get();
mTab = runOnUiThreadBlocking(() -> webEngine.getTabManager().createTab()).get();
String scriptContents = "const div = document.createElement('div');"
+ "div.id = 'id1';"
+ "div.innerText = 'Div1';"
+ "document.body.appendChild(div);";
mDALServerRule.getServer().setResponse("/script.js", scriptContents, null);
}
private void navigateToPage(String pageContents) throws Exception {
String url = mDALServerRule.getServer().setResponse("/page.html", pageContents, null);
CountDownLatch navigationCompletedLatch = new CountDownLatch(1);
runOnUiThreadBlocking(()
-> mTab.getNavigationController().registerNavigationObserver(
new NavigationObserver() {
@Override
public void onNavigationCompleted(
Tab tab, Navigation navigation) {
navigationCompletedLatch.countDown();
}
}));
runOnUiThreadBlocking(() -> mTab.getNavigationController().navigate(url));
navigationCompletedLatch.await();
}
private String executeScript(String scriptContents) {
try {
return runOnUiThreadBlocking(() -> mTab.executeScript(scriptContents, false)).get();
} catch (Exception e) {
Assert.fail("Unexpected exception executing script: " + e.getMessage());
return null;
}
}
@SmallTest
@Test
public void pageContentsAreAvailable() throws Exception {
navigateToPage("<html><head></head><body><div id=\"id1\">Div1</div></body>");
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
executeScript("document.querySelector('#id1').innerText"), is("\"Div1\""));
});
}
@SmallTest
@Test
public void blockingScriptChangesAreAvailable() throws Exception {
navigateToPage("<html><head></head><body><script src=\"/script.js\"></script></body>");
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
executeScript("document.getElementsByTagName('script').length"), is("1"));
Criteria.checkThat(
executeScript("document.querySelector('#id1').innerText"), is("\"Div1\""));
});
}
@SmallTest
@Test
public void asyncScriptChangesAreAvailable() throws Exception {
navigateToPage(
"<html><head></head><body><script async src=\"/script.js\"></script></body>");
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
executeScript("document.getElementsByTagName('script').length"), is("1"));
Criteria.checkThat(
executeScript("document.querySelector('#id1').innerText"), is("\"Div1\""));
});
}
@SmallTest
@Test
public void deferredScriptChangesAreAvailable() throws Exception {
navigateToPage(
"<html><head></head><body><script defer src=\"/script.js\"></script></body>");
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
executeScript("document.getElementsByTagName('script').length"), is("1"));
Criteria.checkThat(
executeScript("document.querySelector('#id1').innerText"), is("\"Div1\""));
});
}
@MediumTest
@Test
public void asyncTasksInScriptsExecute() throws Exception {
navigateToPage(
"<html><head></head><body><script>setTimeout(() => document.body.appendChild(document.createElement('div')), 2000);</script></body>");
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
executeScript("document.getElementsByTagName('div').length"), is("0"));
});
Thread.sleep(5000);
CriteriaHelper.pollInstrumentationThread(() -> {
Criteria.checkThat(
executeScript("document.getElementsByTagName('div').length"), is("1"));
});
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/TabPrerenderTest.java | Java | unknown | 6,129 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import androidx.test.InstrumentationRegistry;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.chromium.base.CommandLine;
import org.chromium.base.test.BaseActivityTestRule;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* Base ActivityTestRule for WebEngine instrumentation tests.
*
* This rule contains some common setup needed to deal with WebEngine's multiple classloaders.
*/
abstract class WebEngineActivityTestRule<T extends Activity> extends BaseActivityTestRule<T> {
private static final String COMMAND_LINE_FILE = "weblayer-command-line";
public WebEngineActivityTestRule(Class<T> clazz) {
super(clazz);
}
/**
* Writes the command line file. This can be useful if a test needs to dynamically add command
* line arguments before WebLayer has been loaded.
*/
public void writeCommandLineFile() throws Exception {
// The CommandLine instance we have here will not be picked up in the
// implementation since they use different class loaders, so we need to write
// all the switches to the WebLayer command line file.
try (Writer writer = new OutputStreamWriter(
InstrumentationRegistry.getInstrumentation().getTargetContext().openFileOutput(
COMMAND_LINE_FILE, Context.MODE_PRIVATE),
"UTF-8")) {
writer.write(TextUtils.join(" ", CommandLine.getJavaSwitchesOrNull()));
}
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
writeCommandLineFile();
base.evaluate();
} finally {
new File(InstrumentationRegistry.getInstrumentation()
.getTargetContext()
.getFilesDir(),
COMMAND_LINE_FILE)
.delete();
}
}
};
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/WebEngineActivityTestRule.java | Java | unknown | 2,463 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import org.junit.runners.model.InitializationError;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.SkipCheck;
import java.util.List;
/**
* A custom runner for //weblayer JUnit4 tests.
*/
public class WebEngineJUnit4ClassRunner extends BaseJUnit4ClassRunner {
/**
* Create a WebEngineJUnit4ClassRunner to run {@code klass} and initialize values.
*
* @throws InitializationError if the test class malformed
*/
public WebEngineJUnit4ClassRunner(final Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected List<SkipCheck> getSkipChecks() {
// TODO(rayankans): Add SkipChecks.
return super.getSkipChecks();
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/WebEngineJUnit4ClassRunner.java | Java | unknown | 930 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.annotation.NonNull;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Navigation;
import org.chromium.webengine.NavigationObserver;
import org.chromium.webengine.Tab;
import org.chromium.webengine.TabListObserver;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
/**
* Tests functions called on the WebEngine object.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class WebEngineTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
WebSandbox mSandbox;
WebEngine mWebEngine;
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
mServer = mTestServerRule.getServer();
mSandbox = mActivityTestRule.getWebSandbox();
mWebEngine = runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
}
@After
public void shutdown() throws Exception {
if (mSandbox != null) {
runOnUiThreadBlocking(() -> mSandbox.shutdown());
}
mActivityTestRule.finish();
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Test
@SmallTest
public void tabManagerIsAvailable() throws Exception {
Assert.assertNotNull(mWebEngine.getTabManager());
}
@Test
@SmallTest
public void tabCookieIsAvailable() throws Exception {
Assert.assertNotNull(mWebEngine.getCookieManager());
}
@Test
@SmallTest
public void navigateBackEngineOnInitialStateReturnsFalse() throws Exception {
boolean handledBackNav = runOnUiThreadBlocking(() -> mWebEngine.tryNavigateBack()).get();
Assert.assertFalse(handledBackNav);
}
@Test
@SmallTest
public void navigateBackEngineHandlesBackNavInTab() throws Exception {
String url1 = getTestDataURL("simple_page.html");
String url2 = getTestDataURL("simple_page2.html");
Tab activeTab = mWebEngine.getTabManager().getActiveTab();
mActivityTestRule.navigateAndWait(activeTab, url1);
mActivityTestRule.navigateAndWait(activeTab, url2);
// Go back and wait until navigation completed.
CountDownLatch navigationCompletedLatch = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
activeTab.getNavigationController().registerNavigationObserver(
new NavigationObserver() {
@Override
public void onNavigationCompleted(Tab tab, @NonNull Navigation navigation) {
navigationCompletedLatch.countDown();
}
});
});
boolean handledBackNav = runOnUiThreadBlocking(() -> mWebEngine.tryNavigateBack()).get();
navigationCompletedLatch.await();
Assert.assertTrue(handledBackNav);
Assert.assertEquals(1, mWebEngine.getTabManager().getAllTabs().size());
Assert.assertEquals(
url1, mWebEngine.getTabManager().getActiveTab().getDisplayUri().toString());
}
@Test
@SmallTest
public void navigateBackEngineClosesTabAndSetsPreviousTabActive() throws Exception {
Tab firstTab = mWebEngine.getTabManager().getActiveTab();
String url1 = getTestDataURL("simple_page.html");
mActivityTestRule.navigateAndWait(firstTab, url1);
Tab secondTab = runOnUiThreadBlocking(() -> mWebEngine.getTabManager().createTab()).get();
Assert.assertEquals(2, mWebEngine.getTabManager().getAllTabs().size());
// Synchronously Set second Tab to active.
CountDownLatch secondTabActiveLatch = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mWebEngine.getTabManager().registerTabListObserver(new TabListObserver() {
@Override
public void onActiveTabChanged(
@NonNull WebEngine webEngine, @NonNull Tab activeTab) {
secondTabActiveLatch.countDown();
}
});
secondTab.setActive();
});
secondTabActiveLatch.await();
Assert.assertEquals(secondTab, mWebEngine.getTabManager().getActiveTab());
String url2 = getTestDataURL("simple_page2.html");
mActivityTestRule.navigateAndWait(secondTab, url2);
// // Go back and wait until active tab changed and second tab was removed.
CountDownLatch activeTabChangedLatch = new CountDownLatch(1);
CountDownLatch prevTabRemovedLatch = new CountDownLatch(1);
runOnUiThreadBlocking(() -> {
mWebEngine.getTabManager().registerTabListObserver(new TabListObserver() {
@Override
public void onActiveTabChanged(
@NonNull WebEngine webEngine, @NonNull Tab activeTab) {
activeTabChangedLatch.countDown();
}
@Override
public void onTabRemoved(@NonNull WebEngine webEngine, @NonNull Tab activeTab) {
prevTabRemovedLatch.countDown();
}
});
});
boolean handledBackNav = runOnUiThreadBlocking(() -> mWebEngine.tryNavigateBack()).get();
activeTabChangedLatch.await();
prevTabRemovedLatch.await();
Assert.assertTrue(handledBackNav);
Assert.assertEquals(1, mWebEngine.getTabManager().getAllTabs().size());
Assert.assertEquals(firstTab, mWebEngine.getTabManager().getActiveTab());
Assert.assertEquals(
url1, mWebEngine.getTabManager().getActiveTab().getDisplayUri().toString());
}
@Test
@SmallTest
public void closingWebEngineRemovesItFromSandbox() throws Exception {
int numWebEngines = runOnUiThreadBlocking(() -> {
mWebEngine.close();
return mSandbox.getWebEngines().size();
});
Assert.assertEquals(0, numWebEngines);
}
@Test
@SmallTest
public void createWebEngineWithTag() throws Exception {
String tag = "web-engine-tag";
WebEngine webEngineWithTag =
runOnUiThreadBlocking(() -> mSandbox.createWebEngine(tag)).get();
Assert.assertEquals(webEngineWithTag, mSandbox.getWebEngine(tag));
Assert.assertEquals(tag, webEngineWithTag.getTag());
}
@Test
@SmallTest
public void createWebEngineWithoutTag() throws Exception {
WebEngine webEngineWithoutGivenTag =
runOnUiThreadBlocking(() -> mSandbox.createWebEngine()).get();
Assert.assertTrue(mSandbox.getWebEngines().contains(webEngineWithoutGivenTag));
// Check that a tag was given to the web-engine
Assert.assertEquals("webengine_1", webEngineWithoutGivenTag.getTag());
}
@Test
@SmallTest
public void cannotCreateWebEngineWithIdenticalTags() throws Exception {
String tag = "web-engine-tag";
WebEngine webEngineWithTag =
runOnUiThreadBlocking(() -> mSandbox.createWebEngine(tag)).get();
Assert.assertThrows(ExecutionException.class,
() -> runOnUiThreadBlocking(() -> mSandbox.createWebEngine(tag)));
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/WebEngineTest.java | Java | unknown | 8,145 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import android.net.Uri;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.Batch;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.EmbeddedTestServerRule;
import org.chromium.webengine.Tab;
import org.chromium.webengine.WebEngine;
import org.chromium.webengine.WebSandbox;
/**
* Tests that basic fragment operations work as intended.
*/
@Batch(Batch.PER_CLASS)
@RunWith(WebEngineJUnit4ClassRunner.class)
public class WebFragmentTest {
@Rule
public EmbeddedTestServerRule mTestServerRule = new EmbeddedTestServerRule();
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
private EmbeddedTestServer mServer;
private WebSandbox mWebSandbox;
@Before
public void setUp() throws Throwable {
mServer = mTestServerRule.getServer();
mActivityTestRule.launchShell();
mWebSandbox = mActivityTestRule.getWebSandbox();
}
@After
public void tearDown() {
mActivityTestRule.finish();
runOnUiThreadBlocking(() -> mWebSandbox.shutdown());
}
private String getTestDataURL(String path) {
return mServer.getURL("/weblayer/test/data/" + path);
}
@Test
@SmallTest
public void loadsPage() throws Exception {
WebEngine webEngine = runOnUiThreadBlocking(() -> mWebSandbox.createWebEngine()).get();
runOnUiThreadBlocking(() -> mActivityTestRule.attachFragment(webEngine.getFragment()));
Tab activeTab = webEngine.getTabManager().getActiveTab();
Assert.assertEquals(activeTab.getDisplayUri(), Uri.EMPTY);
String url = getTestDataURL("simple_page.html");
mActivityTestRule.navigateAndWait(activeTab, url);
Assert.assertEquals(runOnUiThreadBlocking(() -> activeTab.getDisplayUri()), Uri.parse(url));
}
/**
* This test is similar to the previous one and just ensures that these unit tests can be
* batched.
*/
@Test
@SmallTest
public void successfullyLoadDifferentPage() throws Exception {
mActivityTestRule.createWebEngineAttachThenNavigateAndWait(
getTestDataURL("simple_page2.html"));
}
@Test
@SmallTest
public void fragmentTabCanLoadMultiplePages() throws Exception {
mActivityTestRule.createWebEngineAttachThenNavigateAndWait(
getTestDataURL("simple_page.html"));
Tab tab = mActivityTestRule.getActiveTab();
mActivityTestRule.navigateAndWait(tab, getTestDataURL("simple_page2.html"));
Assert.assertTrue(tab.getDisplayUri().toString().endsWith("simple_page2.html"));
}
@Test
@SmallTest
public void fragmentsCanBeReplaced() throws Exception {
mActivityTestRule.createWebEngineAttachThenNavigateAndWait(
getTestDataURL("simple_page.html"));
// New fragment
mActivityTestRule.createWebEngineAttachThenNavigateAndWait(
getTestDataURL("simple_page2.html"));
Tab tab = mActivityTestRule.getActiveTab();
Assert.assertTrue(tab.getDisplayUri().toString().endsWith("simple_page2.html"));
}
@Test
@SmallTest
public void navigationFailure() {
try {
mActivityTestRule.createWebEngineAttachThenNavigateAndWait(
getTestDataURL("missingpage.html"));
Assert.fail("exception not thrown");
} catch (RuntimeException e) {
Assert.assertEquals(e.getMessage(), "Navigation failed.");
} catch (Exception e) {
Assert.fail("RuntimeException not thrown, instead got: " + e);
}
}
}
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/WebFragmentTest.java | Java | unknown | 4,106 |
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webengine.test;
import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.DoNotBatch;
import org.chromium.webengine.WebSandbox;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Tests the WebSandbox API.
*/
@DoNotBatch(reason = "Tests need separate Activities and WebFragments")
@RunWith(WebEngineJUnit4ClassRunner.class)
public class WebSandboxTest {
@Rule
public InstrumentationActivityTestRule mActivityTestRule =
new InstrumentationActivityTestRule();
@Before
public void setUp() throws Exception {
mActivityTestRule.launchShell();
}
@After
public void shutdown() throws Exception {
mActivityTestRule.finish();
}
@Test
@SmallTest
public void canStartSandbox() throws Exception {
Assert.assertNotNull(mActivityTestRule.getWebSandbox());
}
@Test
@SmallTest
public void onlyOneSandboxIsCreated() throws Exception {
WebSandbox sandbox1 = mActivityTestRule.getWebSandbox();
WebSandbox sandbox2 =
runOnUiThreadBlocking(() -> WebSandbox.create(mActivityTestRule.getContext()))
.get();
Assert.assertEquals(sandbox1, sandbox2);
}
@Test
@SmallTest
public void returnsVersion() throws Exception {
String returnedVersion =
runOnUiThreadBlocking(() -> WebSandbox.getVersion(mActivityTestRule.getContext()))
.get();
Assert.assertNotNull(returnedVersion);
Pattern expectedVersionPattern =
Pattern.compile("[0-9]*[.][0-9]*[.][0-9]*", Pattern.CASE_INSENSITIVE);
Matcher returnedVersionMatcher = expectedVersionPattern.matcher(returnedVersion);
Assert.assertTrue(returnedVersionMatcher.find());
}
@Test
@SmallTest
public void returnsIfIsAvailable() throws Exception {
boolean isAvailable =
runOnUiThreadBlocking(() -> WebSandbox.isAvailable(mActivityTestRule.getContext()))
.get();
Assert.assertTrue(isAvailable);
}
@Test
@SmallTest
public void returnsProviderPackageName() throws Exception {
String providerPackageName = runOnUiThreadBlocking(
() -> WebSandbox.getProviderPackageName(mActivityTestRule.getContext()))
.get();
Assert.assertEquals("org.chromium.weblayer.support", providerPackageName);
}
} | Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/src/org/chromium/webengine/test/WebSandboxTest.java | Java | unknown | 2,902 |
#!/usr/bin/env vpython3
#
# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Runs WebLayer instrumentation tests against arbitrary versions of tests, the
# client, and the implementation.
#
# Example usage, testing M80 tests and client against master implementation:
# autoninja -C out/Release weblayer_instrumentation_test_versions_apk
# cipd install --root /tmp/M80 chromium/testing/weblayer-x86 m80
# out/Release/bin/run_weblayer_instrumentation_test_versions_apk \
# --test-runner-outdir out/Release
# --client-outdir /tmp/M80/out/Release
# --implementation-outdir out/Release
import argparse
import logging
import operator
import os
import re
import subprocess
import sys
CUR_DIR = os.path.dirname(os.path.realpath(__file__))
# Find src root starting from either the release bin directory or original path.
if os.path.basename(CUR_DIR) == 'bin':
SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(CUR_DIR)))
else:
SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(
CUR_DIR))))
TYP_DIR = os.path.join(
SRC_DIR, 'third_party', 'catapult', 'third_party', 'typ')
if TYP_DIR not in sys.path:
sys.path.insert(0, TYP_DIR)
import typ
# Mapping of operator string in the expectation file tags to actual operator.
OP_MAP = {'gte': operator.ge, 'lte': operator.le}
def tag_matches(tag, impl_version='trunk', client_version='trunk'):
"""Test if specified versions match the tag.
Args:
tag: skew test expectation tag, e.g. 'impl_lte_5' or 'client_lte_2'.
impl_version: WebLayer implementation version number or 'trunk'.
client_version: WebLayer implementation version number or 'trunk'.
Returns:
True if the specified versions match the tag.
Raises:
AssertionError if the tag is invalid.
"""
# 'All' is special cased to match anything.
if tag == 'all':
return True
# Extract the three components from the tag.
match = re.match(r'(client|impl)_([gl]te)_([0-9]+)', tag)
assert match is not None, (
'tag must be of the form "{client,impl}_{gte,lte}_$version", found %r' %
tag)
target_str, op_str, tag_version_str = match.groups()
# If a version is specified see if the tag refers to the same target or
# return False otherwise.
if impl_version != 'trunk' and target_str != 'impl':
return False
if client_version != 'trunk' and target_str != 'client':
return False
version = impl_version if impl_version != 'trunk' else client_version
assert type(version) == int, 'Specified version must be an integer.'
tag_version = int(tag_version_str)
op = OP_MAP[op_str]
return op(version, tag_version)
def tests_to_skip(expectation_contents, impl_version='trunk',
client_version='trunk'):
"""Get list of tests to skip for the given version.
Args:
expectation_contents: String containing expectation file contents.
impl_version: WebLayer implementation version number or 'trunk'.
client_version: WebLayer implementation version number or 'trunk'.
Returns:
List of test names to skip.
Raises:
AssertionError if both versions are 'trunk'.
"""
assert impl_version != 'trunk' or client_version != 'trunk'
parser = typ.expectations_parser.TaggedTestListParser(expectation_contents)
tests = []
for expectation in parser.expectations:
assert len(expectation.tags) == 1, (
'Only one tag is allowed per expectation.')
assert len(expectation.results) == 1 and (
typ.json_results.ResultType.Skip in expectation.results), (
'Only "Skip" is supported in the skew test expectations.')
# Iterate over the first (and only) item since can't index over a frozenset.
tag = next(iter(expectation.tags))
if tag_matches(tag, impl_version, client_version):
tests.append(expectation.test)
return tests
def main():
"""Wrapper to call weblayer instrumentation tests with different versions."""
parser = argparse.ArgumentParser(
description='Run weblayer instrumentation tests at different versions.')
parser.add_argument(
'--test-runner-outdir',
required=True,
help='Local build output directory for finding the test runner.')
parser.add_argument(
'--client-outdir',
required=True,
help='Build output directory for WebLayer client.')
parser.add_argument(
'--implementation-outdir',
required=True,
help='Build output directory for WebLayer implementation.')
parser.add_argument(
'--test-expectations',
required=False,
default='',
help=('Test expectations file describing which tests are failing at '
'different versions.'))
# There are two Webview apks that are available for WebLayer skew tests.
# crbug.com/1163652.
parser.add_argument(
'--webview-apk-path',
required=True,
help=('Relative path for the WebLayer implementation library apk. '
'The path is relative to the WebLayer implementation '
'output directory.'))
version_group = parser.add_mutually_exclusive_group(required=True)
version_group.add_argument(
'--client-version',
default='trunk',
help=('Version of the client being used if not trunk. Only set one of '
'--client-version and --impl-version.'))
version_group.add_argument(
'--impl-version',
default='trunk',
help=('Version of the implementation being used if not trunk. Only set '
'one of --client-version and --impl-version.'))
args, remaining_args = parser.parse_known_args()
logging.basicConfig(level=logging.INFO)
# The command line is derived from the resulting command line from
# run_weblayer_instrumentation_test_apk but with parameterized client and
# implementation.
test_runner_srcdir = os.path.normpath(
os.path.join(args.test_runner_outdir, '..', '..'))
executable_path = os.path.join(test_runner_srcdir,
'build/android/test_runner.py')
executable_args = [
'instrumentation',
'--output-directory',
args.client_outdir,
'--runtime-deps-path',
os.path.join(args.client_outdir,
('gen.runtime/weblayer/browser/android/javatests/' +
'weblayer_instrumentation_test_apk.runtime_deps')),
'--test-apk',
os.path.join(args.client_outdir,
'apks/WebLayerInstrumentationTest.apk'),
'--apk-under-test',
os.path.join(args.client_outdir, 'apks/WebLayerShellSystemWebView.apk'),
'--use-webview-provider',
os.path.join(args.implementation_outdir, args.webview_apk_path),
'--additional-apk',
os.path.join(args.client_outdir, 'apks/ChromiumNetTestSupport.apk')]
cmd = [sys.executable, executable_path] + executable_args + remaining_args
# Pass along the implementation version if it's set so that tests can
# be filtered through the @MinWebLayerVersion annotation.
# Note: The Chrome Android command line library requires the flag be passed
# with "=" rather than as two arguments.
if args.impl_version != 'trunk':
cmd.append('--impl-version=%s' % args.impl_version)
tests = []
if args.test_expectations:
if args.impl_version != 'trunk':
args.impl_version = int(args.impl_version)
if args.client_version != 'trunk':
args.client_version = int(args.client_version)
with open(args.test_expectations) as expectations_file:
contents = expectations_file.read()
tests = tests_to_skip(contents, impl_version=args.impl_version,
client_version=args.client_version)
if tests:
logging.info('Filtering known failing tests: %s', tests)
cmd.append('--test-filter=-%s' % ':'.join(tests))
logging.info(' '.join(cmd))
return subprocess.call(cmd)
if __name__ == '__main__':
sys.exit(main())
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/weblayer_instrumentation_test_versions.py | Python | unknown | 7,951 |
#!/usr/bin/env python
#
# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Test helper functions in skew test wrapper.
import textwrap
import unittest
import weblayer_instrumentation_test_versions
class ExpectationsTest(unittest.TestCase):
def testMatchesImpl(self):
tag_matches = weblayer_instrumentation_test_versions.tag_matches
self.assertTrue(tag_matches('impl_lte_84', impl_version=83))
self.assertTrue(tag_matches('impl_lte_83', impl_version=83))
self.assertFalse(tag_matches('impl_lte_82', impl_version=83))
def testMatchesClient(self):
tag_matches = weblayer_instrumentation_test_versions.tag_matches
self.assertTrue(tag_matches('client_lte_84', client_version=83))
self.assertTrue(tag_matches('client_lte_83', client_version=83))
self.assertFalse(tag_matches('client_lte_82', client_version=83))
def testMismatchedTargets(self):
tag_matches = weblayer_instrumentation_test_versions.tag_matches
self.assertFalse(tag_matches('client_lte_80', impl_version=80))
self.assertFalse(tag_matches('impl_lte_80', client_version=80))
def testMatchesGreater(self):
tag_matches = weblayer_instrumentation_test_versions.tag_matches
self.assertFalse(tag_matches('client_gte_84', client_version=83))
self.assertTrue(tag_matches('client_gte_83', client_version=83))
self.assertTrue(tag_matches('client_gte_82', client_version=83))
def testMatchesInvalid(self):
tag_matches = weblayer_instrumentation_test_versions.tag_matches
self.assertRaises(AssertionError, tag_matches, 'impl_lte_82')
self.assertRaises(AssertionError, tag_matches, 'impl_x_82',
client_version=83)
self.assertRaises(AssertionError, tag_matches, 'client_lte_82',
client_version='83')
def testTestsToSkip(self):
expectation_contents = textwrap.dedent("""
# tags: [ impl_lte_83 client_lte_80 ]
# results: [ Skip ]
[ impl_lte_83 ] weblayer.NavigationTest#testIntent [ Skip ]
[ client_lte_80 ] weblayer.ExternalTest#testUser [ Skip ]
""")
tests_to_skip = weblayer_instrumentation_test_versions.tests_to_skip
self.assertEquals(
tests_to_skip(expectation_contents, impl_version=80),
['weblayer.NavigationTest#testIntent'])
self.assertEquals(
tests_to_skip(expectation_contents, impl_version=83),
['weblayer.NavigationTest#testIntent'])
self.assertEquals(tests_to_skip(expectation_contents, impl_version=84), [])
self.assertEquals(
tests_to_skip(expectation_contents, client_version=79),
['weblayer.ExternalTest#testUser'])
self.assertEquals(
tests_to_skip(expectation_contents, client_version=80),
['weblayer.ExternalTest#testUser'])
self.assertEquals(
tests_to_skip(expectation_contents, client_version=81), [])
if __name__ == '__main__':
unittest.main()
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/javatests/weblayer_instrumentation_test_versions_test.py | Python | unknown | 2,981 |
include_rules = [
"+components/metrics",
"+google_apis/google_api_keys.h",
"+third_party/metrics_proto"
]
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/DEPS | Python | unknown | 112 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <deque>
#include "base/metrics/metrics_hashes.h"
#include "base/metrics/statistics_recorder.h"
#include "base/test/bind.h"
#include "components/metrics/log_decoder.h"
#include "components/metrics/metrics_log_uploader.h"
#include "components/metrics/metrics_service.h"
#include "components/metrics/metrics_switches.h"
#include "components/metrics/stability_metrics_helper.h"
#include "content/public/test/browser_test_utils.h"
#include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
#include "weblayer/browser/android/metrics/metrics_test_helper.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/profile.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
bool HasHistogramWithHash(const metrics::ChromeUserMetricsExtension& uma_log,
uint64_t hash) {
for (int i = 0; i < uma_log.histogram_event_size(); ++i) {
if (uma_log.histogram_event(i).name_hash() == hash) {
return true;
}
}
return false;
}
} // namespace
class MetricsBrowserTest : public WebLayerBrowserTest {
public:
void SetUp() override {
metrics::ForceEnableMetricsReportingForTesting();
InstallTestGmsBridge(GetConsentType(),
base::BindRepeating(&MetricsBrowserTest::OnLogMetrics,
base::Unretained(this)));
WebLayerMetricsServiceClient::GetInstance()->SetFastStartupForTesting(true);
WebLayerMetricsServiceClient::GetInstance()->SetUploadIntervalForTesting(
base::Milliseconds(10));
WebLayerBrowserTest::SetUp();
}
void TearDown() override {
RemoveTestGmsBridge();
WebLayerBrowserTest::TearDown();
}
void OnLogMetrics(metrics::ChromeUserMetricsExtension metric) {
metrics_logs_.push_back(metric);
if (on_new_log_)
std::move(on_new_log_).Run();
}
metrics::ChromeUserMetricsExtension WaitForNextMetricsLog() {
if (metrics_logs_.empty()) {
base::RunLoop run_loop;
on_new_log_ = run_loop.QuitClosure();
run_loop.Run();
DCHECK(!metrics_logs_.empty());
}
metrics::ChromeUserMetricsExtension tmp = std::move(metrics_logs_.front());
metrics_logs_.pop_front();
return tmp;
}
size_t GetNumLogs() const { return metrics_logs_.size(); }
virtual ConsentType GetConsentType() { return ConsentType::kConsent; }
private:
std::unique_ptr<Profile> profile_;
std::deque<metrics::ChromeUserMetricsExtension> metrics_logs_;
base::OnceClosure on_new_log_;
};
IN_PROC_BROWSER_TEST_F(MetricsBrowserTest, ProtoHasExpectedFields) {
metrics::ChromeUserMetricsExtension log = WaitForNextMetricsLog();
EXPECT_EQ(metrics::ChromeUserMetricsExtension::ANDROID_WEBLAYER,
log.product());
EXPECT_TRUE(log.has_client_id());
EXPECT_TRUE(log.has_session_id());
const metrics::SystemProfileProto& system_profile = log.system_profile();
EXPECT_TRUE(system_profile.has_build_timestamp());
EXPECT_TRUE(system_profile.has_app_version());
EXPECT_TRUE(system_profile.has_channel());
EXPECT_TRUE(system_profile.has_install_date());
EXPECT_TRUE(system_profile.has_application_locale());
EXPECT_TRUE(system_profile.has_low_entropy_source());
EXPECT_TRUE(system_profile.has_old_low_entropy_source());
EXPECT_EQ("Android", system_profile.os().name());
EXPECT_TRUE(system_profile.os().has_version());
EXPECT_TRUE(system_profile.hardware().has_system_ram_mb());
EXPECT_TRUE(system_profile.hardware().has_hardware_class());
EXPECT_TRUE(system_profile.hardware().has_screen_count());
EXPECT_TRUE(system_profile.hardware().has_primary_screen_width());
EXPECT_TRUE(system_profile.hardware().has_primary_screen_height());
EXPECT_TRUE(system_profile.hardware().has_primary_screen_scale_factor());
EXPECT_TRUE(system_profile.hardware().has_cpu_architecture());
EXPECT_TRUE(system_profile.hardware().cpu().has_vendor_name());
EXPECT_TRUE(system_profile.hardware().cpu().has_signature());
EXPECT_TRUE(system_profile.hardware().cpu().has_num_cores());
EXPECT_TRUE(system_profile.hardware().cpu().has_is_hypervisor());
EXPECT_TRUE(system_profile.hardware().gpu().has_driver_version());
EXPECT_TRUE(system_profile.hardware().gpu().has_gl_vendor());
EXPECT_TRUE(system_profile.hardware().gpu().has_gl_renderer());
}
IN_PROC_BROWSER_TEST_F(MetricsBrowserTest, PageLoadsEnableMultipleUploads) {
WaitForNextMetricsLog();
// At this point, the MetricsService should be asleep, and should not have
// created any more metrics logs.
ASSERT_EQ(0u, GetNumLogs());
// The start of a page load should be enough to indicate to the MetricsService
// that the app is "in use" and it's OK to upload the next record. No need to
// wait for onPageFinished, since this behavior should be gated on
// NOTIFICATION_LOAD_START.
shell()->tab()->GetNavigationController()->Navigate(GURL("about:blank"));
// This may take slightly longer than UPLOAD_INTERVAL_MS, due to the time
// spent processing the metrics log, but should be well within the timeout
// (unless something is broken).
WaitForNextMetricsLog();
// If we get here, we got a second metrics log (and the test may pass). If
// there was no second metrics log, then the above call will check fail with a
// timeout. We should not assert the logs are empty however, because it's
// possible we got a metrics log between onPageStarted & onPageFinished, in
// which case onPageFinished would *also* wake up the metrics service, and we
// might potentially have a third metrics log in the queue.
}
IN_PROC_BROWSER_TEST_F(MetricsBrowserTest, NavigationIncrementsPageLoadCount) {
base::HistogramTester histogram_tester;
ASSERT_TRUE(embedded_test_server()->Start());
metrics::ChromeUserMetricsExtension log = WaitForNextMetricsLog();
// The initial log should not have a page load count (because nothing was
// loaded).
{
const metrics::SystemProfileProto& system_profile = log.system_profile();
ASSERT_TRUE(system_profile.has_stability());
EXPECT_EQ(0, system_profile.stability().page_load_count());
histogram_tester.ExpectBucketCount(
"Stability.Counts2", metrics::StabilityEventType::kPageLoad, 0);
}
// Loading a page should increment the page load count.
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
log = WaitForNextMetricsLog();
{
const metrics::SystemProfileProto& system_profile = log.system_profile();
ASSERT_TRUE(system_profile.has_stability());
EXPECT_EQ(1, system_profile.stability().page_load_count());
histogram_tester.ExpectBucketCount(
"Stability.Counts2", metrics::StabilityEventType::kPageLoad, 1);
}
}
IN_PROC_BROWSER_TEST_F(MetricsBrowserTest, RendererHistograms) {
base::HistogramTester histogram_tester;
ASSERT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
uint64_t hash = base::HashMetricName("Android.SeccompStatus.RendererSandbox");
bool collect_final_metrics_for_log_called = false;
WebLayerMetricsServiceClient::GetInstance()
->SetCollectFinalMetricsForLogClosureForTesting(
base::BindLambdaForTesting(
[&]() { collect_final_metrics_for_log_called = true; }));
// Not every WaitForNextMetricsLog call will end up calling
// MetricsServiceClient::CollectFinalMetricsForLog since there may already be
// staged logs to send (see ReportingService::SendNextLog). Since we need to
// wait for CollectFinalMetricsForLog to be run after the navigate call above,
// keep calling WaitForNextMetricsLog until CollectFinalMetricsForLog is
// called.
metrics::ChromeUserMetricsExtension uma_log;
while (!collect_final_metrics_for_log_called)
uma_log = WaitForNextMetricsLog();
ASSERT_TRUE(HasHistogramWithHash(uma_log, hash));
}
class MetricsBrowserTestWithUserOptOut : public MetricsBrowserTest {
ConsentType GetConsentType() override { return ConsentType::kNoConsent; }
};
IN_PROC_BROWSER_TEST_F(MetricsBrowserTestWithUserOptOut, MetricsNotRecorded) {
base::RunLoop().RunUntilIdle();
ASSERT_EQ(0u, GetNumLogs());
}
class MetricsBrowserTestWithConfigurableConsent : public MetricsBrowserTest {
ConsentType GetConsentType() override { return ConsentType::kDelayConsent; }
};
IN_PROC_BROWSER_TEST_F(MetricsBrowserTestWithConfigurableConsent,
IsInForegroundWhenConsentGiven) {
// There should be at least one browser which is resumed. This is the trigger
// for whether the MetricsService is considered in the foreground.
EXPECT_TRUE(BrowserList::GetInstance()->HasAtLeastOneResumedBrowser());
RunConsentCallback(true);
// RunConsentCallback() should trigger the MetricsService to start.
EXPECT_TRUE(WebLayerMetricsServiceClient::GetInstance()
->GetMetricsServiceIfStarted());
EXPECT_TRUE(WebLayerMetricsServiceClient::GetInstance()
->GetMetricsService()
->IsInForegroundForTesting());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/metrics_browsertest.cc | C++ | unknown | 9,542 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/metrics/metrics_test_helper.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/no_destructor.h"
#include "content/public/test/test_utils.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/test/weblayer_browsertests_jni/MetricsTestHelper_jni.h"
namespace weblayer {
namespace {
OnLogsMetricsCallback& GetOnLogMetricsCallback() {
static base::NoDestructor<OnLogsMetricsCallback> s_callback;
return *s_callback;
}
ProfileImpl* GetProfileByName(const std::string& name) {
for (auto* profile : ProfileImpl::GetAllProfiles()) {
if (profile->name() == name)
return profile;
}
return nullptr;
}
} // namespace
void InstallTestGmsBridge(ConsentType consent_type,
const OnLogsMetricsCallback on_log_metrics) {
GetOnLogMetricsCallback() = on_log_metrics;
Java_MetricsTestHelper_installTestGmsBridge(
base::android::AttachCurrentThread(), static_cast<int>(consent_type));
}
void RemoveTestGmsBridge() {
Java_MetricsTestHelper_removeTestGmsBridge(
base::android::AttachCurrentThread());
GetOnLogMetricsCallback().Reset();
}
void RunConsentCallback(bool has_consent) {
Java_MetricsTestHelper_runConsentCallback(
base::android::AttachCurrentThread(), has_consent);
}
ProfileImpl* CreateProfile(const std::string& name, bool incognito) {
DCHECK(!GetProfileByName(name));
JNIEnv* env = base::android::AttachCurrentThread();
Java_MetricsTestHelper_createProfile(
env, base::android::ConvertUTF8ToJavaString(env, name), incognito);
ProfileImpl* profile = GetProfileByName(name);
// Creating a profile may involve storage partition initialization. Wait for
// the initialization to be completed.
content::RunAllTasksUntilIdle();
return profile;
}
void DestroyProfile(const std::string& name, bool incognito) {
DCHECK(GetProfileByName(name));
JNIEnv* env = base::android::AttachCurrentThread();
Java_MetricsTestHelper_destroyProfile(
env, base::android::ConvertUTF8ToJavaString(env, name), incognito);
}
void JNI_MetricsTestHelper_OnLogMetrics(
JNIEnv* env,
const base::android::JavaParamRef<jbyteArray>& data) {
auto& callback = GetOnLogMetricsCallback();
if (!callback)
return;
metrics::ChromeUserMetricsExtension proto;
jbyte* src_bytes = env->GetByteArrayElements(data, nullptr);
proto.ParseFromArray(src_bytes, env->GetArrayLength(data.obj()));
env->ReleaseByteArrayElements(data, src_bytes, JNI_ABORT);
callback.Run(proto);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/metrics_test_helper.cc | C++ | unknown | 2,721 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_METRICS_METRICS_TEST_HELPER_H_
#define WEBLAYER_BROWSER_ANDROID_METRICS_METRICS_TEST_HELPER_H_
#include <string>
#include "base/functional/callback.h"
#include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
namespace weblayer {
class ProfileImpl;
// Various utilities to bridge to Java code for metrics related tests.
using OnLogsMetricsCallback =
base::RepeatingCallback<void(metrics::ChromeUserMetricsExtension)>;
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.weblayer_private
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ConsentType
enum class ConsentType {
kConsent,
kNoConsent,
// If this is supplied to InstallTestGmsBridge(), the callback used to
// determine if consent is given is not automatically called. Use
// RunConsentCallback() to apply consent.
kDelayConsent,
};
// Call this in the SetUp() test harness method to install the test
// GmsBridge and to set the metrics user consent state.
void InstallTestGmsBridge(
ConsentType consent_type,
const OnLogsMetricsCallback on_log_metrics = OnLogsMetricsCallback());
// Call this in the TearDown() test harness method to remove the GmsBridge.
void RemoveTestGmsBridge();
// See comment for kDelayConsent.
void RunConsentCallback(bool has_consent);
ProfileImpl* CreateProfile(const std::string& name, bool incognito = false);
void DestroyProfile(const std::string& name, bool incognito = false);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_METRICS_METRICS_TEST_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/metrics_test_helper.h | C++ | unknown | 1,671 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/bind.h"
#include "components/ukm/ukm_test_helper.h"
#include "weblayer/browser/android/metrics/metrics_test_helper.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/public/tab.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
namespace weblayer {
class UkmBrowserTest : public WebLayerBrowserTest {
public:
void SetUp() override {
InstallTestGmsBridge(user_consent_ ? ConsentType::kConsent
: ConsentType::kNoConsent);
WebLayerBrowserTest::SetUp();
}
void TearDown() override {
RemoveTestGmsBridge();
WebLayerBrowserTest::TearDown();
}
ukm::UkmService* GetUkmService() {
return WebLayerMetricsServiceClient::GetInstance()->GetUkmService();
}
void disable_user_consent() { user_consent_ = false; }
private:
bool user_consent_ = true;
};
// Even if there's user consent for UMA, need to explicitly enable UKM.
IN_PROC_BROWSER_TEST_F(UkmBrowserTest, UserConsentButNotEnabled) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
}
// UKMs are only enabled when there's user consent and it's explicitly enabled.
IN_PROC_BROWSER_TEST_F(UkmBrowserTest, DISABLED_Enabled) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_TRUE(ukm_test_helper.IsRecordingEnabled());
}
// If UKMs are disabled it's reflected accordingly.
IN_PROC_BROWSER_TEST_F(UkmBrowserTest, DISABLED_EnabledThenDisable) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_TRUE(ukm_test_helper.IsRecordingEnabled());
uint64_t original_client_id = ukm_test_helper.GetClientId();
EXPECT_NE(0U, original_client_id);
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, false);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
// Client ID should have been reset.
EXPECT_NE(original_client_id, ukm_test_helper.GetClientId());
}
// Make sure that UKM is disabled while an incognito profile is alive.
IN_PROC_BROWSER_TEST_F(UkmBrowserTest, DISABLED_RegularPlusIncognitoCheck) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_TRUE(ukm_test_helper.IsRecordingEnabled());
uint64_t original_client_id = ukm_test_helper.GetClientId();
EXPECT_NE(0U, original_client_id);
CreateProfile(std::string(), true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
// Creating another regular profile mustn't enable UKM.
auto* profile = CreateProfile("foo");
profile->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
// Opening and closing another Incognito browser mustn't enable UKM.
CreateProfile("bar", true);
DestroyProfile("bar", true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
DestroyProfile("foo");
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
DestroyProfile(std::string(), true);
EXPECT_TRUE(ukm_test_helper.IsRecordingEnabled());
// Client ID should not have been reset.
EXPECT_EQ(original_client_id, ukm_test_helper.GetClientId());
}
// Make sure creating a real profile after Incognito doesn't enable UKM.
IN_PROC_BROWSER_TEST_F(UkmBrowserTest, DISABLED_IncognitoPlusRegularCheck) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
CreateProfile(std::string(), true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
auto* profile = CreateProfile("foo");
profile->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
DestroyProfile(std::string(), true);
EXPECT_TRUE(ukm_test_helper.IsRecordingEnabled());
}
class UkmDisabledBrowserTest : public UkmBrowserTest {
public:
UkmDisabledBrowserTest() { disable_user_consent(); }
};
// If there's no user consent UKMs are disabled.
IN_PROC_BROWSER_TEST_F(UkmDisabledBrowserTest, Disabled) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
// Ensure enabling UKMs still doesn't enable it.
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
}
class UkmIncognitoBrowserTest : public UkmBrowserTest {
public:
UkmIncognitoBrowserTest() { SetShellStartsInIncognitoMode(); }
};
// Starting with one incognito window should disable UKM.
IN_PROC_BROWSER_TEST_F(UkmIncognitoBrowserTest, Disabled) {
ukm::UkmTestHelper ukm_test_helper(GetUkmService());
// Enabling UKMs doesn't enable it because of the incognito window.
GetProfile()->SetBooleanSetting(SettingType::UKM_ENABLED, true);
EXPECT_FALSE(ukm_test_helper.IsRecordingEnabled());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/ukm_browsertest.cc | C++ | unknown | 5,235 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/metrics/uma_utils.h"
#include <stdint.h>
#include "components/metrics/metrics_reporting_default_state.h"
#include "weblayer/browser/java/jni/UmaUtils_jni.h"
using base::android::JavaParamRef;
class PrefService;
namespace weblayer {
base::TimeTicks GetApplicationStartTime() {
JNIEnv* env = base::android::AttachCurrentThread();
return base::TimeTicks::FromUptimeMillis(
Java_UmaUtils_getApplicationStartTime(env));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/uma_utils.cc | C++ | unknown | 638 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_METRICS_UMA_UTILS_H_
#define WEBLAYER_BROWSER_ANDROID_METRICS_UMA_UTILS_H_
#include "base/time/time.h"
namespace weblayer {
base::TimeTicks GetApplicationStartTime();
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_METRICS_UMA_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/uma_utils.h | C++ | unknown | 431 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include <jni.h>
#include <cstdint>
#include <memory>
#include "base/base64.h"
#include "base/no_destructor.h"
#include "components/metrics/metrics_provider.h"
#include "components/metrics/metrics_service.h"
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include "components/prefs/pref_service.h"
#include "components/ukm/ukm_service.h"
#include "components/variations/variations_ids_provider.h"
#include "components/version_info/android/channel_getter.h"
#include "content/public/browser/browser_context.h"
#include "google_apis/google_api_keys.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/java/jni/MetricsServiceClient_jni.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/browser/tab_impl.h"
namespace weblayer {
namespace {
// IMPORTANT: DO NOT CHANGE sample rates without first ensuring the Chrome
// Metrics team has the appropriate backend bandwidth and storage.
// Sample at 10%, which is the same as chrome.
const int kStableSampledInRatePerMille = 100;
// Sample non-stable channels at 99%, to boost volume for pre-stable
// experiments. We choose 99% instead of 100% for consistency with Chrome and to
// exercise the out-of-sample code path.
const int kBetaDevCanarySampledInRatePerMille = 990;
// As a mitigation to preserve user privacy, the privacy team has asked that we
// upload package name with no more than 10% of UMA records. This is to mitigate
// fingerprinting for users on low-usage applications (if an app only has a
// a small handful of users, there's a very good chance many of them won't be
// uploading UMA records due to sampling). Do not change this constant without
// consulting with the privacy team.
const int kPackageNameLimitRatePerMille = 100;
// MetricsProvider that interfaces with page_load_metrics.
class PageLoadMetricsProvider : public metrics::MetricsProvider {
public:
PageLoadMetricsProvider() = default;
PageLoadMetricsProvider(const PageLoadMetricsProvider&) = delete;
PageLoadMetricsProvider& operator=(const PageLoadMetricsProvider&) = delete;
~PageLoadMetricsProvider() override = default;
// metrics:MetricsProvider implementation:
void OnAppEnterBackground() override {
auto tabs = TabImpl::GetAllTabImpl();
for (auto* tab : tabs) {
page_load_metrics::MetricsWebContentsObserver* observer =
page_load_metrics::MetricsWebContentsObserver::FromWebContents(
tab->web_contents());
if (observer)
observer->FlushMetricsOnAppEnterBackground();
}
}
};
} // namespace
// static
WebLayerMetricsServiceClient* WebLayerMetricsServiceClient::GetInstance() {
static base::NoDestructor<WebLayerMetricsServiceClient> client;
client->EnsureOnValidSequence();
return client.get();
}
WebLayerMetricsServiceClient::WebLayerMetricsServiceClient() {
ProfileImpl::AddProfileObserver(this);
BrowserList::GetInstance()->AddObserver(this);
}
WebLayerMetricsServiceClient::~WebLayerMetricsServiceClient() {
BrowserList::GetInstance()->RemoveObserver(this);
ProfileImpl::RemoveProfileObserver(this);
}
void WebLayerMetricsServiceClient::RegisterExternalExperiments(
const std::vector<int>& experiment_ids) {
if (!GetMetricsService()) {
if (!IsConsentDetermined()) {
post_start_tasks_.push_back(base::BindOnce(
&WebLayerMetricsServiceClient::RegisterExternalExperiments,
base::Unretained(this), experiment_ids));
}
return;
}
GetMetricsService()->GetSyntheticTrialRegistry()->RegisterExternalExperiments(
"WebLayerExperiments", experiment_ids,
variations::SyntheticTrialRegistry::kOverrideExistingIds);
}
int32_t WebLayerMetricsServiceClient::GetProduct() {
return metrics::ChromeUserMetricsExtension::ANDROID_WEBLAYER;
}
bool WebLayerMetricsServiceClient::IsExternalExperimentAllowlistEnabled() {
// RegisterExternalExperiments() is actually used to register experiment ids
// coming from the app embedding WebLayer itself, rather than externally. So
// the allowlist shouldn't be applied.
return false;
}
bool WebLayerMetricsServiceClient::IsUkmAllowedForAllProfiles() {
for (auto* profile : ProfileImpl::GetAllProfiles()) {
if (!profile->GetBooleanSetting(SettingType::UKM_ENABLED))
return false;
}
return true;
}
std::string WebLayerMetricsServiceClient::GetUploadSigningKey() {
std::string decoded_key;
base::Base64Decode(google_apis::GetMetricsKey(), &decoded_key);
return decoded_key;
}
const network_time::NetworkTimeTracker*
WebLayerMetricsServiceClient::GetNetworkTimeTracker() {
return BrowserProcess::GetInstance()->GetNetworkTimeTracker();
}
int WebLayerMetricsServiceClient::GetSampleRatePerMille() const {
version_info::Channel channel = version_info::android::GetChannel();
if (channel == version_info::Channel::STABLE ||
channel == version_info::Channel::UNKNOWN) {
return kStableSampledInRatePerMille;
}
return kBetaDevCanarySampledInRatePerMille;
}
void WebLayerMetricsServiceClient::OnMetricsStart() {
for (auto& task : post_start_tasks_) {
std::move(task).Run();
}
post_start_tasks_.clear();
}
void WebLayerMetricsServiceClient::OnMetricsNotStarted() {
post_start_tasks_.clear();
}
int WebLayerMetricsServiceClient::GetPackageNameLimitRatePerMille() {
return kPackageNameLimitRatePerMille;
}
void WebLayerMetricsServiceClient::RegisterAdditionalMetricsProviders(
metrics::MetricsService* service) {
service->RegisterMetricsProvider(std::make_unique<PageLoadMetricsProvider>());
}
bool WebLayerMetricsServiceClient::IsOffTheRecordSessionActive() {
for (auto* profile : ProfileImpl::GetAllProfiles()) {
if (profile->GetBrowserContext()->IsOffTheRecord())
return true;
}
return false;
}
scoped_refptr<network::SharedURLLoaderFactory>
WebLayerMetricsServiceClient::GetURLLoaderFactory() {
return SystemNetworkContextManager::GetInstance()
->GetSharedURLLoaderFactory();
}
void WebLayerMetricsServiceClient::ApplyConsent(bool user_consent,
bool app_consent) {
// TODO(https://crbug.com/1155163): update this once consent can be
// dynamically changed.
// It is expected this function is called only once, and that prior to this
// function the metrics service has not been started. The reason the metric
// service should not have been started prior to this function is that the
// metrics service is only started if consent is given, and this function is
// responsible for setting consent.
DCHECK(!GetMetricsServiceIfStarted());
// UkmService is only created if consent is given.
DCHECK(!GetUkmService());
SetHaveMetricsConsent(user_consent, app_consent);
ApplyForegroundStateToServices();
}
void WebLayerMetricsServiceClient::ApplyForegroundStateToServices() {
const bool is_in_foreground =
BrowserList::GetInstance()->HasAtLeastOneResumedBrowser();
if (auto* metrics_service = WebLayerMetricsServiceClient::GetInstance()
->GetMetricsServiceIfStarted()) {
if (is_in_foreground)
metrics_service->OnAppEnterForeground();
else
metrics_service->OnAppEnterBackground();
}
if (auto* ukm_service = GetUkmService()) {
if (is_in_foreground)
ukm_service->OnAppEnterForeground();
else
ukm_service->OnAppEnterBackground();
}
}
void WebLayerMetricsServiceClient::ProfileCreated(ProfileImpl* profile) {
UpdateUkmService();
}
void WebLayerMetricsServiceClient::ProfileDestroyed(ProfileImpl* profile) {
UpdateUkmService();
}
void WebLayerMetricsServiceClient::OnHasAtLeastOneResumedBrowserStateChanged(
bool new_value) {
ApplyForegroundStateToServices();
}
void JNI_ApplyConsentHelper(bool user_consent, bool app_consent) {
WebLayerMetricsServiceClient::GetInstance()->ApplyConsent(user_consent,
app_consent);
}
// static
void JNI_MetricsServiceClient_SetHaveMetricsConsent(JNIEnv* env,
jboolean user_consent,
jboolean app_consent) {
JNI_ApplyConsentHelper(user_consent, app_consent);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/weblayer_metrics_service_client.cc | C++ | unknown | 8,578 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_METRICS_WEBLAYER_METRICS_SERVICE_CLIENT_H_
#define WEBLAYER_BROWSER_ANDROID_METRICS_WEBLAYER_METRICS_SERVICE_CLIENT_H_
#include <memory>
#include <string>
#include "base/metrics/field_trial.h"
#include "base/no_destructor.h"
#include "base/sequence_checker.h"
#include "components/embedder_support/android/metrics/android_metrics_service_client.h"
#include "components/metrics/metrics_log_uploader.h"
#include "components/metrics/metrics_service_client.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "weblayer/browser/browser_list_observer.h"
#include "weblayer/browser/profile_impl.h"
namespace weblayer {
class WebLayerMetricsServiceClient
: public ::metrics::AndroidMetricsServiceClient,
public ProfileImpl::ProfileObserver,
public BrowserListObserver {
friend class base::NoDestructor<WebLayerMetricsServiceClient>;
public:
static WebLayerMetricsServiceClient* GetInstance();
WebLayerMetricsServiceClient();
WebLayerMetricsServiceClient(const WebLayerMetricsServiceClient&) = delete;
WebLayerMetricsServiceClient& operator=(const WebLayerMetricsServiceClient&) =
delete;
~WebLayerMetricsServiceClient() override;
void RegisterExternalExperiments(const std::vector<int>& experiment_ids);
// metrics::MetricsServiceClient
int32_t GetProduct() override;
bool IsExternalExperimentAllowlistEnabled() override;
bool IsUkmAllowedForAllProfiles() override;
std::string GetUploadSigningKey() override;
// metrics::AndroidMetricsServiceClient:
const network_time::NetworkTimeTracker* GetNetworkTimeTracker() override;
int GetSampleRatePerMille() const override;
void OnMetricsStart() override;
void OnMetricsNotStarted() override;
int GetPackageNameLimitRatePerMille() override;
void RegisterAdditionalMetricsProviders(
metrics::MetricsService* service) override;
bool IsOffTheRecordSessionActive() override;
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
private:
friend void JNI_ApplyConsentHelper(bool user_consent, bool app_consent);
// Called once when consent has been determined.
void ApplyConsent(bool user_consent, bool app_consent);
// Updates the services based on the foreground state.
void ApplyForegroundStateToServices();
// ProfileImpl::ProfileObserver:
void ProfileCreated(ProfileImpl* profile) override;
void ProfileDestroyed(ProfileImpl* profile) override;
// BrowserListObserver:
void OnHasAtLeastOneResumedBrowserStateChanged(bool new_value) override;
std::vector<base::OnceClosure> post_start_tasks_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_METRICS_WEBLAYER_METRICS_SERVICE_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/metrics/weblayer_metrics_service_client.h | C++ | unknown | 2,928 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/permission_request_utils.h"
#include <algorithm>
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "content/public/browser/web_contents.h"
#include "ui/android/window_android.h"
#include "weblayer/browser/java/jni/PermissionRequestUtils_jni.h"
namespace weblayer {
void RequestAndroidPermissions(
content::WebContents* web_contents,
const std::vector<ContentSettingsType>& content_settings_types,
PermissionsUpdatedCallback callback) {
if (!web_contents) {
std::move(callback).Run(false);
return;
}
auto* window = web_contents->GetTopLevelNativeWindow();
if (!window) {
std::move(callback).Run(false);
return;
}
std::vector<int> content_settings_ints;
for (auto type : content_settings_types)
content_settings_ints.push_back(static_cast<int>(type));
// The callback allocated here will be deleted in the call to OnResult, which
// is guaranteed to be called.
Java_PermissionRequestUtils_requestPermission(
base::android::AttachCurrentThread(), window->GetJavaObject(),
reinterpret_cast<jlong>(
new PermissionsUpdatedCallback(std::move(callback))),
base::android::ToJavaIntArray(base::android::AttachCurrentThread(),
content_settings_ints));
}
void JNI_PermissionRequestUtils_OnResult(JNIEnv* env,
jlong callback_ptr,
jboolean result) {
auto* callback = reinterpret_cast<PermissionsUpdatedCallback*>(callback_ptr);
std::move(*callback).Run(result);
delete callback;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/permission_request_utils.cc | C++ | unknown | 1,817 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_PERMISSION_REQUEST_UTILS_H_
#define WEBLAYER_BROWSER_ANDROID_PERMISSION_REQUEST_UTILS_H_
#include <vector>
#include "base/functional/callback_forward.h"
#include "components/content_settings/core/common/content_settings_types.h"
namespace content {
class WebContents;
}
namespace weblayer {
using PermissionsUpdatedCallback = base::OnceCallback<void(bool)>;
// Requests all necessary Android permissions related to
// |content_settings_types|, and calls |callback|. |callback| will be called
// with true if all permissions were successfully granted, and false otherwise.
void RequestAndroidPermissions(
content::WebContents* web_contents,
const std::vector<ContentSettingsType>& content_settings_type,
PermissionsUpdatedCallback callback);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_PERMISSION_REQUEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/permission_request_utils.h | C++ | unknown | 1,027 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/android/resource_mapper.h"
#include <map>
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/check_op.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "components/resources/android/theme_resources.h"
#include "weblayer/browser/java/jni/ResourceMapper_jni.h"
namespace weblayer {
namespace {
using ResourceMap = std::map<int, int>;
ResourceMap* GetIdMap() {
static base::NoDestructor<ResourceMap> id_map;
return id_map.get();
}
// Create the mapping. IDs start at 0 to correspond to the array that gets
// built in the corresponding ResourceID Java class.
void ConstructMap() {
DCHECK(GetIdMap()->empty());
JNIEnv* env = base::android::AttachCurrentThread();
base::android::ScopedJavaLocalRef<jintArray> java_id_array =
Java_ResourceMapper_getResourceIdList(env);
std::vector<int> resource_id_list;
base::android::JavaIntArrayToIntVector(env, java_id_array, &resource_id_list);
size_t next_id = 0;
#define LINK_RESOURCE_ID(c_id, java_id) \
(*GetIdMap())[c_id] = resource_id_list[next_id++];
#define DECLARE_RESOURCE_ID(c_id, java_id) \
(*GetIdMap())[c_id] = resource_id_list[next_id++];
#include "components/resources/android/blocked_content_resource_id.h"
#include "components/resources/android/page_info_resource_id.h"
#include "components/resources/android/permissions_resource_id.h"
#include "components/resources/android/sms_resource_id.h"
#include "components/resources/android/webxr_resource_id.h"
#undef LINK_RESOURCE_ID
#undef DECLARE_RESOURCE_ID
// Make sure ID list sizes match up.
DCHECK_EQ(next_id, resource_id_list.size());
}
} // namespace
int MapToJavaDrawableId(int resource_id) {
if (GetIdMap()->empty()) {
ConstructMap();
}
ResourceMap::iterator iterator = GetIdMap()->find(resource_id);
if (iterator != GetIdMap()->end()) {
return iterator->second;
}
// The resource couldn't be found.
// If you've landed here, please ensure that the header that declares the
// mapping of your native resource to Java resource is listed both in
// ResourceId.tempalate and in this file, next to other *resource_id.h
// headers.
NOTREACHED();
return 0;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/resource_mapper.cc | C++ | unknown | 2,390 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_RESOURCE_MAPPER_H_
#define WEBLAYER_BROWSER_ANDROID_RESOURCE_MAPPER_H_
namespace weblayer {
// Converts the given chromium |resource_id| (e.g. IDR_INFOBAR_TRANSLATE) to
// an Android drawable resource ID. Returns 0 if a mapping wasn't found.
int MapToJavaDrawableId(int resource_id);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_RESOURCE_MAPPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android/resource_mapper.h | C++ | unknown | 545 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_ANDROID_DESCRIPTORS_H_
#define WEBLAYER_BROWSER_ANDROID_DESCRIPTORS_H_
#include "content/public/common/content_descriptors.h"
namespace weblayer {
// This is a list of global descriptor keys to be used with the
// base::GlobalDescriptors object (see base/posix/global_descriptors.h)
enum {
kWebLayerLocalePakDescriptor = kContentIPCDescriptorMax + 1,
kWebLayerMainPakDescriptor,
kWebLayer100PercentPakDescriptor,
kWebLayerSecondaryLocalePakDescriptor,
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ANDROID_DESCRIPTORS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/android_descriptors.h | C++ | unknown | 713 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/autocomplete_scheme_classifier_impl.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "content/public/common/url_constants.h"
#include "third_party/metrics_proto/omnibox_input_type.pb.h"
#include "url/url_constants.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/java/jni/AutocompleteSchemeClassifierImpl_jni.h"
#endif
namespace weblayer {
#if BUILDFLAG(IS_ANDROID)
static jlong JNI_AutocompleteSchemeClassifierImpl_CreateAutocompleteClassifier(
JNIEnv* env) {
return reinterpret_cast<intptr_t>(new AutocompleteSchemeClassifierImpl());
}
static void JNI_AutocompleteSchemeClassifierImpl_DeleteAutocompleteClassifier(
JNIEnv* env,
jlong autocomplete_scheme_classifier_impl) {
delete reinterpret_cast<AutocompleteSchemeClassifierImpl*>(
autocomplete_scheme_classifier_impl);
}
#endif
metrics::OmniboxInputType
AutocompleteSchemeClassifierImpl::GetInputTypeForScheme(
const std::string& scheme) const {
DCHECK_EQ(scheme, base::ToLowerASCII(scheme));
// Check against an allowlist of schemes.
const char* kKnownURLSchemes[] = {
url::kHttpScheme, url::kHttpsScheme,
url::kWsScheme, url::kWssScheme,
url::kFileScheme, url::kAboutScheme,
url::kFtpScheme, url::kBlobScheme,
url::kFileSystemScheme, content::kViewSourceScheme,
url::kJavaScriptScheme};
for (const char* known_scheme : kKnownURLSchemes) {
if (scheme == known_scheme)
return metrics::OmniboxInputType::URL;
}
return metrics::OmniboxInputType::EMPTY;
}
} // namespace weblayer | Zhao-PengFei35/chromium_src_4 | weblayer/browser/autocomplete_scheme_classifier_impl.cc | C++ | unknown | 1,763 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_AUTOCOMPLETE_SCHEME_CLASSIFIER_IMPL_H_
#define WEBLAYER_BROWSER_AUTOCOMPLETE_SCHEME_CLASSIFIER_IMPL_H_
#include "components/omnibox/browser/autocomplete_scheme_classifier.h"
namespace weblayer {
class AutocompleteSchemeClassifierImpl : public AutocompleteSchemeClassifier {
public:
AutocompleteSchemeClassifierImpl() = default;
// AutocompleteInputSchemeChecker:
metrics::OmniboxInputType GetInputTypeForScheme(
const std::string& scheme) const override;
~AutocompleteSchemeClassifierImpl() override = default;
AutocompleteSchemeClassifierImpl(const AutocompleteSchemeClassifierImpl&) =
delete;
AutocompleteSchemeClassifierImpl& operator=(
const AutocompleteSchemeClassifierImpl&) = delete;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_AUTOCOMPLETE_SCHEME_CLASSIFIER_IMPL_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/browser/autocomplete_scheme_classifier_impl.h | C++ | unknown | 989 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/test/weblayer_browser_test.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_field_data.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
// Method that is passed to the autofill system to be invoked on detection of
// autofill forms.
// NOTE: This method can currently be invoked only once within the context of
// a given test. If that restriction ever needs to be relaxed, it could be
// done by changing |quit_closure| to a global that could be reset between
// expected invocations of the method.
void OnReceivedFormDataFromRenderer(base::OnceClosure quit_closure,
autofill::FormData* output,
const autofill::FormData& form) {
ASSERT_TRUE(quit_closure);
*output = form;
std::move(quit_closure).Run();
}
} // namespace
// Cross-platform tests of autofill parsing in the renderer and communication
// to the browser. Does not test integration with any platform's underlying
// system autofill mechanisms.
class AutofillBrowserTest : public WebLayerBrowserTest {
public:
AutofillBrowserTest() = default;
AutofillBrowserTest(const AutofillBrowserTest&) = delete;
AutofillBrowserTest& operator=(const AutofillBrowserTest&) = delete;
~AutofillBrowserTest() override = default;
void SetUp() override {
#if BUILDFLAG(IS_ANDROID)
TabImpl::DisableAutofillSystemIntegrationForTesting();
#endif
WebLayerBrowserTest::SetUp();
}
};
// Tests that the renderer detects a password form and passes the appropriate
// data to the browser.
IN_PROC_BROWSER_TEST_F(AutofillBrowserTest, TestPasswordFormDetection) {
ASSERT_TRUE(embedded_test_server()->Start());
base::RunLoop run_loop;
autofill::FormData observed_form;
InitializeAutofillWithEventForwarding(
shell(), base::BindRepeating(&OnReceivedFormDataFromRenderer,
run_loop.QuitClosure(), &observed_form));
GURL password_form_url =
embedded_test_server()->GetURL("/simple_password_form.html");
NavigateAndWaitForCompletion(password_form_url, shell());
// Focus the username field (note that a user gesture is necessary for
// autofill to trigger) ...
ExecuteScriptWithUserGesture(
shell(), "document.getElementById('username_field').focus();");
// ... and wait for the parsed data to be passed to the browser.
run_loop.Run();
// Verify that that the form data matches that of the document.
EXPECT_EQ(u"testform", observed_form.name);
EXPECT_EQ(password_form_url.spec(), observed_form.url);
auto fields = observed_form.fields;
EXPECT_EQ(2u, fields.size());
autofill::FormFieldData username_field = fields[0];
EXPECT_EQ(u"username_field", username_field.name);
autofill::FormFieldData password_field = fields[1];
EXPECT_EQ(u"password_field", password_field.name);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/autofill_browsertest.cc | C++ | unknown | 3,325 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/autofill_client_impl.h"
#include <utility>
#include "build/build_config.h"
#include "components/android_autofill/browser/android_autofill_manager.h"
#include "components/autofill/core/browser/autofill_download_manager.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/ui/suggestion.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/ssl_status.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "weblayer/browser/translate_client_impl.h"
namespace weblayer {
AutofillClientImpl::~AutofillClientImpl() = default;
bool AutofillClientImpl::IsOffTheRecord() {
return web_contents()->GetBrowserContext()->IsOffTheRecord();
}
scoped_refptr<network::SharedURLLoaderFactory>
AutofillClientImpl::GetURLLoaderFactory() {
return web_contents()
->GetBrowserContext()
->GetDefaultStoragePartition()
->GetURLLoaderFactoryForBrowserProcess();
}
autofill::AutofillDownloadManager* AutofillClientImpl::GetDownloadManager() {
if (!download_manager_) {
// Lazy initialization to avoid virtual function calls in the constructor.
download_manager_ = std::make_unique<autofill::AutofillDownloadManager>(
this, GetChannel(), GetLogManager());
}
return download_manager_.get();
}
autofill::PersonalDataManager* AutofillClientImpl::GetPersonalDataManager() {
NOTREACHED();
return nullptr;
}
autofill::AutocompleteHistoryManager*
AutofillClientImpl::GetAutocompleteHistoryManager() {
NOTREACHED();
return nullptr;
}
PrefService* AutofillClientImpl::GetPrefs() {
return const_cast<PrefService*>(std::as_const(*this).GetPrefs());
}
const PrefService* AutofillClientImpl::GetPrefs() const {
NOTREACHED();
return nullptr;
}
syncer::SyncService* AutofillClientImpl::GetSyncService() {
NOTREACHED();
return nullptr;
}
signin::IdentityManager* AutofillClientImpl::GetIdentityManager() {
NOTREACHED();
return nullptr;
}
autofill::FormDataImporter* AutofillClientImpl::GetFormDataImporter() {
NOTREACHED();
return nullptr;
}
autofill::payments::PaymentsClient* AutofillClientImpl::GetPaymentsClient() {
NOTREACHED();
return nullptr;
}
autofill::StrikeDatabase* AutofillClientImpl::GetStrikeDatabase() {
NOTREACHED();
return nullptr;
}
ukm::UkmRecorder* AutofillClientImpl::GetUkmRecorder() {
// TODO(crbug.com/1181141): Enable the autofill UKM.
return nullptr;
}
ukm::SourceId AutofillClientImpl::GetUkmSourceId() {
// TODO(crbug.com/1181141): Enable the autofill UKM.
return ukm::kInvalidSourceId;
}
autofill::AddressNormalizer* AutofillClientImpl::GetAddressNormalizer() {
NOTREACHED();
return nullptr;
}
const GURL& AutofillClientImpl::GetLastCommittedPrimaryMainFrameURL() const {
NOTREACHED();
return GURL::EmptyGURL();
}
url::Origin AutofillClientImpl::GetLastCommittedPrimaryMainFrameOrigin() const {
NOTREACHED();
return url::Origin();
}
security_state::SecurityLevel
AutofillClientImpl::GetSecurityLevelForUmaHistograms() {
NOTREACHED();
return security_state::SecurityLevel::SECURITY_LEVEL_COUNT;
}
const translate::LanguageState* AutofillClientImpl::GetLanguageState() {
return nullptr;
}
translate::TranslateDriver* AutofillClientImpl::GetTranslateDriver() {
// The TranslateDriver is used by AutofillManager to observe the page language
// and run the type-prediction heuristics with language-dependent regexps.
auto* translate_client = TranslateClientImpl::FromWebContents(web_contents());
if (translate_client)
return translate_client->translate_driver();
return nullptr;
}
void AutofillClientImpl::ShowAutofillSettings(autofill::PopupType popup_type) {
NOTREACHED();
}
void AutofillClientImpl::ShowUnmaskPrompt(
const autofill::CreditCard& card,
const autofill::CardUnmaskPromptOptions& card_unmask_prompt_options,
base::WeakPtr<autofill::CardUnmaskDelegate> delegate) {
NOTREACHED();
}
void AutofillClientImpl::OnUnmaskVerificationResult(PaymentsRpcResult result) {
NOTREACHED();
}
#if !BUILDFLAG(IS_ANDROID)
std::vector<std::string>
AutofillClientImpl::GetAllowedMerchantsForVirtualCards() {
NOTREACHED();
return std::vector<std::string>();
}
std::vector<std::string>
AutofillClientImpl::GetAllowedBinRangesForVirtualCards() {
NOTREACHED();
return std::vector<std::string>();
}
void AutofillClientImpl::ShowLocalCardMigrationDialog(
base::OnceClosure show_migration_dialog_closure) {
NOTREACHED();
}
void AutofillClientImpl::ConfirmMigrateLocalCardToCloud(
const autofill::LegalMessageLines& legal_message_lines,
const std::string& user_email,
const std::vector<autofill::MigratableCreditCard>& migratable_credit_cards,
LocalCardMigrationCallback start_migrating_cards_callback) {
NOTREACHED();
}
void AutofillClientImpl::ShowLocalCardMigrationResults(
const bool has_server_error,
const std::u16string& tip_message,
const std::vector<autofill::MigratableCreditCard>& migratable_credit_cards,
MigrationDeleteCardCallback delete_local_card_callback) {
NOTREACHED();
}
void AutofillClientImpl::ShowWebauthnOfferDialog(
WebauthnDialogCallback offer_dialog_callback) {
NOTREACHED();
}
void AutofillClientImpl::ShowWebauthnVerifyPendingDialog(
WebauthnDialogCallback verify_pending_dialog_callback) {
NOTREACHED();
}
void AutofillClientImpl::UpdateWebauthnOfferDialogWithError() {
NOTREACHED();
}
bool AutofillClientImpl::CloseWebauthnDialog() {
NOTREACHED();
return false;
}
void AutofillClientImpl::ConfirmSaveUpiIdLocally(
const std::string& upi_id,
base::OnceCallback<void(bool user_decision)> callback) {
NOTREACHED();
}
void AutofillClientImpl::OfferVirtualCardOptions(
const std::vector<autofill::CreditCard*>& candidates,
base::OnceCallback<void(const std::string&)> callback) {
NOTREACHED();
}
#else // !BUILDFLAG(IS_ANDROID)
void AutofillClientImpl::ConfirmAccountNameFixFlow(
base::OnceCallback<void(const std::u16string&)> callback) {
NOTREACHED();
}
void AutofillClientImpl::ConfirmExpirationDateFixFlow(
const autofill::CreditCard& card,
base::OnceCallback<void(const std::u16string&, const std::u16string&)>
callback) {
NOTREACHED();
}
#endif
void AutofillClientImpl::ConfirmSaveCreditCardLocally(
const autofill::CreditCard& card,
SaveCreditCardOptions options,
LocalSaveCardPromptCallback callback) {
NOTREACHED();
}
void AutofillClientImpl::ConfirmSaveCreditCardToCloud(
const autofill::CreditCard& card,
const autofill::LegalMessageLines& legal_message_lines,
SaveCreditCardOptions options,
UploadSaveCardPromptCallback callback) {
NOTREACHED();
}
void AutofillClientImpl::CreditCardUploadCompleted(bool card_saved) {
NOTREACHED();
}
void AutofillClientImpl::ConfirmCreditCardFillAssist(
const autofill::CreditCard& card,
base::OnceClosure callback) {
NOTREACHED();
}
void AutofillClientImpl::ConfirmSaveAddressProfile(
const autofill::AutofillProfile& profile,
const autofill::AutofillProfile* original_profile,
SaveAddressProfilePromptOptions options,
AddressProfileSavePromptCallback callback) {
NOTREACHED();
}
bool AutofillClientImpl::HasCreditCardScanFeature() {
NOTREACHED();
return false;
}
void AutofillClientImpl::ScanCreditCard(CreditCardScanCallback callback) {
NOTREACHED();
}
bool AutofillClientImpl::IsTouchToFillCreditCardSupported() {
return false;
}
bool AutofillClientImpl::ShowTouchToFillCreditCard(
base::WeakPtr<autofill::TouchToFillDelegate> delegate,
base::span<const autofill::CreditCard> cards_to_suggest) {
NOTREACHED();
return false;
}
void AutofillClientImpl::HideTouchToFillCreditCard() {
NOTREACHED();
}
void AutofillClientImpl::ShowAutofillPopup(
const autofill::AutofillClient::PopupOpenArgs& open_args,
base::WeakPtr<autofill::AutofillPopupDelegate> delegate) {
NOTREACHED();
}
void AutofillClientImpl::UpdateAutofillPopupDataListValues(
const std::vector<std::u16string>& values,
const std::vector<std::u16string>& labels) {
NOTREACHED();
}
void AutofillClientImpl::HideAutofillPopup(autofill::PopupHidingReason reason) {
// This is invoked on the user moving away from an autofill context (e.g., a
// navigation finishing or a tab being hidden). As all showing/hiding of
// autofill UI in WebLayer is driven by the system, there is no action to
// take.
}
std::vector<autofill::Suggestion> AutofillClientImpl::GetPopupSuggestions()
const {
NOTIMPLEMENTED();
return {};
}
void AutofillClientImpl::PinPopupView() {
NOTIMPLEMENTED();
}
autofill::AutofillClient::PopupOpenArgs AutofillClientImpl::GetReopenPopupArgs()
const {
NOTIMPLEMENTED();
return {};
}
void AutofillClientImpl::UpdatePopup(
const std::vector<autofill::Suggestion>& suggestions,
autofill::PopupType popup_type) {
NOTREACHED();
}
bool AutofillClientImpl::IsAutocompleteEnabled() const {
NOTREACHED();
return false;
}
bool AutofillClientImpl::IsPasswordManagerEnabled() {
// This function is currently only used by the BrowserAutofillManager,
// but not by the AndroidAutofillManager. See crbug.com/1293341 for context.
NOTREACHED();
return false;
}
void AutofillClientImpl::PropagateAutofillPredictions(
autofill::AutofillDriver* driver,
const std::vector<autofill::FormStructure*>& forms) {
NOTREACHED();
}
void AutofillClientImpl::DidFillOrPreviewForm(
autofill::mojom::RendererFormDataAction action,
autofill::AutofillTriggerSource trigger_source,
bool is_refill) {
NOTREACHED();
}
void AutofillClientImpl::DidFillOrPreviewField(
const std::u16string& autofilled_value,
const std::u16string& profile_full_name) {
NOTREACHED();
}
bool AutofillClientImpl::IsContextSecure() const {
NOTREACHED();
return false;
}
void AutofillClientImpl::ExecuteCommand(int id) {
NOTREACHED();
}
void AutofillClientImpl::OpenPromoCodeOfferDetailsURL(const GURL& url) {
NOTREACHED();
}
autofill::FormInteractionsFlowId
AutofillClientImpl::GetCurrentFormInteractionsFlowId() {
// Currently not in use here. See `ChromeAutofillClient` for a proper
// implementation.
return {};
}
void AutofillClientImpl::LoadRiskData(
base::OnceCallback<void(const std::string&)> callback) {
NOTREACHED();
}
AutofillClientImpl::AutofillClientImpl(content::WebContents* web_contents)
: autofill::ContentAutofillClient(
web_contents,
base::BindRepeating(&autofill::AndroidDriverInitHook, this)),
content::WebContentsObserver(web_contents) {}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/autofill_client_impl.cc | C++ | unknown | 10,930 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_AUTOFILL_CLIENT_IMPL_H_
#define WEBLAYER_BROWSER_AUTOFILL_CLIENT_IMPL_H_
#include "base/compiler_specific.h"
#include "build/build_config.h"
#include "components/autofill/content/browser/content_autofill_client.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
namespace weblayer {
// A minimal implementation of autofill::AutofillClient to satisfy the minor
// touchpoints between the autofill implementation and its client that get
// exercised within the WebLayer autofill flow.
class AutofillClientImpl : public autofill::ContentAutofillClient,
public content::WebContentsObserver {
public:
static AutofillClientImpl* FromWebContents(
content::WebContents* web_contents) {
return static_cast<AutofillClientImpl*>(
ContentAutofillClient::FromWebContents(web_contents));
}
static void CreateForWebContents(content::WebContents* contents) {
DCHECK(contents);
if (!ContentAutofillClient::FromWebContents(contents)) {
contents->SetUserData(UserDataKey(),
base::WrapUnique(new AutofillClientImpl(contents)));
}
}
AutofillClientImpl(const AutofillClientImpl&) = delete;
AutofillClientImpl& operator=(const AutofillClientImpl&) = delete;
~AutofillClientImpl() override;
// AutofillClient:
bool IsOffTheRecord() override;
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
autofill::AutofillDownloadManager* GetDownloadManager() override;
autofill::PersonalDataManager* GetPersonalDataManager() override;
autofill::AutocompleteHistoryManager* GetAutocompleteHistoryManager()
override;
PrefService* GetPrefs() override;
const PrefService* GetPrefs() const override;
syncer::SyncService* GetSyncService() override;
signin::IdentityManager* GetIdentityManager() override;
autofill::FormDataImporter* GetFormDataImporter() override;
autofill::payments::PaymentsClient* GetPaymentsClient() override;
autofill::StrikeDatabase* GetStrikeDatabase() override;
ukm::UkmRecorder* GetUkmRecorder() override;
ukm::SourceId GetUkmSourceId() override;
autofill::AddressNormalizer* GetAddressNormalizer() override;
const GURL& GetLastCommittedPrimaryMainFrameURL() const override;
url::Origin GetLastCommittedPrimaryMainFrameOrigin() const override;
security_state::SecurityLevel GetSecurityLevelForUmaHistograms() override;
const translate::LanguageState* GetLanguageState() override;
translate::TranslateDriver* GetTranslateDriver() override;
void ShowAutofillSettings(autofill::PopupType popup_type) override;
void ShowUnmaskPrompt(
const autofill::CreditCard& card,
const autofill::CardUnmaskPromptOptions& card_unmask_prompt_options,
base::WeakPtr<autofill::CardUnmaskDelegate> delegate) override;
void OnUnmaskVerificationResult(PaymentsRpcResult result) override;
#if !BUILDFLAG(IS_ANDROID)
std::vector<std::string> GetAllowedMerchantsForVirtualCards() override;
std::vector<std::string> GetAllowedBinRangesForVirtualCards() override;
void ShowLocalCardMigrationDialog(
base::OnceClosure show_migration_dialog_closure) override;
void ConfirmMigrateLocalCardToCloud(
const autofill::LegalMessageLines& legal_message_lines,
const std::string& user_email,
const std::vector<autofill::MigratableCreditCard>&
migratable_credit_cards,
LocalCardMigrationCallback start_migrating_cards_callback) override;
void ShowLocalCardMigrationResults(
const bool has_server_error,
const std::u16string& tip_message,
const std::vector<autofill::MigratableCreditCard>&
migratable_credit_cards,
MigrationDeleteCardCallback delete_local_card_callback) override;
void ShowWebauthnOfferDialog(
WebauthnDialogCallback offer_dialog_callback) override;
void ShowWebauthnVerifyPendingDialog(
WebauthnDialogCallback verify_pending_dialog_callback) override;
void UpdateWebauthnOfferDialogWithError() override;
bool CloseWebauthnDialog() override;
void ConfirmSaveUpiIdLocally(
const std::string& upi_id,
base::OnceCallback<void(bool user_decision)> callback) override;
void OfferVirtualCardOptions(
const std::vector<autofill::CreditCard*>& candidates,
base::OnceCallback<void(const std::string&)> callback) override;
#else // !BUILDFLAG(IS_ANDROID)
void ConfirmAccountNameFixFlow(
base::OnceCallback<void(const std::u16string&)> callback) override;
void ConfirmExpirationDateFixFlow(
const autofill::CreditCard& card,
base::OnceCallback<void(const std::u16string&, const std::u16string&)>
callback) override;
#endif // !BUILDFLAG(IS_ANDROID)
void ConfirmSaveCreditCardLocally(
const autofill::CreditCard& card,
SaveCreditCardOptions options,
LocalSaveCardPromptCallback callback) override;
void ConfirmSaveCreditCardToCloud(
const autofill::CreditCard& card,
const autofill::LegalMessageLines& legal_message_lines,
SaveCreditCardOptions options,
UploadSaveCardPromptCallback callback) override;
void CreditCardUploadCompleted(bool card_saved) override;
void ConfirmCreditCardFillAssist(const autofill::CreditCard& card,
base::OnceClosure callback) override;
void ConfirmSaveAddressProfile(
const autofill::AutofillProfile& profile,
const autofill::AutofillProfile* original_profile,
SaveAddressProfilePromptOptions options,
AddressProfileSavePromptCallback callback) override;
bool HasCreditCardScanFeature() override;
void ScanCreditCard(CreditCardScanCallback callback) override;
bool IsTouchToFillCreditCardSupported() override;
bool ShowTouchToFillCreditCard(
base::WeakPtr<autofill::TouchToFillDelegate> delegate,
base::span<const autofill::CreditCard> cards_to_suggest) override;
void HideTouchToFillCreditCard() override;
void ShowAutofillPopup(
const autofill::AutofillClient::PopupOpenArgs& open_args,
base::WeakPtr<autofill::AutofillPopupDelegate> delegate) override;
void UpdateAutofillPopupDataListValues(
const std::vector<std::u16string>& values,
const std::vector<std::u16string>& labels) override;
std::vector<autofill::Suggestion> GetPopupSuggestions() const override;
void PinPopupView() override;
autofill::AutofillClient::PopupOpenArgs GetReopenPopupArgs() const override;
void UpdatePopup(const std::vector<autofill::Suggestion>& suggestions,
autofill::PopupType popup_type) override;
void HideAutofillPopup(autofill::PopupHidingReason reason) override;
bool IsAutocompleteEnabled() const override;
bool IsPasswordManagerEnabled() override;
void PropagateAutofillPredictions(
autofill::AutofillDriver* driver,
const std::vector<autofill::FormStructure*>& forms) override;
void DidFillOrPreviewForm(autofill::mojom::RendererFormDataAction action,
autofill::AutofillTriggerSource trigger_source,
bool is_refill) override;
void DidFillOrPreviewField(const std::u16string& autofilled_value,
const std::u16string& profile_full_name) override;
bool IsContextSecure() const override;
void ExecuteCommand(int id) override;
void OpenPromoCodeOfferDetailsURL(const GURL& url) override;
autofill::FormInteractionsFlowId GetCurrentFormInteractionsFlowId() override;
// RiskDataLoader:
void LoadRiskData(
base::OnceCallback<void(const std::string&)> callback) override;
private:
explicit AutofillClientImpl(content::WebContents* web_contents);
std::unique_ptr<autofill::AutofillDownloadManager> download_manager_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_AUTOFILL_CLIENT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/autofill_client_impl.h | C++ | unknown | 8,006 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/background_download_service_factory.h"
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "components/background_fetch/download_client.h"
#include "components/download/content/factory/download_service_factory_helper.h"
#include "components/download/content/factory/navigation_monitor_factory.h"
#include "components/download/public/background_service/background_download_service.h"
#include "components/download/public/background_service/basic_task_scheduler.h"
#include "components/download/public/background_service/blob_context_getter_factory.h"
#include "components/download/public/background_service/clients.h"
#include "components/download/public/common/simple_download_manager_coordinator.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/leveldb_proto/public/proto_database_provider.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/system_network_context_manager.h"
namespace weblayer {
namespace {
// Like BackgroundDownloadServiceFactory, this is a
// BrowserContextKeyedServiceFactory although the Chrome version is a
// SimpleKeyedServiceFactory.
class SimpleDownloadManagerCoordinatorFactory
: public BrowserContextKeyedServiceFactory {
public:
// Returns singleton instance of SimpleDownloadManagerCoordinatorFactory.
static SimpleDownloadManagerCoordinatorFactory* GetInstance() {
static base::NoDestructor<SimpleDownloadManagerCoordinatorFactory> instance;
return instance.get();
}
static download::SimpleDownloadManagerCoordinator* GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<download::SimpleDownloadManagerCoordinator*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
SimpleDownloadManagerCoordinatorFactory(
const SimpleDownloadManagerCoordinatorFactory& other) = delete;
SimpleDownloadManagerCoordinatorFactory& operator=(
const SimpleDownloadManagerCoordinatorFactory& other) = delete;
private:
friend class base::NoDestructor<SimpleDownloadManagerCoordinatorFactory>;
SimpleDownloadManagerCoordinatorFactory()
: BrowserContextKeyedServiceFactory(
"SimpleDownloadManagerCoordinator",
BrowserContextDependencyManager::GetInstance()) {}
~SimpleDownloadManagerCoordinatorFactory() override = default;
// BrowserContextKeyedService:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override {
auto* service_instance = new download::SimpleDownloadManagerCoordinator({});
service_instance->SetSimpleDownloadManager(context->GetDownloadManager(),
true);
return service_instance;
}
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override {
return context;
}
};
// An implementation of BlobContextGetterFactory that returns the
// BlobStorageContext without delay (since WebLayer must be in "full browser"
// mode).
class DownloadBlobContextGetterFactory
: public download::BlobContextGetterFactory {
public:
explicit DownloadBlobContextGetterFactory(
content::BrowserContext* browser_context)
: browser_context_(browser_context) {}
DownloadBlobContextGetterFactory(const DownloadBlobContextGetterFactory&) =
delete;
DownloadBlobContextGetterFactory& operator=(
const DownloadBlobContextGetterFactory&) = delete;
~DownloadBlobContextGetterFactory() override = default;
private:
// download::BlobContextGetterFactory:
void RetrieveBlobContextGetter(
download::BlobContextGetterCallback callback) override {
std::move(callback).Run(browser_context_->GetBlobStorageContext());
}
raw_ptr<content::BrowserContext> browser_context_;
};
} // namespace
// static
download::BackgroundDownloadService*
BackgroundDownloadServiceFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<download::BackgroundDownloadService*>(
GetInstance()->GetServiceForBrowserContext(browser_context,
/*create=*/true));
}
// static
BackgroundDownloadServiceFactory*
BackgroundDownloadServiceFactory::GetInstance() {
static base::NoDestructor<BackgroundDownloadServiceFactory> factory;
return factory.get();
}
BackgroundDownloadServiceFactory::BackgroundDownloadServiceFactory()
: BrowserContextKeyedServiceFactory(
"BackgroundDownloadServiceFactory",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(SimpleDownloadManagerCoordinatorFactory::GetInstance());
DependsOn(download::NavigationMonitorFactory::GetInstance());
}
KeyedService* BackgroundDownloadServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
SimpleFactoryKey* key = ProfileImpl::FromBrowserContext(context)
->GetBrowserContext()
->simple_factory_key();
auto clients = std::make_unique<download::DownloadClientMap>();
clients->insert(std::make_pair(
download::DownloadClient::BACKGROUND_FETCH,
std::make_unique<background_fetch::DownloadClient>(context)));
// Build in memory download service for an off the record context.
if (context->IsOffTheRecord()) {
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
content::GetIOThreadTaskRunner({});
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory =
SystemNetworkContextManager::GetInstance()->GetSharedURLLoaderFactory();
return download::BuildInMemoryDownloadService(
key, std::move(clients), content::GetNetworkConnectionTracker(),
base::FilePath(),
std::make_unique<DownloadBlobContextGetterFactory>(context),
io_task_runner, url_loader_factory)
.release();
}
// Build download service for a regular browsing context.
base::FilePath storage_dir;
if (!context->IsOffTheRecord() && !context->GetPath().empty()) {
const base::FilePath::CharType kDownloadServiceStorageDirname[] =
FILE_PATH_LITERAL("Download Service");
storage_dir = context->GetPath().Append(kDownloadServiceStorageDirname);
}
scoped_refptr<base::SequencedTaskRunner> background_task_runner =
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT});
leveldb_proto::ProtoDatabaseProvider* proto_db_provider =
context->GetDefaultStoragePartition()->GetProtoDatabaseProvider();
return download::BuildDownloadService(
key, std::move(clients), content::GetNetworkConnectionTracker(),
storage_dir,
SimpleDownloadManagerCoordinatorFactory::GetForBrowserContext(
context),
proto_db_provider, background_task_runner,
std::make_unique<download::BasicTaskScheduler>(base::BindRepeating(
[](content::BrowserContext* context) {
return BackgroundDownloadServiceFactory::
GetForBrowserContext(context);
},
context)))
.release();
}
content::BrowserContext*
BackgroundDownloadServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_download_service_factory.cc | C++ | unknown | 8,137 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_BACKGROUND_DOWNLOAD_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_BACKGROUND_DOWNLOAD_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace download {
class BackgroundDownloadService;
} // namespace download
namespace weblayer {
// Unlike Chrome, which can operate outside of full browser mode, WebLayer can
// assume the full BrowserContext is available. For that reason this class is a
// BrowserContextKeyedService rather than a SimpleKeyedServiceFactory.
class BackgroundDownloadServiceFactory
: public BrowserContextKeyedServiceFactory {
public:
static BackgroundDownloadServiceFactory* GetInstance();
static download::BackgroundDownloadService* GetForBrowserContext(
content::BrowserContext* context);
BackgroundDownloadServiceFactory(
const BackgroundDownloadServiceFactory& other) = delete;
BackgroundDownloadServiceFactory& operator=(
const BackgroundDownloadServiceFactory& other) = delete;
private:
friend class base::NoDestructor<BackgroundDownloadServiceFactory>;
BackgroundDownloadServiceFactory();
~BackgroundDownloadServiceFactory() override = default;
// BrowserContextKeyedService:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_DOWNLOAD_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_download_service_factory.h | C++ | unknown | 1,709 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/background_fetch/background_fetch_delegate_factory.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/background_fetch_delegate.h"
#include "weblayer/browser/background_download_service_factory.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/android/application_info_helper.h"
#endif
namespace weblayer {
// static
BackgroundFetchDelegateImpl*
BackgroundFetchDelegateFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<BackgroundFetchDelegateImpl*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
BackgroundFetchDelegateFactory* BackgroundFetchDelegateFactory::GetInstance() {
return base::Singleton<BackgroundFetchDelegateFactory>::get();
}
BackgroundFetchDelegateFactory::BackgroundFetchDelegateFactory()
: BrowserContextKeyedServiceFactory(
"BackgroundFetchService",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(BackgroundDownloadServiceFactory::GetInstance());
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
BackgroundFetchDelegateFactory::~BackgroundFetchDelegateFactory() = default;
KeyedService* BackgroundFetchDelegateFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new BackgroundFetchDelegateImpl(context);
}
content::BrowserContext* BackgroundFetchDelegateFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_delegate_factory.cc | C++ | unknown | 1,940 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_FACTORY_H_
#define WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_FACTORY_H_
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace weblayer {
class BackgroundFetchDelegateImpl;
class BackgroundFetchDelegateFactory
: public BrowserContextKeyedServiceFactory {
public:
static BackgroundFetchDelegateImpl* GetForBrowserContext(
content::BrowserContext* context);
static BackgroundFetchDelegateFactory* GetInstance();
BackgroundFetchDelegateFactory(const BackgroundFetchDelegateFactory&) =
delete;
BackgroundFetchDelegateFactory& operator=(
const BackgroundFetchDelegateFactory&) = delete;
private:
friend struct base::DefaultSingletonTraits<BackgroundFetchDelegateFactory>;
BackgroundFetchDelegateFactory();
~BackgroundFetchDelegateFactory() override;
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_delegate_factory.h | C++ | unknown | 1,411 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/background_fetch/background_fetch_delegate_impl.h"
#include <utility>
#include "base/check_op.h"
#include "base/task/sequenced_task_runner.h"
#include "build/build_config.h"
#include "components/background_fetch/download_client.h"
#include "components/background_fetch/job_details.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "content/public/browser/background_fetch_description.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/background_download_service_factory.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/public/download_delegate.h"
namespace weblayer {
BackgroundFetchDelegateImpl::BackgroundFetchDelegateImpl(
content::BrowserContext* context)
: background_fetch::BackgroundFetchDelegateBase(context) {}
BackgroundFetchDelegateImpl::~BackgroundFetchDelegateImpl() = default;
void BackgroundFetchDelegateImpl::MarkJobComplete(const std::string& job_id) {
BackgroundFetchDelegateBase::MarkJobComplete(job_id);
#if BUILDFLAG(IS_ANDROID)
background_fetch::JobDetails* job_details =
GetJobDetails(job_id, /*allow_null=*/true);
if (job_details && job_details->job_state ==
background_fetch::JobDetails::State::kJobComplete) {
// The UI should have already been updated to the Completed state, however,
// sometimes Android drops notification updates if there have been too many
// requested in a short span of time, so make sure the completed state is
// reflected in the UI after a brief delay. See
// https://developer.android.com/training/notify-user/build-notification#Updating
static constexpr auto kDelay = base::Milliseconds(1500);
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&BackgroundFetchDelegateImpl::DoUpdateUi,
weak_ptr_factory_.GetWeakPtr(), job_id),
kDelay);
}
#endif
}
void BackgroundFetchDelegateImpl::UpdateUI(
const std::string& job_id,
const absl::optional<std::string>& title,
const absl::optional<SkBitmap>& icon) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(title || icon); // One of the UI options must be updatable.
DCHECK(!icon || !icon->isNull()); // The |icon|, if provided, is not null.
background_fetch::JobDetails* job_details =
GetJobDetails(job_id, /*allow_null=*/true);
if (!job_details)
return;
if (title)
job_details->fetch_description->title = *title;
if (icon)
job_details->fetch_description->icon = *icon;
DoUpdateUi(job_id);
if (auto client = GetClient(job_id))
client->OnUIUpdated(job_id);
}
download::BackgroundDownloadService*
BackgroundFetchDelegateImpl::GetDownloadService() {
return BackgroundDownloadServiceFactory::GetForBrowserContext(context());
}
void BackgroundFetchDelegateImpl::OnJobDetailsCreated(
const std::string& job_id) {
// WebLayer doesn't create the UI until a download actually starts.
}
void BackgroundFetchDelegateImpl::DoShowUi(const std::string& job_id) {
// Create the UI the first time a download starts. (There may be multiple
// downloads for a single background fetch job.)
background_fetch::JobDetails* job = GetJobDetails(job_id);
auto inserted = ui_item_map_.emplace(
std::piecewise_construct, std::forward_as_tuple(job_id),
std::forward_as_tuple(this, job_id, job));
DCHECK(inserted.second);
ProfileImpl::FromBrowserContext(context())
->download_delegate()
->DownloadStarted(&inserted.first->second);
}
void BackgroundFetchDelegateImpl::DoUpdateUi(const std::string& job_id) {
auto iter = ui_item_map_.find(job_id);
if (iter == ui_item_map_.end())
return;
BackgroundFetchDownload* download = &iter->second;
if (!download->HasBeenAddedToUi())
return;
ProfileImpl::FromBrowserContext(context())
->download_delegate()
->DownloadProgressChanged(download);
}
void BackgroundFetchDelegateImpl::DoCleanUpUi(const std::string& job_id) {
ui_item_map_.erase(job_id);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_delegate_impl.cc | C++ | unknown | 4,486 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_IMPL_H_
#define WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_IMPL_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include "base/memory/weak_ptr.h"
#include "components/background_fetch/background_fetch_delegate_base.h"
#include "components/download/public/background_service/download_params.h"
#include "components/keyed_service/core/keyed_service.h"
#include "ui/gfx/image/image.h"
#include "url/origin.h"
#include "weblayer/browser/background_fetch/background_fetch_download.h"
namespace content {
class BrowserContext;
}
namespace weblayer {
// Implementation of BackgroundFetchDelegate using the
// BackgroundDownloadService.
class BackgroundFetchDelegateImpl
: public background_fetch::BackgroundFetchDelegateBase,
public KeyedService {
public:
explicit BackgroundFetchDelegateImpl(content::BrowserContext* context);
BackgroundFetchDelegateImpl(const BackgroundFetchDelegateImpl&) = delete;
BackgroundFetchDelegateImpl& operator=(const BackgroundFetchDelegateImpl&) =
delete;
~BackgroundFetchDelegateImpl() override;
// BackgroundFetchDelegate:
void MarkJobComplete(const std::string& job_id) override;
void UpdateUI(const std::string& job_id,
const absl::optional<std::string>& title,
const absl::optional<SkBitmap>& icon) override;
protected:
// BackgroundFetchDelegateBase:
download::BackgroundDownloadService* GetDownloadService() override;
void OnJobDetailsCreated(const std::string& job_id) override;
void DoShowUi(const std::string& job_id) override;
void DoUpdateUi(const std::string& job_id) override;
void DoCleanUpUi(const std::string& job_id) override;
private:
// Map from job unique ids to the UI item for the job.
std::map<std::string, BackgroundFetchDownload> ui_item_map_;
base::WeakPtrFactory<BackgroundFetchDelegateImpl> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_delegate_impl.h | C++ | unknown | 2,220 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/background_fetch/background_fetch_download.h"
#include "base/strings/utf_string_conversions.h"
#include "components/background_fetch/job_details.h"
#include "content/public/browser/background_fetch_description.h"
#include "url/origin.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_impl.h"
using background_fetch::JobDetails;
namespace weblayer {
BackgroundFetchDownload::BackgroundFetchDownload(
BackgroundFetchDelegateImpl* controller,
const std::string& job_id,
const JobDetails* job)
: controller_(controller), job_id_(job_id), job_(job) {
// The only other kind of DownloadImpl uses the DownloadItem's ID as its
// notification ID, and that's constrained to positive integers.
static int id = 0;
if (id > 0)
id = 0;
notification_id_ = --id;
}
BackgroundFetchDownload::~BackgroundFetchDownload() = default;
DownloadState BackgroundFetchDownload::GetState() {
switch (job_->job_state) {
case JobDetails::State::kPendingWillStartDownloading:
case JobDetails::State::kStartedAndDownloading:
return DownloadState::kInProgress;
case JobDetails::State::kPendingWillStartPaused:
case JobDetails::State::kStartedButPaused:
return DownloadState::kPaused;
case JobDetails::State::kCancelled:
return DownloadState::kCancelled;
case JobDetails::State::kDownloadsComplete:
case JobDetails::State::kJobComplete:
return DownloadState::kComplete;
}
}
int64_t BackgroundFetchDownload::GetTotalBytes() {
return job_->GetTotalBytes();
}
int64_t BackgroundFetchDownload::GetReceivedBytes() {
return job_->GetProcessedBytes();
}
void BackgroundFetchDownload::Pause() {
controller_->PauseDownload(job_id_);
}
void BackgroundFetchDownload::Resume() {
controller_->ResumeDownload(job_id_);
}
void BackgroundFetchDownload::Cancel() {
controller_->CancelDownload(job_id_);
}
base::FilePath BackgroundFetchDownload::GetLocation() {
NOTREACHED();
return {};
}
std::u16string BackgroundFetchDownload::GetFileNameToReportToUser() {
return base::UTF8ToUTF16(job_->fetch_description->title);
}
std::string BackgroundFetchDownload::GetMimeType() {
NOTREACHED();
return {};
}
DownloadError BackgroundFetchDownload::GetError() {
NOTREACHED();
return DownloadError::kNoError;
}
int BackgroundFetchDownload::GetNotificationId() {
return notification_id_;
}
bool BackgroundFetchDownload::IsTransient() {
return true;
}
GURL BackgroundFetchDownload::GetSourceUrl() {
return job_->fetch_description->origin.GetURL();
}
const SkBitmap* BackgroundFetchDownload::GetLargeIcon() {
return &job_->fetch_description->icon;
}
void BackgroundFetchDownload::OnFinished(bool activated) {
if (activated)
controller_->OnUiActivated(job_id_);
controller_->OnUiFinished(job_id_);
// |this| is deleted.
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_download.cc | C++ | unknown | 3,026 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DOWNLOAD_H_
#define WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DOWNLOAD_H_
#include <string>
#include "base/memory/raw_ptr.h"
#include "weblayer/browser/download_impl.h"
namespace background_fetch {
struct JobDetails;
}
namespace weblayer {
class BackgroundFetchDelegateImpl;
// The UI object for an in-progress BackgroundFetch download job.
class BackgroundFetchDownload : public DownloadImpl {
public:
BackgroundFetchDownload(BackgroundFetchDelegateImpl* controller,
const std::string& job_id,
const background_fetch::JobDetails* job);
BackgroundFetchDownload(const BackgroundFetchDownload& other) = delete;
BackgroundFetchDownload& operator=(const BackgroundFetchDownload& other) =
delete;
~BackgroundFetchDownload() override;
// Download implementation:
DownloadState GetState() override;
int64_t GetTotalBytes() override;
int64_t GetReceivedBytes() override;
void Pause() override;
void Resume() override;
void Cancel() override;
base::FilePath GetLocation() override;
std::u16string GetFileNameToReportToUser() override;
std::string GetMimeType() override;
DownloadError GetError() override;
// DownloadImpl:
int GetNotificationId() override;
bool IsTransient() override;
GURL GetSourceUrl() override;
const SkBitmap* GetLargeIcon() override;
void OnFinished(bool activated) override;
private:
raw_ptr<BackgroundFetchDelegateImpl> controller_;
std::string job_id_;
int notification_id_ = 0;
raw_ptr<const background_fetch::JobDetails> job_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_DOWNLOAD_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_download.h | C++ | unknown | 1,881 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/background_fetch/background_fetch_permission_context.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
BackgroundFetchPermissionContext::BackgroundFetchPermissionContext(
content::BrowserContext* browser_context)
: PermissionContextBase(browser_context,
ContentSettingsType::BACKGROUND_FETCH,
blink::mojom::PermissionsPolicyFeature::kNotFound) {
}
ContentSetting BackgroundFetchPermissionContext::GetPermissionStatusInternal(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const GURL& embedding_origin) const {
// Follow the AUTOMATIC_DOWNLOADS setting. TODO(crbug.com/1189247): can this
// be improved upon? It's not really "automatic" if it's in direct response to
// a user action, but WebLayer doesn't implement Chrome's download request
// limiting logic.
auto* host_content_settings_map =
HostContentSettingsMapFactory::GetForBrowserContext(browser_context());
ContentSetting setting = host_content_settings_map->GetContentSetting(
requesting_origin, requesting_origin,
ContentSettingsType::AUTOMATIC_DOWNLOADS);
// Matching Chrome behavior: when the request originates from a non-main frame
// or a service worker, the most permissive we'll allow is ASK. This causes
// the download to start in a paused state.
if (setting == CONTENT_SETTING_ALLOW &&
(!render_frame_host || render_frame_host->GetParent())) {
setting = CONTENT_SETTING_ASK;
}
return setting;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_permission_context.cc | C++ | unknown | 1,990 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_PERMISSION_CONTEXT_H_
#define WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_PERMISSION_CONTEXT_H_
#include "components/content_settings/core/common/content_settings.h"
#include "components/permissions/permission_context_base.h"
class GURL;
namespace weblayer {
// Manages user permissions for Background Fetch. Background Fetch permission
// is currently dynamic and relies on the Automatic Downloads content setting.
class BackgroundFetchPermissionContext
: public permissions::PermissionContextBase {
public:
explicit BackgroundFetchPermissionContext(
content::BrowserContext* browser_context);
BackgroundFetchPermissionContext(
const BackgroundFetchPermissionContext& other) = delete;
BackgroundFetchPermissionContext& operator=(
const BackgroundFetchPermissionContext& other) = delete;
~BackgroundFetchPermissionContext() override = default;
private:
// PermissionContextBase implementation.
ContentSetting GetPermissionStatusInternal(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const GURL& embedding_origin) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_PERMISSION_CONTEXT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_fetch/background_fetch_permission_context.h | C++ | unknown | 1,443 |