feat: MessagePorts in the main process (#22404)

This commit is contained in:
Jeremy Apthorp 2020-03-11 18:07:54 -07:00 committed by GitHub
parent c4c0888972
commit b4d07f76d3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
34 changed files with 1316 additions and 113 deletions

View file

@ -7,6 +7,7 @@
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
@ -44,12 +45,17 @@
#include "content/public/common/context_menu_params.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
@ -84,11 +90,14 @@
#include "shell/common/mouse_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/v8_value_serializer.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
@ -1088,6 +1097,49 @@ void WebContents::Invoke(bool internal,
std::move(callback), internal, channel, std::move(arguments));
}
void WebContents::ReceivePostMessage(const std::string& channel,
blink::TransferableMessage message) {
v8::HandleScope handle_scope(isolate());
auto wrapped_ports =
MessagePort::EntanglePorts(isolate(), std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate(), message);
EmitWithSender("-ipc-ports", bindings_.dispatch_context(), InvokeCallback(),
false, channel, message_value, std::move(wrapped_ports));
}
void WebContents::PostMessage(const std::string& channel,
v8::Local<v8::Value> message_value,
base::Optional<v8::Local<v8::Value>> transfer) {
blink::TransferableMessage transferable_message;
if (!electron::SerializeV8Value(isolate(), message_value,
&transferable_message)) {
// SerializeV8Value sets an exception.
return;
}
std::vector<gin::Handle<MessagePort>> wrapped_ports;
if (transfer) {
if (!gin::ConvertFromV8(isolate(), *transfer, &wrapped_ports)) {
isolate()->ThrowException(v8::Exception::Error(
gin::StringToV8(isolate(), "Invalid value for transfer")));
return;
}
}
bool threw_exception = false;
transferable_message.ports =
MessagePort::DisentanglePorts(isolate(), wrapped_ports, &threw_exception);
if (threw_exception)
return;
content::RenderFrameHost* frame_host = web_contents()->GetMainFrame();
mojo::AssociatedRemote<mojom::ElectronRenderer> electron_renderer;
frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&electron_renderer);
electron_renderer->ReceivePostMessage(channel,
std::move(transferable_message));
}
void WebContents::MessageSync(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
@ -2663,6 +2715,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("tabTraverse", &WebContents::TabTraverse)
.SetMethod("_send", &WebContents::SendIPCMessage)
.SetMethod("_postMessage", &WebContents::PostMessage)
.SetMethod("_sendToFrame", &WebContents::SendIPCMessageToFrame)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)

View file

@ -256,6 +256,10 @@ class WebContents : public gin_helper::TrackableObject<WebContents>,
const std::string& channel,
v8::Local<v8::Value> args);
void PostMessage(const std::string& channel,
v8::Local<v8::Value> message,
base::Optional<v8::Local<v8::Value>> transfer);
// Send WebInputEvent to the page.
void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event);
@ -525,6 +529,8 @@ class WebContents : public gin_helper::TrackableObject<WebContents>,
const std::string& channel,
blink::CloneableMessage arguments,
InvokeCallback callback) override;
void ReceivePostMessage(const std::string& channel,
blink::TransferableMessage message) override;
void MessageSync(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,

View file

@ -0,0 +1,276 @@
// Copyright (c) 2020 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/message_port.h"
#include <string>
#include <unordered_set>
#include <utility>
#include "base/strings/string_number_conversions.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/event_emitter_caller.h"
#include "shell/common/node_includes.h"
#include "shell/common/v8_value_serializer.h"
#include "third_party/blink/public/common/messaging/transferable_message.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
namespace electron {
gin::WrapperInfo MessagePort::kWrapperInfo = {gin::kEmbedderNativeGin};
MessagePort::MessagePort() = default;
MessagePort::~MessagePort() = default;
// static
gin::Handle<MessagePort> MessagePort::Create(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, new MessagePort());
}
void MessagePort::PostMessage(gin::Arguments* args) {
if (!IsEntangled())
return;
DCHECK(!IsNeutered());
blink::TransferableMessage transferable_message;
v8::Local<v8::Value> message_value;
if (!args->GetNext(&message_value)) {
args->ThrowTypeError("Expected at least one argument to postMessage");
return;
}
electron::SerializeV8Value(args->isolate(), message_value,
&transferable_message);
v8::Local<v8::Value> transferables;
std::vector<gin::Handle<MessagePort>> wrapped_ports;
if (args->GetNext(&transferables)) {
if (!gin::ConvertFromV8(args->isolate(), transferables, &wrapped_ports)) {
args->ThrowError();
return;
}
}
// Make sure we aren't connected to any of the passed-in ports.
for (unsigned i = 0; i < wrapped_ports.size(); ++i) {
if (wrapped_ports[i].get() == this) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Port at index " + base::NumberToString(i) +
" contains the source port.");
return;
}
}
bool threw_exception = false;
transferable_message.ports = MessagePort::DisentanglePorts(
args->isolate(), wrapped_ports, &threw_exception);
if (threw_exception)
return;
mojo::Message mojo_message = blink::mojom::TransferableMessage::WrapAsMessage(
std::move(transferable_message));
connector_->Accept(&mojo_message);
}
void MessagePort::Start() {
if (!IsEntangled())
return;
if (started_)
return;
started_ = true;
if (HasPendingActivity())
Pin();
connector_->ResumeIncomingMethodCallProcessing();
}
void MessagePort::Close() {
if (closed_)
return;
if (!IsNeutered()) {
connector_ = nullptr;
Entangle(mojo::MessagePipe().handle0);
}
closed_ = true;
if (!HasPendingActivity())
Unpin();
}
void MessagePort::Entangle(mojo::ScopedMessagePipeHandle handle) {
DCHECK(handle.is_valid());
DCHECK(!connector_);
connector_ = std::make_unique<mojo::Connector>(
std::move(handle), mojo::Connector::SINGLE_THREADED_SEND,
base::ThreadTaskRunnerHandle::Get());
connector_->PauseIncomingMethodCallProcessing();
connector_->set_incoming_receiver(this);
connector_->set_connection_error_handler(
base::Bind(&MessagePort::Close, weak_factory_.GetWeakPtr()));
if (HasPendingActivity())
Pin();
}
void MessagePort::Entangle(blink::MessagePortChannel channel) {
Entangle(channel.ReleaseHandle());
}
blink::MessagePortChannel MessagePort::Disentangle() {
DCHECK(!IsNeutered());
auto result = blink::MessagePortChannel(connector_->PassMessagePipe());
connector_ = nullptr;
if (!HasPendingActivity())
Unpin();
return result;
}
bool MessagePort::HasPendingActivity() const {
// The spec says that entangled message ports should always be treated as if
// they have a strong reference.
// We'll also stipulate that the queue needs to be open (if the app drops its
// reference to the port before start()-ing it, then it's not really entangled
// as it's unreachable).
return started_ && IsEntangled();
}
// static
std::vector<gin::Handle<MessagePort>> MessagePort::EntanglePorts(
v8::Isolate* isolate,
std::vector<blink::MessagePortChannel> channels) {
std::vector<gin::Handle<MessagePort>> wrapped_ports;
for (auto& port : channels) {
auto wrapped_port = MessagePort::Create(isolate);
wrapped_port->Entangle(std::move(port));
wrapped_ports.emplace_back(wrapped_port);
}
return wrapped_ports;
}
// static
std::vector<blink::MessagePortChannel> MessagePort::DisentanglePorts(
v8::Isolate* isolate,
const std::vector<gin::Handle<MessagePort>>& ports,
bool* threw_exception) {
if (!ports.size())
return std::vector<blink::MessagePortChannel>();
std::unordered_set<MessagePort*> visited;
// Walk the incoming array - if there are any duplicate ports, or null ports
// or cloned ports, throw an error (per section 8.3.3 of the HTML5 spec).
for (unsigned i = 0; i < ports.size(); ++i) {
auto* port = ports[i].get();
if (!port || port->IsNeutered() || visited.find(port) != visited.end()) {
std::string type;
if (!port)
type = "null";
else if (port->IsNeutered())
type = "already neutered";
else
type = "a duplicate";
gin_helper::ErrorThrower(isolate).ThrowError(
"Port at index " + base::NumberToString(i) + " is " + type + ".");
*threw_exception = true;
return std::vector<blink::MessagePortChannel>();
}
visited.insert(port);
}
// Passed-in ports passed validity checks, so we can disentangle them.
std::vector<blink::MessagePortChannel> channels;
channels.reserve(ports.size());
for (unsigned i = 0; i < ports.size(); ++i)
channels.push_back(ports[i]->Disentangle());
return channels;
}
void MessagePort::Pin() {
if (!pinned_.IsEmpty())
return;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Value> self;
if (GetWrapper(isolate).ToLocal(&self)) {
pinned_.Reset(isolate, self);
}
}
void MessagePort::Unpin() {
pinned_.Reset();
}
bool MessagePort::Accept(mojo::Message* mojo_message) {
blink::TransferableMessage message;
if (!blink::mojom::TransferableMessage::DeserializeFromMessage(
std::move(*mojo_message), &message)) {
return false;
}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
auto ports = EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value = DeserializeV8Value(isolate, message);
v8::Local<v8::Object> self;
if (!GetWrapper(isolate).ToLocal(&self))
return false;
auto event = gin::DataObjectBuilder(isolate)
.Set("data", message_value)
.Set("ports", ports)
.Build();
gin_helper::EmitEvent(isolate, self, "message", event);
return true;
}
gin::ObjectTemplateBuilder MessagePort::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<MessagePort>::GetObjectTemplateBuilder(isolate)
.SetMethod("postMessage", &MessagePort::PostMessage)
.SetMethod("start", &MessagePort::Start)
.SetMethod("close", &MessagePort::Close);
}
const char* MessagePort::GetTypeName() {
return "MessagePort";
}
} // namespace electron
namespace {
using electron::MessagePort;
v8::Local<v8::Value> CreatePair(v8::Isolate* isolate) {
auto port1 = MessagePort::Create(isolate);
auto port2 = MessagePort::Create(isolate);
mojo::MessagePipe pipe;
port1->Entangle(std::move(pipe.handle0));
port2->Entangle(std::move(pipe.handle1));
return gin::DataObjectBuilder(isolate)
.Set("port1", port1)
.Set("port2", port2)
.Build();
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.SetMethod("createPair", &CreatePair);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_message_port, Initialize)

View file

@ -0,0 +1,86 @@
// Copyright (c) 2020 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef SHELL_BROWSER_API_MESSAGE_PORT_H_
#define SHELL_BROWSER_API_MESSAGE_PORT_H_
#include <memory>
#include <vector>
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/connector.h"
#include "mojo/public/cpp/bindings/message.h"
#include "third_party/blink/public/common/messaging/message_port_channel.h"
namespace gin {
class Arguments;
template <typename T>
class Handle;
} // namespace gin
namespace electron {
// A non-blink version of blink::MessagePort.
class MessagePort : public gin::Wrappable<MessagePort>, mojo::MessageReceiver {
public:
~MessagePort() override;
static gin::Handle<MessagePort> Create(v8::Isolate* isolate);
void PostMessage(gin::Arguments* args);
void Start();
void Close();
void Entangle(mojo::ScopedMessagePipeHandle handle);
void Entangle(blink::MessagePortChannel channel);
blink::MessagePortChannel Disentangle();
bool IsEntangled() const { return !closed_ && !IsNeutered(); }
bool IsNeutered() const { return !connector_ || !connector_->is_valid(); }
static std::vector<gin::Handle<MessagePort>> EntanglePorts(
v8::Isolate* isolate,
std::vector<blink::MessagePortChannel> channels);
static std::vector<blink::MessagePortChannel> DisentanglePorts(
v8::Isolate* isolate,
const std::vector<gin::Handle<MessagePort>>& ports,
bool* threw_exception);
// gin::Wrappable
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
private:
MessagePort();
// The blink version of MessagePort uses the very nice "ActiveScriptWrapper"
// class, which keeps the object alive through the V8 embedder hooks into the
// GC lifecycle: see
// https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/platform/heap/thread_state.cc;l=258;drc=b892cf58e162a8f66cd76d7472f129fe0fb6a7d1
// We do not have that luxury, so we brutishly use v8::Global to accomplish
// something similar. Critically, whenever the value of
// "HasPendingActivity()" changes, we must call Pin() or Unpin() as
// appropriate.
bool HasPendingActivity() const;
void Pin();
void Unpin();
// mojo::MessageReceiver
bool Accept(mojo::Message* mojo_message) override;
std::unique_ptr<mojo::Connector> connector_;
bool started_ = false;
bool closed_ = false;
v8::Global<v8::Value> pinned_;
base::WeakPtrFactory<MessagePort> weak_factory_{this};
};
} // namespace electron
#endif // SHELL_BROWSER_API_MESSAGE_PORT_H_