electron/shell/common/gin_converters/net_converter.cc
electron-roller[bot] 5513e66982
chore: bump chromium to 95.0.4612.5 (main) (#30503)
* chore: bump chromium in DEPS to 94.0.4604.0

* build: 3-way merge of chromium patches

* chore: bump chromium in DEPS to 94.0.4605.0

* build: 3-way merge of chromium patches

* 3076040: Reland Remove delete_children RemoveAllChildViews arg

Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3076040

* 3069287: Remove the remaining uses and delete the deprecated API

Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3069287

* 2297212: Replace RemoveWithoutPathExpansion(.*, nullptr) with Value::RemoveKey()

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2297212

Also: https://chromium-review.googlesource.com/c/chromium/src/+/3060296

* 3082756: Change transport_security_persister_path param to be a path to a file.

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3082756

> this CL intentionally changes the name of the parameter
> in the network context parameters and the order of the constructor
> parameters to ensure all callers update their code to pass a full
> file path rather than a path to a directory.

The 'path' in this diff is already an absolute path, coming from
`CHECK(base::PathService::Get(chrome::DIR_USER_DATA, &path_));` at
08ff1c2cbf/shell/browser/electron_browser_context.cc (L126)

* iwyu: network::mojom::HttpRawHeaderPair

* fixup! 3076040: Reland Remove delete_children RemoveAllChildViews arg

Missed one.

* 2999884: CodeHealth: Remove DictionaryValue::GetStringWithoutPathExpansion

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2999884
(example of replacing GetStringWithoutPathExpansion() w/FindStringKey())

Also: https://chromium-review.googlesource.com/c/chromium/src/+/3060296
(removal of DictionaryValue::GetStringWithoutPathExpansion)

* 3059260: Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3059260

We had both of these in a 'disable_features' list. Since these feature have
been removed upstream, remove them from our disable list, too.

IMPORTANT: this commit should not be backported to older branches that
still have these features, because doing so would un-disable them.

* 2920890: Load reroute_info from download in-progress and history db back into DownloadItem.

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/2920890

* 3039323: [Clipboard API] Clipboard Custom Formats implementation Part 5.

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3039323

* chore: bump chromium in DEPS to 94.0.4606.0

* 3084502: Add a new PrintRasterizePdfDpi policy.

Refs: https://chromium-review.googlesource.com/c/chromium/src/+/3084502

* chore: update patches

* chore: bump chromium in DEPS to 94.0.4606.3

* chore: bump chromium in DEPS to 95.0.4608.0

* chore: bump chromium in DEPS to 95.0.4609.0

* [DevTools] Remove report_raw_headers from network::ResourceRequest

https://chromium-review.googlesource.com/c/chromium/src/+/2856099

* Remove content::WebContentsObserver::OnInterfaceRequestFromFrame

https://chromium-review.googlesource.com/c/chromium/src/+/3092665

* Disable kDesktopCaptureMacV2

https://chromium-review.googlesource.com/c/chromium/src/+/3069272

* Add a new PrintRasterizePdfDpi policy.

https://chromium-review.googlesource.com/c/chromium/src/+/3084502

* chore: update patches

* chore: bump chromium in DEPS to 95.0.4609.3

* disable `use_lld` for macos

* chore: update patches

* Linux: use chrome_crashpad_handler instead of crashpad_handler

https://chromium-review.googlesource.com/c/chromium/src/+/3054290

* chore: fix lint

* Revert "[DevTools] Remove report_raw_headers from network::ResourceRequest"

This reverts commit 28f4da1582d046e96cb58f3cbb590503e89dfd0d.

* [DevTools] Remove report_raw_headers from network::ResourceRequest (Attempt #2)

https://chromium-review.googlesource.com/c/chromium/src/+/2856099

* DCHECK that predictor always has a non-empty NetworkIsolationKey.

https://chromium-review.googlesource.com/c/chromium/src/+/3067698

* Remove --no-untrusted-code-mitigations from //content and //gin

https://chromium-review.googlesource.com/c/chromium/src/+/3096585

* fixup! Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure

https://chromium-review.googlesource.com/c/chromium/src/+/3059260

* fixup! Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure

* Convert PrintManager to RenderFrameHostReceiverSet.

https://chromium-review.googlesource.com/c/chromium/src/+/3072019

* chore: bump chromium in DEPS to 95.0.4612.5

* chore: disable v8 oilpan

* [Compiler] Remove untrusted code mitigations.

https://chromium-review.googlesource.com/c/v8/v8/+/3045704

* Remove most FTP logic from services/network.

https://chromium-review.googlesource.com/c/chromium/src/+/3076119

* Rename scale_factor.h -> resource_scale_factor.h

https://chromium-review.googlesource.com/c/chromium/src/+/3057113

* [GURL -> SiteForCookies] extensions/

https://chromium-review.googlesource.com/c/chromium/src/+/3100825

* breadcrumbs: add desktop entry point

https://chromium-review.googlesource.com/c/chromium/src/+/3021746

* Move args_ to private in ExtensionFunction

https://chromium-review.googlesource.com/c/chromium/src/+/3076261

* chore: iwyu

* fixup! Remove kSameSiteByDefaultCookies and kCookiesWithoutSameSiteMustBeSecure

* Disable kDesktopCaptureMacV2

https://chromium-review.googlesource.com/c/chromium/src/+/3069272

* fixup! [Compiler] Remove untrusted code mitigations.

* fixup! Disable kDesktopCaptureMacV2

* Revert "chore: disable v8 oilpan"

This reverts commit 5d255cf1d8e8efbb906047937a713279e5f800d0.

* Reland "chore: disable v8 oilpan"

This reverts commit 1c252765b07a205560e7b5eed06de2605336e2d8.

The previous revert was to test on which platforms did the
heapsnapshot test actually fail.

* [Clipboard API] Clipboard Custom Formats implementation Part 5.

https://chromium-review.googlesource.com/c/chromium/src/+/3039323

* Convert ExtensionFrameHost to RenderFrameHostReceiverSet.

https://chromium-review.googlesource.com/c/chromium/src/+/3063358

* Convert PDFWebContentsHelper to RenderFrameHostReceiverSet.

https://chromium-review.googlesource.com/c/chromium/src/+/3049751

* [Underscore Migration] Migrate ui/legacy

https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3093160

* chore: remove unknown permission error

* chore: fix lint

* chore: ignore -Wunreachable-code-return for node deps/

* fixup! chore: ignore -Wunreachable-code-return for node deps/

* fix: windows build

* fix: build dependency

Dependency was missed in cbeae20438

* 3108669: arm,dsp: Fix 8bpp Dct64_NEON().

https://chromium-review.googlesource.com/c/codecs/libgav1/+/3108669

* chore: revert libgav1 roll

* Revert "3108669: arm,dsp: Fix 8bpp Dct64_NEON()."

This reverts commit 7ed31323127aac8ba2eaff9cae6c9be9a4954f33.

* Revert "chore: revert libgav1 roll"

This reverts commit 084a490d298811267316c786762fe7aa91b6318d.

* chore: revert clang roll

* chore:  Fix -Wunreachable-code-aggressive warnings in arm and arm64 code

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
Co-authored-by: mlaurencin <mlaurencin@electronjs.org>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
2021-08-23 20:52:17 -04:00

407 lines
14 KiB
C++

// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/gin_converters/net_converter.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/span.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "gin/converter.h"
#include "gin/dictionary.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_version.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/cpp/resource_request.h"
#include "shell/browser/api/electron_api_data_pipe_holder.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/std_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/node_includes.h"
namespace gin {
namespace {
bool CertFromData(const std::string& data,
scoped_refptr<net::X509Certificate>* out) {
auto cert_list = net::X509Certificate::CreateCertificateListFromBytes(
base::as_bytes(base::make_span(data)),
net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
if (cert_list.empty())
return false;
auto leaf_cert = cert_list.front();
if (!leaf_cert)
return false;
*out = leaf_cert;
return true;
}
} // namespace
// static
v8::Local<v8::Value> Converter<net::AuthChallengeInfo>::ToV8(
v8::Isolate* isolate,
const net::AuthChallengeInfo& val) {
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("isProxy", val.is_proxy);
dict.Set("scheme", val.scheme);
dict.Set("host", val.challenger.host());
dict.Set("port", static_cast<uint32_t>(val.challenger.port()));
dict.Set("realm", val.realm);
return gin::ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
v8::Isolate* isolate,
const scoped_refptr<net::X509Certificate>& val) {
gin::Dictionary dict(isolate, v8::Object::New(isolate));
std::string encoded_data;
net::X509Certificate::GetPEMEncoded(val->cert_buffer(), &encoded_data);
dict.Set("data", encoded_data);
dict.Set("issuer", val->issuer());
dict.Set("issuerName", val->issuer().GetDisplayName());
dict.Set("subject", val->subject());
dict.Set("subjectName", val->subject().GetDisplayName());
dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
val->serial_number().size()));
dict.Set("validStart", val->valid_start().ToDoubleT());
dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
dict.Set("fingerprint",
net::HashValue(val->CalculateFingerprint256(val->cert_buffer()))
.ToString());
const auto& intermediate_buffers = val->intermediate_buffers();
if (!intermediate_buffers.empty()) {
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> issuer_intermediates;
issuer_intermediates.reserve(intermediate_buffers.size() - 1);
for (size_t i = 1; i < intermediate_buffers.size(); ++i) {
issuer_intermediates.push_back(
bssl::UpRef(intermediate_buffers[i].get()));
}
const scoped_refptr<net::X509Certificate>& issuer_cert =
net::X509Certificate::CreateFromBuffer(
bssl::UpRef(intermediate_buffers[0].get()),
std::move(issuer_intermediates));
dict.Set("issuerCert", issuer_cert);
}
return ConvertToV8(isolate, dict);
}
bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
scoped_refptr<net::X509Certificate>* out) {
gin::Dictionary dict(nullptr);
if (!ConvertFromV8(isolate, val, &dict))
return false;
std::string data;
dict.Get("data", &data);
scoped_refptr<net::X509Certificate> leaf_cert;
if (!CertFromData(data, &leaf_cert))
return false;
scoped_refptr<net::X509Certificate> issuer_cert;
if (dict.Get("issuerCert", &issuer_cert)) {
std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
intermediates.push_back(bssl::UpRef(issuer_cert->cert_buffer()));
auto cert = net::X509Certificate::CreateFromBuffer(
bssl::UpRef(leaf_cert->cert_buffer()), std::move(intermediates));
if (!cert)
return false;
*out = cert;
} else {
*out = leaf_cert;
}
return true;
}
// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
v8::Isolate* isolate,
const net::CertPrincipal& val) {
gin::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("commonName", val.common_name);
dict.Set("organizations", val.organization_names);
dict.Set("organizationUnits", val.organization_unit_names);
dict.Set("locality", val.locality_name);
dict.Set("state", val.state_or_province_name);
dict.Set("country", val.country_name);
return ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
base::Value* values = response_headers.FindListKey(key);
if (!values)
values = response_headers.SetKey(key, base::ListValue());
values->Append(value);
}
}
return ConvertToV8(isolate, response_headers);
}
bool Converter<net::HttpResponseHeaders*>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::HttpResponseHeaders* out) {
if (!val->IsObject()) {
return false;
}
auto addHeaderFromValue = [&isolate, &out](
const std::string& key,
const v8::Local<v8::Value>& localVal) {
auto context = isolate->GetCurrentContext();
v8::Local<v8::String> localStrVal;
if (!localVal->ToString(context).ToLocal(&localStrVal)) {
return false;
}
std::string value;
gin::ConvertFromV8(isolate, localStrVal, &value);
out->AddHeader(key, value);
return true;
};
auto context = isolate->GetCurrentContext();
auto headers = val.As<v8::Object>();
auto keys = headers->GetOwnPropertyNames(context).ToLocalChecked();
for (uint32_t i = 0; i < keys->Length(); i++) {
v8::Local<v8::Value> keyVal;
if (!keys->Get(context, i).ToLocal(&keyVal)) {
return false;
}
std::string key;
gin::ConvertFromV8(isolate, keyVal, &key);
auto localVal = headers->Get(context, keyVal).ToLocalChecked();
if (localVal->IsArray()) {
auto values = localVal.As<v8::Array>();
for (uint32_t j = 0; j < values->Length(); j++) {
if (!addHeaderFromValue(key,
values->Get(context, j).ToLocalChecked())) {
return false;
}
}
} else {
if (!addHeaderFromValue(key, localVal)) {
return false;
}
}
}
return true;
}
// static
v8::Local<v8::Value> Converter<net::HttpRequestHeaders>::ToV8(
v8::Isolate* isolate,
const net::HttpRequestHeaders& val) {
gin::Dictionary headers(isolate, v8::Object::New(isolate));
for (net::HttpRequestHeaders::Iterator it(val); it.GetNext();)
headers.Set(it.name(), it.value());
return ConvertToV8(isolate, headers);
}
// static
bool Converter<net::HttpRequestHeaders>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::HttpRequestHeaders* out) {
base::DictionaryValue dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
for (base::DictionaryValue::Iterator it(dict); !it.IsAtEnd(); it.Advance()) {
if (it.value().is_string()) {
std::string value = it.value().GetString();
out->SetHeader(it.key(), value);
}
}
return true;
}
// static
v8::Local<v8::Value> Converter<network::ResourceRequestBody>::ToV8(
v8::Isolate* isolate,
const network::ResourceRequestBody& val) {
const auto& elements = *val.elements();
v8::Local<v8::Array> arr = v8::Array::New(isolate, elements.size());
for (size_t i = 0; i < elements.size(); ++i) {
const auto& element = elements[i];
gin::Dictionary upload_data(isolate, v8::Object::New(isolate));
switch (element.type()) {
case network::mojom::DataElement::Tag::kFile: {
const auto& element_file = element.As<network::DataElementFile>();
upload_data.Set("type", "file");
upload_data.Set("file", element_file.path().value());
upload_data.Set("filePath",
base::Value(element_file.path().AsUTF8Unsafe()));
upload_data.Set("offset", static_cast<int>(element_file.offset()));
upload_data.Set("length", static_cast<int>(element_file.length()));
upload_data.Set("modificationTime",
element_file.expected_modification_time().ToDoubleT());
break;
}
case network::mojom::DataElement::Tag::kBytes: {
upload_data.Set("type", "rawData");
const auto& bytes = element.As<network::DataElementBytes>().bytes();
const char* data = reinterpret_cast<const char*>(bytes.data());
upload_data.Set(
"bytes",
node::Buffer::Copy(isolate, data, bytes.size()).ToLocalChecked());
break;
}
case network::mojom::DataElement::Tag::kDataPipe: {
upload_data.Set("type", "blob");
// TODO(zcbenz): After the NetworkService refactor, the old blobUUID API
// becomes unnecessarily complex, we should deprecate the getBlobData
// API and return the DataPipeHolder wrapper directly.
auto holder = electron::api::DataPipeHolder::Create(isolate, element);
upload_data.Set("blobUUID", holder->id());
// The lifetime of data pipe is bound to the uploadData object.
upload_data.Set("dataPipe", holder);
break;
}
default:
NOTREACHED() << "Found unsupported data element";
}
arr->Set(isolate->GetCurrentContext(), static_cast<uint32_t>(i),
ConvertToV8(isolate, upload_data))
.Check();
}
return arr;
}
// static
v8::Local<v8::Value>
Converter<scoped_refptr<network::ResourceRequestBody>>::ToV8(
v8::Isolate* isolate,
const scoped_refptr<network::ResourceRequestBody>& val) {
if (!val)
return v8::Null(isolate);
return ConvertToV8(isolate, *val);
}
// static
bool Converter<scoped_refptr<network::ResourceRequestBody>>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
scoped_refptr<network::ResourceRequestBody>* out) {
auto list = std::make_unique<base::ListValue>();
if (!ConvertFromV8(isolate, val, list.get()))
return false;
*out = base::MakeRefCounted<network::ResourceRequestBody>();
for (size_t i = 0; i < list->GetSize(); ++i) {
base::DictionaryValue* dict = nullptr;
std::string type;
if (!list->GetDictionary(i, &dict))
return false;
dict->GetString("type", &type);
if (type == "rawData") {
base::Value* bytes = nullptr;
dict->GetBinary("bytes", &bytes);
(*out)->AppendBytes(
reinterpret_cast<const char*>(bytes->GetBlob().data()),
base::checked_cast<int>(bytes->GetBlob().size()));
} else if (type == "file") {
const std::string* file = dict->FindStringKey("filePath");
if (file == nullptr) {
return false;
}
int offset = 0, length = -1;
double modification_time = 0.0;
dict->GetInteger("offset", &offset);
dict->GetInteger("file", &length);
dict->GetDouble("modificationTime", &modification_time);
(*out)->AppendFileRange(base::FilePath::FromUTF8Unsafe(*file),
static_cast<uint64_t>(offset),
static_cast<uint64_t>(length),
base::Time::FromDoubleT(modification_time));
}
}
return true;
}
// static
v8::Local<v8::Value> Converter<network::ResourceRequest>::ToV8(
v8::Isolate* isolate,
const network::ResourceRequest& val) {
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("method", val.method);
dict.Set("url", val.url.spec());
dict.Set("referrer", val.referrer.spec());
dict.Set("headers", val.headers);
if (val.request_body)
dict.Set("uploadData", ConvertToV8(isolate, *val.request_body));
return ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<electron::VerifyRequestParams>::ToV8(
v8::Isolate* isolate,
electron::VerifyRequestParams val) {
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("hostname", val.hostname);
dict.Set("certificate", val.certificate);
dict.Set("validatedCertificate", val.validated_certificate);
dict.Set("isIssuedByKnownRoot", val.is_issued_by_known_root);
dict.Set("verificationResult", val.default_result);
dict.Set("errorCode", val.error_code);
return ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<net::HttpVersion>::ToV8(
v8::Isolate* isolate,
const net::HttpVersion& val) {
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("major", static_cast<uint32_t>(val.major_value()));
dict.Set("minor", static_cast<uint32_t>(val.minor_value()));
return ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<net::RedirectInfo>::ToV8(
v8::Isolate* isolate,
const net::RedirectInfo& val) {
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("statusCode", val.status_code);
dict.Set("newMethod", val.new_method);
dict.Set("newUrl", val.new_url);
dict.Set("newSiteForCookies", val.new_site_for_cookies.RepresentativeUrl());
dict.Set("newReferrer", val.new_referrer);
dict.Set("insecureSchemeWasUpgraded", val.insecure_scheme_was_upgraded);
dict.Set("isSignedExchangeFallbackRedirect",
val.is_signed_exchange_fallback_redirect);
return ConvertToV8(isolate, dict);
}
} // namespace gin