MessagePort.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Andrew Kaster <akaster@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/MemoryStream.h>
  8. #include <LibCore/Socket.h>
  9. #include <LibCore/System.h>
  10. #include <LibIPC/Decoder.h>
  11. #include <LibIPC/Encoder.h>
  12. #include <LibIPC/File.h>
  13. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  14. #include <LibWeb/Bindings/Intrinsics.h>
  15. #include <LibWeb/Bindings/MessagePortPrototype.h>
  16. #include <LibWeb/DOM/EventDispatcher.h>
  17. #include <LibWeb/HTML/EventNames.h>
  18. #include <LibWeb/HTML/MessageEvent.h>
  19. #include <LibWeb/HTML/MessagePort.h>
  20. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  21. #include <LibWeb/HTML/WorkerGlobalScope.h>
  22. namespace Web::HTML {
  23. constexpr u8 IPC_FILE_TAG = 0xA5;
  24. JS_DEFINE_ALLOCATOR(MessagePort);
  25. JS::NonnullGCPtr<MessagePort> MessagePort::create(JS::Realm& realm)
  26. {
  27. return realm.heap().allocate<MessagePort>(realm, realm);
  28. }
  29. MessagePort::MessagePort(JS::Realm& realm)
  30. : DOM::EventTarget(realm)
  31. {
  32. }
  33. MessagePort::~MessagePort()
  34. {
  35. disentangle();
  36. }
  37. void MessagePort::initialize(JS::Realm& realm)
  38. {
  39. Base::initialize(realm);
  40. WEB_SET_PROTOTYPE_FOR_INTERFACE(MessagePort);
  41. }
  42. void MessagePort::visit_edges(Cell::Visitor& visitor)
  43. {
  44. Base::visit_edges(visitor);
  45. visitor.visit(m_remote_port);
  46. // FIXME: This is incorrect!! We *should* be visiting the worker event target,
  47. // but CI hangs if we do: https://github.com/SerenityOS/serenity/issues/23899
  48. visitor.ignore(m_worker_event_target);
  49. }
  50. void MessagePort::set_worker_event_target(JS::NonnullGCPtr<DOM::EventTarget> target)
  51. {
  52. m_worker_event_target = target;
  53. }
  54. // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-steps
  55. WebIDL::ExceptionOr<void> MessagePort::transfer_steps(HTML::TransferDataHolder& data_holder)
  56. {
  57. // 1. Set value's has been shipped flag to true.
  58. m_has_been_shipped = true;
  59. // FIXME: 2. Set dataHolder.[[PortMessageQueue]] to value's port message queue.
  60. // FIXME: Support delivery of messages that haven't been delivered yet on the other side
  61. // 3. If value is entangled with another port remotePort, then:
  62. if (is_entangled()) {
  63. // 1. Set remotePort's has been shipped flag to true.
  64. m_remote_port->m_has_been_shipped = true;
  65. // 2. Set dataHolder.[[RemotePort]] to remotePort.
  66. auto fd = MUST(m_socket->release_fd());
  67. m_socket = nullptr;
  68. data_holder.fds.append(IPC::File(fd, IPC::File::CloseAfterSending));
  69. data_holder.data.append(IPC_FILE_TAG);
  70. auto fd_passing_socket = MUST(m_fd_passing_socket->release_fd());
  71. m_fd_passing_socket = nullptr;
  72. data_holder.fds.append(IPC::File(fd_passing_socket, IPC::File::CloseAfterSending));
  73. data_holder.data.append(IPC_FILE_TAG);
  74. }
  75. // 4. Otherwise, set dataHolder.[[RemotePort]] to null.
  76. else {
  77. data_holder.data.append(0);
  78. }
  79. return {};
  80. }
  81. WebIDL::ExceptionOr<void> MessagePort::transfer_receiving_steps(HTML::TransferDataHolder& data_holder)
  82. {
  83. // 1. Set value's has been shipped flag to true.
  84. m_has_been_shipped = true;
  85. // FIXME 2. Move all the tasks that are to fire message events in dataHolder.[[PortMessageQueue]] to the port message queue of value,
  86. // if any, leaving value's port message queue in its initial disabled state, and, if value's relevant global object is a Window,
  87. // associating the moved tasks with value's relevant global object's associated Document.
  88. // 3. If dataHolder.[[RemotePort]] is not null, then entangle dataHolder.[[RemotePort]] and value.
  89. // (This will disentangle dataHolder.[[RemotePort]] from the original port that was transferred.)
  90. auto fd_tag = data_holder.data.take_first();
  91. if (fd_tag == IPC_FILE_TAG) {
  92. auto fd = data_holder.fds.take_first();
  93. m_socket = MUST(Core::LocalSocket::adopt_fd(fd.take_fd()));
  94. fd_tag = data_holder.data.take_first();
  95. VERIFY(fd_tag == IPC_FILE_TAG);
  96. fd = data_holder.fds.take_first();
  97. m_fd_passing_socket = MUST(Core::LocalSocket::adopt_fd(fd.take_fd()));
  98. m_socket->on_ready_to_read = [strong_this = JS::make_handle(this)]() {
  99. strong_this->read_from_socket();
  100. };
  101. } else if (fd_tag != 0) {
  102. dbgln("Unexpected byte {:x} in MessagePort transfer data", fd_tag);
  103. VERIFY_NOT_REACHED();
  104. }
  105. return {};
  106. }
  107. void MessagePort::disentangle()
  108. {
  109. if (m_remote_port)
  110. m_remote_port->m_remote_port = nullptr;
  111. m_remote_port = nullptr;
  112. m_socket = nullptr;
  113. m_fd_passing_socket = nullptr;
  114. }
  115. // https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
  116. void MessagePort::entangle_with(MessagePort& remote_port)
  117. {
  118. if (m_remote_port.ptr() == &remote_port)
  119. return;
  120. // 1. If one of the ports is already entangled, then disentangle it and the port that it was entangled with.
  121. if (is_entangled())
  122. disentangle();
  123. if (remote_port.is_entangled())
  124. remote_port.disentangle();
  125. // 2. Associate the two ports to be entangled, so that they form the two parts of a new channel.
  126. // (There is no MessageChannel object that represents this channel.)
  127. remote_port.m_remote_port = this;
  128. m_remote_port = &remote_port;
  129. auto create_paired_sockets = []() -> Array<NonnullOwnPtr<Core::LocalSocket>, 2> {
  130. int fds[2] = {};
  131. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fds));
  132. auto socket0 = MUST(Core::LocalSocket::adopt_fd(fds[0]));
  133. MUST(socket0->set_blocking(false));
  134. MUST(socket0->set_close_on_exec(true));
  135. auto socket1 = MUST(Core::LocalSocket::adopt_fd(fds[1]));
  136. MUST(socket1->set_blocking(false));
  137. MUST(socket1->set_close_on_exec(true));
  138. return Array { move(socket0), move(socket1) };
  139. };
  140. auto sockets = create_paired_sockets();
  141. m_socket = move(sockets[0]);
  142. m_remote_port->m_socket = move(sockets[1]);
  143. m_socket->on_ready_to_read = [strong_this = JS::make_handle(this)]() {
  144. strong_this->read_from_socket();
  145. };
  146. m_remote_port->m_socket->on_ready_to_read = [remote_port = JS::make_handle(m_remote_port)]() {
  147. remote_port->read_from_socket();
  148. };
  149. auto fd_sockets = create_paired_sockets();
  150. m_fd_passing_socket = move(fd_sockets[0]);
  151. m_remote_port->m_fd_passing_socket = move(fd_sockets[1]);
  152. }
  153. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage-options
  154. WebIDL::ExceptionOr<void> MessagePort::post_message(JS::Value message, Vector<JS::Handle<JS::Object>> const& transfer)
  155. {
  156. // 1. Let targetPort be the port with which this MessagePort is entangled, if any; otherwise let it be null.
  157. JS::GCPtr<MessagePort> target_port = m_remote_port;
  158. // 2. Let options be «[ "transfer" → transfer ]».
  159. auto options = StructuredSerializeOptions { transfer };
  160. // 3. Run the message port post message steps providing this, targetPort, message and options.
  161. return message_port_post_message_steps(target_port, message, options);
  162. }
  163. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage
  164. WebIDL::ExceptionOr<void> MessagePort::post_message(JS::Value message, StructuredSerializeOptions const& options)
  165. {
  166. // 1. Let targetPort be the port with which this MessagePort is entangled, if any; otherwise let it be null.
  167. JS::GCPtr<MessagePort> target_port = m_remote_port;
  168. // 2. Run the message port post message steps providing targetPort, message and options.
  169. return message_port_post_message_steps(target_port, message, options);
  170. }
  171. // https://html.spec.whatwg.org/multipage/web-messaging.html#message-port-post-message-steps
  172. WebIDL::ExceptionOr<void> MessagePort::message_port_post_message_steps(JS::GCPtr<MessagePort> target_port, JS::Value message, StructuredSerializeOptions const& options)
  173. {
  174. auto& realm = this->realm();
  175. auto& vm = this->vm();
  176. // 1. Let transfer be options["transfer"].
  177. auto const& transfer = options.transfer;
  178. // 2. If transfer contains this MessagePort, then throw a "DataCloneError" DOMException.
  179. for (auto const& handle : transfer) {
  180. if (handle == this)
  181. return WebIDL::DataCloneError::create(realm, "Cannot transfer a MessagePort to itself"_fly_string);
  182. }
  183. // 3. Let doomed be false.
  184. bool doomed = false;
  185. // 4. If targetPort is not null and transfer contains targetPort, then set doomed to true and optionally report to a developer console that the target port was posted to itself, causing the communication channel to be lost.
  186. if (target_port) {
  187. for (auto const& handle : transfer) {
  188. if (handle == target_port.ptr()) {
  189. doomed = true;
  190. dbgln("FIXME: Report to a developer console that the target port was posted to itself, causing the communication channel to be lost");
  191. }
  192. }
  193. }
  194. // 5. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
  195. auto serialize_with_transfer_result = TRY(structured_serialize_with_transfer(vm, message, transfer));
  196. // 6. If targetPort is null, or if doomed is true, then return.
  197. // IMPLEMENTATION DEFINED: Actually check the socket here, not the target port.
  198. // If there's no target message port in the same realm, we still want to send the message over IPC
  199. if (!m_socket || doomed) {
  200. return {};
  201. }
  202. // 7. Add a task that runs the following steps to the port message queue of targetPort:
  203. post_port_message(move(serialize_with_transfer_result));
  204. return {};
  205. }
  206. ErrorOr<void> MessagePort::send_message_on_socket(SerializedTransferRecord const& serialize_with_transfer_result)
  207. {
  208. IPC::MessageBuffer buffer;
  209. IPC::Encoder encoder(buffer);
  210. MUST(encoder.encode(serialize_with_transfer_result));
  211. TRY(buffer.transfer_message(*m_fd_passing_socket, *m_socket));
  212. return {};
  213. }
  214. void MessagePort::post_port_message(SerializedTransferRecord serialize_with_transfer_result)
  215. {
  216. // FIXME: Use the correct task source?
  217. queue_global_task(Task::Source::PostedMessage, relevant_global_object(*this), [this, serialize_with_transfer_result = move(serialize_with_transfer_result)]() mutable {
  218. if (!m_socket || !m_socket->is_open())
  219. return;
  220. if (auto result = send_message_on_socket(serialize_with_transfer_result); result.is_error()) {
  221. dbgln("Failed to post message: {}", result.error());
  222. disentangle();
  223. }
  224. });
  225. }
  226. void MessagePort::read_from_socket()
  227. {
  228. auto num_bytes_ready = MUST(m_socket->pending_bytes());
  229. switch (m_socket_state) {
  230. case SocketState::Header: {
  231. if (num_bytes_ready < sizeof(u32))
  232. break;
  233. m_socket_incoming_message_size = MUST(m_socket->read_value<u32>());
  234. num_bytes_ready -= sizeof(u32);
  235. m_socket_state = SocketState::Data;
  236. }
  237. [[fallthrough]];
  238. case SocketState::Data: {
  239. if (num_bytes_ready < m_socket_incoming_message_size)
  240. break;
  241. Vector<u8, 1024> data;
  242. data.resize(m_socket_incoming_message_size, true);
  243. MUST(m_socket->read_until_filled(data));
  244. FixedMemoryStream stream { data, FixedMemoryStream::Mode::ReadOnly };
  245. IPC::Decoder decoder(stream, *m_fd_passing_socket);
  246. auto serialize_with_transfer_result = MUST(decoder.decode<SerializedTransferRecord>());
  247. // Make sure to advance our state machine before dispatching the MessageEvent,
  248. // as dispatching events can run arbitrary JS (and cause us to receive another message!)
  249. m_socket_state = SocketState::Header;
  250. post_message_task_steps(serialize_with_transfer_result);
  251. break;
  252. }
  253. case SocketState::Error:
  254. VERIFY_NOT_REACHED();
  255. break;
  256. }
  257. }
  258. void MessagePort::post_message_task_steps(SerializedTransferRecord& serialize_with_transfer_result)
  259. {
  260. // 1. Let finalTargetPort be the MessagePort in whose port message queue the task now finds itself.
  261. // NOTE: This can be different from targetPort, if targetPort itself was transferred and thus all its tasks moved along with it.
  262. auto* final_target_port = this;
  263. // IMPLEMENTATION DEFINED:
  264. // https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-worker-interface
  265. // Worker objects act as if they had an implicit MessagePort associated with them.
  266. // All messages received by that port must immediately be retargeted at the Worker object.
  267. // We therefore set a special event target for those implicit ports on the Worker and the WorkerGlobalScope objects
  268. EventTarget* message_event_target = final_target_port;
  269. if (m_worker_event_target != nullptr) {
  270. message_event_target = m_worker_event_target;
  271. }
  272. // 2. Let targetRealm be finalTargetPort's relevant realm.
  273. auto& target_realm = relevant_realm(*final_target_port);
  274. auto& target_vm = target_realm.vm();
  275. // 3. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
  276. TemporaryExecutionContext context { relevant_settings_object(*final_target_port) };
  277. auto deserialize_record_or_error = structured_deserialize_with_transfer(target_vm, serialize_with_transfer_result);
  278. if (deserialize_record_or_error.is_error()) {
  279. // If this throws an exception, catch it, fire an event named messageerror at finalTargetPort, using MessageEvent, and then return.
  280. auto exception = deserialize_record_or_error.release_error();
  281. MessageEventInit event_init {};
  282. message_event_target->dispatch_event(MessageEvent::create(target_realm, HTML::EventNames::messageerror, event_init));
  283. return;
  284. }
  285. auto deserialize_record = deserialize_record_or_error.release_value();
  286. // 4. Let messageClone be deserializeRecord.[[Deserialized]].
  287. auto message_clone = deserialize_record.deserialized;
  288. // 5. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.
  289. // FIXME: Use a FrozenArray
  290. Vector<JS::Handle<JS::Object>> new_ports;
  291. for (auto const& object : deserialize_record.transferred_values) {
  292. if (is<HTML::MessagePort>(*object)) {
  293. new_ports.append(object);
  294. }
  295. }
  296. // 6. Fire an event named message at finalTargetPort, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.
  297. MessageEventInit event_init {};
  298. event_init.data = message_clone;
  299. event_init.ports = move(new_ports);
  300. message_event_target->dispatch_event(MessageEvent::create(target_realm, HTML::EventNames::message, event_init));
  301. }
  302. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-start
  303. void MessagePort::start()
  304. {
  305. if (!is_entangled())
  306. return;
  307. VERIFY(m_socket);
  308. VERIFY(m_fd_passing_socket);
  309. // TODO: The start() method steps are to enable this's port message queue, if it is not already enabled.
  310. }
  311. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-close
  312. void MessagePort::close()
  313. {
  314. // 1. Set this MessagePort object's [[Detached]] internal slot value to true.
  315. set_detached(true);
  316. // 2. If this MessagePort object is entangled, disentangle it.
  317. if (is_entangled())
  318. disentangle();
  319. }
  320. #undef __ENUMERATE
  321. #define __ENUMERATE(attribute_name, event_name) \
  322. void MessagePort::set_##attribute_name(WebIDL::CallbackType* value) \
  323. { \
  324. set_event_handler_attribute(event_name, value); \
  325. } \
  326. WebIDL::CallbackType* MessagePort::attribute_name() \
  327. { \
  328. return event_handler_attribute(event_name); \
  329. }
  330. ENUMERATE_MESSAGE_PORT_EVENT_HANDLERS(__ENUMERATE)
  331. #undef __ENUMERATE
  332. }