Skip to content

Truly independent web browser

RequestServer: Hand responses over between RequestServers

Ali Mohammad Purc855deedc1a7
diff --git a/Libraries/LibCore/System.h b/Libraries/LibCore/System.h
index 3077560047e..39ad81470d8 100644
--- a/Libraries/LibCore/System.h
+++ b/Libraries/LibCore/System.h
@@ -160,7 +160,7 @@ ErrorOr<void> connect(int sockfd, struct sockaddr const*, socklen_t);
CORE_API ErrorOr<size_t> send(int sockfd, ReadonlyBytes, int flags);
ErrorOr<size_t> sendmsg(int sockfd, const struct msghdr*, int flags);
ErrorOr<size_t> sendto(int sockfd, ReadonlyBytes, int flags, struct sockaddr const*, socklen_t);
-ErrorOr<size_t> recv(int sockfd, Bytes, int flags);
+CORE_API ErrorOr<size_t> recv(int sockfd, Bytes, int flags);
ErrorOr<size_t> recvmsg(int sockfd, struct msghdr*, int flags);
ErrorOr<size_t> recvfrom(int sockfd, Bytes, int flags, struct sockaddr*, socklen_t*);
ErrorOr<void> getsockopt(int sockfd, int level, int option, void* value, socklen_t* value_size);
diff --git a/Libraries/LibCore/SystemWindows.cpp b/Libraries/LibCore/SystemWindows.cpp
index 624bd19f6f9..1e000f2a847 100644
--- a/Libraries/LibCore/SystemWindows.cpp
+++ b/Libraries/LibCore/SystemWindows.cpp
@@ -207,6 +207,21 @@ ErrorOr<size_t> sendto(int sockfd, ReadonlyBytes data, int flags, struct sockadd
return sent;
}
+ErrorOr<size_t> recv(int sockfd, Bytes buffer, int flags)
+{
+ auto received = ::recv(sockfd, reinterpret_cast<char*>(buffer.data()), static_cast<int>(buffer.size()), flags);
+
+ if (received == SOCKET_ERROR) {
+ auto error = WSAGetLastError();
+
+ return error == WSAEWOULDBLOCK
+ ? Error::from_errno(EWOULDBLOCK)
+ : Error::from_windows_error(error);
+ }
+
+ return received;
+}
+
ErrorOr<size_t> recvfrom(int sockfd, Bytes buffer, int flags, struct sockaddr* address, socklen_t* address_length)
{
auto received = ::recvfrom(sockfd, reinterpret_cast<char*>(buffer.data()), static_cast<int>(buffer.size()), flags, address, address_length);
diff --git a/Libraries/LibRequests/RequestClient.cpp b/Libraries/LibRequests/RequestClient.cpp
index 51b740b313f..6cb0c645f68 100644
--- a/Libraries/LibRequests/RequestClient.cpp
+++ b/Libraries/LibRequests/RequestClient.cpp
@@ -100,6 +100,27 @@ RefPtr<Request> RequestClient::adopt_request(int source_client_id, u64 source_re
return request;
}
+ErrorOr<ExportedRequest> RequestClient::export_request(Request& request)
+{
+ auto exported = IPCProxy::export_request(request.id());
+ if (!exported.has_value())
+ return Error::from_string_literal("RequestServer refused to export the request");
+ return exported.release_value();
+}
+
+RefPtr<Request> RequestClient::import_request(ExportedRequest exported, TransferLease transfer_lease)
+{
+ auto request_id = m_next_request_id++;
+
+ auto transfer_lease_key = transfer_lease == TransferLease::Yes
+ ? Optional<RequestTransferLeaseKey> { { m_request_server_client_id, request_id } }
+ : Optional<RequestTransferLeaseKey> {};
+ IPCProxy::async_import_request(request_id, move(exported), transfer_lease_key.has_value());
+ auto request = Request::create_from_id({}, *this, request_id, move(transfer_lease_key));
+ m_requests.set(request_id, request);
+ return request;
+}
+
ErrorOr<Optional<Core::ImmutableBytes>> RequestClient::store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key, URL::URL const& url, ByteString const& method, Optional<HTTP::HeaderList const&> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, ReadonlyBytes data)
{
auto buffer = TRY(Core::AnonymousBuffer::create_with_size(data.size()));
@@ -226,8 +247,9 @@ void RequestClient::headers_became_available(u64 request_id, Vector<HTTP::Header
if (javascript_bytecode_file.has_value())
javascript_bytecode = map_cache_associated_data_file(javascript_bytecode_file->take_fd(), javascript_bytecode_size);
- if (auto request = m_requests.get(request_id); request.has_value())
- (*request)->did_receive_headers({}, HTTP::HeaderList::create(move(response_headers)), status_code, reason_phrase, move(javascript_bytecode), javascript_bytecode_cache_vary_key, cache_state);
+ RefPtr<Request> request = m_requests.get(request_id).value_or(nullptr);
+ if (request)
+ request->did_receive_headers({}, HTTP::HeaderList::create(move(response_headers)), status_code, reason_phrase, move(javascript_bytecode), javascript_bytecode_cache_vary_key, cache_state);
else
warnln("Received headers for non-existent request {}", request_id);
}
diff --git a/Libraries/LibRequests/RequestClient.h b/Libraries/LibRequests/RequestClient.h
index f1f8122b670..b8bf7ebcd3e 100644
--- a/Libraries/LibRequests/RequestClient.h
+++ b/Libraries/LibRequests/RequestClient.h
@@ -16,6 +16,7 @@
#include <LibHTTP/NetworkIsolationKey.h>
#include <LibIPC/ConnectionToServer.h>
#include <LibRequests/CacheState.h>
+#include <LibRequests/ExportedRequest.h>
#include <LibRequests/RequestTimingInfo.h>
#include <LibRequests/RequestTransferLease.h>
#include <LibRequests/WebSocket.h>
@@ -52,6 +53,11 @@ public:
// Best-effort index into the resolved address pool.
RefPtr<Request> start_request(ByteString const& method, URL::URL const&, Optional<HTTP::HeaderList const&> request_headers = {}, ReadonlyBytes request_body = {}, HTTP::CacheMode = HTTP::CacheMode::Default, HTTP::Cookie::IncludeCredentials = HTTP::Cookie::IncludeCredentials::Yes, TransferLease = TransferLease::No, Optional<u32> address_selection_hint = {}, CacheMissNotification = CacheMissNotification::No, u64 originating_page_id = 0, Optional<HTTP::NetworkIsolationKey> = {});
RefPtr<Request> adopt_request(int source_client_id, u64 source_request_id, TransferLease = TransferLease::No);
+
+ // Moves a response between RequestServers. The request leaves this client on export; the imported one is a new
+ // request of the importing client.
+ ErrorOr<ExportedRequest> export_request(Request&);
+ RefPtr<Request> import_request(ExportedRequest, TransferLease = TransferLease::No);
bool stop_request(Badge<Request>, Request&);
void release_request_transfer_lease(Badge<Request>, Request&, RequestTransferLeaseKey);
void release_request_transfer_lease(RequestTransferLeaseKey);
diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cpp
index af11d1a8bc9..837d97b25d2 100644
--- a/Services/RequestServer/ConnectionFromClient.cpp
+++ b/Services/RequestServer/ConnectionFromClient.cpp
@@ -759,6 +759,59 @@ Messages::RequestServer::StopRequestResponse ConnectionFromClient::stop_request(
return true;
}
+Messages::RequestServer::ExportRequestResponse ConnectionFromClient::export_request(u64 request_id)
+{
+ if (m_site_binding != SiteBinding::Unrestricted) {
+ did_misbehave("export of a request by a bound client");
+ return Optional<Requests::ExportedRequest> {};
+ }
+
+ auto request = m_active_requests.get(request_id);
+ if (!request.has_value())
+ return Optional<Requests::ExportedRequest> {};
+
+ auto transfer_lease = (*request)->transfer_lease();
+ auto exported = (*request)->export_response();
+ if (exported.is_error()) {
+ dbgln("RequestServer: Failed to export request {}: {}", request_id, exported.error());
+ return Optional<Requests::ExportedRequest> {};
+ }
+
+ if (transfer_lease.has_value())
+ m_request_transfer_leases.remove(*transfer_lease);
+
+ // A finished transfer has nothing left to do here once its outcome is on its way.
+ if ((*request)->is_complete()) {
+ Core::deferred_invoke([weak_self = make_weak_ptr<ConnectionFromClient>(), request_id] {
+ if (auto self = weak_self.strong_ref())
+ self->m_active_requests.remove(request_id);
+ });
+ }
+
+ return exported.release_value();
+}
+
+void ConnectionFromClient::import_request(u64 request_id, Requests::ExportedRequest exported_request, bool create_transfer_lease)
+{
+ if (m_site_binding != SiteBinding::Unrestricted) {
+ did_misbehave("import of a request by a bound client");
+ return;
+ }
+ if (is_live_request_id(request_id)) {
+ did_misbehave("reused live request ID");
+ return;
+ }
+
+ Optional<Requests::RequestTransferLeaseKey> transfer_lease;
+ if (create_transfer_lease) {
+ transfer_lease = Requests::RequestTransferLeaseKey { client_id(), request_id };
+ m_request_transfer_leases.set(*transfer_lease, RequestTransferLease { *this, request_id });
+ }
+
+ auto request = Request::import(request_id, m_disk_cache, *this, m_resolver, move(exported_request), transfer_lease);
+ m_active_requests.set(request_id, move(request));
+}
+
void ConnectionFromClient::ensure_connection(u64 request_id, URL::URL url, ::RequestServer::CacheLevel cache_level)
{
if (is_live_request_id(request_id)) {
diff --git a/Services/RequestServer/ConnectionFromClient.h b/Services/RequestServer/ConnectionFromClient.h
index 0dbcc433efa..44ef2f43684 100644
--- a/Services/RequestServer/ConnectionFromClient.h
+++ b/Services/RequestServer/ConnectionFromClient.h
@@ -92,6 +92,8 @@ private:
virtual void adopt_request(int source_client_id, u64 source_request_id, u64 target_request_id, bool preserve_transfer_lease) override;
virtual void release_request_transfer_lease(int source_client_id, u64 source_request_id) override;
virtual Messages::RequestServer::StopRequestResponse stop_request(u64 request_id) override;
+ virtual Messages::RequestServer::ExportRequestResponse export_request(u64 request_id) override;
+ virtual void import_request(u64 request_id, Requests::ExportedRequest, bool create_transfer_lease) override;
virtual void ensure_connection(u64 request_id, URL::URL url, ::RequestServer::CacheLevel cache_level) override;
virtual Messages::RequestServer::StoreCacheAssociatedDataResponse store_cache_associated_data(Optional<HTTP::NetworkIsolationKey>, URL::URL, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData, Core::AnonymousBuffer) override;
diff --git a/Services/RequestServer/ControlConnectionFromClient.cpp b/Services/RequestServer/ControlConnectionFromClient.cpp
index f556e08e4af..8ad5c462d8c 100644
--- a/Services/RequestServer/ControlConnectionFromClient.cpp
+++ b/Services/RequestServer/ControlConnectionFromClient.cpp
@@ -233,6 +233,7 @@ void ControlConnectionFromClient::retrieved_http_cookie(int client_id, u64 reque
auto request = [&]() {
switch (request_type) {
case RequestType::Fetch:
+ case RequestType::Imported:
return (*connection)->m_active_requests.get(request_id);
case RequestType::BackgroundRevalidation:
return (*connection)->m_active_revalidation_requests.get(request_id);
diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cpp
index 4c6ed1c37d4..35c2167c206 100644
--- a/Services/RequestServer/Request.cpp
+++ b/Services/RequestServer/Request.cpp
@@ -579,6 +579,26 @@ void Request::set_revalidation_stall_timeout(AK::Duration timeout)
s_revalidation_stall_timeout = timeout;
}
+NonnullOwnPtr<Request> Request::import(
+ u64 request_id,
+ Optional<HTTP::DiskCache&> disk_cache,
+ ConnectionFromClient& client,
+ Resolver& resolver,
+ Requests::ExportedRequest exported,
+ Optional<Requests::RequestTransferLeaseKey> transfer_lease)
+{
+ auto request = adopt_own(*new Request { request_id, RequestType::Imported, disk_cache, move(exported.network_isolation_key), HTTP::CacheMode::Default, client, nullptr, resolver, move(exported.url), move(exported.method), HTTP::HeaderList::create(move(exported.request_headers)), ByteBuffer {}, HTTP::Cookie::IncludeCredentials::No, move(transfer_lease) });
+ request->m_request_start_time = exported.request_start_time;
+ request->m_status_code = exported.status_code;
+ request->m_reason_phrase = move(exported.reason_phrase);
+ request->m_response_headers = HTTP::HeaderList::create(move(exported.response_headers));
+ request->m_import = Import {};
+ request->m_import->body_fd = exported.body.take_fd();
+ request->m_import->status_fd = exported.status.take_fd();
+ request->transition_to_state(State::ReadImported);
+ return request;
+}
+
Request::~Request()
{
if constexpr (REQUESTSERVER_DEBUG) {
@@ -961,6 +981,9 @@ void Request::process()
case State::WaitForAIA:
// Do nothing; we are waiting for the AIA intermediate-certificate fetch to notify us to proceed.
break;
+ case State::ReadImported:
+ handle_read_imported_state();
+ break;
case State::FailedCacheOnly:
handle_failed_cache_only_state();
break;
@@ -1577,7 +1600,7 @@ void Request::handle_fetch_state()
void Request::handle_complete_state()
{
- if (m_type == RequestType::Fetch) {
+ if (delivers_response_to_client()) {
VERIFY(m_curl_result_code.has_value());
if (should_retry_after_fetching_aia_intermediate(*m_curl_result_code)) {
@@ -1585,6 +1608,12 @@ void Request::handle_complete_state()
return;
}
+ if (m_import.has_value() && m_import->network_error.has_value()) {
+ m_network_error = m_import->network_error;
+ transition_to_state(State::Error);
+ return;
+ }
+
if (m_curl_result_code != CURLE_OK) {
m_network_error = curl_code_to_network_error(*m_curl_result_code);
@@ -1615,10 +1644,14 @@ void Request::handle_complete_state()
m_cache_entry_writer.clear();
}
- if (cached_body_file.has_value())
- m_client->async_request_cached_body_file_available(m_request_id, IPC::File::adopt_fd(cached_body_file->fd), cached_body_file->offset, cached_body_file->size);
+ if (m_export.has_value()) {
+ write_export_result();
+ } else {
+ if (cached_body_file.has_value())
+ m_client->async_request_cached_body_file_available(m_request_id, IPC::File::adopt_fd(cached_body_file->fd), cached_body_file->offset, cached_body_file->size);
- m_client->async_request_finished(m_request_id, m_bytes_transferred_to_client, timing_info, m_network_error);
+ m_client->async_request_finished(m_request_id, m_bytes_transferred_to_client, timing_info, m_network_error);
+ }
}
if (m_cache_entry_writer.has_value()) {
@@ -1634,7 +1667,9 @@ void Request::handle_complete_state()
void Request::handle_error_state()
{
- if (m_type == RequestType::Fetch) {
+ if (m_export.has_value()) {
+ write_export_result();
+ } else if (delivers_response_to_client()) {
// FIXME: Implement timing info for failed requests.
m_client->async_request_finished(m_request_id, m_bytes_transferred_to_client, {}, m_network_error.value_or(Requests::NetworkError::Unknown));
}
@@ -1642,6 +1677,264 @@ void Request::handle_error_state()
m_client->request_complete({}, *this);
}
+// The outcome of an exported transfer, as written to its status socket.
+struct ExportedRequestResult {
+ Requests::RequestTimingInfo timing_info;
+ u64 total_size { 0 };
+ bool has_network_error { false };
+ Requests::NetworkError network_error { Requests::NetworkError::Unknown };
+};
+
+Request::Export::Export(Export&& other)
+ : status_fd(exchange(other.status_fd, -1))
+ , notifier(move(other.notifier))
+{
+}
+
+Request::Export& Request::Export::operator=(Export&& other)
+{
+ if (this != &other) {
+ close();
+ status_fd = exchange(other.status_fd, -1);
+ notifier = move(other.notifier);
+ }
+ return *this;
+}
+
+Request::Export::~Export()
+{
+ close();
+}
+
+void Request::Export::close()
+{
+ if (notifier) {
+ notifier->close();
+ notifier = nullptr;
+ }
+ if (status_fd != -1) {
+ (void)Core::System::close(status_fd);
+ status_fd = -1;
+ }
+}
+
+Request::Import::Import(Import&& other)
+ : body_fd(exchange(other.body_fd, -1))
+ , status_fd(exchange(other.status_fd, -1))
+ , body_notifier(move(other.body_notifier))
+ , status_notifier(move(other.status_notifier))
+ , body_ended(other.body_ended)
+ , status_bytes(move(other.status_bytes))
+ , timing_info(move(other.timing_info))
+ , network_error(move(other.network_error))
+{
+}
+
+Request::Import& Request::Import::operator=(Import&& other)
+{
+ if (this != &other) {
+ this->~Import();
+ new (this) Import(move(other));
+ }
+ return *this;
+}
+
+Request::Import::~Import()
+{
+ if (body_notifier)
+ body_notifier->close();
+ if (status_notifier)
+ status_notifier->close();
+ if (body_fd != -1)
+ (void)Core::System::close(body_fd);
+ if (status_fd != -1)
+ (void)Core::System::close(status_fd);
+}
+
+ErrorOr<Requests::ExportedRequest> Request::export_response()
+{
+ if (m_type != RequestType::Fetch || m_export.has_value())
+ return Error::from_string_literal("Only a fetched response can be exported");
+ if (!m_client_request_pipe.has_value() || !m_sent_response_headers_to_client)
+ return Error::from_string_literal("The response head has not arrived yet");
+
+ int status_fds[2] {};
+ TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, status_fds));
+ TRY(Core::System::set_socket_blocking(status_fds[0], false));
+ TRY(Core::System::set_socket_blocking(status_fds[1], false));
+ auto status = IPC::File::adopt_fd(status_fds[1]);
+ auto body = IPC::File::adopt_fd(TRY(Core::System::dup(m_client_request_pipe->reader_fd())));
+
+ m_export = Export {};
+ m_export->status_fd = status_fds[0];
+ m_export->notifier = Core::Notifier::construct(status_fds[0], Core::NotificationType::Read);
+ m_export->notifier->on_activation = weak_callback(*this, [](auto& self) { self.importer_went_away(); });
+
+ Requests::ExportedRequest exported {
+ .network_isolation_key = m_network_isolation_key,
+ .url = m_url,
+ .method = m_method,
+ .request_headers = m_request_headers->headers(),
+ .request_start_time = m_request_start_time,
+ .status_code = m_status_code,
+ .reason_phrase = m_reason_phrase,
+ .response_headers = m_response_headers->headers(),
+ .body = move(body),
+ .status = move(status),
+ };
+
+ m_transfer_lease.clear();
+ m_client->async_request_transferred(m_request_id);
+
+ // A transfer that is already over has its whole body in the pipe.
+ if (is_complete())
+ write_export_result();
+
+ return exported;
+}
+
+void Request::write_export_result()
+{
+ if (!m_export.has_value() || m_export->status_fd == -1)
+ return;
+
+ ExportedRequestResult result {
+ .timing_info = acquire_timing_info(),
+ .total_size = m_bytes_transferred_to_client,
+ .has_network_error = m_network_error.has_value(),
+ .network_error = m_network_error.value_or(Requests::NetworkError::Unknown),
+ };
+ (void)Core::System::send(m_export->status_fd, { &result, sizeof(result) }, MSG_NOSIGNAL);
+ m_export->close();
+}
+
+// The importing RequestServer closes its end of the status socket when it has no more use for the response.
+void Request::importer_went_away()
+{
+ u8 byte;
+ auto result = Core::System::recv(m_export->status_fd, { &byte, 1 }, 0);
+ if (!result.is_error() && result.value() != 0)
+ return;
+ if (result.is_error() && first_is_one_of(result.error().code(), EAGAIN, EWOULDBLOCK))
+ return;
+
+ m_export->close();
+ if (is_complete())
+ return;
+
+ MUST(free_curl_structs());
+ m_network_error = Requests::NetworkError::Unknown;
+ transition_to_state(State::Error);
+}
+
+void Request::handle_read_imported_state()
+{
+ if (inform_client_request_started().is_error())
+ return;
+
+ if (m_disk_cache.has_value()) {
+ m_disk_cache->create_entry(*this, *m_disk_cache_partition, m_url, m_method, m_request_headers, m_request_start_time)
+ .visit(
+ [&](Optional<HTTP::CacheEntryWriter&> cache_entry_writer) {
+ m_cache_entry_writer = cache_entry_writer;
+ if (!m_cache_entry_writer.has_value())
+ m_cache_status = CacheStatus::NotCached;
+ },
+ [&](HTTP::DiskCache::CacheHasOpenEntry) {
+ m_cache_status = CacheStatus::NotCached;
+ });
+ } else {
+ m_cache_status = CacheStatus::NotCached;
+ }
+
+ transfer_headers_to_client_if_needed();
+
+ (void)Core::System::set_socket_blocking(m_import->body_fd, false);
+ (void)Core::System::set_socket_blocking(m_import->status_fd, false);
+
+ m_import->body_notifier = Core::Notifier::construct(m_import->body_fd, Core::NotificationType::Read);
+ m_import->body_notifier->on_activation = weak_callback(*this, [](auto& self) { self.read_imported_body(); });
+ m_import->status_notifier = Core::Notifier::construct(m_import->status_fd, Core::NotificationType::Read);
+ m_import->status_notifier->on_activation = weak_callback(*this, [](auto& self) { self.read_imported_status(); });
+}
+
+void Request::read_imported_body()
+{
+ u8 buffer[64 * KiB];
+ while (true) {
+ auto result = Core::System::recv(m_import->body_fd, { buffer, sizeof(buffer) }, 0);
+ if (result.is_error()) {
+ if (first_is_one_of(result.error().code(), EAGAIN, EWOULDBLOCK))
+ return;
+ }
+ if (result.is_error() || result.value() == 0) {
+ m_import->body_ended = true;
+ m_import->body_notifier->close();
+ m_import->body_notifier = nullptr;
+ complete_import_if_finished();
+ return;
+ }
+
+ mark_activity();
+ if (auto write_result = m_response_buffer.write_some({ buffer, static_cast<size_t>(result.value()) }); write_result.is_error()) {
+ m_network_error = Requests::NetworkError::Unknown;
+ transition_to_state(State::Error);
+ return;
+ }
+ if (auto write_result = write_queued_bytes_without_blocking(); write_result.is_error()) {
+ dbgln("Request::read_imported_body: Aborting request because error occurred whilst writing data to the client: {}", write_result.error());
+ m_network_error = Requests::NetworkError::Unknown;
+ transition_to_state(State::Error);
+ return;
+ }
+ }
+}
+
+void Request::read_imported_status()
+{
+ u8 buffer[sizeof(ExportedRequestResult)];
+ auto result = Core::System::recv(m_import->status_fd, { buffer, sizeof(buffer) }, 0);
+ if (result.is_error() && first_is_one_of(result.error().code(), EAGAIN, EWOULDBLOCK))
+ return;
+
+ if (!result.is_error() && result.value() != 0) {
+ (void)m_import->status_bytes.try_append(buffer, result.value());
+ if (m_import->status_bytes.size() < sizeof(ExportedRequestResult))
+ return;
+ }
+
+ m_import->status_notifier->close();
+ m_import->status_notifier = nullptr;
+
+ if (m_import->status_bytes.size() >= sizeof(ExportedRequestResult)) {
+ ExportedRequestResult exported_result;
+ memcpy(&exported_result, m_import->status_bytes.data(), sizeof(exported_result));
+ m_import->timing_info = exported_result.timing_info;
+ if (exported_result.has_network_error)
+ m_import->network_error = exported_result.network_error;
+ } else {
+ // The exporting RequestServer went away before the transfer was over.
+ m_import->timing_info = Requests::RequestTimingInfo {};
+ m_import->network_error = Requests::NetworkError::Unknown;
+ }
+
+ complete_import_if_finished();
+}
+
+void Request::complete_import_if_finished()
+{
+ if (!m_import->body_ended || !m_import->timing_info.has_value())
+ return;
+ if (m_curl_result_code.has_value())
+ return;
+
+ m_curl_result_code = CURLE_OK;
+ if (auto result = write_queued_bytes_without_blocking(); result.is_error()) {
+ m_network_error = Requests::NetworkError::Unknown;
+ transition_to_state(State::Error);
+ }
+}
+
size_t Request::on_header_received(void* buffer, size_t size, size_t nmemb, void* user_data)
{
auto& request = *static_cast<Request*>(user_data);
@@ -2058,6 +2351,7 @@ bool Request::is_revalidation_request() const
return m_cache_entry_reader.has_value() && m_cache_entry_reader->revalidation_type() == HTTP::CacheEntryReader::RevalidationType::MustRevalidate;
case RequestType::Connect:
case RequestType::WebSocket:
+ case RequestType::Imported:
return false;
case RequestType::BackgroundRevalidation:
return m_cache_entry_reader.has_value();
@@ -2112,6 +2406,9 @@ Requests::RequestTimingInfo Request::acquire_timing_info() const
// |--|--|--|--|--|--|--|--TOTAL
// |--|--|--|--|--|--|--|--REDIRECT
+ if (m_import.has_value())
+ return m_import->timing_info.value_or({});
+
// FIXME: Implement timing info for cache hits.
if (m_cache_entry_reader.has_value())
return {};
diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.h
index d74a55c2571..63fd505c1f4 100644
--- a/Services/RequestServer/Request.h
+++ b/Services/RequestServer/Request.h
@@ -28,6 +28,7 @@
#include <LibHTTP/NetworkIsolationKey.h>
#include <LibHTTP/Proxy.h>
#include <LibIPC/File.h>
+#include <LibRequests/ExportedRequest.h>
#include <LibRequests/NetworkError.h>
#include <LibRequests/RequestTimingInfo.h>
#include <LibRequests/RequestTransferLease.h>
@@ -86,8 +87,20 @@ public:
ByteBuffer request_body,
HTTP::Cookie::IncludeCredentials include_credentials);
+ static NonnullOwnPtr<Request> import(
+ u64 request_id,
+ Optional<HTTP::DiskCache&> disk_cache,
+ ConnectionFromClient& client,
+ Resolver& resolver,
+ Requests::ExportedRequest,
+ Optional<Requests::RequestTransferLeaseKey>);
+
virtual ~Request() override;
+ // Hands the response over to another RequestServer. The body keeps flowing into the response pipe, and the outcome
+ // goes to the status socket instead of to a client. The exporting client is told the request was transferred.
+ ErrorOr<Requests::ExportedRequest> export_response();
+
static void set_performance_monitor_enabled(bool);
static Vector<Requests::NetworkUsage> take_network_usage();
void set_performance_origin(i32 process_id, u64 page_id);
@@ -141,6 +154,7 @@ private:
Connect, // Issue a network request to connect to the URL.
Fetch, // Issue a network request to fetch the URL.
WaitForAIA, // Wait for an AIA intermediate-certificate fetch to complete, then retry the fetch.
+ ReadImported, // Read the response another RequestServer is streaming to this one.
Complete, // Finalize the request with the client.
Error, // Any error occured during the request's lifetime.
};
@@ -156,6 +170,8 @@ private:
return "WaitForCache"sv;
case State::WaitForAIA:
return "WaitForAIA"sv;
+ case State::ReadImported:
+ return "ReadImported"sv;
case State::FailedCacheOnly:
return "FailedCacheOnly"sv;
case State::ServeSubstitution:
@@ -218,6 +234,12 @@ private:
void handle_retrieve_cookie_state();
void handle_connect_state();
void handle_fetch_state();
+ void handle_read_imported_state();
+ void read_imported_body();
+ void read_imported_status();
+ void complete_import_if_finished();
+ void write_export_result();
+ void importer_went_away();
void handle_complete_state();
void handle_error_state();
@@ -251,6 +273,8 @@ private:
bool is_cache_only_request() const;
+ bool delivers_response_to_client() const { return m_type == RequestType::Fetch || m_type == RequestType::Imported; }
+
u32 acquire_status_code() const;
Requests::RequestTimingInfo acquire_timing_info() const;
@@ -348,6 +372,41 @@ private:
Optional<Requests::RequestTransferLeaseKey> m_transfer_lease;
RefPtr<ConnectionFromClient> m_network_connection_keep_alive;
+
+ struct Export {
+ AK_MAKE_NONCOPYABLE(Export);
+
+ public:
+ Export() = default;
+ Export(Export&&);
+ Export& operator=(Export&&);
+ ~Export();
+ void close();
+
+ int status_fd { -1 };
+ RefPtr<Core::Notifier> notifier;
+ };
+ Optional<Export> m_export;
+
+ struct Import {
+ AK_MAKE_NONCOPYABLE(Import);
+
+ public:
+ Import() = default;
+ Import(Import&&);
+ Import& operator=(Import&&);
+ ~Import();
+
+ int body_fd { -1 };
+ int status_fd { -1 };
+ RefPtr<Core::Notifier> body_notifier;
+ RefPtr<Core::Notifier> status_notifier;
+ bool body_ended { false };
+ ByteBuffer status_bytes;
+ Optional<Requests::RequestTimingInfo> timing_info;
+ Optional<Requests::NetworkError> network_error;
+ };
+ Optional<Import> m_import;
};
}
diff --git a/Services/RequestServer/RequestServer.ipc b/Services/RequestServer/RequestServer.ipc
index 54a6f3b3ddb..d95ace54f71 100644
--- a/Services/RequestServer/RequestServer.ipc
+++ b/Services/RequestServer/RequestServer.ipc
@@ -4,6 +4,7 @@
#include <LibHTTP/Cookie/IncludeCredentials.h>
#include <LibHTTP/Header.h>
#include <LibHTTP/NetworkIsolationKey.h>
+#include <LibRequests/ExportedRequest.h>
#include <LibURL/URL.h>
#include <RequestServer/CacheLevel.h>
#include <RequestServer/IsPrivate.h>
@@ -22,6 +23,11 @@ endpoint RequestServer
release_request_transfer_lease(int source_client_id, u64 source_request_id) =|
stop_request(u64 request_id) => (bool success)
+ // Only the UI process's own clients move responses between RequestServers: a response fetched by one site's
+ // RequestServer is exported from it and imported into the RequestServer of the site that navigates to it.
+ export_request(u64 request_id) => (Optional<Requests::ExportedRequest> exported_request)
+ import_request(u64 request_id, Requests::ExportedRequest exported_request, bool create_transfer_lease) =|
+
ensure_connection(u64 request_id, URL::URL url, ::RequestServer::CacheLevel cache_level) =|
store_cache_associated_data(Optional<HTTP::NetworkIsolationKey> network_isolation_key, URL::URL url, ByteString method, Vector<HTTP::Header> request_headers, Optional<u64> vary_key, HTTP::CacheEntryAssociatedData associated_data, Core::AnonymousBuffer data) => (Optional<IPC::File> file, u64 size)
diff --git a/Services/RequestServer/RequestType.h b/Services/RequestServer/RequestType.h
index fa78e3b030b..2c980f0c072 100644
--- a/Services/RequestServer/RequestType.h
+++ b/Services/RequestServer/RequestType.h
@@ -15,6 +15,8 @@ enum class RequestType : u8 {
Connect,
BackgroundRevalidation,
WebSocket,
+ // A response another RequestServer is streaming to this one.
+ Imported,
};
}
diff --git a/Tests/RequestServer/CMakeLists.txt b/Tests/RequestServer/CMakeLists.txt
index a2cb9199e0d..355b82f3c52 100644
--- a/Tests/RequestServer/CMakeLists.txt
+++ b/Tests/RequestServer/CMakeLists.txt
@@ -29,3 +29,6 @@ endif()
ladybird_test(TestAlternativeServices.cpp RequestServer LIBS requestserverservice)
target_include_directories(TestAlternativeServices PRIVATE ${LADYBIRD_SOURCE_DIR}/Services)
+
+ladybird_test(TestExportImport.cpp RequestServer LIBS requestserverservice)
+target_include_directories(TestExportImport PRIVATE ${LADYBIRD_SOURCE_DIR}/Services)
diff --git a/Tests/RequestServer/TestExportImport.cpp b/Tests/RequestServer/TestExportImport.cpp
new file mode 100644
index 00000000000..8c0ea84c733
--- /dev/null
+++ b/Tests/RequestServer/TestExportImport.cpp
@@ -0,0 +1,458 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/EventLoop.h>
+#include <LibCore/Socket.h>
+#include <LibCore/StandardPaths.h>
+#include <LibCore/System.h>
+#include <LibCore/TCPServer.h>
+#include <LibCore/Timer.h>
+#include <LibHTTP/Cache/DiskCache.h>
+#include <LibHTTP/Cache/Utilities.h>
+#include <LibIPC/Transport.h>
+#include <LibTest/TestCase.h>
+#include <LibURL/Origin.h>
+#include <LibURL/Parser.h>
+#include <LibURL/Site.h>
+#include <RequestServer/CURL.h>
+#include <RequestServer/ConnectionFromClient.h>
+#include <RequestServer/Resolver.h>
+#include <RequestServer/ResourceSubstitutionMap.h>
+
+namespace RequestServer {
+
+OwnPtr<ResourceSubstitutionMap> g_resource_substitution_map;
+
+}
+
+namespace {
+
+static void initialize_libcurl()
+{
+ static bool libcurl_initialized = [] {
+ MUST(RequestServer::initialize_libcurl());
+ return true;
+ }();
+ (void)libcurl_initialized;
+}
+
+struct TestServer {
+ explicit TestServer(StringView name)
+ {
+ auto cache_root = LexicalPath::join(Core::StandardPaths::cache_directory(), "Ladybird"sv, name);
+ disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, cache_root)).release_value();
+ }
+
+ RequestServer::ConnectionFromClient::ConnectionMap connections;
+ RequestServer::ConnectionFromClient::RequestTransferLeaseMap request_transfer_leases;
+ Optional<HTTP::DiskCache> disk_cache;
+};
+
+HTTP::NetworkIsolationKey navigation_key_for(URL::URL const& url)
+{
+ auto site = URL::Site::serialize_for_partitioning(url.origin()).release_value();
+ return HTTP::NetworkIsolationKey {
+ .top_level_site = site,
+ .frame_site = site,
+ .is_cross_site_main_frame_navigation = true,
+ };
+}
+
+Vector<HTTP::Header> cacheable_request_headers()
+{
+ return { { ByteString { HTTP::TEST_CACHE_ENABLED_HEADER }, "1"sv } };
+}
+
+// A connection passing a response on leaves the body for its recipient, like a renderer with delivery paused.
+enum class ReadsBodies {
+ No,
+ Yes,
+};
+
+// A data connection and the messages it receives, read from outside the event loop.
+class TestConnection {
+public:
+ TestConnection(TestServer& server, ReadsBodies reads_bodies = ReadsBodies::Yes, RequestServer::SiteBinding site_binding = RequestServer::SiteBinding::Unrestricted)
+ : m_reads_bodies(reads_bodies)
+ {
+ initialize_libcurl();
+
+ auto pair = MUST(IPC::Transport::create_paired());
+ m_remote_transport = MUST(pair.remote_handle.create_transport());
+ m_connection = RequestServer::ConnectionFromClient::construct(
+ move(pair.local), RequestServer::IsPrivate::No, site_binding,
+ server.connections, server.request_transfer_leases, server.disk_cache);
+#ifdef AK_OS_WINDOWS
+ auto pid = Core::System::getpid();
+ m_connection->transport().set_peer_pid(pid);
+ m_remote_transport->set_peer_pid(pid);
+#endif
+ }
+
+ ~TestConnection()
+ {
+ if (m_connection->is_open())
+ m_connection->shutdown();
+ }
+
+ int client_id() const { return m_connection->client_id(); }
+ bool is_open() const { return m_connection->is_open(); }
+
+ void start_request(u64 request_id, URL::URL url, HTTP::NetworkIsolationKey network_isolation_key, bool create_transfer_lease)
+ {
+ auto message = make<Messages::RequestServer::StartRequest>(request_id, ByteString { "GET" }, move(url), cacheable_request_headers(), ByteBuffer {}, HTTP::CacheMode::Default, move(network_isolation_key), HTTP::Cookie::IncludeCredentials::No, create_transfer_lease, Optional<u32> {}, false, 0, 0);
+ VERIFY(!dispatch(move(message)));
+ }
+
+ void adopt_request(int source_client_id, u64 source_request_id, u64 target_request_id, bool preserve_transfer_lease)
+ {
+ auto message = make<Messages::RequestServer::AdoptRequest>(source_client_id, source_request_id, target_request_id, preserve_transfer_lease);
+ VERIFY(!dispatch(move(message)));
+ }
+
+ void stop_request(u64 request_id)
+ {
+ VERIFY(dispatch(make<Messages::RequestServer::StopRequest>(request_id)));
+ }
+
+ Optional<Requests::ExportedRequest> export_request(u64 request_id)
+ {
+ auto response = dispatch(make<Messages::RequestServer::ExportRequest>(request_id));
+ if (!response)
+ return {};
+
+ Queue<IPC::Attachment> attachments;
+ for (auto& attachment : response->take_attachments())
+ attachments.enqueue(move(attachment));
+ auto message = MUST(RequestServerEndpoint::decode_message(response->data(), attachments));
+ VERIFY(message->message_id() == Messages::RequestServer::ExportRequestResponse::static_message_id());
+ return message.template release_nonnull<Messages::RequestServer::ExportRequestResponse>()->take_exported_request();
+ }
+
+ void import_request(u64 request_id, Requests::ExportedRequest exported, bool create_transfer_lease)
+ {
+ auto message = make<Messages::RequestServer::ImportRequest>(request_id, move(exported), create_transfer_lease);
+ VERIFY(!dispatch(move(message)));
+ }
+
+ // Drain response bodies while waiting so the transfer cannot stall on a full pipe.
+ template<typename MessageType>
+ NonnullOwnPtr<MessageType> wait_for(Core::EventLoop& event_loop, u64 request_id)
+ {
+ auto wake_timer = Core::Timer::create_repeating(5, [] { });
+ wake_timer->start();
+
+ OwnPtr<MessageType> result;
+ event_loop.spin_until([&] {
+ read_client_messages();
+ read_response_bodies();
+ for (size_t i = 0; i < m_messages.size(); ++i) {
+ if (m_messages[i]->message_id() != MessageType::static_message_id())
+ continue;
+ auto message = m_messages.take(i).template release_nonnull<MessageType>();
+ if (message->request_id() != request_id)
+ continue;
+ result = move(message);
+ return true;
+ }
+ return false;
+ });
+ return result.release_nonnull();
+ }
+
+ ByteBuffer read_whole_body(Core::EventLoop& event_loop, u64 request_id)
+ {
+ auto wake_timer = Core::Timer::create_repeating(5, [] { });
+ wake_timer->start();
+
+ event_loop.spin_until([&] {
+ read_client_messages();
+ read_response_bodies();
+ return m_ended_bodies.contains(request_id);
+ });
+ return m_bodies.take(request_id).release_value();
+ }
+
+ size_t body_size_so_far(u64 request_id) const
+ {
+ return m_bodies.get(request_id).map([](auto const& body) { return body.size(); }).value_or(0);
+ }
+
+ void read_client_messages()
+ {
+ (void)m_remote_transport->read_as_many_messages_as_possible_without_blocking([&](auto&& raw_message) {
+ auto message = MUST(RequestClientEndpoint::decode_message(raw_message.bytes.bytes(), raw_message.attachments));
+ if (message->message_id() == Messages::RequestClient::RequestStarted::static_message_id()) {
+ auto& started = static_cast<Messages::RequestClient::RequestStarted&>(*message);
+ auto socket = MUST(Core::LocalSocket::adopt_fd(started.fd().take_fd()));
+ socket->set_notifications_enabled(false);
+ MUST(socket->set_blocking(false));
+ m_response_sockets.set(started.request_id(), move(socket));
+ m_bodies.ensure(started.request_id());
+ }
+ m_messages.append(move(message));
+ });
+ }
+
+ void read_response_bodies()
+ {
+ if (m_reads_bodies == ReadsBodies::No)
+ return;
+
+ u8 buffer[64 * KiB];
+ Vector<u64> ended;
+ for (auto& [request_id, socket] : m_response_sockets) {
+ while (true) {
+ auto bytes = socket->read_some({ buffer, sizeof(buffer) });
+ if (bytes.is_error()) {
+ if (bytes.error().code() != EAGAIN && bytes.error().code() != EWOULDBLOCK)
+ ended.append(request_id);
+ break;
+ }
+ if (bytes.value().is_empty()) {
+ if (socket->is_eof())
+ ended.append(request_id);
+ break;
+ }
+ MUST(m_bodies.ensure(request_id).try_append(bytes.value()));
+ }
+ }
+ for (auto request_id : ended) {
+ m_response_sockets.remove(request_id);
+ m_ended_bodies.set(request_id);
+ }
+ }
+
+private:
+ OwnPtr<IPC::MessageBuffer> dispatch(NonnullOwnPtr<IPC::Message> message)
+ {
+ return MUST(static_cast<RequestServerEndpoint::Stub&>(*m_connection).handle(move(message)));
+ }
+
+ ReadsBodies m_reads_bodies { ReadsBodies::Yes };
+ OwnPtr<IPC::Transport> m_remote_transport;
+ RefPtr<RequestServer::ConnectionFromClient> m_connection;
+ Vector<NonnullOwnPtr<IPC::Message>> m_messages;
+ HashMap<u64, NonnullOwnPtr<Core::LocalSocket>> m_response_sockets;
+ HashMap<u64, ByteBuffer> m_bodies;
+ HashTable<u64> m_ended_bodies;
+};
+
+// A local HTTP server that answers every request with the same cacheable body, a piece at a time.
+class DrippingServer {
+public:
+ DrippingServer(ByteBuffer body, size_t piece_size, AK::Duration interval)
+ : m_body(move(body))
+ , m_piece_size(piece_size)
+ , m_interval(interval)
+ {
+ m_server = MUST(Core::TCPServer::try_create());
+ MUST(m_server->listen(IPv4Address { 127, 0, 0, 1 }, 0));
+ m_server->on_ready_to_accept = [this] {
+ auto socket = MUST(m_server->accept());
+ MUST(socket->set_blocking(false));
+ ++m_request_count;
+ m_connections.append(make<Connection>(move(socket)));
+ auto& connection = *m_connections.last();
+ connection.socket->on_ready_to_read = [this, &connection] {
+ if (!connection.socket->is_open())
+ return;
+ u8 buffer[4096];
+ auto bytes = connection.socket->read_some({ buffer, sizeof(buffer) });
+ if (bytes.is_error() || bytes.value().is_empty()) {
+ connection.socket->on_ready_to_read = nullptr;
+ if (connection.piece_timer)
+ connection.piece_timer->stop();
+ connection.peer_closed = true;
+ return;
+ }
+ if (connection.started)
+ return;
+ connection.started = true;
+ MUST(connection.socket->set_blocking(true));
+ auto head = ByteString::formatted("HTTP/1.1 200 OK\r\nCache-Control: max-age=600\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", m_body.size());
+ MUST(connection.socket->write_until_depleted(head.bytes()));
+ MUST(connection.socket->set_blocking(false));
+ connection.piece_timer = Core::Timer::create_repeating(static_cast<int>(m_interval.to_milliseconds()), [this, &connection] { write_piece(connection); });
+ write_piece(connection);
+ connection.piece_timer->start();
+ };
+ };
+ }
+
+ URL::URL url() const
+ {
+ return URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/document", *m_server->local_port())).release_value();
+ }
+
+ size_t request_count() const { return m_request_count; }
+ bool peer_closed(size_t index) const { return m_connections[index]->peer_closed; }
+ bool finished(size_t index) const { return m_connections[index]->offset == m_body.size(); }
+
+private:
+ struct Connection {
+ AK_ALLOC_WITH_KMALLOC;
+
+ explicit Connection(NonnullOwnPtr<Core::TCPSocket> socket)
+ : socket(move(socket))
+ {
+ }
+
+ NonnullOwnPtr<Core::TCPSocket> socket;
+ bool started { false };
+ bool peer_closed { false };
+ size_t offset { 0 };
+ RefPtr<Core::Timer> piece_timer;
+ };
+
+ void write_piece(Connection& connection)
+ {
+ // A timer tick may already be queued when the transfer ends.
+ if (connection.peer_closed || connection.offset == m_body.size() || !connection.socket->is_open())
+ return;
+ auto piece = m_body.bytes().slice(connection.offset, min(m_piece_size, m_body.size() - connection.offset));
+ MUST(connection.socket->set_blocking(true));
+ if (connection.socket->write_until_depleted(piece).is_error()) {
+ connection.peer_closed = true;
+ connection.piece_timer->stop();
+ return;
+ }
+ MUST(connection.socket->set_blocking(false));
+ connection.offset += piece.size();
+ if (connection.offset == m_body.size()) {
+ connection.piece_timer->stop();
+ connection.socket->close();
+ }
+ }
+
+ RefPtr<Core::TCPServer> m_server;
+ Vector<NonnullOwnPtr<Connection>> m_connections;
+ ByteBuffer m_body;
+ size_t m_piece_size { 0 };
+ AK::Duration m_interval;
+ size_t m_request_count { 0 };
+};
+
+ByteBuffer patterned_body(size_t size)
+{
+ auto body = MUST(ByteBuffer::create_uninitialized(size));
+ for (size_t i = 0; i < size; ++i)
+ body[i] = static_cast<u8>('a' + ((i * 7) % 26));
+ return body;
+}
+
+}
+
+TEST_CASE(exported_response_is_delivered_and_cached_by_the_importing_request_server)
+{
+ Core::EventLoop event_loop;
+ TestServer source_server { "export-source"sv };
+ TestServer target_server { "export-target"sv };
+ DrippingServer http_server { patterned_body(300 * KiB), 16 * KiB, AK::Duration::from_milliseconds(2) };
+ auto url = http_server.url();
+ auto key = navigation_key_for(url);
+
+ // Mirror navigation: the document's process fetches the response, then the UI process adopts it.
+ TestConnection navigator { source_server, ReadsBodies::No };
+ TestConnection source_ui { source_server, ReadsBodies::No };
+ navigator.start_request(1, url, key, true);
+ (void)navigator.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 1);
+ source_ui.adopt_request(navigator.client_id(), 1, 10, true);
+ (void)source_ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 10);
+
+ // Transfer through the target site's UI client before the target document adopts the response.
+ auto exported = source_ui.export_request(10);
+ EXPECT(exported.has_value());
+ (void)source_ui.wait_for<Messages::RequestClient::RequestTransferred>(event_loop, 10);
+
+ TestConnection target_ui { target_server, ReadsBodies::No };
+ TestConnection target { target_server };
+ target_ui.import_request(20, exported.release_value(), true);
+ (void)target_ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 20);
+ target.adopt_request(target_ui.client_id(), 20, 30, false);
+
+ auto headers = target.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 30);
+ EXPECT_EQ(headers->status_code(), 200u);
+ EXPECT(headers->response_headers().first_matching([](auto const& header) { return header.name == "Cache-Control"sv; }).has_value());
+
+ auto finished = target.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 30);
+ EXPECT(!finished->network_error().has_value());
+ EXPECT_EQ(finished->total_size(), 300 * KiB);
+
+ auto body = target.read_whole_body(event_loop, 30);
+ EXPECT_EQ(body.size(), 300 * KiB);
+ EXPECT(body == patterned_body(300 * KiB));
+
+ target.start_request(31, url, key, false);
+ auto cached_headers = target.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 31);
+ auto cache_status = cached_headers->response_headers().first_matching([](auto const& header) { return header.name == HTTP::TEST_CACHE_STATUS_HEADER; });
+ EXPECT(cache_status.has_value());
+ EXPECT_EQ(cache_status->value, "read-from-cache"sv);
+ (void)target.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 31);
+ EXPECT_EQ(http_server.request_count(), 1u);
+}
+
+TEST_CASE(stopping_an_imported_request_aborts_the_transfer)
+{
+ Core::EventLoop event_loop;
+ TestServer source_server { "abort-source"sv };
+ TestServer target_server { "abort-target"sv };
+ // A body that takes far longer to arrive than the test runs for.
+ DrippingServer http_server { patterned_body(8 * MiB), 4 * KiB, AK::Duration::from_milliseconds(10) };
+ auto url = http_server.url();
+ auto key = navigation_key_for(url);
+
+ TestConnection navigator { source_server, ReadsBodies::No };
+ TestConnection source_ui { source_server, ReadsBodies::No };
+ navigator.start_request(1, url, key, true);
+ (void)navigator.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 1);
+ source_ui.adopt_request(navigator.client_id(), 1, 10, true);
+ (void)source_ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 10);
+
+ auto exported = source_ui.export_request(10);
+ EXPECT(exported.has_value());
+
+ TestConnection target_ui { target_server, ReadsBodies::No };
+ TestConnection target { target_server };
+ target_ui.import_request(20, exported.release_value(), true);
+ target.adopt_request(target_ui.client_id(), 20, 30, false);
+ (void)target.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 30);
+
+ event_loop.spin_until([&] {
+ target.read_client_messages();
+ target.read_response_bodies();
+ return target.body_size_so_far(30) >= 16 * KiB;
+ });
+ target.stop_request(30);
+
+ auto wake_timer = Core::Timer::create_repeating(5, [] { });
+ wake_timer->start();
+ event_loop.spin_until([&] { return http_server.peer_closed(0); });
+ EXPECT(!http_server.finished(0));
+}
+
+TEST_CASE(only_unrestricted_clients_may_move_responses)
+{
+ Core::EventLoop event_loop;
+ TestServer server { "bound-export"sv };
+ DrippingServer http_server { patterned_body(1 * KiB), 1 * KiB, AK::Duration::from_milliseconds(1) };
+ auto url = http_server.url();
+ auto key = navigation_key_for(url);
+
+ TestConnection exporter { server, ReadsBodies::No, RequestServer::SiteBinding::Bound };
+ EXPECT(!exporter.export_request(1).has_value());
+ EXPECT(!exporter.is_open());
+
+ TestConnection navigator { server, ReadsBodies::No };
+ navigator.start_request(1, url, key, true);
+ (void)navigator.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 1);
+ auto exported = navigator.export_request(1);
+ EXPECT(exported.has_value());
+
+ TestConnection importer { server, ReadsBodies::No, RequestServer::SiteBinding::Bound };
+ importer.import_request(2, exported.release_value(), true);
+ EXPECT(!importer.is_open());
+}