electron/shell/common/gin_converters/net_converter.cc
Electron Bot 46f3491c7d
chore: bump chromium to 6b9fa6b352d824d052222e1abe541 (master) (#25558)
* chore: bump chromium in DEPS to d5c9bf9e2a18fa508201a88e5803bec1d107b1ae

* chore: bump chromium in DEPS to 45f1316afae33e52c92480b34bf4f7fe4a7db898

* update patches

* WillCreateURLLoaderFactory now gets a ukm_source_id

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

* ink_drop_visible_opacity -> GetInkDropVisibleOpacity

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

* chore: bump chromium in DEPS to ddb5b6db5e35ab1a7b5adbd9f15373af6c35ea2a

* 2418471: PDF Viewer update: Add missing aria-labels to various buttons.

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

* update printing.patch given print settings mojoification

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

* update patches

* content::BluetoothChooser::Event -> content::BluetoothChooserEvent

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

* set_ink_drop_base_color -> SetInkDropBaseColor

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

* chore: bump chromium in DEPS to ecf7c9ee830d4d85f300b461a2fa13aa40c79a4c

* update patches

* gfx::ConvertPointToPixel -> gfx::ConvertPointToPixels

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

* remove ContentSettingsObserver::AllowStorage()

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

* service_manager::kCrashDumpSignal -> kCrashDumpSignal

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

* chore: bump chromium in DEPS to abdb7ebe5f8c8328b8f435283df90d0a3ecff7bd

* chore: bump chromium in DEPS to 2a7e138ab1066534ceb2622e8a9d2c8ebf574215

* chore: bump chromium in DEPS to ab1884e75ced904e4276851eb4e1ad89919ca93b

* chore: bump chromium in DEPS to a12413902380dcc2a73ac74d582328280a8af686

* Fixup printing patch

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

* Fixup OSR patch

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

* Make ExtensionURLLoaderFactory always owned by its |receivers_|.

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

* Add deprecated_default_sources_assignment_filter variable

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

* Fixup patch indices

* Remove several references to BrowserPlugin from content

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

* Remove SurfaceEmbeddingTime and LocalSurfaceIdAllocation

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

* Add DragOperation and AllowedDragOperations Mojo types

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

* chore: bump chromium in DEPS to 378450342cf6aa160663d0ce3a178a11b570c25a

* Fixup patch indices

* Remove SurfaceEmbeddingTime and LocalSurfaceIdAllocation

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

* Add DragOperation and AllowedDragOperations Mojo types

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

* 2426564: Remove global sources assignment filter value

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

* Fixup blink_local_frame.patch

* [XProto] Remove a subset of ui/gfx/x/x11.h

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

* Fixup patch indices

* Remove several references to BrowserPlugin from content

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

* Remove lossy ConvertSizeToPixel() methods

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

* serial: Use USB driver name to disambiguate ports

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

* Remove set_sources_filter import

* Fix ModMask usage

* [XProto] Remove usage of all Xlib headers

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

* [XProto] Remove usage of Xlib Visuals

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

* Skip Angle manifest file

https://chromium-review.googlesource.com/c/angle/angle/+/2425197

* Add whole src\third_party\angle\.git directory

This directory is needed in order to properly generate gen/angle/angle_commit.h

* [libvpx] Fix HighBD config on Windows ARM64

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

* update patches

* fix: correct calling convention for Windows on Arm

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

* Add third_party/angle/.git to the archive before adding the rest of the source

* fixup source caching on Windows

* Fixup erroneous close paren

* fixup for goma issues

* This should work

* chore: bump chromium roll manually

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

This landed the day after we paused roller-bot and may resolve the
visibility test flakes that we're seeing. h/t to @jkleinsc for
finding this with me.

* chore: remove obsoleted cherry-pick fix for libvpx

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

* chore: remove obsoleted cherry-pick libvpx patch

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

* chore: re-export patches

* chore: add tracer comment to visibility-stat-spec.

The line numbers between the source and the CI runs don't seem to match
up, so this temp tracer is to help track the source of that difference.

* chore: bump chromium in DEPS to 7c2b8cc3b8638aee8abeb013042a6c1d15b2da6b

* update patches

* impl SortingLSH service

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

* 2446525: [Flash] Remove some Flash APIs

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

* 2440974: Reland "Delete service_manager/embedder/switches.h"

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

* 2359402: Remove ContentBrowserClient::NonNetworkURLLoaderFactoryDeprecatedMap.

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

* 2250506: Implement tabs.removeCSS

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

* 2429143: Remove implicit-conversion-to-integer ConvertRectToPixel() methods.

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

* 2444430: Remove DataElementType::kBlob

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

* 2441964: Clean up WebView public API

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

* 2357523: Make ExtensionURLLoaderFactory always owned by its |receivers_|.

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

* 2461606: Use blink::mojom::PreferredColorScheme instead of blink::PreferredColorScheme

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

* 2461235: a11y inspect reorg: move PropertyFilter struct to a new location

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

* remove flash support

* fix frame_host_manager patch

* fix lint

* remove flash info from docs

* fix build

* fix osr

* chore: bump chromium in DEPS to 9269f9eb1d98d29564c2b2ab97f30c6e148c4e11

* fix visibilityState tests

* 2463049: Replace all uses of web_pref::AutoplayPolicy with mojom::AutoplayPolicy

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

* update patches

* fix tests harder

* 2414921: Add Group and Ungroup functions to Tabs extension API

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

* more test fix

* Remove all keyboard related usage of Xlib

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

* fix linux build

* 2453807: [XProto] Remove usage of Xlib error handling

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

* lint

* fixup! 2453807: [XProto] Remove usage of Xlib error handling

* disable CalculateNativeWinOcclusion on win ci

* remove UploadBlob from docs

* Update appveyor.yml

Co-authored-by: Andy Locascio <andy@slack-corp.com>
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Electron Bot <anonymous@electronjs.org>
Co-authored-by: Charles Kerr <charles@charleskerr.com>
Co-authored-by: Samuel Attard <samuel.r.attard@gmail.com>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
2020-10-15 18:30:41 -07:00

397 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/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(
data.c_str(), data.length(),
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 = v8::Local<v8::Object>::Cast(val);
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 = v8::Local<v8::Array>::Cast(localVal);
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::DataElementType::kFile:
upload_data.Set("type", "file");
upload_data.Set("file", element.path().value());
upload_data.Set("filePath", base::Value(element.path().AsUTF8Unsafe()));
upload_data.Set("offset", static_cast<int>(element.offset()));
upload_data.Set("length", static_cast<int>(element.length()));
upload_data.Set("modificationTime",
element.expected_modification_time().ToDoubleT());
break;
case network::mojom::DataElementType::kBytes:
upload_data.Set("type", "rawData");
upload_data.Set("bytes", node::Buffer::Copy(isolate, element.bytes(),
element.length())
.ToLocalChecked());
break;
case network::mojom::DataElementType::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 = new 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") {
std::string file;
int offset = 0, length = -1;
double modification_time = 0.0;
dict->GetStringWithoutPathExpansion("filePath", &file);
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("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