Skip to content

Commit

Permalink
Replace some ptr/len APIs in //url with std::string_view
Browse files Browse the repository at this point in the history
This is both safer and more convenient.

Change-Id: Id5ef1701f49c08f39564d977ddf18c8cfe35cb1a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4897456
Commit-Queue: David Benjamin <davidben@chromium.org>
Owners-Override: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1204344}
  • Loading branch information
davidben authored and Chromium LUCI CQ committed Oct 2, 2023
1 parent 9eb9749 commit cc4d2b2
Show file tree
Hide file tree
Showing 45 changed files with 156 additions and 194 deletions.
9 changes: 4 additions & 5 deletions android_webview/renderer/aw_render_frame_ext.cc
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,10 @@ bool RemovePrefixAndAssignIfMatches(const base::StringPiece& prefix,

if (base::StartsWith(spec, prefix)) {
url::RawCanonOutputW<1024> output;
url::DecodeURLEscapeSequences(
spec.data() + prefix.length(), spec.length() - prefix.length(),
url::DecodeURLMode::kUTF8OrIsomorphic, &output);
*dest =
base::UTF16ToUTF8(base::StringPiece16(output.data(), output.length()));
url::DecodeURLEscapeSequences(spec.substr(prefix.length()),
url::DecodeURLMode::kUTF8OrIsomorphic,
&output);
*dest = base::UTF16ToUTF8(output.view());
return true;
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1792,8 +1792,8 @@ class DocumentsProviderTestVolume : public TestVolume {

std::string EncodeURI(const std::string& component) {
url::RawCanonOutputT<char> encoded;
url::EncodeURIComponent(component.c_str(), component.size(), &encoded);
return {encoded.data(), static_cast<size_t>(encoded.length())};
url::EncodeURIComponent(component, &encoded);
return std::string(encoded.view());
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include "base/base64.h"
#include "base/containers/span.h"
#include "base/strings/strcat.h"
#include "components/qr_code_generator/qr_code_generator.h"
#include "url/url_util.h"

Expand Down Expand Up @@ -50,15 +51,13 @@ std::vector<uint8_t> QRCode::GetQRCodeData() {
std::string shared_secret_base64;
base::Base64Encode(shared_secret_str, &shared_secret_base64);
url::RawCanonOutputT<char> shared_secret_base64_uriencoded;
url::EncodeURIComponent(shared_secret_base64.data(),
shared_secret_base64.size(),
url::EncodeURIComponent(shared_secret_base64,
&shared_secret_base64_uriencoded);

std::string url = "https://signin.google/qs/" + advertising_id_.ToString() +
"?key=" +
std::string(shared_secret_base64_uriencoded.data(),
shared_secret_base64_uriencoded.length()) +
"&t=" + std::string(kDeviceTypeQueryParamValue);
std::string url =
base::StrCat({"https://signin.google/qs/", advertising_id_.ToString(),
"?key=", shared_secret_base64_uriencoded.view(),
"&t=", kDeviceTypeQueryParamValue});

return std::vector<uint8_t>(url.begin(), url.end());
}
Expand Down
9 changes: 4 additions & 5 deletions chrome/browser/devtools/devtools_file_helper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -265,14 +265,13 @@ void DevToolsFileHelper::Save(const std::string& url,
if (gurl.is_valid()) {
url::RawCanonOutputW<1024> unescaped_content;
std::string escaped_content = gurl.ExtractFileName();
url::DecodeURLEscapeSequences(
escaped_content.c_str(), escaped_content.length(),
url::DecodeURLMode::kUTF8OrIsomorphic, &unescaped_content);
url::DecodeURLEscapeSequences(escaped_content,
url::DecodeURLMode::kUTF8OrIsomorphic,
&unescaped_content);
// TODO(crbug.com/1324254): Due to filename encoding on Windows we can't
// expect to always be able to convert to UTF8 and back
std::string unescaped_content_string =
base::UTF16ToUTF8(base::StringPiece16(unescaped_content.data(),
unescaped_content.length()));
base::UTF16ToUTF8(unescaped_content.view());
suggested_file_name = unescaped_content_string;
} else {
suggested_file_name = url;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,15 +179,13 @@ history::Cluster GenerateSampleCluster(int64_t cluster_id,

std::string kSampleSearchQuery = "google store products";
url::RawCanonOutputT<char> encoded_query;
url::EncodeURIComponent(kSampleSearchQuery.c_str(),
kSampleSearchQuery.length(), &encoded_query);
url::EncodeURIComponent(kSampleSearchQuery, &encoded_query);
sample_visits.insert(
sample_visits.begin(),
GenerateSampleVisit(
0, kSampleSearchQuery + " - Google Search",
GURL("https://www.google.com/search?q=" +
std::string(encoded_query.data(), encoded_query.length())),
false));
GenerateSampleVisit(0, kSampleSearchQuery + " - Google Search",
GURL("https://www.google.com/search?q=" +
std::string(encoded_query.view())),
false));

return history::Cluster(
cluster_id, sample_visits, {},
Expand Down
20 changes: 8 additions & 12 deletions chrome/browser/safe_browsing/chrome_password_protection_service.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "base/observer_list.h"
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
Expand Down Expand Up @@ -932,18 +933,13 @@ GURL ChromePasswordProtectionService::GetDefaultChangePasswordURL() const {
"password?utm_source=Google&utm_campaign=PhishGuard";
url::RawCanonOutputT<char> percent_encoded_email;
url::RawCanonOutputT<char> percent_encoded_account_url;
url::EncodeURIComponent(account_email.c_str(), account_email.length(),
&percent_encoded_email);
url::EncodeURIComponent(account_url.c_str(), account_url.length(),
&percent_encoded_account_url);
GURL change_password_url = GURL(base::StringPrintf(
"https://accounts.google.com/"
"AccountChooser?Email=%s&continue=%s",
std::string(percent_encoded_email.data(), percent_encoded_email.length())
.c_str(),
std::string(percent_encoded_account_url.data(),
percent_encoded_account_url.length())
.c_str()));
url::EncodeURIComponent(account_email, &percent_encoded_email);
url::EncodeURIComponent(account_url, &percent_encoded_account_url);
GURL change_password_url =
GURL(base::StrCat({"https://accounts.google.com/"
"AccountChooser?Email=",
percent_encoded_email.view(),
"&continue=", percent_encoded_account_url.view()}));
return google_util::AppendGoogleLocaleParam(
change_password_url, g_browser_process->GetApplicationLocale());
}
Expand Down
5 changes: 2 additions & 3 deletions chrome/browser/sharing/click_to_call/click_to_call_utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,10 @@ absl::optional<std::string> ExtractPhoneNumber(
std::string GetUnescapedURLContent(const GURL& url) {
std::string content_string(url.GetContent());
url::RawCanonOutputT<char16_t> unescaped_content;
url::DecodeURLEscapeSequences(content_string.data(), content_string.size(),
url::DecodeURLEscapeSequences(content_string,
url::DecodeURLMode::kUTF8OrIsomorphic,
&unescaped_content);
return base::UTF16ToUTF8(
std::u16string(unescaped_content.data(), unescaped_content.length()));
return base::UTF16ToUTF8(unescaped_content.view());
}

} // namespace
Expand Down
4 changes: 2 additions & 2 deletions chrome/browser/ssl/ssl_browsertest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -353,8 +353,8 @@ class ChromeContentBrowserClientForMixedContentTest

std::string EncodeQuery(const std::string& query) {
url::RawCanonOutputT<char> buffer;
url::EncodeURIComponent(query.data(), query.size(), &buffer);
return std::string(buffer.data(), buffer.length());
url::EncodeURIComponent(query, &buffer);
return std::string(buffer.view());
}

// Returns the Sha256 hash of the SPKI of |cert|.
Expand Down
8 changes: 3 additions & 5 deletions chrome/browser/ui/chrome_pages.cc
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,9 @@ void ShowSiteSettingsImpl(Browser* browser, Profile* profile, const GURL& url) {
url.SchemeIs(chrome::kIsolatedAppScheme))) {
std::string origin_string = site_origin.Serialize();
url::RawCanonOutputT<char> percent_encoded_origin;
url::EncodeURIComponent(origin_string.c_str(), origin_string.length(),
&percent_encoded_origin);
link_destination = chrome::kChromeUISiteDetailsPrefixURL +
std::string(percent_encoded_origin.data(),
percent_encoded_origin.length());
url::EncodeURIComponent(origin_string, &percent_encoded_origin);
link_destination = base::StrCat(
{chrome::kChromeUISiteDetailsPrefixURL, percent_encoded_origin.view()});
}
NavigateParams params(profile, GURL(link_destination),
ui::PAGE_TRANSITION_TYPED);
Expand Down
5 changes: 2 additions & 3 deletions chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc
Original file line number Diff line number Diff line change
Expand Up @@ -988,14 +988,13 @@ void NewTabPageUI::OnCustomBackgroundImageUpdated() {
: absl::optional<CustomBackground>())
.value_or(CustomBackground())
.custom_background_url;
url::EncodeURIComponent(custom_background_url.spec().c_str(),
custom_background_url.spec().size(), &encoded_url);
url::EncodeURIComponent(custom_background_url.spec(), &encoded_url);
update.Set(
"backgroundImageUrl",
encoded_url.length() > 0
? base::StrCat(
{"chrome-untrusted://new-tab-page/custom_background_image?url=",
std::string(encoded_url.data(), encoded_url.length())})
encoded_url.view()})
: "");
content::WebUIDataSource::Update(profile_, chrome::kChromeUINewTabPageHost,
std::move(update));
Expand Down
9 changes: 4 additions & 5 deletions chrome/browser/ui/webui/new_tab_page/untrusted_source.cc
Original file line number Diff line number Diff line change
Expand Up @@ -153,17 +153,16 @@ void UntrustedSource::StartDataRequest(
if (path == "custom_background_image") {
// Parse all query parameters to hash map and decode values.
std::unordered_map<std::string, std::string> params;
url::Component query(0, url.query().length());
url::Component query(0, url.query_piece().length());
url::Component key, value;
while (
url::ExtractQueryKeyValue(url.query().c_str(), &query, &key, &value)) {
url::RawCanonOutputW<kMaxUriDecodeLen> output;
url::DecodeURLEscapeSequences(
url.query().c_str() + value.begin, value.len,
url.query_piece().substr(value.begin, value.len),
url::DecodeURLMode::kUTF8OrIsomorphic, &output);
params.insert(
{url.query().substr(key.begin, key.len),
base::UTF16ToUTF8(std::u16string(output.data(), output.length()))});
params.insert({std::string(url.query_piece().substr(key.begin, key.len)),
base::UTF16ToUTF8(output.view())});
}
// Extract desired values.
ServeBackgroundImage(
Expand Down
14 changes: 6 additions & 8 deletions chrome/browser/ui/webui/sanitized_image_source.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <map>
#include <memory>
#include <string>
#include <string_view>

#include "base/containers/contains.h"
#include "base/memory/ref_counted_memory.h"
Expand Down Expand Up @@ -51,22 +52,19 @@ constexpr char kIsGooglePhotosKey[] = "isGooglePhotos";
constexpr char kStaticEncodeKey[] = "staticEncode";
constexpr char kUrlKey[] = "url";

std::map<std::string, std::string> ParseParams(
const std::string& param_string) {
std::map<std::string, std::string> ParseParams(std::string_view param_string) {
url::Component query(0, param_string.size());
url::Component key;
url::Component value;
constexpr int kMaxUriDecodeLen = 2048;
std::map<std::string, std::string> params;
while (
url::ExtractQueryKeyValue(param_string.c_str(), &query, &key, &value)) {
while (url::ExtractQueryKeyValue(param_string.data(), &query, &key, &value)) {
url::RawCanonOutputW<kMaxUriDecodeLen> output;
url::DecodeURLEscapeSequences(param_string.c_str() + value.begin, value.len,
url::DecodeURLEscapeSequences(param_string.substr(value.begin, value.len),
url::DecodeURLMode::kUTF8OrIsomorphic,
&output);
params.insert({param_string.substr(key.begin, key.len),
base::UTF16ToUTF8(
base::StringPiece16(output.data(), output.length()))});
params.insert({std::string(param_string.substr(key.begin, key.len)),
base::UTF16ToUTF8(output.view())});
}
return params;
}
Expand Down
19 changes: 8 additions & 11 deletions chrome/browser/ui/webui/sanitized_image_source_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,12 @@ TEST_F(SanitizedImageSourceTest, GooglePhotosImage) {

// Encode a URL so that it can be used as a param value.
url::RawCanonOutputT<char> encoded_url;
url::EncodeURIComponent(kImageUrl, std::size(kImageUrl), &encoded_url);
url::EncodeURIComponent(kImageUrl, &encoded_url);
EXPECT_GT(encoded_url.length(), 0u);
base::StringPiece encoded_url_str(encoded_url.data(), encoded_url.length());

// Verify that param-formatted requests can be sent with auth tokens.
sanitized_image_source_->StartDataRequest(
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url_str,
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url.view(),
"&isGooglePhotos=true"})),
content::WebContents::Getter(), callback.Get());
ASSERT_EQ(1, test_url_loader_factory_.NumPending());
Expand All @@ -228,7 +227,7 @@ TEST_F(SanitizedImageSourceTest, GooglePhotosImage) {

// Verify that param-formatted requests can be sent without auth tokens.
sanitized_image_source_->StartDataRequest(
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url_str,
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url.view(),
"&isGooglePhotos=false"})),
content::WebContents::Getter(), callback.Get());
EXPECT_FALSE(identity_test_env.IsAccessTokenRequestPending());
Expand All @@ -238,7 +237,8 @@ TEST_F(SanitizedImageSourceTest, GooglePhotosImage) {
net::HttpRequestHeaders::kAuthorization));

sanitized_image_source_->StartDataRequest(
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url_str})),
GURL(base::StrCat(
{chrome::kChromeUIImageURL, "?url=", encoded_url.view()})),
content::WebContents::Getter(), callback.Get());
EXPECT_FALSE(identity_test_env.IsAccessTokenRequestPending());

Expand All @@ -249,7 +249,7 @@ TEST_F(SanitizedImageSourceTest, GooglePhotosImage) {

// Verify that no download is attempted when authentication fails.
sanitized_image_source_->StartDataRequest(
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url_str,
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=", encoded_url.view(),
"&isGooglePhotos=true"})),
content::WebContents::Getter(), callback.Get());
ASSERT_EQ(4, test_url_loader_factory_.NumPending());
Expand All @@ -262,15 +262,12 @@ TEST_F(SanitizedImageSourceTest, GooglePhotosImage) {
// Verify that no auth token is sent for URLs not served by Google Photos.
constexpr char kBadImageUrl[] = "https://foo.com/img.png";
url::RawCanonOutputT<char> encoded_bad_url;
url::EncodeURIComponent(kBadImageUrl, std::size(kBadImageUrl),
&encoded_bad_url);
url::EncodeURIComponent(kBadImageUrl, &encoded_bad_url);
EXPECT_GT(encoded_bad_url.length(), 0u);
base::StringPiece encoded_bad_url_str(encoded_bad_url.data(),
encoded_bad_url.length());

sanitized_image_source_->StartDataRequest(
GURL(base::StrCat({chrome::kChromeUIImageURL, "?url=",
encoded_bad_url_str, "&isGooglePhotos=true"})),
encoded_bad_url.view(), "&isGooglePhotos=true"})),
content::WebContents::Getter(), callback.Get());
EXPECT_FALSE(identity_test_env.IsAccessTokenRequestPending());
ASSERT_EQ(5, test_url_loader_factory_.NumPending());
Expand Down
4 changes: 2 additions & 2 deletions chrome/test/base/devtools_listener.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ base::StringPiece SpanToStringPiece(const base::span<const uint8_t>& s) {

std::string EncodeURIComponent(const std::string& component) {
url::RawCanonOutputT<char> encoded;
url::EncodeURIComponent(component.c_str(), component.size(), &encoded);
return {encoded.data(), static_cast<size_t>(encoded.length())};
url::EncodeURIComponent(component, &encoded);
return std::string(encoded.view());
}

} // namespace
Expand Down
6 changes: 2 additions & 4 deletions chrome/test/chromedriver/server/http_handler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1705,10 +1705,8 @@ bool MatchesCommand(const std::string& method,
CHECK(name.length());
url::RawCanonOutputT<char16_t> output;
url::DecodeURLEscapeSequences(
path_parts[i].data(), path_parts[i].length(),
url::DecodeURLMode::kUTF8OrIsomorphic, &output);
std::string decoded =
base::UTF16ToASCII(std::u16string(output.data(), output.length()));
path_parts[i], url::DecodeURLMode::kUTF8OrIsomorphic, &output);
std::string decoded = base::UTF16ToASCII(output.view());
// Due to crbug.com/533361, the url decoding libraries decodes all of the
// % escape sequences except for %%. We need to handle this case manually.
// So, replacing all the instances of "%%" with "%".
Expand Down
11 changes: 6 additions & 5 deletions components/arc/common/intent_helper/link_handler_model.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include "components/arc/common/intent_helper/link_handler_model.h"

#include <string_view>
#include <utility>

#include "base/functional/bind.h"
Expand All @@ -28,25 +29,25 @@ namespace {
constexpr int kMaxValueLen = 2048;

bool GetQueryValue(const GURL& url,
const std::string& key_to_find,
std::string_view key_to_find,
std::u16string* out) {
const std::string str(url.query());
const std::string_view str = url.query_piece();

url::Component query(0, str.length());
url::Component key;
url::Component value;

while (url::ExtractQueryKeyValue(str.c_str(), &query, &key, &value)) {
while (url::ExtractQueryKeyValue(str.data(), &query, &key, &value)) {
if (value.is_empty())
continue;
if (str.substr(key.begin, key.len) == key_to_find) {
if (value.len >= kMaxValueLen)
return false;
url::RawCanonOutputW<kMaxValueLen> output;
url::DecodeURLEscapeSequences(str.c_str() + value.begin, value.len,
url::DecodeURLEscapeSequences(str.substr(value.begin, value.len),
url::DecodeURLMode::kUTF8OrIsomorphic,
&output);
*out = std::u16string(output.data(), output.length());
*out = std::u16string(output.view());
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ bool CanonicalizeHashComponent(const base::StringPiece& input_hash,
CanonicalizeBase64Padding(&base64_encoded_hash) &&
ContainsOnlyAlphanumericAnd(base64_encoded_hash,
kBase64NonAlphanumericChars)) {
canonical_output->Append(base64_encoded_hash.data(),
base64_encoded_hash.size());
canonical_output->Append(base64_encoded_hash);
canonical_output->push_back('@');
return true;
}
Expand All @@ -127,7 +126,7 @@ bool CanonicalizePackageNameComponent(
if (!package_name.empty() &&
ContainsOnlyAlphanumericAnd(package_name,
kPackageNameNonAlphanumericChars)) {
canonical_output->Append(package_name.data(), package_name.size());
canonical_output->Append(package_name);
return true;
}
return false;
Expand Down
Loading

0 comments on commit cc4d2b2

Please sign in to comment.