Skip to content

Truly independent web browser

LibIPC+LibWeb: Hand a partly read message over with a transport

Andreas Klingf6f94dda67f3
diff --git a/Libraries/LibIPC/TransportHandle.cpp b/Libraries/LibIPC/TransportHandle.cpp
index c1fca56ef4a..50fbbfed9af 100644
--- a/Libraries/LibIPC/TransportHandle.cpp
+++ b/Libraries/LibIPC/TransportHandle.cpp
@@ -17,6 +17,28 @@
namespace IPC {
+static ErrorOr<void> encode_unprocessed(Encoder& encoder, ByteBuffer const& bytes, Vector<Attachment>& attachments)
+{
+ TRY(encoder.encode(bytes));
+ TRY(encoder.encode_size(attachments.size()));
+ for (auto& attachment : attachments)
+ TRY(encoder.append_attachment(move(attachment)));
+ attachments.clear();
+ return {};
+}
+
+static ErrorOr<void> decode_unprocessed(Decoder& decoder, ByteBuffer& bytes, Vector<Attachment>& attachments)
+{
+ bytes = TRY(decoder.decode<ByteBuffer>());
+ auto attachment_count = TRY(decoder.decode_size());
+ if (attachment_count > decoder.attachments().size())
+ return Error::from_string_literal("TransportHandle::decode: Missing attachments");
+ TRY(attachments.try_ensure_capacity(attachment_count));
+ for (size_t i = 0; i < attachment_count; ++i)
+ attachments.unchecked_append(decoder.attachments().dequeue());
+ return {};
+}
+
#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
TransportHandle::TransportHandle(Core::MachPort receive_right, Core::MachPort send_right)
@@ -66,7 +88,7 @@ ErrorOr<void> encode(Encoder& encoder, TransportHandle const& handle)
TRY(encoder.append_attachment(Attachment::from_mach_port(move(handle.m_receive_right), Core::MachPort::MessageRight::MoveReceive)));
TRY(encoder.append_attachment(Attachment::from_mach_port(move(handle.m_send_right), Core::MachPort::MessageRight::MoveSend)));
- return {};
+ return encode_unprocessed(encoder, handle.m_unprocessed_bytes, handle.m_unprocessed_attachments);
}
template<>
@@ -80,7 +102,9 @@ ErrorOr<TransportHandle> decode(Decoder& decoder)
VERIFY(send_attachment.message_right() == Core::MachPort::MessageRight::MoveSend);
auto receive_right = recv_attachment.release_mach_port();
auto send_right = send_attachment.release_mach_port();
- return TransportHandle { move(receive_right), move(send_right) };
+ TransportHandle handle { move(receive_right), move(send_right) };
+ TRY(decode_unprocessed(decoder, handle.m_unprocessed_bytes, handle.m_unprocessed_attachments));
+ return handle;
}
#else
@@ -90,9 +114,20 @@ TransportHandle::TransportHandle(File file)
{
}
+TransportHandle::TransportHandle(File file, ByteBuffer unprocessed_bytes, Vector<Attachment> unprocessed_attachments)
+ : m_file(move(file))
+ , m_unprocessed_bytes(move(unprocessed_bytes))
+ , m_unprocessed_attachments(move(unprocessed_attachments))
+{
+}
+
ErrorOr<NonnullOwnPtr<Transport>> TransportHandle::create_transport() const
{
+# if defined(AK_OS_WINDOWS)
return Transport::adopt_fd(m_file.take_fd());
+# else
+ return Transport::adopt_fd(m_file.take_fd(), move(m_unprocessed_bytes), move(m_unprocessed_attachments));
+# endif
}
ErrorOr<TransportHandlePair> TransportHandle::create_pair()
@@ -110,14 +145,16 @@ ErrorOr<TransportHandlePair> TransportHandle::create_pair()
template<>
ErrorOr<void> encode(Encoder& encoder, TransportHandle const& handle)
{
- return encoder.encode(handle.m_file);
+ TRY(encoder.encode(handle.m_file));
+ return encode_unprocessed(encoder, handle.m_unprocessed_bytes, handle.m_unprocessed_attachments);
}
template<>
ErrorOr<TransportHandle> decode(Decoder& decoder)
{
- auto file = TRY(decoder.decode<File>());
- return TransportHandle { move(file) };
+ TransportHandle handle { TRY(decoder.decode<File>()) };
+ TRY(decode_unprocessed(decoder, handle.m_unprocessed_bytes, handle.m_unprocessed_attachments));
+ return handle;
}
#endif
diff --git a/Libraries/LibIPC/TransportHandle.h b/Libraries/LibIPC/TransportHandle.h
index eb1d7475827..9fda654db02 100644
--- a/Libraries/LibIPC/TransportHandle.h
+++ b/Libraries/LibIPC/TransportHandle.h
@@ -6,10 +6,13 @@
#pragma once
+#include <AK/ByteBuffer.h>
#include <AK/Error.h>
#include <AK/Noncopyable.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/Platform.h>
+#include <AK/Vector.h>
+#include <LibIPC/Attachment.h>
#include <LibIPC/File.h>
#include <LibIPC/Forward.h>
@@ -35,6 +38,10 @@ public:
TransportHandle(Core::MachPort receive_right, Core::MachPort send_right);
#else
explicit TransportHandle(File);
+
+ // For a transport that hands over the start of a message that it has read off the socket. The rest of the message
+ // is still on the socket, so the next owner has to go on from here.
+ TransportHandle(File, ByteBuffer unprocessed_bytes, Vector<Attachment> unprocessed_attachments);
#endif
ErrorOr<NonnullOwnPtr<Transport>> create_transport() const;
@@ -49,6 +56,8 @@ private:
#else
mutable File m_file;
#endif
+ mutable ByteBuffer m_unprocessed_bytes;
+ mutable Vector<Attachment> m_unprocessed_attachments;
template<typename U>
friend ErrorOr<void> encode(Encoder&, U const&);
diff --git a/Libraries/LibIPC/TransportSocket.cpp b/Libraries/LibIPC/TransportSocket.cpp
index c75efd98586..ea492930ea2 100644
--- a/Libraries/LibIPC/TransportSocket.cpp
+++ b/Libraries/LibIPC/TransportSocket.cpp
@@ -61,10 +61,15 @@ ErrorOr<NonnullOwnPtr<TransportSocket>> TransportSocket::from_socket(NonnullOwnP
}
ErrorOr<NonnullOwnPtr<TransportSocket>> TransportSocket::adopt_fd(int fd)
+{
+ return adopt_fd(fd, {}, {});
+}
+
+ErrorOr<NonnullOwnPtr<TransportSocket>> TransportSocket::adopt_fd(int fd, ByteBuffer unprocessed_bytes, Vector<Attachment> unprocessed_attachments)
{
auto socket = TRY(Core::LocalSocket::adopt_fd(fd));
TRY(socket->set_blocking(false));
- return make<TransportSocket>(move(socket));
+ return make<TransportSocket>(move(socket), move(unprocessed_bytes), move(unprocessed_attachments));
}
ErrorOr<TransportSocket::Paired> TransportSocket::create_paired()
@@ -322,10 +327,14 @@ void TransportSocket::set_share_io_thread_on_this_thread(bool share_io_thread)
s_share_io_thread_on_this_thread = share_io_thread;
}
-TransportSocket::TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket)
+TransportSocket::TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket, ByteBuffer unprocessed_bytes, Vector<Attachment> unprocessed_attachments)
: m_socket(move(socket))
, m_shares_io_thread(s_share_io_thread_on_this_thread)
+ , m_unprocessed_bytes(move(unprocessed_bytes))
{
+ for (auto& attachment : unprocessed_attachments)
+ m_unprocessed_attachments.enqueue(move(attachment));
+
// Disable the socket's built-in notifier. TransportSocket uses its own pipe-based notification mechanism on the IO
// thread, so this notifier is unused. Otherwise, when the socket reaches EOF, this notifier is disabled from the IO
// thread. In the Qt UI, this causes QSocketNotifier destruction to be deferred. If the socket is closed before the
@@ -968,7 +977,14 @@ ErrorOr<TransportHandle> TransportSocket::release_for_transfer()
stop_io_thread(IOThreadState::SendPendingMessagesAndStop);
MutexLocker locker(m_send_mutex);
auto fd = TRY(m_socket->release_fd());
- return TransportHandle { File::adopt_fd(fd) };
+
+ // NB: A read stops wherever the bytes on the socket happen to end, which is often inside a message. The rest of that
+ // message is what the new owner reads first, so it needs this part to make sense of it.
+ Vector<Attachment> unprocessed_attachments;
+ TRY(unprocessed_attachments.try_ensure_capacity(m_unprocessed_attachments.size()));
+ while (!m_unprocessed_attachments.is_empty())
+ unprocessed_attachments.unchecked_append(m_unprocessed_attachments.dequeue());
+ return TransportHandle { File::adopt_fd(fd), move(m_unprocessed_bytes), move(unprocessed_attachments) };
}
}
diff --git a/Libraries/LibIPC/TransportSocket.h b/Libraries/LibIPC/TransportSocket.h
index 53bba6cf311..879d0f61ead 100644
--- a/Libraries/LibIPC/TransportSocket.h
+++ b/Libraries/LibIPC/TransportSocket.h
@@ -94,8 +94,10 @@ public:
static ErrorOr<Paired> create_paired();
static ErrorOr<NonnullOwnPtr<TransportSocket>> from_socket(NonnullOwnPtr<Core::LocalSocket> socket);
static ErrorOr<NonnullOwnPtr<TransportSocket>> adopt_fd(int fd);
+ // The bytes and attachments are what the last owner read off the socket without seeing the end of the message.
+ static ErrorOr<NonnullOwnPtr<TransportSocket>> adopt_fd(int fd, ByteBuffer unprocessed_bytes, Vector<Attachment> unprocessed_attachments);
- explicit TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket);
+ explicit TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket, ByteBuffer unprocessed_bytes = {}, Vector<Attachment> unprocessed_attachments = {});
~TransportSocket();
// Makes the transports that this thread creates from now on share one IO thread with all others made this way, or
@@ -141,6 +143,8 @@ public:
};
ShouldShutdown read_as_many_messages_as_possible_without_blocking(Function<void(Message&&)>&&);
+ // Whole messages that have been read stay here for the old owner to take, and anything newer reaches the new owner.
+ // A message read in part goes to the new owner, along with the handle.
ErrorOr<TransportHandle> release_for_transfer();
// Test seam: When set to a non-zero value, the IO thread wakes the consumer and then pauses for the given duration
diff --git a/Libraries/LibIPC/TransportWindows.cpp b/Libraries/LibIPC/TransportWindows.cpp
index b64d88b5da7..40429e2eb35 100644
--- a/Libraries/LibIPC/TransportWindows.cpp
+++ b/Libraries/LibIPC/TransportWindows.cpp
@@ -646,6 +646,8 @@ ErrorOr<TransportHandle> TransportWindows::release_for_transfer()
stop_watching();
if (m_handle == -1)
return Error::from_errno(ENOTCONN);
+ // FIXME: Hand m_unprocessed_bytes to the new owner, as TransportSocket does. It holds the start of a message whose
+ // rest stays in the pipe. Messages that an IO thread has queued are lost as well.
return TransportHandle { File::adopt_fd(exchange(m_handle, -1)) };
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index c7548489ee9..e2cd68222e9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -283,10 +283,7 @@ impl<'a> TransferDataWriter<'a> {
}
TransferredTransport::Socket(handle) => {
self.write_bool(false);
- self.data_holder.with_encoder(|encoder| {
- handle.encode_into(encoder);
- Ok(())
- });
+ self.data_holder.with_encoder(|encoder| handle.encode_into(encoder));
}
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
index bc037c0734b..20dccd79616 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
@@ -18,7 +18,7 @@ use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use ak::Utf16String;
-use libipc_rust::{Attachment, DecodeError, Decoder, Encoder};
+use libipc_rust::{Attachment, DecodeError, Decoder, EncodeError, Encoder};
use libjs_rust::api::{
CellRoot, DeferGc, EmbedderCell, Gc, GcRefCell, GcWeak, MarkedVec, Object, Realm, Trace, Value, Vm,
is_host_instance_of,
@@ -805,9 +805,11 @@ unsafe extern "C" {
}
/// The rights of one end of an IPC transport, which this owns until a data holder carries them to another agent, or a
-/// transport takes them.
+/// transport takes them. The rest is the start of a message that the last owner read off the transport: IPC::TransportHandle.
pub(crate) struct TransportHandle {
attachments: Vec<Attachment>,
+ unprocessed_bytes: Vec<u8>,
+ unprocessed_attachments: Vec<Attachment>,
}
impl TransportHandle {
@@ -827,8 +829,12 @@ impl TransportHandle {
handle
}
- pub(crate) fn encode_into(self, encoder: &mut Encoder) {
+ pub(crate) fn encode_into(self, encoder: &mut Encoder) -> Result<(), EncodeError> {
append_attachments(encoder, self.attachments);
+ encoder.encode(self.unprocessed_bytes.as_slice())?;
+ encoder.encode_size(self.unprocessed_attachments.len())?;
+ append_attachments(encoder, self.unprocessed_attachments);
+ Ok(())
}
pub(crate) fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
@@ -862,12 +868,27 @@ impl TransportHandle {
let _ = index;
attachments.push(attachment);
}
- Ok(Self { attachments })
+ let unprocessed_bytes = decoder.decode::<Vec<u8>>()?;
+ let unprocessed_count = decoder.decode_size()?;
+ if decoder.remaining_attachments() < unprocessed_count {
+ return Err(DecodeError::MissingAttachment);
+ }
+ let unprocessed_attachments = (0..unprocessed_count)
+ .map(|_| decoder.take_attachment())
+ .collect::<Result<_, _>>()?;
+ Ok(Self {
+ attachments,
+ unprocessed_bytes,
+ unprocessed_attachments,
+ })
}
/// The IPC transport of the end that the handle holds the rights of, which it gives up.
fn create_socket(self) -> SocketTransport {
- TransferPayload::new(Vec::new(), self.attachments).with_raw(|bytes, attachments| {
+ let mut encoder = Encoder::new();
+ self.encode_into(&mut encoder).expect("a transport handle encodes");
+ let (bytes, attachments) = encoder.finish();
+ TransferPayload::new(bytes, attachments).with_raw(|bytes, attachments| {
// SAFETY: The call takes every right, and LibWeb hands over the transport.
unsafe {
SocketTransport::from_raw(web_bindings_transport_handle_create_transport(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs
index f7410c488f3..db477956faf 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs
@@ -148,7 +148,7 @@ impl CarriedChannelEnd {
}
encoder.encode(&transport.is_some())?;
if let Some(transport) = transport {
- transport.encode_into(encoder);
+ transport.encode_into(encoder)?;
}
Ok(())
}
diff --git a/Tests/LibIPC/TestTransportSocket.cpp b/Tests/LibIPC/TestTransportSocket.cpp
index 2dcf1f68c0a..0b5154ecef4 100644
--- a/Tests/LibIPC/TestTransportSocket.cpp
+++ b/Tests/LibIPC/TestTransportSocket.cpp
@@ -770,6 +770,139 @@ TEST_CASE(transports_that_share_an_io_thread_work_alone)
EXPECT_EQ(received, (Vector<u8> { 42, 43 }));
}
+TEST_CASE(a_frame_cut_in_two_by_a_transfer_arrives_whole)
+{
+ Core::EventLoop loop;
+
+ int fds[2] {};
+ TRY_OR_FAIL(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fds));
+ ScopeGuard close_sender = [&] { MUST(Core::System::close(fds[1])); };
+ auto socket = TRY_OR_FAIL(Core::LocalSocket::adopt_fd(fds[0]));
+ MUST(socket->set_blocking(false));
+ IPC::TransportSocket transport(move(socket));
+
+ IPC::SocketMessageHeader header {
+ .type = IPC::SocketMessageHeader::Type::Payload,
+ .payload_size = 4,
+ .fd_count = 0,
+ };
+ EXPECT_EQ(TRY_OR_FAIL(Core::System::write(fds[1], ReadonlyBytes { reinterpret_cast<u8 const*>(&header), sizeof(header) })), sizeof(header));
+ Array<u8, 4> payload { 'a', 'b', 'c', 'd' };
+ EXPECT_EQ(TRY_OR_FAIL(Core::System::write(fds[1], payload.span().trim(2))), 2uz);
+
+ // The old owner has read the first half of the frame off the socket, and the second half is yet to come.
+ transport.wait_until_incoming_is_current();
+ auto handle = TRY_OR_FAIL(transport.release_for_transfer());
+ auto new_owner = TRY_OR_FAIL(handle.create_transport());
+ EXPECT_EQ(TRY_OR_FAIL(Core::System::write(fds[1], payload.span().slice(2))), 2uz);
+
+ ByteBuffer received;
+ spin_until(loop, [&] {
+ (void)new_owner->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {
+ received.append(message.bytes.bytes());
+ });
+ return !received.is_empty();
+ });
+ EXPECT_EQ(received.bytes(), ReadonlyBytes { payload });
+}
+
+TEST_CASE(descriptors_ahead_of_their_message_go_along_with_a_transfer)
+{
+ Core::EventLoop loop;
+
+ int fds[2] {};
+ TRY_OR_FAIL(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fds));
+ auto peer = TRY_OR_FAIL(Core::LocalSocket::adopt_fd(fds[1]));
+ auto socket = TRY_OR_FAIL(Core::LocalSocket::adopt_fd(fds[0]));
+ MUST(socket->set_blocking(false));
+ IPC::TransportSocket transport(move(socket));
+
+ IPC::SocketMessageHeader attachments_header {
+ .type = IPC::SocketMessageHeader::Type::Attachments,
+ .payload_size = 0,
+ .fd_count = 1,
+ };
+ auto attachments_bytes = ReadonlyBytes { reinterpret_cast<u8 const*>(&attachments_header), sizeof(attachments_header) };
+ auto first_descriptor = pipe_holding('a');
+ EXPECT_EQ(TRY_OR_FAIL(peer->send_message(attachments_bytes, 0, Vector<int, 1> { first_descriptor })), sizeof(attachments_header));
+ MUST(Core::System::close(first_descriptor));
+
+ // The old owner has taken the descriptor off the socket, and the message that claims it is yet to come.
+ transport.wait_until_incoming_is_current();
+ auto handle = TRY_OR_FAIL(transport.release_for_transfer());
+ auto new_owner = TRY_OR_FAIL(handle.create_transport());
+
+ IPC::SocketMessageHeader header {
+ .type = IPC::SocketMessageHeader::Type::Payload,
+ .payload_size = 1,
+ .fd_count = 2,
+ };
+ ByteBuffer frame;
+ frame.append(&header, sizeof(header));
+ frame.append('X');
+ auto second_descriptor = pipe_holding('b');
+ EXPECT_EQ(TRY_OR_FAIL(peer->send_message(frame.bytes(), 0, Vector<int, 1> { second_descriptor })), frame.size());
+ MUST(Core::System::close(second_descriptor));
+
+ Vector<u8> tags;
+ spin_until(loop, [&] {
+ (void)new_owner->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {
+ while (!message.attachments.is_empty()) {
+ auto fd = message.attachments.dequeue().to_fd();
+ tags.append(byte_in_descriptor(fd).value_or(0));
+ MUST(Core::System::close(fd));
+ }
+ });
+ return !tags.is_empty();
+ });
+ EXPECT_EQ(tags, (Vector<u8> { 'a', 'b' }));
+}
+
+TEST_CASE(messages_arrive_in_order_while_the_reader_is_transferred_again_and_again)
+{
+ Core::EventLoop loop;
+
+ auto paired = TRY_OR_FAIL(IPC::TransportSocket::create_paired());
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto sender = move(paired.local);
+ auto reader = TRY_OR_FAIL(paired.remote_handle.create_transport());
+
+ // NB: The padding makes a message end anywhere in a read of the transport.
+ static constexpr u32 message_count = 20000;
+ static constexpr size_t padding = 701;
+ auto sending_thread = Threading::Thread::construct("Sender"sv, [&sender] {
+ for (u32 i = 0; i < message_count; ++i) {
+ IPC::MessageDataType payload;
+ payload.resize(sizeof(i) + padding);
+ memcpy(payload.data(), &i, sizeof(i));
+ Vector<IPC::Attachment> attachments;
+ MUST(sender->post_message(move(payload), attachments));
+ }
+ return static_cast<intptr_t>(0);
+ });
+ sending_thread->start();
+
+ u32 next = 0;
+ bool in_order = true;
+ auto read_what_is_there = [&](IPC::TransportSocket& transport) {
+ (void)transport.read_as_many_messages_as_possible_without_blocking([&](auto&& message) {
+ u32 value = 0;
+ memcpy(&value, message.bytes.bytes().data(), sizeof(value));
+ in_order = in_order && value == next;
+ ++next;
+ });
+ };
+ spin_until(loop, [&] {
+ read_what_is_there(*reader);
+ auto handle = MUST(reader->release_for_transfer());
+ read_what_is_there(*reader);
+ reader = MUST(handle.create_transport());
+ return next >= message_count || !in_order; }, 30000_ms);
+ (void)sending_thread->join();
+
+ EXPECT(in_order);
+ EXPECT_EQ(next, message_count);
+}
+
TEST_CASE(read_hook_is_notified_on_peer_hangup)
{
Core::EventLoop loop;
diff --git a/Tests/LibWeb/Text/expected/Workers/message-port-transferred-during-flood.txt b/Tests/LibWeb/Text/expected/Workers/message-port-transferred-during-flood.txt
new file mode 100644
index 00000000000..7386318ff9a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Workers/message-port-transferred-during-flood.txt
@@ -0,0 +1,4 @@
+port: socket
+received: 1000
+out of order: 0
+several owners: true
diff --git a/Tests/LibWeb/Text/input/Workers/message-port-transferred-during-flood.html b/Tests/LibWeb/Text/input/Workers/message-port-transferred-during-flood.html
new file mode 100644
index 00000000000..85832c25b9e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Workers/message-port-transferred-during-flood.html
@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ const MESSAGE_COUNT = 1000;
+ const MESSAGES_PER_OWNER = 50;
+
+ const SCRIPT = `
+ onconnect = event => {
+ const port = event.ports[0];
+ port.onmessage = event => {
+ const padding = "x".repeat(3001);
+ for (let i = 0; i < event.data; ++i) port.postMessage({ i, padding });
+ };
+ };
+ `;
+
+ function transferToNewOwner(port) {
+ const channel = new MessageChannel();
+ return new Promise(resolve => {
+ channel.port2.onmessage = event => resolve(event.ports[0]);
+ channel.port1.postMessage(null, [port]);
+ });
+ }
+
+ // NB: The port moves on while the worker sends, so the socket changes owner in the middle of a message most times.
+ promiseTest(async () => {
+ const scriptURL = URL.createObjectURL(new Blob([SCRIPT], { type: "text/javascript" }));
+ let port = new SharedWorker(scriptURL, uniqueID()).port;
+
+ let expected = 0;
+ let outOfOrder = 0;
+ let owners = 1;
+ let lastOwner = port;
+ await new Promise(resolve => {
+ function receiveWithOwner(owner) {
+ lastOwner = owner;
+ let received = 0;
+ owner.onmessage = async event => {
+ if (event.data.i !== expected) ++outOfOrder;
+ expected = event.data.i + 1;
+ if (expected === MESSAGE_COUNT) {
+ resolve();
+ return;
+ }
+ if (++received === MESSAGES_PER_OWNER) {
+ owner.onmessage = null;
+ ++owners;
+ receiveWithOwner(await transferToNewOwner(owner));
+ }
+ };
+ }
+ port.postMessage(MESSAGE_COUNT);
+ receiveWithOwner(port);
+ });
+
+ println(`port: ${internals.messagePortEntanglementKind(lastOwner)}`);
+ println(`received: ${expected}`);
+ println(`out of order: ${outOfOrder}`);
+ println(`several owners: ${owners > 2}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Workers/message-port-transferred-during-flood.html.headers b/Tests/LibWeb/Text/input/Workers/message-port-transferred-during-flood.html.headers
new file mode 100644
index 00000000000..63b60e490f4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Workers/message-port-transferred-during-flood.html.headers
@@ -0,0 +1,2 @@
+Cross-Origin-Opener-Policy: same-origin
+Cross-Origin-Embedder-Policy: require-corp