Skip to content

Truly independent web browser

LibIPC+LibCore+LibWebView+UI: Carry Windows IPC over named pipes

Zaggy1024a339a5343c3e
diff --git a/Libraries/LibCore/System.h b/Libraries/LibCore/System.h
index 70140573fd1..5d10605d13c 100644
--- a/Libraries/LibCore/System.h
+++ b/Libraries/LibCore/System.h
@@ -155,6 +155,10 @@ enum class PipeReadEnd : u8 {
ReadExternally,
};
CORE_API ErrorOr<Array<int, 2>> pipe2(int flags, PipeReadEnd = PipeReadEnd::ReadInternally);
+#if defined(AK_OS_WINDOWS)
+// Two connected ends of a named pipe, each read and written, as socketpair() gives elsewhere.
+CORE_API ErrorOr<Array<int, 2>> duplex_pipe();
+#endif
CORE_API ErrorOr<void> set_close_on_exec(int fd, bool enabled);
CORE_API bool is_socket(int fd);
diff --git a/Libraries/LibCore/SystemServerTakeover.cpp b/Libraries/LibCore/SystemServerTakeover.cpp
index 09047f66ff5..15113f87a08 100644
--- a/Libraries/LibCore/SystemServerTakeover.cpp
+++ b/Libraries/LibCore/SystemServerTakeover.cpp
@@ -44,22 +44,25 @@ static void parse_sockets_from_system_server()
MUST(Environment::unset(socket_takeover));
}
-ErrorOr<NonnullOwnPtr<Core::LocalSocket>> take_over_socket_from_system_server(ByteString const& socket_path)
+ErrorOr<int> take_over_descriptor_from_system_server(ByteString const& name)
{
if (!s_overtaken_sockets_parsed)
parse_sockets_from_system_server();
- int fd;
- if (socket_path.is_empty()) {
+ if (name.is_empty()) {
// We want the first (and only) socket.
VERIFY(overtaken_sockets().size() == 1);
- fd = overtaken_sockets().begin()->value;
- } else {
- auto it = overtaken_sockets().find(socket_path);
- if (it == overtaken_sockets().end())
- return Error::from_string_literal("Non-existent socket requested");
- fd = it->value;
+ return overtaken_sockets().begin()->value;
}
+ auto it = overtaken_sockets().find(name);
+ if (it == overtaken_sockets().end())
+ return Error::from_string_literal("Non-existent socket requested");
+ return it->value;
+}
+
+ErrorOr<NonnullOwnPtr<Core::LocalSocket>> take_over_socket_from_system_server(ByteString const& socket_path)
+{
+ auto fd = TRY(take_over_descriptor_from_system_server(socket_path));
// Sanity check: it has to be a socket.
if (!System::is_socket(fd))
diff --git a/Libraries/LibCore/SystemServerTakeover.h b/Libraries/LibCore/SystemServerTakeover.h
index 59b1ed98b67..12ca4893176 100644
--- a/Libraries/LibCore/SystemServerTakeover.h
+++ b/Libraries/LibCore/SystemServerTakeover.h
@@ -11,6 +11,7 @@
namespace Core {
+CORE_API ErrorOr<int> take_over_descriptor_from_system_server(ByteString const& name);
CORE_API ErrorOr<NonnullOwnPtr<Core::LocalSocket>> take_over_socket_from_system_server(ByteString const& socket_path = {});
}
diff --git a/Libraries/LibCore/SystemWindows.cpp b/Libraries/LibCore/SystemWindows.cpp
index 86d31dbcd6d..c273421ad22 100644
--- a/Libraries/LibCore/SystemWindows.cpp
+++ b/Libraries/LibCore/SystemWindows.cpp
@@ -12,9 +12,11 @@
*/
#include <AK/Array.h>
+#include <AK/ByteBuffer.h>
#include <AK/ByteString.h>
#include <AK/Checked.h>
#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
#include <LibCore/MappedFile.h>
#include <LibCore/Process.h>
#include <LibCore/SocketAddress.h>
@@ -22,6 +24,7 @@
#include <direct.h>
#include <AK/Windows.h>
+#include <sddl.h>
#include <ws2tcpip.h>
namespace Core::System {
@@ -260,6 +263,112 @@ ErrorOr<void> socketpair(int domain, int type, int protocol, int sv[2])
return {};
}
+// A security descriptor that admits only the user this process runs as, where the default would let every user on
+// the machine open what it protects for reading.
+class CurrentUserOnlySecurityAttributes {
+ AK_MAKE_NONCOPYABLE(CurrentUserOnlySecurityAttributes);
+ AK_MAKE_NONMOVABLE(CurrentUserOnlySecurityAttributes);
+
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ static ErrorOr<NonnullOwnPtr<CurrentUserOnlySecurityAttributes>> create()
+ {
+ HANDLE token = nullptr;
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
+ return Error::from_windows_error();
+ ScopeGuard close_token = [&] { CloseHandle(token); };
+
+ DWORD size = 0;
+ GetTokenInformation(token, TokenUser, nullptr, 0, &size);
+ auto user_buffer = TRY(ByteBuffer::create_zeroed(size));
+ if (!GetTokenInformation(token, TokenUser, user_buffer.data(), size, &size))
+ return Error::from_windows_error();
+
+ LPSTR user_sid = nullptr;
+ if (!ConvertSidToStringSidA(reinterpret_cast<TOKEN_USER*>(user_buffer.data())->User.Sid, &user_sid))
+ return Error::from_windows_error();
+ ScopeGuard free_sid = [&] { LocalFree(user_sid); };
+
+ auto descriptor_string = ByteString::formatted("D:P(A;;GA;;;{})", user_sid);
+ PSECURITY_DESCRIPTOR descriptor = nullptr;
+ if (!ConvertStringSecurityDescriptorToSecurityDescriptorA(descriptor_string.characters(), SDDL_REVISION_1, &descriptor, nullptr))
+ return Error::from_windows_error();
+ return adopt_own(*new CurrentUserOnlySecurityAttributes(descriptor));
+ }
+
+ ~CurrentUserOnlySecurityAttributes()
+ {
+ LocalFree(m_attributes.lpSecurityDescriptor);
+ }
+
+ SECURITY_ATTRIBUTES* attributes() { return &m_attributes; }
+
+private:
+ explicit CurrentUserOnlySecurityAttributes(PSECURITY_DESCRIPTOR descriptor)
+ {
+ m_attributes.nLength = sizeof(m_attributes);
+ m_attributes.lpSecurityDescriptor = descriptor;
+ m_attributes.bInheritHandle = FALSE;
+ }
+
+ SECURITY_ATTRIBUTES m_attributes {};
+};
+
+static ErrorOr<void> wait_for_pipe_client(HANDLE server)
+{
+ OVERLAPPED overlapped {};
+ overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+ if (!overlapped.hEvent)
+ return Error::from_windows_error();
+ ScopeGuard close_event = [&] { CloseHandle(overlapped.hEvent); };
+
+ if (ConnectNamedPipe(server, &overlapped))
+ return {};
+ auto error = GetLastError();
+ if (error == ERROR_PIPE_CONNECTED)
+ return {};
+ if (error != ERROR_IO_PENDING)
+ return Error::from_windows_error(error);
+ DWORD ignored = 0;
+ if (!GetOverlappedResult(server, &overlapped, &ignored, TRUE))
+ return Error::from_windows_error();
+ return {};
+}
+
+// Two ends of one connection, as socketpair() gives on other systems. A named pipe, rather than a loopback socket,
+// keeps what one end wrote readable after that end has closed, however the other end behaves meanwhile. Both ends
+// are overlapped, so that a Notifier can watch them, and neither is inherited by a spawned process unless asked to.
+ErrorOr<Array<int, 2>> duplex_pipe()
+{
+ auto security_attributes = TRY(CurrentUserOnlySecurityAttributes::create());
+ auto name = ByteString::formatted("\\\\.\\pipe\\ladybird-{}-{:016x}", GetCurrentProcessId(), get_random<u64>());
+
+ constexpr DWORD buffer_size = 1 * MiB;
+ HANDLE server = CreateNamedPipeA(name.characters(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, buffer_size, buffer_size, 0, security_attributes->attributes());
+ if (server == INVALID_HANDLE_VALUE)
+ return Error::from_windows_error();
+ ArmedScopeGuard close_server = [&] { CloseHandle(server); };
+
+ HANDLE client = CreateFileA(name.characters(), GENERIC_READ | GENERIC_WRITE, 0, security_attributes->attributes(), OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
+ if (client == INVALID_HANDLE_VALUE)
+ return Error::from_windows_error();
+ ArmedScopeGuard close_client = [&] { CloseHandle(client); };
+
+ TRY(wait_for_pipe_client(server));
+
+ // The name was ours alone to know, but a stranger that raced us to it must not get a channel for it.
+ DWORD client_process_id = 0;
+ if (!GetNamedPipeClientProcessId(server, &client_process_id))
+ return Error::from_windows_error();
+ if (client_process_id != GetCurrentProcessId())
+ return Error::from_string_literal("Another process connected to our pipe");
+
+ close_server.disarm();
+ close_client.disarm();
+ return Array<int, 2> { to_fd(server), to_fd(client) };
+}
+
ErrorOr<void> sleep_ms(u32 milliseconds)
{
Sleep(milliseconds);
diff --git a/Libraries/LibIPC/CMakeLists.txt b/Libraries/LibIPC/CMakeLists.txt
index c17271a85cd..a4cd61e23ed 100644
--- a/Libraries/LibIPC/CMakeLists.txt
+++ b/Libraries/LibIPC/CMakeLists.txt
@@ -28,7 +28,7 @@ else()
Attachment.cpp
HandleBroker.cpp
HandleBrokerServer.cpp
- TransportSocketWindows.cpp)
+ TransportWindows.cpp)
endif()
ladybird_lib(LibIPC ipc)
diff --git a/Libraries/LibIPC/Forward.h b/Libraries/LibIPC/Forward.h
index 2f6c022af58..e3cae82e712 100644
--- a/Libraries/LibIPC/Forward.h
+++ b/Libraries/LibIPC/Forward.h
@@ -34,8 +34,8 @@ using Transport = TransportMachPort;
class TransportSocket;
using Transport = TransportSocket;
#else
-class TransportSocketWindows;
-using Transport = TransportSocketWindows;
+class TransportWindows;
+using Transport = TransportWindows;
#endif
template<typename T>
diff --git a/Libraries/LibIPC/HandleBrokerServer.cpp b/Libraries/LibIPC/HandleBrokerServer.cpp
index 162a89cb88c..1dcfe835636 100644
--- a/Libraries/LibIPC/HandleBrokerServer.cpp
+++ b/Libraries/LibIPC/HandleBrokerServer.cpp
@@ -6,7 +6,6 @@
#include <AK/MemoryStream.h>
#include <LibCore/EventLoop.h>
-#include <LibCore/Socket.h>
#include <LibCore/System.h>
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
@@ -210,12 +209,12 @@ void HandleBrokerServer::remove_child(HandleBrokerChildConnection& child)
m_children.remove_first_matching([&](auto const& entry) { return entry.ptr() == &child; });
}
-void HandleBrokerServer::add_child(pid_t pid, int socket_fd)
+void HandleBrokerServer::add_child(pid_t pid, int channel_handle)
{
HANDLE process_handle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid);
if (!process_handle) {
dbgln("HandleBrokerServer: Could not open process {} to serve it handles: {}", pid, Error::from_windows_error());
- (void)Core::System::close(socket_fd);
+ (void)Core::System::close(channel_handle);
return;
}
@@ -224,17 +223,15 @@ void HandleBrokerServer::add_child(pid_t pid, int socket_fd)
// A transport is read on the thread that constructs it, so the broker thread constructs this one.
event_loop->deferred_invoke([=, this] {
- auto socket = Core::LocalSocket::adopt_fd(socket_fd);
- if (!socket.is_error() && socket.value()->set_blocking(false).is_error())
- socket = Error::from_string_literal("Could not make the socket non-blocking");
- if (socket.is_error()) {
- dbgln("HandleBrokerServer: Could not adopt the handle broker socket of process {}: {}", pid, socket.error());
- (void)Core::System::close(socket_fd);
+ auto transport_or_error = Transport::adopt_fd(channel_handle);
+ if (transport_or_error.is_error()) {
+ dbgln("HandleBrokerServer: Could not adopt the handle broker channel of process {}: {}", pid, transport_or_error.error());
+ (void)Core::System::close(channel_handle);
CloseHandle(process_handle);
return;
}
- auto transport = make<Transport>(socket.release_value());
+ auto transport = transport_or_error.release_value();
// Every other process waits on this thread, so one that stops reading its answers is dropped, not waited for.
transport->set_disconnects_when_peer_stops_reading(true);
auto child = make<HandleBrokerChildConnection>(*this, pid, move(transport), process_handle);
diff --git a/Libraries/LibIPC/HandleBrokerServer.h b/Libraries/LibIPC/HandleBrokerServer.h
index ad77d9303d2..6fd309da7a4 100644
--- a/Libraries/LibIPC/HandleBrokerServer.h
+++ b/Libraries/LibIPC/HandleBrokerServer.h
@@ -38,7 +38,7 @@ public:
~HandleBrokerServer();
// The caller keeps the child's process alive until this returns, so its process ID cannot name another by then.
- void add_child(pid_t, int socket_fd);
+ void add_child(pid_t, int channel_handle);
private:
friend class HandleBrokerChildConnection;
diff --git a/Libraries/LibIPC/StartupTransport.cpp b/Libraries/LibIPC/StartupTransport.cpp
index 52ec7a3a571..c0fddf7b647 100644
--- a/Libraries/LibIPC/StartupTransport.cpp
+++ b/Libraries/LibIPC/StartupTransport.cpp
@@ -32,14 +32,13 @@ ErrorOr<NonnullOwnPtr<Transport>> take_over_startup_transport(StringView mach_se
ErrorOr<NonnullOwnPtr<Transport>> take_over_startup_transport(StringView)
{
# if defined(AK_OS_WINDOWS)
- auto broker_socket = TRY(Core::take_over_socket_from_system_server("handle-broker"));
- broker_socket->set_notifications_enabled(false);
- TRY(broker_socket->set_blocking(false));
- HandleBroker::install(make<HandleBrokerClient>(make<Transport>(move(broker_socket))));
-# endif
-
+ auto broker_transport = TRY(Transport::adopt_fd(TRY(Core::take_over_descriptor_from_system_server("handle-broker"))));
+ HandleBroker::install(make<HandleBrokerClient>(move(broker_transport)));
+ return Transport::adopt_fd(TRY(Core::take_over_descriptor_from_system_server("ipc")));
+# else
auto socket = TRY(Core::take_over_socket_from_system_server("ipc"));
return make<Transport>(move(socket));
+# endif
}
#endif
diff --git a/Libraries/LibIPC/Transport.h b/Libraries/LibIPC/Transport.h
index e0819b1f850..a41b19992bf 100644
--- a/Libraries/LibIPC/Transport.h
+++ b/Libraries/LibIPC/Transport.h
@@ -14,7 +14,7 @@
#elif !defined(AK_OS_WINDOWS)
# include <LibIPC/TransportSocket.h>
#else
-# include <LibIPC/TransportSocketWindows.h>
+# include <LibIPC/TransportWindows.h>
#endif
namespace IPC {
diff --git a/Libraries/LibIPC/TransportHandle.cpp b/Libraries/LibIPC/TransportHandle.cpp
index c0922dcd26a..c1fca56ef4a 100644
--- a/Libraries/LibIPC/TransportHandle.cpp
+++ b/Libraries/LibIPC/TransportHandle.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibCore/Socket.h>
#include <LibCore/System.h>
#include <LibIPC/Attachment.h>
#include <LibIPC/Decoder.h>
@@ -12,9 +11,7 @@
#include <LibIPC/Transport.h>
#include <LibIPC/TransportHandle.h>
-#if defined(AK_OS_WINDOWS)
-# include <AK/Windows.h>
-#else
+#if !defined(AK_OS_WINDOWS)
# include <sys/socket.h>
#endif
@@ -95,25 +92,19 @@ TransportHandle::TransportHandle(File file)
ErrorOr<NonnullOwnPtr<Transport>> TransportHandle::create_transport() const
{
- auto socket = TRY(Core::LocalSocket::adopt_fd(m_file.take_fd()));
- TRY(socket->set_blocking(false));
- return make<Transport>(move(socket));
+ return Transport::adopt_fd(m_file.take_fd());
}
ErrorOr<TransportHandlePair> TransportHandle::create_pair()
{
- int fds[2] {};
# if defined(AK_OS_WINDOWS)
- TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fds));
+ auto handles = TRY(Core::System::duplex_pipe());
+ return TransportHandlePair { TransportHandle { File::adopt_fd(handles[0]) }, TransportHandle { File::adopt_fd(handles[1]) } };
# else
+ int fds[2] {};
TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, fds));
+ return TransportHandlePair { TransportHandle { File::adopt_fd(fds[0]) }, TransportHandle { File::adopt_fd(fds[1]) } };
# endif
- TransportHandlePair pair { TransportHandle { File::adopt_fd(fds[0]) }, TransportHandle { File::adopt_fd(fds[1]) } };
-# if defined(AK_OS_WINDOWS)
- TRY(Core::System::set_close_on_exec(fds[0], true));
- TRY(Core::System::set_close_on_exec(fds[1], true));
-# endif
- return pair;
}
template<>
diff --git a/Libraries/LibIPC/TransportSocket.cpp b/Libraries/LibIPC/TransportSocket.cpp
index 84116f0a569..5b5a5993855 100644
--- a/Libraries/LibIPC/TransportSocket.cpp
+++ b/Libraries/LibIPC/TransportSocket.cpp
@@ -54,6 +54,13 @@ ErrorOr<NonnullOwnPtr<TransportSocket>> TransportSocket::from_socket(NonnullOwnP
return make<TransportSocket>(move(socket));
}
+ErrorOr<NonnullOwnPtr<TransportSocket>> TransportSocket::adopt_fd(int fd)
+{
+ auto socket = TRY(Core::LocalSocket::adopt_fd(fd));
+ TRY(socket->set_blocking(false));
+ return make<TransportSocket>(move(socket));
+}
+
ErrorOr<TransportSocket::Paired> TransportSocket::create_paired()
{
int fds[2] {};
diff --git a/Libraries/LibIPC/TransportSocket.h b/Libraries/LibIPC/TransportSocket.h
index 15a93d6cf71..1caf17443fe 100644
--- a/Libraries/LibIPC/TransportSocket.h
+++ b/Libraries/LibIPC/TransportSocket.h
@@ -89,6 +89,7 @@ public:
};
static ErrorOr<Paired> create_paired();
static ErrorOr<NonnullOwnPtr<TransportSocket>> from_socket(NonnullOwnPtr<Core::LocalSocket> socket);
+ static ErrorOr<NonnullOwnPtr<TransportSocket>> adopt_fd(int fd);
explicit TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket);
~TransportSocket();
diff --git a/Libraries/LibIPC/TransportSocketWindows.cpp b/Libraries/LibIPC/TransportSocketWindows.cpp
deleted file mode 100644
index 202cfd59227..00000000000
--- a/Libraries/LibIPC/TransportSocketWindows.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- * Copyright (c) 2025, stasoid <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Checked.h>
-#include <AK/Mutex.h>
-#include <AK/Random.h>
-#include <AK/ScopeGuard.h>
-#include <AK/Types.h>
-#include <LibCore/System.h>
-#include <LibIPC/File.h>
-#include <LibIPC/HandleBroker.h>
-#include <LibIPC/Limits.h>
-#include <LibIPC/TransportHandle.h>
-#include <LibIPC/TransportSocketWindows.h>
-
-#include <AK/Windows.h>
-
-namespace IPC {
-
-// A message with attachments carries the handle broker token that names them right after its header.
-struct TransportSocketWindows::MessageHeader {
- u32 payload_size { 0 };
- u32 attachment_count { 0 };
-
- size_t token_size() const { return attachment_count > 0 ? sizeof(HandleBrokerToken) : 0; }
-};
-
-ErrorOr<NonnullOwnPtr<TransportSocketWindows>> TransportSocketWindows::from_socket(NonnullOwnPtr<Core::LocalSocket> socket)
-{
- return make<TransportSocketWindows>(move(socket));
-}
-
-ErrorOr<TransportSocketWindows::Paired> TransportSocketWindows::create_paired()
-{
- int fds[2] {};
- TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fds));
-
- ArmedScopeGuard guard_fd_0 { [&] { MUST(Core::System::close(fds[0])); } };
- ArmedScopeGuard guard_fd_1 { [&] { MUST(Core::System::close(fds[1])); } };
-
- auto socket0 = TRY(Core::LocalSocket::adopt_fd(fds[0]));
- guard_fd_0.disarm();
- TRY(socket0->set_close_on_exec(true));
- TRY(socket0->set_blocking(false));
-
- TRY(Core::System::set_close_on_exec(fds[1], true));
- guard_fd_1.disarm();
-
- return Paired {
- make<TransportSocketWindows>(move(socket0)),
- TransportHandle { File::adopt_fd(fds[1]) },
- };
-}
-
-TransportSocketWindows::TransportSocketWindows(NonnullOwnPtr<Core::LocalSocket> socket)
- : m_socket(move(socket))
- , m_handle_broker_channel(get_random<HandleBrokerChannel>())
-{
-}
-
-TransportSocketWindows::~TransportSocketWindows() = default;
-
-void TransportSocketWindows::set_up_read_hook(Function<void()> hook)
-{
- VERIFY(m_socket->is_open());
- m_socket->on_ready_to_read = move(hook);
-}
-
-bool TransportSocketWindows::is_open() const
-{
- return m_socket_is_open.load(AK::MemoryOrder::memory_order_relaxed);
-}
-
-void TransportSocketWindows::close()
-{
- m_socket_is_open.store(false, AK::MemoryOrder::memory_order_relaxed);
- MutexLocker locker(m_send_mutex);
- m_socket->close();
-}
-
-void TransportSocketWindows::close_after_sending_all_pending_messages()
-{
- close();
-}
-
-void TransportSocketWindows::wait_until_readable()
-{
- auto readable = MUST(m_socket->can_read_without_blocking(-1));
- VERIFY(readable);
-}
-
-// Maximum size of accumulated unprocessed bytes before we disconnect the peer
-static constexpr size_t MAX_UNPROCESSED_BUFFER_SIZE = 128 * MiB;
-
-ErrorOr<void> TransportSocketWindows::post_message(MessageDataType bytes, Vector<Attachment>& attachments)
-{
- VERIFY(bytes.size() <= MAX_MESSAGE_PAYLOAD_SIZE);
- VERIFY(attachments.size() <= MAX_MESSAGE_FD_COUNT);
-
- MutexLocker locker(m_send_mutex);
-
- MessageHeader header {
- .payload_size = static_cast<u32>(bytes.size()),
- .attachment_count = static_cast<u32>(attachments.size()),
- };
- HandleBrokerToken attachment_token = 0;
- if (!attachments.is_empty()) {
- attachment_token = TRY(HandleBroker::the().park(m_handle_broker_channel, move(attachments)));
- attachments.clear();
- m_has_parked_attachments = true;
- }
-
- Vector<u8> message_buffer;
- TRY(message_buffer.try_resize(sizeof(MessageHeader) + header.token_size() + bytes.size()));
- memcpy(message_buffer.data(), &header, sizeof(header));
- if (header.token_size() > 0)
- memcpy(message_buffer.data() + sizeof(MessageHeader), &attachment_token, sizeof(attachment_token));
- if (!bytes.is_empty())
- memcpy(message_buffer.data() + sizeof(MessageHeader) + header.token_size(), bytes.data(), bytes.size());
-
- TRY(transfer(message_buffer.span()));
- return {};
-}
-
-ErrorOr<void> TransportSocketWindows::transfer(ReadonlyBytes bytes_to_write)
-{
- // FIXME: The timeout to re-check the open flag will not be needed once sends are moved to an IO thread that
- // teardown stops, as TransportSocket does.
- static constexpr int SEND_POLL_TIMEOUT_MS = 100;
-
- while (!bytes_to_write.is_empty()) {
- if (!is_open())
- return Error::from_string_literal("Transport closed during send");
-
- ErrorOr<size_t> maybe_nwritten = m_socket->write_some(bytes_to_write);
-
- if (maybe_nwritten.is_error()) {
- auto error = maybe_nwritten.release_error();
- if (error.code() != EWOULDBLOCK)
- return error;
- if (m_disconnects_when_peer_stops_reading)
- return Error::from_string_literal("Peer has stopped reading");
-
- struct pollfd pollfd = {
- .fd = static_cast<SOCKET>(m_socket->fd().value()),
- .events = POLLOUT,
- .revents = 0
- };
-
- auto result = WSAPoll(&pollfd, 1, SEND_POLL_TIMEOUT_MS);
- if (result == 1 || result == 0)
- continue;
- if (result == SOCKET_ERROR)
- return Error::from_windows_error();
- dbgln("TransportSocketWindows::transfer: Unexpected WSAPoll result {}", result);
- return Error::from_string_literal("Unexpected WSAPoll result");
- }
-
- bytes_to_write = bytes_to_write.slice(maybe_nwritten.value());
- }
- return {};
-}
-
-TransportSocketWindows::ShouldShutdown TransportSocketWindows::read_as_many_messages_as_possible_without_blocking(Function<void(Message&&)>&& callback)
-{
- auto should_shutdown = ShouldShutdown::No;
-
- while (is_open()) {
-
- u8 buffer[4096];
- auto maybe_bytes_read = m_socket->read_without_waiting({ buffer, sizeof(buffer) });
-
- if (maybe_bytes_read.is_error()) {
- auto error = maybe_bytes_read.release_error();
- if (error.code() == EWOULDBLOCK)
- break;
- if (error.code() == ECONNRESET) {
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
- dbgln("TransportSocketWindows::read_as_many_messages_as_possible_without_blocking: {}", error);
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
-
- auto bytes_read = maybe_bytes_read.release_value();
- if (bytes_read.is_empty()) {
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
-
- if (m_unprocessed_bytes.size() + bytes_read.size() > MAX_UNPROCESSED_BUFFER_SIZE) {
- dbgln("TransportSocketWindows: Unprocessed buffer would exceed {} bytes, disconnecting peer", MAX_UNPROCESSED_BUFFER_SIZE);
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
- if (m_unprocessed_bytes.try_append(bytes_read.data(), bytes_read.size()).is_error()) {
- dbgln("TransportSocketWindows: Failed to append to unprocessed_bytes buffer");
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
- }
-
- size_t index = 0;
- while (index + sizeof(MessageHeader) <= m_unprocessed_bytes.size()) {
- MessageHeader header;
- memcpy(&header, m_unprocessed_bytes.data() + index, sizeof(MessageHeader));
- if (header.payload_size > MAX_MESSAGE_PAYLOAD_SIZE) {
- dbgln("TransportSocketWindows: Rejecting message with payload_size {} exceeding limit {}", header.payload_size, MAX_MESSAGE_PAYLOAD_SIZE);
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
- if (header.attachment_count > MAX_MESSAGE_FD_COUNT) {
- dbgln("TransportSocketWindows: Rejecting message with attachment_count {} exceeding limit {}", header.attachment_count, MAX_MESSAGE_FD_COUNT);
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
-
- Checked<size_t> message_size = header.payload_size;
- message_size += sizeof(MessageHeader);
- message_size += header.token_size();
- if (message_size.has_overflow() || message_size.value() > m_unprocessed_bytes.size() - index)
- break;
-
- Message message;
- if (header.attachment_count > 0) {
- HandleBrokerToken attachment_token = 0;
- memcpy(&attachment_token, m_unprocessed_bytes.data() + index + sizeof(MessageHeader), sizeof(attachment_token));
- auto attachments = HandleBroker::the().redeem(attachment_token);
- if (attachments.is_error() || attachments.value().size() != header.attachment_count) {
- dbgln("TransportSocketWindows: Rejecting message whose attachments the handle broker does not hold");
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
- for (auto& attachment : attachments.value())
- message.attachments.enqueue(move(attachment));
- }
-
- auto const* payload = m_unprocessed_bytes.data() + index + sizeof(MessageHeader) + header.token_size();
- Vector<u8> payload_bytes;
- if (payload_bytes.try_append(payload, header.payload_size).is_error()) {
- dbgln("TransportSocketWindows: Failed to allocate message buffer for payload_size {}", header.payload_size);
- should_shutdown = ShouldShutdown::Yes;
- break;
- }
- message.bytes = ReceivedMessageBytes::from_vector(move(payload_bytes));
- callback(move(message));
- index = message_size.value() + index;
- }
-
- if (index < m_unprocessed_bytes.size()) {
- auto remaining_bytes_or_error = ByteBuffer::copy(m_unprocessed_bytes.span().slice(index));
- if (remaining_bytes_or_error.is_error()) {
- dbgln("TransportSocketWindows: Failed to copy remaining bytes");
- should_shutdown = ShouldShutdown::Yes;
- } else {
- m_unprocessed_bytes = remaining_bytes_or_error.release_value();
- }
- } else {
- m_unprocessed_bytes.clear();
- }
-
- // Nothing the peer has not read by now will ever be read, so the handles that were waiting for it can go.
- if (should_shutdown == ShouldShutdown::Yes && m_has_parked_attachments) {
- HandleBroker::the().forget_channel(m_handle_broker_channel);
- m_has_parked_attachments = false;
- }
-
- return should_shutdown;
-}
-
-ErrorOr<TransportHandle> TransportSocketWindows::release_for_transfer()
-{
- m_socket_is_open.store(false, AK::MemoryOrder::memory_order_relaxed);
- MutexLocker locker(m_send_mutex);
- auto fd = TRY(m_socket->release_fd());
- return TransportHandle { File::adopt_fd(fd) };
-}
-
-}
diff --git a/Libraries/LibIPC/TransportWindows.cpp b/Libraries/LibIPC/TransportWindows.cpp
new file mode 100644
index 00000000000..8b528f69e8f
--- /dev/null
+++ b/Libraries/LibIPC/TransportWindows.cpp
@@ -0,0 +1,449 @@
+/*
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2025, stasoid <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Checked.h>
+#include <AK/NumericLimits.h>
+#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
+#include <LibCore/Notifier.h>
+#include <LibCore/Socket.h>
+#include <LibCore/System.h>
+#include <LibIPC/File.h>
+#include <LibIPC/Limits.h>
+#include <LibIPC/TransportHandle.h>
+#include <LibIPC/TransportWindows.h>
+
+#include <AK/Windows.h>
+
+namespace IPC {
+
+// A message with attachments carries the handle broker token that names them right after its header.
+struct TransportWindows::MessageHeader {
+ u32 payload_size { 0 };
+ u32 attachment_count { 0 };
+
+ size_t token_size() const { return attachment_count > 0 ? sizeof(HandleBrokerToken) : 0; }
+};
+
+// Maximum size of accumulated unprocessed bytes before we disconnect the peer
+static constexpr size_t MAX_UNPROCESSED_BUFFER_SIZE = 128 * MiB;
+
+// A send that cannot complete at once waits in slices this long, so that closing the transport ends the wait.
+static constexpr DWORD SEND_WAIT_SLICE_MS = 100;
+
+class OverlappedOperation {
+ AK_MAKE_NONCOPYABLE(OverlappedOperation);
+ AK_MAKE_NONMOVABLE(OverlappedOperation);
+
+public:
+ OverlappedOperation()
+ {
+ m_overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+ VERIFY(m_overlapped.hEvent);
+ }
+
+ ~OverlappedOperation()
+ {
+ CloseHandle(m_overlapped.hEvent);
+ }
+
+ OVERLAPPED* overlapped() { return &m_overlapped; }
+ HANDLE event() const { return m_overlapped.hEvent; }
+
+private:
+ OVERLAPPED m_overlapped {};
+};
+
+ErrorOr<TransportWindows::Paired> TransportWindows::create_paired()
+{
+ auto handles = TRY(Core::System::duplex_pipe());
+ ArmedScopeGuard guard_remote { [&] { MUST(Core::System::close(handles[1])); } };
+ auto local = TRY(adopt_fd(handles[0]));
+ guard_remote.disarm();
+ return Paired { move(local), TransportHandle { File::adopt_fd(handles[1]) } };
+}
+
+ErrorOr<NonnullOwnPtr<TransportWindows>> TransportWindows::from_socket(NonnullOwnPtr<Core::LocalSocket> socket)
+{
+ socket->set_notifications_enabled(false);
+ return adopt_fd(TRY(socket->release_fd()));
+}
+
+ErrorOr<NonnullOwnPtr<TransportWindows>> TransportWindows::adopt_fd(int handle)
+{
+ if (handle == -1)
+ return Error::from_errno(EBADF);
+ auto kind = Core::System::is_socket(handle) ? Kind::Socket : Kind::Pipe;
+ if (kind == Kind::Socket) {
+ u_long non_blocking = 1;
+ if (ioctlsocket(handle, FIONBIO, &non_blocking) == SOCKET_ERROR)
+ return Error::from_windows_error();
+ }
+ return adopt_own(*new TransportWindows(handle, kind));
+}
+
+TransportWindows::TransportWindows(int handle, Kind kind)
+ : m_handle(handle)
+ , m_kind(kind)
+ , m_handle_broker_channel(get_random<HandleBrokerChannel>())
+{
+}
+
+TransportWindows::~TransportWindows()
+{
+ close();
+}
+
+void TransportWindows::set_up_read_hook(Function<void()> hook)
+{
+ VERIFY(is_open());
+ m_on_read_hook = move(hook);
+ m_read_notifier = Core::Notifier::construct(m_handle, Core::NotificationType::Read);
+ m_read_notifier->on_activation = [this] {
+ if (m_on_read_hook)
+ m_on_read_hook();
+ };
+}
+
+bool TransportWindows::is_open() const
+{
+ return m_is_open.load(AK::MemoryOrder::memory_order_relaxed) && !m_peer_has_hung_up.load(AK::MemoryOrder::memory_order_relaxed);
+}
+
+static bool send_error_means_peer_has_hung_up(Error const& error)
+{
+ if (!error.is_windows_error())
+ return false;
+ switch (error.code()) {
+ case ERROR_NO_DATA:
+ case ERROR_BROKEN_PIPE:
+ case ERROR_PIPE_NOT_CONNECTED:
+ case WSAECONNRESET:
+ case WSAECONNABORTED:
+ case WSAESHUTDOWN:
+ case WSAENOTCONN:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// The notifier has a read of its own in flight on a pipe, which has to end before the handle may go anywhere.
+void TransportWindows::stop_watching()
+{
+ if (auto notifier = move(m_read_notifier))
+ notifier->close();
+}
+
+void TransportWindows::close()
+{
+ m_is_open.store(false, AK::MemoryOrder::memory_order_relaxed);
+ MutexLocker locker(m_send_mutex);
+ stop_watching();
+ if (m_handle != -1) {
+ (void)Core::System::close(m_handle);
+ m_handle = -1;
+ }
+}
+
+void TransportWindows::close_after_sending_all_pending_messages()
+{
+ close();
+}
+
+void TransportWindows::wait_until_readable()
+{
+ if (m_kind == Kind::Socket) {
+ WSAPOLLFD poll_fd {
+ .fd = static_cast<SOCKET>(m_handle),
+ .events = POLLRDNORM,
+ .revents = 0,
+ };
+ auto result = WSAPoll(&poll_fd, 1, -1);
+ VERIFY(result != SOCKET_ERROR);
+ return;
+ }
+
+ // A zero-byte read completes once there is something to read, or once the pipe is broken.
+ OverlappedOperation operation;
+ static u8 s_zero_byte_buffer;
+ if (ReadFile(to_handle(m_handle), &s_zero_byte_buffer, 0, nullptr, operation.overlapped()))
+ return;
+ if (GetLastError() != ERROR_IO_PENDING)
+ return;
+ WaitForSingleObject(operation.event(), INFINITE);
+}
+
+ErrorOr<size_t> TransportWindows::write_some(ReadonlyBytes bytes)
+{
+ if (m_kind == Kind::Socket) {
+ auto sent = ::send(static_cast<SOCKET>(m_handle), reinterpret_cast<char const*>(bytes.data()), static_cast<int>(min(bytes.size(), static_cast<size_t>(NumericLimits<int>::max()))), 0);
+ if (sent == SOCKET_ERROR) {
+ if (WSAGetLastError() == WSAEWOULDBLOCK)
+ return Error::from_errno(EWOULDBLOCK);
+ return Error::from_windows_error();
+ }
+ return static_cast<size_t>(sent);
+ }
+
+ // A pipe write completes only once every byte is in the pipe, so it is waited for in slices that notice a close.
+ OverlappedOperation operation;
+ DWORD bytes_written = 0;
+ auto size = static_cast<DWORD>(min(bytes.size(), static_cast<size_t>(NumericLimits<DWORD>::max())));
+ if (WriteFile(to_handle(m_handle), bytes.data(), size, &bytes_written, operation.overlapped()))
+ return static_cast<size_t>(bytes_written);
+ if (GetLastError() != ERROR_IO_PENDING)
+ return Error::from_windows_error();
+
+ for (;;) {
+ if (m_disconnects_when_peer_stops_reading || !is_open()) {
+ CancelIoEx(to_handle(m_handle), operation.overlapped());
+ GetOverlappedResult(to_handle(m_handle), operation.overlapped(), &bytes_written, TRUE);
+ if (!is_open())
+ return Error::from_string_literal("Transport closed during send");
+ return Error::from_string_literal("Peer has stopped reading");
+ }
+ if (WaitForSingleObject(operation.event(), SEND_WAIT_SLICE_MS) == WAIT_OBJECT_0)
+ break;
+ }
+ if (!GetOverlappedResult(to_handle(m_handle), operation.overlapped(), &bytes_written, FALSE))
+ return Error::from_windows_error();
+ return static_cast<size_t>(bytes_written);
+}
+
+ErrorOr<void> TransportWindows::transfer(ReadonlyBytes bytes_to_write)
+{
+ while (!bytes_to_write.is_empty()) {
+ if (!is_open())
+ return Error::from_string_literal("Transport closed during send");
+
+ auto written = write_some(bytes_to_write);
+ if (written.is_error()) {
+ auto error = written.release_error();
+ if (!error.is_errno() || error.code() != EWOULDBLOCK) {
+ if (send_error_means_peer_has_hung_up(error))
+ m_peer_has_hung_up.store(true, AK::MemoryOrder::memory_order_relaxed);
+ return error;
+ }
+ if (m_disconnects_when_peer_stops_reading)
+ return Error::from_string_literal("Peer has stopped reading");
+
+ WSAPOLLFD poll_fd {
+ .fd = static_cast<SOCKET>(m_handle),
+ .events = POLLWRNORM,
+ .revents = 0,
+ };
+ if (WSAPoll(&poll_fd, 1, SEND_WAIT_SLICE_MS) == SOCKET_ERROR)
+ return Error::from_windows_error();
+ continue;
+ }
+ bytes_to_write = bytes_to_write.slice(written.value());
+ }
+ return {};
+}
+
+ErrorOr<void> TransportWindows::post_message(MessageDataType bytes, Vector<Attachment>& attachments)
+{
+ VERIFY(bytes.size() <= MAX_MESSAGE_PAYLOAD_SIZE);
+ VERIFY(attachments.size() <= MAX_MESSAGE_FD_COUNT);
+
+ MutexLocker locker(m_send_mutex);
+
+ MessageHeader header {
+ .payload_size = static_cast<u32>(bytes.size()),
+ .attachment_count = static_cast<u32>(attachments.size()),
+ };
+ HandleBrokerToken attachment_token = 0;
+ if (!attachments.is_empty()) {
+ attachment_token = TRY(HandleBroker::the().park(m_handle_broker_channel, move(attachments)));
+ attachments.clear();
+ m_has_parked_attachments = true;
+ }
+
+ Vector<u8> message_buffer;
+ TRY(message_buffer.try_resize(sizeof(MessageHeader) + header.token_size() + bytes.size()));
+ memcpy(message_buffer.data(), &header, sizeof(header));
+ if (header.token_size() > 0)
+ memcpy(message_buffer.data() + sizeof(MessageHeader), &attachment_token, sizeof(attachment_token));
+ if (!bytes.is_empty())
+ memcpy(message_buffer.data() + sizeof(MessageHeader) + header.token_size(), bytes.data(), bytes.size());
+
+ return transfer(message_buffer.span());
+}
+
+TransportWindows::ReadOutcome TransportWindows::read_some_without_waiting(Bytes buffer, size_t& bytes_read)
+{
+ bytes_read = 0;
+ if (m_kind == Kind::Socket) {
+ WSAPOLLFD poll_fd {
+ .fd = static_cast<SOCKET>(m_handle),
+ .events = POLLRDNORM,
+ .revents = 0,
+ };
+ auto ready = WSAPoll(&poll_fd, 1, 0);
+ if (ready == 0)
+ return ReadOutcome::WouldBlock;
+ if (ready == SOCKET_ERROR)
+ return ReadOutcome::Failed;
+ auto received = ::recv(static_cast<SOCKET>(m_handle), reinterpret_cast<char*>(buffer.data()), static_cast<int>(min(buffer.size(), static_cast<size_t>(NumericLimits<int>::max()))), 0);
+ if (received == 0)
+ return ReadOutcome::EndOfStream;
+ if (received == SOCKET_ERROR) {
+ auto error = WSAGetLastError();
+ if (error == WSAEWOULDBLOCK)
+ return ReadOutcome::WouldBlock;
+ if (error == WSAECONNRESET || error == WSAECONNABORTED)
+ return ReadOutcome::EndOfStream;
+ dbgln("TransportWindows: recv failed: {}", Error::from_windows_error(error));
+ return ReadOutcome::Failed;
+ }
+ bytes_read = static_cast<size_t>(received);
+ return ReadOutcome::Read;
+ }
+
+ DWORD bytes_available = 0;
+ if (!PeekNamedPipe(to_handle(m_handle), nullptr, 0, nullptr, &bytes_available, nullptr)) {
+ auto error = GetLastError();
+ if (error == ERROR_BROKEN_PIPE || error == ERROR_PIPE_NOT_CONNECTED || error == ERROR_NO_DATA)
+ return ReadOutcome::EndOfStream;
+ dbgln("TransportWindows: PeekNamedPipe failed: {}", Error::from_windows_error(error));
+ return ReadOutcome::Failed;
+ }
+ if (bytes_available == 0)
+ return ReadOutcome::WouldBlock;
+
+ // What is there to read is read at once, so this never waits.
+ OverlappedOperation operation;
+ DWORD read_now = 0;
+ auto size = static_cast<DWORD>(min(buffer.size(), static_cast<size_t>(bytes_available)));
+ if (!ReadFile(to_handle(m_handle), buffer.data(), size, &read_now, operation.overlapped())) {
+ auto error = GetLastError();
+ if (error == ERROR_IO_PENDING) {
+ if (!GetOverlappedResult(to_handle(m_handle), operation.overlapped(), &read_now, TRUE))
+ error = GetLastError();
+ else
+ error = ERROR_SUCCESS;
+ }
+ if (error == ERROR_BROKEN_PIPE || error == ERROR_PIPE_NOT_CONNECTED)
+ return ReadOutcome::EndOfStream;
+ if (error != ERROR_SUCCESS) {
+ dbgln("TransportWindows: ReadFile failed: {}", Error::from_windows_error(error));
+ return ReadOutcome::Failed;
+ }
+ }
+ bytes_read = read_now;
+ return ReadOutcome::Read;
+}
+
+TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_possible_without_blocking(Function<void(Message&&)>&& callback)
+{
+ auto should_shutdown = ShouldShutdown::No;
+
+ // What the peer sent before hanging up is still here to be read, so only this end closing stops the reading.
+ while (m_is_open.load(AK::MemoryOrder::memory_order_relaxed)) {
+ u8 buffer[4096];
+ size_t bytes_read = 0;
+ auto outcome = read_some_without_waiting({ buffer, sizeof(buffer) }, bytes_read);
+ if (outcome == ReadOutcome::WouldBlock)
+ break;
+ if (outcome != ReadOutcome::Read) {
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+
+ if (m_unprocessed_bytes.size() + bytes_read > MAX_UNPROCESSED_BUFFER_SIZE) {
+ dbgln("TransportWindows: Unprocessed buffer would exceed {} bytes, disconnecting peer", MAX_UNPROCESSED_BUFFER_SIZE);
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+ if (m_unprocessed_bytes.try_append(buffer, bytes_read).is_error()) {
+ dbgln("TransportWindows: Failed to append to unprocessed_bytes buffer");
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+ }
+
+ size_t index = 0;
+ while (index + sizeof(MessageHeader) <= m_unprocessed_bytes.size()) {
+ MessageHeader header;
+ memcpy(&header, m_unprocessed_bytes.data() + index, sizeof(MessageHeader));
+ if (header.payload_size > MAX_MESSAGE_PAYLOAD_SIZE) {
+ dbgln("TransportWindows: Rejecting message with payload_size {} exceeding limit {}", header.payload_size, MAX_MESSAGE_PAYLOAD_SIZE);
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+ if (header.attachment_count > MAX_MESSAGE_FD_COUNT) {
+ dbgln("TransportWindows: Rejecting message with attachment_count {} exceeding limit {}", header.attachment_count, MAX_MESSAGE_FD_COUNT);
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+
+ Checked<size_t> message_size = header.payload_size;
+ message_size += sizeof(MessageHeader);
+ message_size += header.token_size();
+ if (message_size.has_overflow() || message_size.value() > m_unprocessed_bytes.size() - index)
+ break;
+
+ Message message;
+ if (header.attachment_count > 0) {
+ HandleBrokerToken attachment_token = 0;
+ memcpy(&attachment_token, m_unprocessed_bytes.data() + index + sizeof(MessageHeader), sizeof(attachment_token));
+ auto attachments = HandleBroker::the().redeem(attachment_token);
+ if (attachments.is_error() || attachments.value().size() != header.attachment_count) {
+ dbgln("TransportWindows: Rejecting message whose attachments the handle broker does not hold");
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+ for (auto& attachment : attachments.value())
+ message.attachments.enqueue(move(attachment));
+ }
+
+ auto const* payload = m_unprocessed_bytes.data() + index + sizeof(MessageHeader) + header.token_size();
+ Vector<u8> payload_bytes;
+ if (payload_bytes.try_append(payload, header.payload_size).is_error()) {
+ dbgln("TransportWindows: Failed to allocate message buffer for payload_size {}", header.payload_size);
+ should_shutdown = ShouldShutdown::Yes;
+ break;
+ }
+ message.bytes = ReceivedMessageBytes::from_vector(move(payload_bytes));
+ callback(move(message));
+ index = message_size.value() + index;
+ }
+
+ if (index < m_unprocessed_bytes.size()) {
+ auto remaining_bytes_or_error = ByteBuffer::copy(m_unprocessed_bytes.span().slice(index));
+ if (remaining_bytes_or_error.is_error()) {
+ dbgln("TransportWindows: Failed to copy remaining bytes");
+ should_shutdown = ShouldShutdown::Yes;
+ } else {
+ m_unprocessed_bytes = remaining_bytes_or_error.release_value();
+ }
+ } else {
+ m_unprocessed_bytes.clear();
+ }
+
+ // Nothing the peer has not read by now will ever be read, so the handles that were waiting for it can go.
+ if (should_shutdown == ShouldShutdown::Yes && m_has_parked_attachments) {
+ HandleBroker::the().forget_channel(m_handle_broker_channel);
+ m_has_parked_attachments = false;
+ }
+
+ return should_shutdown;
+}
+
+ErrorOr<TransportHandle> TransportWindows::release_for_transfer()
+{
+ m_is_open.store(false, AK::MemoryOrder::memory_order_relaxed);
+ MutexLocker locker(m_send_mutex);
+ stop_watching();
+ if (m_handle == -1)
+ return Error::from_errno(ENOTCONN);
+ return TransportHandle { File::adopt_fd(exchange(m_handle, -1)) };
+}
+
+}
diff --git a/Libraries/LibIPC/TransportSocketWindows.h b/Libraries/LibIPC/TransportWindows.h
similarity index 51%
rename from Libraries/LibIPC/TransportSocketWindows.h
rename to Libraries/LibIPC/TransportWindows.h
index 21350f202f5..88dfa0ca30d 100644
--- a/Libraries/LibIPC/TransportSocketWindows.h
+++ b/Libraries/LibIPC/TransportWindows.h
@@ -1,6 +1,7 @@
/*
* Copyright (c) 2024, Andrew Kaster <[email protected]>
* Copyright (c) 2025, stasoid <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -8,10 +9,13 @@
#pragma once
#include <AK/Atomic.h>
+#include <AK/ByteBuffer.h>
+#include <AK/Function.h>
#include <AK/Mutex.h>
#include <AK/Queue.h>
+#include <AK/RefPtr.h>
#include <AK/kmalloc.h>
-#include <LibCore/Socket.h>
+#include <LibCore/Forward.h>
#include <LibIPC/Attachment.h>
#include <LibIPC/Forward.h>
#include <LibIPC/HandleBroker.h>
@@ -20,25 +24,25 @@
namespace IPC {
-// A Windows socket carries bytes alone, so the attachments of a message are parked with the handle broker and the
-// message carries their token. The Browser copies them out of this process and into the peer, so neither needs any
-// right over the other.
-class TransportSocketWindows {
- AK_MAKE_NONCOPYABLE(TransportSocketWindows);
- AK_MAKE_NONMOVABLE(TransportSocketWindows);
+// Moves messages over a duplex named pipe, or over a socket for the few connections that arrive on one. Neither can
+// carry a handle, so the attachments of a message are parked with the handle broker and the message carries their
+// token. The Browser copies them out of this process and into the peer, so neither needs any right over the other.
+class TransportWindows {
+ AK_MAKE_NONCOPYABLE(TransportWindows);
+ AK_MAKE_NONMOVABLE(TransportWindows);
public:
AK_ALLOC_WITH_KMALLOC;
struct Paired {
- NonnullOwnPtr<TransportSocketWindows> local;
+ NonnullOwnPtr<TransportWindows> local;
TransportHandle remote_handle;
};
static ErrorOr<Paired> create_paired();
- static ErrorOr<NonnullOwnPtr<TransportSocketWindows>> from_socket(NonnullOwnPtr<Core::LocalSocket> socket);
+ static ErrorOr<NonnullOwnPtr<TransportWindows>> from_socket(NonnullOwnPtr<Core::LocalSocket>);
+ static ErrorOr<NonnullOwnPtr<TransportWindows>> adopt_fd(int handle);
- explicit TransportSocketWindows(NonnullOwnPtr<Core::LocalSocket> socket);
- ~TransportSocketWindows();
+ ~TransportWindows();
void set_up_read_hook(Function<void()>);
bool is_open() const;
@@ -50,8 +54,8 @@ public:
void wait_until_readable();
- // Both are no-ops here: post_message() writes to the socket before it returns, and the read path below reads the
- // socket itself, so neither direction has a queue that can lag behind another transport.
+ // Both are no-ops here: post_message() writes to the pipe before it returns, and the read path below reads the
+ // pipe itself, so neither direction has a queue that can lag behind another transport.
void flush() { }
void wait_until_incoming_is_current() { }
@@ -70,14 +74,34 @@ public:
ErrorOr<TransportHandle> release_for_transfer();
private:
+ enum class Kind : u8 {
+ Pipe,
+ Socket,
+ };
struct MessageHeader;
+ enum class ReadOutcome : u8 {
+ Read,
+ WouldBlock,
+ EndOfStream,
+ Failed,
+ };
- ErrorOr<void> transfer(ReadonlyBytes);
+ TransportWindows(int handle, Kind);
- NonnullOwnPtr<Core::LocalSocket> m_socket;
- Atomic<bool> m_socket_is_open { true };
+ ErrorOr<void> transfer(ReadonlyBytes);
+ ErrorOr<size_t> write_some(ReadonlyBytes);
+ ReadOutcome read_some_without_waiting(Bytes, size_t& bytes_read);
+ void stop_watching();
+
+ int m_handle { -1 };
+ Kind m_kind { Kind::Pipe };
+ Atomic<bool> m_is_open { true };
+ // Set once a send has found the peer gone, so is_open() says so before the read side has reached its end.
+ Atomic<bool> m_peer_has_hung_up { false };
Mutex m_send_mutex;
ByteBuffer m_unprocessed_bytes;
+ RefPtr<Core::Notifier> m_read_notifier;
+ Function<void()> m_on_read_hook;
// Names this end to the handle broker, so what it parked can be forgotten once the peer can no longer read it.
HandleBrokerChannel m_handle_broker_channel { 0 };
bool m_has_parked_attachments { false };
diff --git a/Libraries/LibWebView/Process.cpp b/Libraries/LibWebView/Process.cpp
index f028f3f8af0..00dc9e6b76c 100644
--- a/Libraries/LibWebView/Process.cpp
+++ b/Libraries/LibWebView/Process.cpp
@@ -217,13 +217,30 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
Application::transport_bootstrap_server().register_child_transport(process.pid(), IPC::TransportBootstrapMachPorts { move(port_b_recv), move(port_a_send) });
auto transport = make<IPC::Transport>(move(port_a_recv), move(port_b_send));
+#elif defined(AK_OS_WINDOWS)
+ // A Windows pipe cannot carry a handle, so the helper also gets a line to the Browser's handle broker.
+ auto channel = TRY(Core::System::duplex_pipe());
+ ArmedScopeGuard guard_channel_0 { [&] { MUST(Core::System::close(channel[0])); } };
+ ArmedScopeGuard guard_channel_1 { [&] { MUST(Core::System::close(channel[1])); } };
+ auto broker_channel = TRY(Core::System::duplex_pipe());
+ ArmedScopeGuard guard_broker_channel_0 { [&] { MUST(Core::System::close(broker_channel[0])); } };
+ ArmedScopeGuard guard_broker_channel_1 { [&] { MUST(Core::System::close(broker_channel[1])); } };
+
+ // Only the helper's ends reach the helper, and only this helper.
+ spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = channel[1], .fd = channel[1] });
+ spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = broker_channel[1], .fd = broker_channel[1] });
+ TRY(Core::Environment::set("SOCKET_TAKEOVER"sv, ByteString::formatted("ipc:{};handle-broker:{}", channel[1], broker_channel[1]), Core::Environment::Overwrite::Yes));
+
+ auto process = TRY(Core::Process::spawn(spawn_options));
+
+ auto transport = TRY(IPC::Transport::adopt_fd(channel[0]));
+ guard_channel_0.disarm();
+
+ guard_broker_channel_0.disarm();
+ Application::handle_broker_server().add_child(process.pid(), broker_channel[0]);
#else
int socket_fds[2] {};
-# if defined(AK_OS_WINDOWS)
- TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds));
-# else
TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, socket_fds));
-# endif
ArmedScopeGuard guard_fd_0 { [&] { MUST(Core::System::close(socket_fds[0])); } };
ArmedScopeGuard guard_fd_1 { [&] { MUST(Core::System::close(socket_fds[1])); } };
@@ -233,17 +250,6 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
// NB: Only the helper gets to see this, if it has an environment of its own.
auto takeover_string = ByteString::formatted("ipc:{}", socket_fds[1]);
-
-# if defined(AK_OS_WINDOWS)
- // A Windows socket cannot carry a handle, so the helper also gets a line to the Browser's handle broker.
- int broker_socket_fds[2] {};
- TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, broker_socket_fds));
- ArmedScopeGuard guard_broker_fd_0 { [&] { MUST(Core::System::close(broker_socket_fds[0])); } };
- ArmedScopeGuard guard_broker_fd_1 { [&] { MUST(Core::System::close(broker_socket_fds[1])); } };
- spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = broker_socket_fds[1], .fd = broker_socket_fds[1] });
- takeover_string = ByteString::formatted("{};handle-broker:{}", takeover_string, broker_socket_fds[1]);
-# endif
-
if (spawn_options.environment.has_value())
spawn_options.environment->append(ByteString::formatted("SOCKET_TAKEOVER={}", takeover_string));
else
@@ -256,11 +262,6 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
TRY(ipc_socket->set_blocking(true));
auto transport = make<IPC::Transport>(move(ipc_socket));
-
-# if defined(AK_OS_WINDOWS)
- guard_broker_fd_0.disarm();
- Application::handle_broker_server().add_child(process.pid(), broker_socket_fds[0]);
-# endif
#endif
if (capture_output) {
diff --git a/Services/WebDriver/Session.cpp b/Services/WebDriver/Session.cpp
index 6e27ffa3c6d..8c0cf350eb1 100644
--- a/Services/WebDriver/Session.cpp
+++ b/Services/WebDriver/Session.cpp
@@ -594,7 +594,7 @@ void Session::remove_window(StringView window_handle)
ErrorOr<void> Session::create_server()
{
#if defined(AK_OS_WINDOWS)
- static_assert(IsSame<IPC::Transport, IPC::TransportSocketWindows>, "Need to handle other IPC transports here");
+ static_assert(IsSame<IPC::Transport, IPC::TransportWindows>, "Need to handle other IPC transports here");
#elif defined(AK_OS_MACOS)
static_assert(IsSame<IPC::Transport, IPC::TransportMachPort>, "Need to handle other IPC transports here");
#else
diff --git a/UI/Qt/EventLoopImplementationQt.cpp b/UI/Qt/EventLoopImplementationQt.cpp
index 0005741ba02..c96d0c59c2d 100644
--- a/UI/Qt/EventLoopImplementationQt.cpp
+++ b/UI/Qt/EventLoopImplementationQt.cpp
@@ -30,6 +30,7 @@
#include <QTimer>
#if defined(AK_OS_WINDOWS)
# include <AK/Windows.h>
+# include <QPointer>
# include <QWinEventNotifier>
#endif
@@ -39,8 +40,87 @@ constexpr bool AllocatedWithSystemAllocator<QEventLoop> = true;
template<>
constexpr bool AllocatedWithSystemAllocator<QSocketNotifier> = true;
+template<>
+constexpr bool AllocatedWithSystemAllocator<QObject> = true;
+
+#if defined(AK_OS_WINDOWS)
+namespace Ladybird {
+
+class PipeNotifier;
+
+}
+
+template<>
+constexpr bool AllocatedWithSystemAllocator<Ladybird::PipeNotifier> = true;
+#endif
+
namespace Ladybird {
+static void qt_notifier_activated(Core::Notifier&);
+
+#if defined(AK_OS_WINDOWS)
+
+// QSocketNotifier watches only a socket on Windows. A pipe is watched by a zero-byte overlapped read of it, which ends
+// once there is something to read or the pipe is broken, and signals the event this waits on.
+class PipeNotifier final : public QWinEventNotifier {
+public:
+ explicit PipeNotifier(Core::Notifier& notifier)
+ : QWinEventNotifier(CreateEvent(nullptr, FALSE, FALSE, nullptr))
+ , m_pipe(to_handle(notifier.fd()))
+ {
+ VERIFY(handle());
+ QObject::connect(this, &QWinEventNotifier::activated, this, [self = QPointer<PipeNotifier>(this), weak_notifier = notifier.make_weak_ptr()] {
+ if (auto notifier = weak_notifier.strong_ref())
+ qt_notifier_activated(static_cast<Core::Notifier&>(*notifier));
+ // The reader may have unregistered this, and so deleted it, from within the activation.
+ if (self)
+ self->read_until_readable();
+ });
+ read_until_readable();
+ }
+
+ ~PipeNotifier()
+ {
+ setEnabled(false);
+ cancel_read();
+ CloseHandle(handle());
+ }
+
+private:
+ void read_until_readable()
+ {
+ static u8 s_zero_byte_buffer;
+ m_read = {};
+ m_read.hEvent = handle();
+ m_read_is_pending = false;
+ if (ReadFile(m_pipe, &s_zero_byte_buffer, 0, nullptr, &m_read))
+ return;
+ if (GetLastError() == ERROR_IO_PENDING) {
+ m_read_is_pending = true;
+ return;
+ }
+ // A read that fails at once, as one does at the end of the pipe, does not set the event, but the reader must
+ // still be activated to see it.
+ SetEvent(handle());
+ }
+
+ void cancel_read()
+ {
+ if (!m_read_is_pending || HasOverlappedIoCompleted(&m_read))
+ return;
+ CancelIoEx(m_pipe, &m_read);
+ // The read must have stopped writing to m_read before it can be freed.
+ while (!HasOverlappedIoCompleted(&m_read))
+ WaitForSingleObject(handle(), INFINITE);
+ }
+
+ ::HANDLE m_pipe { nullptr };
+ OVERLAPPED m_read {};
+ bool m_read_is_pending { false };
+};
+
+#endif
+
struct ThreadData;
static thread_local OwnPtr<ThreadData> s_this_thread_data;
static HashMap<pthread_t, ThreadData*> s_thread_data;
@@ -79,7 +159,7 @@ struct ThreadData {
}
Mutex mutex;
- HashMap<Core::Notifier*, NonnullOwnPtr<QSocketNotifier>> notifiers;
+ HashMap<Core::Notifier*, NonnullOwnPtr<QObject>> notifiers;
};
class QtEventLoopManagerEvent final : public QEvent {
@@ -336,7 +416,7 @@ static void qt_notifier_activated(Core::Notifier& notifier)
notifier.dispatch_event(event);
}
-void EventLoopManagerQt::register_notifier(Core::Notifier& notifier)
+static NonnullOwnPtr<QObject> make_socket_notifier(Core::Notifier& notifier)
{
QSocketNotifier::Type type;
switch (notifier.type()) {
@@ -355,11 +435,25 @@ void EventLoopManagerQt::register_notifier(Core::Notifier& notifier)
if (auto notifier = weak_notifier.strong_ref())
qt_notifier_activated(static_cast<Core::Notifier&>(*notifier));
});
+ return socket_notifier;
+}
+
+void EventLoopManagerQt::register_notifier(Core::Notifier& notifier)
+{
+ NonnullOwnPtr<QObject> qt_notifier = [&]() -> NonnullOwnPtr<QObject> {
+#if defined(AK_OS_WINDOWS)
+ if (!Core::System::is_socket(notifier.fd()) && GetFileType(to_handle(notifier.fd())) == FILE_TYPE_PIPE) {
+ VERIFY(notifier.type() == Core::Notifier::Type::Read);
+ return make<PipeNotifier>(notifier);
+ }
+#endif
+ return make_socket_notifier(notifier);
+ }();
{
auto& thread_data = ThreadData::the();
MutexLocker locker(thread_data.mutex);
- thread_data.notifiers.set(&notifier, move(socket_notifier));
+ thread_data.notifiers.set(&notifier, move(qt_notifier));
}
notifier.set_owner_thread(s_thread_id.value());
}