electron/shell/common/gin_converters/net_converter.cc
electron-roller[bot] 3da598015b
chore: bump chromium to 100.0.4894.0 (main) (#32852)
* chore: bump chromium in DEPS to 100.0.4880.0

* resolve conflicts

* chore: update patches

* fix patch

* PIP20: add a new DocumentOverlayWindowViews subtype

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

* Clean up PictureInPictureWindowManager::EnterPictureInPicture()

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

* Remove StoragePartitionId.

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

* Remove FLoC code

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

* media: Make AddSupportedKeySystems() Async

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

* [Extensions] Move some l10n file util methods to //extensions/browser

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

* chore: IWYU

* Reland "webhid: Grant permissions for policy-allowed devices"

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

* Migrate base::Value::GetList() to base::Value::GetListDeprecated(): 2/N.

https://chromium-review.googlesource.com/c/chromium/src/+/3435727
https://chromium-review.googlesource.com/c/chromium/src/+/3440910
https://chromium-review.googlesource.com/c/chromium/src/+/3440088

* [text blink period] Cache blink period instead of fetching from defaults

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

* chore: update picture-in-picture.patch

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

* ci: update to Xcode 13.2.1

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

* chore: bump chromium in DEPS to 100.0.4882.1

* chore: update patches

* chore: bump chromium in DEPS to 100.0.4884.0

* chore: update patches

* chore: bump chromium in DEPS to 100.0.4886.0

* chore: update patches

* Refactor DownloadManager to use StoragePartitionConfig

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

* Remove ToWebInputElement() in favor of new WebNode::DynamicTo<> helpers.

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

* refactor: autofill to use the color pipeline

https://bugs.chromium.org/p/chromium/issues/detail?id=1249558
https://bugs.chromium.org/p/chromium/issues/detail?id=1003612

* [ProcessSingleton] Add many more trace events to cover all scenarios

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

* fixup! PIP20: add a new DocumentOverlayWindowViews subtype

* chore: bump chromium in DEPS to 100.0.4888.0

* chore: update patches

* chore: update picture-in-picture.patch

* fixup! refactor: autofill to use the color pipeline

* ci: fixup fix sync

(cherry picked from commit c1e3e395465739bce5ca8e1c5ec1f5bd72b99ebd)

* chore: bump chromium in DEPS to 100.0.4889.0

* chore: update patches

* chore: fix feat_add_data_transfer_to_requestsingleinstancelock.patch

* fixup! PIP20: add a new DocumentOverlayWindowViews subtype

* Remove remaining NativeTheme::GetSystemColor() machinery.

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

* ci: fetch proper esbuild for macos

* ci: fixup fetch proper esbuild for macos

* fix: failing Node.js test on outdated CurrentValueSerializerFormatVersion

* chore: bump chromium in DEPS to 100.0.4892.0

* 3460365: Set V8 fatal error callbacks during Isolate initialization

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

* 3454343: PIP20: use permanent top controls

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

* 3465574: Move most of GTK color mixers to ui/color/.

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

* chore: fixup patch indices

* 3445327: [locales] Remove locales reference

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

* 3456548: [DBB][#7] Blue border falls back to all tab if cropped-to zero pixels

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

* 3441196: Convert GuestView's remaining legacy IPC messages to Mojo

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

* 3455491: Don't include run_loop.h in thread_task_runner_handle.h

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

* fixup! 3454343: PIP20: use permanent top controls

* 3442501: Add missing includes of //base/observer_list.h

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

* 3437552: mac: Deploy a new hermetic build of Xcode 13.2.1 13C100

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

* chore: bump chromium in DEPS to 100.0.4894.0

* fixup! 3460365: Set V8 fatal error callbacks during Isolate initialization

* chore: update patches

* 3425231: Use DnsOverHttpsConfig where appropriate

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

* test: disable test-heapsnapshot-near-heap-limit-worker.js

As a result of CLs linked in https://bugs.chromium.org/p/v8/issues/detail?id=12503,
heap snapshotting near the heap limit DCHECKS in Node.js specs. This will
likely require a larger refactor in Node.js so i've disabled the test for
now and opened an upstream issue on node-v8 issue
at https://github.com/nodejs/node-v8/issues/218.

* Port all usage of NativeTheme color IDs to color pipeline

https://bugs.chromium.org/p/chromium/issues/detail?id=1249558

* chore: update patches after rebase

* ci: use gen2 machine for more disk space

* ci: don't try to make root volume writeable

* ci: use older xcode/macos for tests

* fix: html fullscreen transitions stacking

(cherry picked from commit 5e10965cdd7b2a024def5fc568912cefd0f05b44)

* ci: speed up woa testing

(cherry picked from commit 75c33c48b032137794f5734348a9ee3daa60d9de)
(cherry picked from commit e81996234029669663bf0daaababd34684dcbb17)

* ci: disable flaky tests on WOA

* ci: run remote tests separately to isolate issue there

* tests: disable node test parallel/test-worker-debug for now

* revert: fix: html fullscreen transitions stacking

* tests: disable flaky test on macOS arm64

* fixup circleci config so build tools can find xcode version

* make sure the workspace is clean before job runs

(cherry picked from commit 75f713c9748ac1a356846c39f268886130554fd6)

* tests: disable flaky test on Linux

* ci: debug why windows i32 is crashing

* Revert "ci: debug why windows i32 is crashing"

This reverts commit 4c4bba87ea76f16ef3b304dadff59ad4d366f60f.

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
2022-02-25 13:17:35 -05:00

408 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->GetListDeprecated().size(); ++i) {
base::DictionaryValue* dict = nullptr;
std::string type;
if (!list->GetDictionary(i, &dict))
return false;
dict->GetString("type", &type);
if (type == "rawData") {
const base::Value::BlobStorage* bytes = dict->FindBlobKey("bytes");
(*out)->AppendBytes(reinterpret_cast<const char*>(bytes->data()),
base::checked_cast<int>(bytes->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;
absl::optional<double> maybe_modification_time =
dict->FindDoubleKey("modificationTime");
if (maybe_modification_time.has_value())
modification_time = maybe_modification_time.value();
dict->GetInteger("offset", &offset);
dict->GetInteger("file", &length);
(*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