Skip to content

Truly independent web browser

LibWeb+LibRequests: Transfer navigation bodies out of their channel

Luke Wilde82f246312aa7
diff --git a/Libraries/LibRequests/Request.cpp b/Libraries/LibRequests/Request.cpp
index 7ee16b363e4..6042c88fbc2 100644
--- a/Libraries/LibRequests/Request.cpp
+++ b/Libraries/LibRequests/Request.cpp
@@ -84,7 +84,7 @@ bool Request::stop()
if (had_active_request && on_stop)
on_stop();
if (teardown)
- teardown();
+ teardown(TeardownReason::Stopped);
return had_active_request;
}
@@ -352,7 +352,7 @@ void Request::did_transfer(Badge<RequestClient>)
if (on_stop)
on_stop();
if (teardown)
- teardown();
+ teardown(TeardownReason::Transferred);
}
void Request::defer_teardown()
diff --git a/Libraries/LibRequests/Request.h b/Libraries/LibRequests/Request.h
index ec980f270f6..05d75d51064 100644
--- a/Libraries/LibRequests/Request.h
+++ b/Libraries/LibRequests/Request.h
@@ -126,8 +126,13 @@ public:
Function<void()> on_requires_network;
+ enum class TeardownReason : u8 {
+ Stopped,
+ Transferred,
+ };
+
// Invoked at most once, when the request drops its delivery callbacks without a finish: a stop() or a transfer.
- Function<void()> on_teardown;
+ Function<void(TeardownReason)> on_teardown;
void did_finish(Badge<RequestClient>, u64 total_size, RequestTimingInfo const& timing_info, Optional<NetworkError> const& network_error);
void did_receive_headers(Badge<RequestClient>, NonnullRefPtr<HTTP::HeaderList> response_headers, Optional<u32> response_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, CacheState cache_state, ByteString http_version);
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cpp b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cpp
index a47c59ae677..38d3f71d59d 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cpp
@@ -122,6 +122,13 @@ void FetchBodyDeliveryGate::detach_transport()
m_transport = nullptr;
}
+void FetchBodyDeliveryGate::release_transport()
+{
+ if (auto transport = exchange(m_transport, nullptr))
+ transport->pause_body_delivery();
+ m_terminated = true;
+}
+
void FetchBodyDeliveryGate::apply_to_transport()
{
if (!m_transport)
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h
index 89a5b364aca..be3b3b5abb5 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h
@@ -62,6 +62,9 @@ public:
// A detached transport is never touched again.
void detach_transport();
+ // Pauses the transport and detaches it.
+ void release_transport();
+
void grant_credit(u64 byte_count);
private:
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp
index 1fbd095f4d2..c3f3d77d877 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp
@@ -179,6 +179,25 @@ FetchByteChannel::TerminateResult FetchByteChannel::cancel()
return result;
}
+Vector<Core::ImmutableBytes> FetchByteChannel::transfer_out()
+{
+ PendingNotifications notifications;
+ Vector<Core::ImmutableBytes> undrained_bytes;
+ {
+ MutexLocker locker { m_mutex };
+ if (!m_state.has<Open>() && !m_state.has<Closed>())
+ return {};
+
+ seal_copied_tail_locked();
+ undrained_bytes = move(m_chunks);
+ m_buffered_byte_count = 0;
+ m_state = Transferred {};
+ wake_armed_waiter_locked(notifications);
+ }
+ dispatch(notifications);
+ return undrained_bytes;
+}
+
// This implements the buffer-draining half of the pullAlgorithm in HTTP-network fetch.
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
FetchByteChannel::TakeResult FetchByteChannel::take_locked(u64 limit, PendingNotifications& notifications)
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h
index 3a157385393..d8830fbe3aa 100644
--- a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h
+++ b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h
@@ -58,7 +58,8 @@ public:
ByteBuffer message;
};
struct ConsumerCancelled { };
- using State = Variant<Open, Closed, Errored, ConsumerCancelled>;
+ struct Transferred { };
+ using State = Variant<Open, Closed, Errored, ConsumerCancelled, Transferred>;
// Snapshotted atomically with the removal of the bytes.
struct TakeResult {
@@ -97,6 +98,10 @@ public:
// Either side may cancel; the producer hears of it unless it has already ended the body.
TerminateResult cancel();
+ // Ends an open or closed channel for a body that moves to another process, returning its undrained bytes. The
+ // transport hears nothing, and later writes and endings do nothing.
+ [[nodiscard]] Vector<Core::ImmutableBytes> transfer_out();
+
// Returns the ticket the wake will carry; a wake already due fires before this returns, outside the lock.
WakeTicket arm_waiter();
diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp
index bde3ef2fba8..0024f1bd420 100644
--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp
+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.cpp
@@ -48,7 +48,7 @@ void NetworkTransportHandle::set_on_requires_network(Function<void()> on_require
m_request->on_requires_network = move(on_requires_network);
}
-void NetworkTransportHandle::set_on_teardown(Function<void()> on_teardown)
+void NetworkTransportHandle::set_on_teardown(Function<void(Requests::Request::TeardownReason)> on_teardown)
{
m_request->on_teardown = move(on_teardown);
}
diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h
index ff46a1335d4..0e765e5f35e 100644
--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h
+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h
@@ -32,7 +32,7 @@ public:
void release_transfer_lease();
void set_on_requires_network(Function<void()>);
- void set_on_teardown(Function<void()>);
+ void set_on_teardown(Function<void(Requests::Request::TeardownReason)>);
private:
explicit NetworkTransportHandle(NonnullRefPtr<Requests::Request>);
diff --git a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
index 531133d5e4b..bc71364fde4 100644
--- a/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/BodyStreamPullSource.cpp
@@ -188,6 +188,7 @@ void BodyStreamPullSource::settle_stream(Engine::FetchByteChannel::TakeResult co
result.state.visit(
[](Engine::FetchByteChannel::Open) { },
[](Engine::FetchByteChannel::ConsumerCancelled) { },
+ [](Engine::FetchByteChannel::Transferred) { },
[&](Engine::FetchByteChannel::Closed) {
// 2. Otherwise, if the bytes transmission for response’s message body is done normally and stream is
// readable, then close stream, and abort these in-parallel steps.
@@ -271,7 +272,7 @@ void BodyStreamPullSource::drain_into_stream()
m_fetch_params->controller()->terminate();
settle_stream(result);
- if (result.state.has<Engine::FetchByteChannel::ConsumerCancelled>())
+ if (result.state.has<Engine::FetchByteChannel::ConsumerCancelled>() || result.state.has<Engine::FetchByteChannel::Transferred>())
m_detached = true;
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 09fe48b08d8..87074fbb74f 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -2601,16 +2601,6 @@ static URL::URL content_blocker_source_url_for_request(Infrastructure::Request&
return request.current_url();
}
-static NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate& delivery_gate, Engine::FetchByteChannel& channel)
-{
- auto transport = Engine::WholeBodyTransport::create();
- transport->set_on_stop([delivery_gate = NonnullRefPtr { delivery_gate }, channel = NonnullRefPtr { channel }] {
- delivery_gate->detach_transport();
- channel->cancel();
- });
- return transport;
-}
-
namespace {
// A network response's body stream and the objects that fill it from the transport.
@@ -2658,6 +2648,30 @@ static NetworkBodyStream create_network_body_stream(JS::Realm& realm, GC::Ptr<In
return { stream, move(channel), move(delivery_gate), body_pump, pull_source };
}
+// The gate detaches before the channel's ending reaches it.
+static void tear_down_network_body(Engine::FetchBodyDeliveryGate& delivery_gate, Engine::FetchByteChannel& channel, Requests::Request::TeardownReason reason)
+{
+ delivery_gate.detach_transport();
+ switch (reason) {
+ case Requests::Request::TeardownReason::Stopped:
+ (void)channel.cancel();
+ return;
+ case Requests::Request::TeardownReason::Transferred:
+ (void)channel.transfer_out();
+ return;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+static NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate& delivery_gate, Engine::FetchByteChannel& channel)
+{
+ auto transport = Engine::WholeBodyTransport::create();
+ transport->set_on_stop([delivery_gate = NonnullRefPtr { delivery_gate }, channel = NonnullRefPtr { channel }] {
+ tear_down_network_body(*delivery_gate, *channel, Requests::Request::TeardownReason::Stopped);
+ });
+ return transport;
+}
+
GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Infrastructure::Response& response, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey transfer_lease, RefPtr<Infrastructure::FetchTimingInfo> timing_info, Function<void(Optional<StringView> error)> on_network_settled)
{
if (!ResourceLoader::is_initialized())
@@ -2686,11 +2700,11 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
delivery_gate->attach_transport(network_transport);
// A request either finishes or tears down, so the observer hears the body's end once.
auto network_settled = GC::make_root(GC::create_function(GC::Heap::the(), move(on_network_settled)));
- // The gate detaches before the cancellation reaches it.
- network_transport->set_on_teardown([delivery_gate, channel, network_settled] {
- delivery_gate->detach_transport();
- channel->cancel();
- network_settled->function()("Transferred navigation response was stopped"sv);
+ network_transport->set_on_teardown([delivery_gate, channel, network_settled](Requests::Request::TeardownReason reason) {
+ tear_down_network_body(*delivery_gate, *channel, reason);
+ // A body that moves to another owner is reported there.
+ if (reason == Requests::Request::TeardownReason::Stopped)
+ network_settled->function()("Transferred navigation response was stopped"sv);
});
auto body_pump = GC::make_root(network_body_stream.body_pump);
@@ -2728,6 +2742,7 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, I
response.set_network_transport({
.handle = move(network_transport),
.body_delivery_gate = move(delivery_gate),
+ .body_channel = move(channel),
});
return body;
}
@@ -2808,7 +2823,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
// A load without a RequestServer request, such as one for a file: URL, hands over its whole body at once.
auto whole_body_transport = create_whole_body_transport(*delivery_gate, *channel);
- auto on_headers_received = GC::create_function(GC::Heap::the(), [&fetch_params, pending_response, stream, request, body_pump, delivery_gate, whole_body_transport, http_cache](Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state) {
+ auto on_headers_received = GC::create_function(GC::Heap::the(), [&fetch_params, pending_response, stream, request, body_pump, channel, delivery_gate, whole_body_transport, http_cache](Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Optional<Core::ImmutableBytes> javascript_bytecode, Optional<u64> javascript_bytecode_cache_vary_key, Requests::CacheState cache_state) {
if (pending_response->is_resolved()) {
// RequestServer will send us the response headers twice, the second time being for HTTP trailers. This
// fetch algorithm is not interested in trailers, so just drop them here.
@@ -2846,6 +2861,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
response->set_network_transport({
.handle = *network_transport,
.body_delivery_gate = delivery_gate,
+ .body_channel = channel,
});
} else {
// A body without a RequestServer request is never held for its navigation.
@@ -2939,10 +2955,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
auto network_transport = ResourceLoader::the().load(load_request, on_headers_received, on_data_received, on_cached_body_available, on_complete, transfer_lease);
if (network_transport) {
delivery_gate->attach_transport(*network_transport);
- // The gate detaches before the cancellation reaches it.
- network_transport->set_on_teardown([delivery_gate, channel, body_pump = GC::Root { body_pump }] {
- delivery_gate->detach_transport();
- channel->cancel();
+ network_transport->set_on_teardown([delivery_gate, channel, body_pump = GC::Root { body_pump }](Requests::Request::TeardownReason reason) {
+ tear_down_network_body(*delivery_gate, *channel, reason);
body_pump->abandon_cache_entry();
});
fetch_params.controller()->set_network_transport(*network_transport);
diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
index 639f04f586e..f3b9850d16c 100644
--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp
@@ -100,7 +100,16 @@ void NetworkBodyPump::handle_network_data(Requests::ResponseData data)
if (m_delivery_gate->did_deliver(bytes.size()) == Engine::FetchBodyDeliveryGate::DeliveryResult::Rejected)
return;
+ // 10. Increase response’s body info’s decoded size by bytes’s length.
+ // NB: The response's body info is updated once the network completes.
+ m_decoded_body_size += bytes.size();
+
+ // 12. Append bytes to buffer. (Steps 12 and 13 live in FetchByteChannel's writes.)
auto const* file_backed = data.file_backed_slice();
+ if (file_backed)
+ m_channel->write(file_backed->slice);
+ else
+ m_channel->write_copy(bytes);
// Capture bytes for MIME sniffing
if (m_body) {
@@ -124,16 +133,6 @@ void NetworkBodyPump::handle_network_data(Requests::ResponseData data)
m_cache_buffer.append(bytes);
}
}
-
- // 10. Increase response’s body info’s decoded size by bytes’s length.
- // NB: The response's body info is updated once the network completes.
- m_decoded_body_size += bytes.size();
-
- // 12. Append bytes to buffer. (Steps 12 and 13 live in FetchByteChannel's writes.)
- if (file_backed)
- m_channel->write(file_backed->slice);
- else
- m_channel->write_copy(bytes);
}
void NetworkBodyPump::handle_network_complete(Optional<u64> encoded_body_size)
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
index ab9060971ef..917563df577 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.cpp
@@ -133,6 +133,18 @@ void Response::resume_body_delivery_up_to(size_t byte_count) const
m_network_transport->body_delivery_gate->release_hold_up_to(byte_count);
}
+Vector<Core::ImmutableBytes> Response::release_body_for_transfer() const
+{
+ VERIFY(m_network_transport.has_value());
+ m_network_transport->body_delivery_gate->release_transport();
+ auto prefix = m_network_transport->body_channel->transfer_out();
+
+ // A file-backed body reaches the next process whole, with the bytes this one already received.
+ if (m_network_transport->handle->has_file_backed_response_body())
+ return {};
+ return prefix;
+}
+
// https://fetch.spec.whatwg.org/#concept-response-url
Optional<URL::URL const&> Response::url() const
{
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
index 290a1b4baed..f800caf9bb7 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Responses.h
@@ -64,6 +64,7 @@ public:
struct NetworkTransport {
NonnullRefPtr<Engine::NetworkTransportHandle> handle;
NonnullRefPtr<Engine::FetchBodyDeliveryGate> body_delivery_gate;
+ NonnullRefPtr<Engine::FetchByteChannel> body_channel;
};
[[nodiscard]] static GC::Ref<Response> create();
@@ -150,6 +151,10 @@ public:
virtual void resume_body_delivery() const;
virtual void resume_body_delivery_up_to(size_t) const;
+ // Stops this process taking the body, whose request another process adopts next, and returns the bytes that
+ // process reads before the rest.
+ virtual Vector<Core::ImmutableBytes> release_body_for_transfer() const;
+
protected:
explicit Response(NonnullRefPtr<HTTP::HeaderList>);
@@ -291,6 +296,7 @@ public:
virtual void release_request_transfer_lease() const override { m_internal_response->release_request_transfer_lease(); }
virtual void resume_body_delivery() const override { m_internal_response->resume_body_delivery(); }
virtual void resume_body_delivery_up_to(size_t byte_count) const override { m_internal_response->resume_body_delivery_up_to(byte_count); }
+ virtual Vector<Core::ImmutableBytes> release_body_for_transfer() const override { return m_internal_response->release_body_for_transfer(); }
[[nodiscard]] GC::Ref<Response> internal_response() const { return m_internal_response; }
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index c5dbd9ac12e..dabb68ea36e 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -550,7 +550,7 @@ static void stop_response_body_delivery(LocalNavigable::NavigationParamsVariant
stop_response_body_delivery(**nav_params);
}
-static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> navigation_params, bool source_allows_downloading, Optional<URL::Origin> interface_origin, Optional<ReadonlyBytes> initial_data = {})
+static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> navigation_params, bool source_allows_downloading, Optional<URL::Origin> interface_origin)
{
auto response = navigation_params->response;
if (!response || !response->body())
@@ -600,8 +600,7 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
auto download_url = response->url().value_or(navigation_params->request ? navigation_params->request->current_url() : URL::about_blank());
if (auto const& network_transport = response->network_transport(); network_transport.has_value()) {
- auto const& transport_handle = *network_transport->handle;
- auto const& lease = transport_handle.transfer_lease();
+ auto const& lease = network_transport->handle->transfer_lease();
// A request that another client adopted has no lease to hand over.
if (!lease.has_value()) {
report_download_rejected();
@@ -609,18 +608,16 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> nav
return true;
}
auto suggested_filename = suggested_download_filename(download_url, *response->header_list(), {}, interface_origin);
- auto response_body_will_be_transferred_in_full = transport_handle.has_file_backed_response_body();
- ByteBuffer initial_data_buffer;
- if (initial_data.has_value() && !initial_data->is_empty() && !response_body_will_be_transferred_in_full)
- initial_data_buffer = MUST(ByteBuffer::copy(*initial_data));
- auto download_id = navigation_params->navigable->page().client().page_did_start_download(navigation_params->navigable->id(), navigation_params->id, download_url, suggested_filename, response_content_length(*response->header_list()), lease->source_client_id, lease->source_request_id, move(initial_data_buffer),
+ // The UI process downloads the bytes this process received from the body first, then the rest of the request.
+ ByteBuffer initial_data;
+ for (auto const& received : response->release_body_for_transfer())
+ initial_data.append(received.bytes());
+
+ auto download_id = navigation_params->navigable->page().client().page_did_start_download(navigation_params->navigable->id(), navigation_params->id, download_url, suggested_filename, response_content_length(*response->header_list()), lease->source_client_id, lease->source_request_id, move(initial_data),
move(network_response));
if (!download_id.has_value()) {
- if (navigation_params->fetch_controller)
- navigation_params->fetch_controller->stop_fetch();
- else
- response->resume_body_delivery();
+ stop_response_body_delivery(*navigation_params);
return true;
}
@@ -3060,7 +3057,7 @@ static void load_document_or_handle_download(GC::Ref<NavigationParams> navigatio
output.document = load_document(navigation_params, sniff_bytes);
if (!output.document) {
- output.download_handled = handle_navigation_response_as_download(navigation_params, source_allows_downloading, source_interface_origin, sniff_bytes);
+ output.download_handled = handle_navigation_response_as_download(navigation_params, source_allows_downloading, source_interface_origin);
output.save_extra_document_state = false;
} else {
navigation_params->response->resume_body_delivery();
diff --git a/Tests/LibWeb/TestFetchBodyDeliveryGate.cpp b/Tests/LibWeb/TestFetchBodyDeliveryGate.cpp
index 117ce810e4b..d89df5b8848 100644
--- a/Tests/LibWeb/TestFetchBodyDeliveryGate.cpp
+++ b/Tests/LibWeb/TestFetchBodyDeliveryGate.cpp
@@ -215,6 +215,23 @@ TEST_CASE(detached_transport_is_never_touched_again)
EXPECT(harness.transport->take_calls().is_empty());
}
+TEST_CASE(released_transport_is_paused_and_never_touched_again)
+{
+ // A body handed to another process leaves the transport paused for its next owner, which reads the rest.
+ GateHarness harness { NavigationHold::None };
+ harness.gate->attach_transport(harness.transport);
+ harness.gate->grant_credit(10);
+ (void)harness.transport->take_calls();
+
+ harness.gate->release_transport();
+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Pause } }));
+
+ harness.gate->consumer_cancelled();
+ harness.gate->grant_credit(10);
+ harness.gate->release_hold();
+ EXPECT(harness.transport->take_calls().is_empty());
+}
+
TEST_CASE(channel_sink_posts_commands_onto_the_creating_loop)
{
Core::EventLoop loop;
diff --git a/Tests/LibWeb/TestFetchByteChannel.cpp b/Tests/LibWeb/TestFetchByteChannel.cpp
index e8ac011ac48..7c787777b35 100644
--- a/Tests/LibWeb/TestFetchByteChannel.cpp
+++ b/Tests/LibWeb/TestFetchByteChannel.cpp
@@ -23,6 +23,7 @@ using Closed = FetchByteChannel::Closed;
using ConsumerCancelled = FetchByteChannel::ConsumerCancelled;
using Errored = FetchByteChannel::Errored;
using Open = FetchByteChannel::Open;
+using Transferred = FetchByteChannel::Transferred;
struct SinkEvent {
enum class Kind : u8 {
@@ -127,14 +128,19 @@ bool spin_until_or_timeout(Condition condition)
return true;
}
-ByteString flatten(FetchByteChannel::TakeResult const& result)
+ByteString flatten(Vector<Core::ImmutableBytes> const& taken_bytes)
{
ByteBuffer flat;
- for (auto const& taken : result.taken)
+ for (auto const& taken : taken_bytes)
flat.append(taken.bytes());
return ByteString { flat.bytes() };
}
+ByteString flatten(FetchByteChannel::TakeResult const& result)
+{
+ return flatten(result.taken);
+}
+
}
TEST_CASE(write_take_ordering_and_chunk_integrity)
@@ -415,8 +421,9 @@ TEST_CASE(every_ending_wakes_a_waiter)
Close,
Error,
Cancel,
+ Transfer,
};
- for (auto ending : { Ending::Close, Ending::Error, Ending::Cancel }) {
+ for (auto ending : { Ending::Close, Ending::Error, Ending::Cancel, Ending::Transfer }) {
ChannelHarness harness;
auto ticket = harness.channel->arm_waiter();
@@ -430,6 +437,9 @@ TEST_CASE(every_ending_wakes_a_waiter)
case Ending::Cancel:
EXPECT_EQ(harness.channel->cancel(), TerminateResult::Terminated);
break;
+ case Ending::Transfer:
+ EXPECT(harness.channel->transfer_out().is_empty());
+ break;
}
auto events = harness.take_events();
@@ -454,6 +464,93 @@ TEST_CASE(cancellation_notifies_the_producer)
EXPECT(result.state.has<ConsumerCancelled>());
}
+TEST_CASE(transfer_out_returns_the_undrained_bytes)
+{
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("first "sv)), WriteResult::Accepted);
+ EXPECT_EQ(harness.channel->write(bytes_of("second "sv)), WriteResult::Accepted);
+ EXPECT_EQ(harness.channel->write(bytes_of("third"sv)), WriteResult::Accepted);
+ EXPECT_EQ(flatten(harness.channel->take_up_to(3)), "fir"sv);
+ (void)harness.take_events();
+
+ EXPECT_EQ(flatten(harness.channel->transfer_out()), "st second third"sv);
+ EXPECT(harness.take_events().is_empty());
+
+ auto result = harness.channel->take_all();
+ EXPECT(result.taken.is_empty());
+ EXPECT(result.state.has<Transferred>());
+ EXPECT_EQ(result.buffered_byte_count, 0u);
+}
+
+TEST_CASE(transfer_out_of_an_undrained_close_returns_its_tail)
+{
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("tail"sv)), WriteResult::Accepted);
+ EXPECT_EQ(harness.channel->close(), TerminateResult::Terminated);
+
+ EXPECT_EQ(flatten(harness.channel->transfer_out()), "tail"sv);
+ EXPECT(harness.channel->take_all().state.has<Transferred>());
+}
+
+TEST_CASE(transfer_out_returns_copied_bytes_in_order)
+{
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("adopted "sv)), WriteResult::Accepted);
+ EXPECT_EQ(harness.channel->write_copy("copied"sv.bytes()), WriteResult::Accepted);
+
+ EXPECT_EQ(flatten(harness.channel->transfer_out()), "adopted copied"sv);
+}
+
+TEST_CASE(a_transferred_channel_tells_neither_side)
+{
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("moving"sv)), WriteResult::Accepted);
+ (void)harness.take_events();
+ EXPECT_EQ(flatten(harness.channel->transfer_out()), "moving"sv);
+
+ EXPECT_EQ(harness.channel->write(bytes_of("late"sv)), WriteResult::Rejected);
+ EXPECT_EQ(harness.channel->close(), TerminateResult::AlreadyTerminated);
+ EXPECT_EQ(harness.channel->cancel(), TerminateResult::AlreadyTerminated);
+ EXPECT(harness.channel->transfer_out().is_empty());
+
+ auto result = harness.channel->take_all();
+ EXPECT(result.taken.is_empty());
+ EXPECT(result.state.has<Transferred>());
+
+ // Neither a consumer cancellation nor credit reaches the transport.
+ EXPECT(harness.take_events().is_empty());
+}
+
+TEST_CASE(an_error_after_a_transfer_tells_neither_side)
+{
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("moving"sv)), WriteResult::Accepted);
+ (void)harness.take_events();
+ (void)harness.channel->transfer_out();
+
+ EXPECT_EQ(harness.channel->error({}), TerminateResult::AlreadyTerminated);
+ EXPECT(harness.channel->take_all().state.has<Transferred>());
+ EXPECT(harness.take_events().is_empty());
+}
+
+TEST_CASE(an_errored_or_cancelled_channel_transfers_nothing)
+{
+ {
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("junk"sv)), WriteResult::Accepted);
+ EXPECT_EQ(harness.channel->error({}), TerminateResult::Terminated);
+ EXPECT(harness.channel->transfer_out().is_empty());
+ EXPECT(harness.channel->take_all().state.has<Errored>());
+ }
+ {
+ ChannelHarness harness;
+ EXPECT_EQ(harness.channel->write(bytes_of("junk"sv)), WriteResult::Accepted);
+ EXPECT_EQ(harness.channel->cancel(), TerminateResult::Terminated);
+ EXPECT(harness.channel->transfer_out().is_empty());
+ EXPECT(harness.channel->take_all().state.has<ConsumerCancelled>());
+ }
+}
+
TEST_CASE(no_credit_replenishment_after_terminal)
{
ChannelHarness harness { { .low = 16, .high = 64 } };
@@ -595,6 +692,69 @@ TEST_CASE(concurrent_cancellation_rejects_every_later_write)
EXPECT(channel->take_all().state.has<ConsumerCancelled>());
}
+TEST_CASE(concurrent_transfer_moves_every_accepted_byte_once)
+{
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto consumer_sink = adopt_ref(*new LatestTicketSink);
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto producer_sink = adopt_ref(*new CountingProducerSink);
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto channel = FetchByteChannel::create({ .low = 16, .high = 64 }, *consumer_sink, *producer_sink);
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> timed_out { false };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> transferred { false };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<u64> accepted { 0 };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<u64> accepted_after_rejection { 0 };
+ producer_sink->credit.store(channel->initial_credit(), AK::MemoryOrder::memory_order_release);
+
+ // A transfer tells the transport nothing, so the writer learns of it from the test and from its rejected writes.
+ auto writer = Threading::Thread::construct("channel writer"sv, [&channel, &producer_sink, &timed_out, &transferred, &accepted, &accepted_after_rejection]() -> intptr_t {
+ for (;;) {
+ auto may_write = spin_until_or_timeout([&] {
+ return producer_sink->credit.load(AK::MemoryOrder::memory_order_acquire) > 0 || transferred.load();
+ });
+ if (!may_write) {
+ timed_out.store(true);
+ return 1;
+ }
+ if (!transferred.load())
+ producer_sink->credit.fetch_sub(1, AK::MemoryOrder::memory_order_acq_rel);
+ if (channel->write(MUST(Core::ImmutableBytes::copy("x"sv.bytes()))) == WriteResult::Rejected)
+ break;
+ accepted.fetch_add(1);
+ }
+ for (int i = 0; i < 16; ++i) {
+ if (channel->write(MUST(Core::ImmutableBytes::copy("x"sv.bytes()))) == WriteResult::Accepted)
+ accepted_after_rejection.fetch_add(1);
+ }
+ return 0;
+ });
+ writer->start();
+
+ // The consumer drains a while, then transfers the body while the writer is mid-stream.
+ u64 total_bytes_taken = 0;
+ while (total_bytes_taken < 5'000) {
+ auto ticket = channel->arm_waiter();
+ auto woken = spin_until_or_timeout([&] {
+ return consumer_sink->latest.load(AK::MemoryOrder::memory_order_acquire) >= ticket.value();
+ });
+ if (!woken) {
+ timed_out.store(true);
+ warnln("No wake arrived for ticket {}", ticket.value());
+ break;
+ }
+ for (auto const& taken : channel->take_all().taken)
+ total_bytes_taken += taken.size();
+ }
+ u64 total_bytes_moved = 0;
+ for (auto const& moved : channel->transfer_out())
+ total_bytes_moved += moved.size();
+ transferred.store(true);
+
+ MUST(writer->join());
+ EXPECT(!timed_out.load());
+ EXPECT_EQ(total_bytes_taken + total_bytes_moved, accepted.load());
+ EXPECT_EQ(accepted_after_rejection.load(), 0u);
+ EXPECT_EQ(producer_sink->cancellations.load(), 0u);
+ EXPECT(channel->take_all().state.has<Transferred>());
+}
+
TEST_CASE(arming_after_an_ending_fires_at_once)
{
ChannelHarness harness;
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index b60f2a07d40..46ea770b984 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -295,6 +295,13 @@ if (NOT WIN32)
target_compile_definitions(TestFileDownloader PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")
endif()
+ add_executable(TestNavigationDownloads TestNavigationDownloads.cpp)
+ add_dependencies(TestNavigationDownloads ladybird_build_resource_files ${ladybird_helper_processes})
+ target_link_libraries(TestNavigationDownloads PRIVATE AK LibCore LibFileSystem LibGfx LibIPC LibMain LibThreading LibURL LibWeb LibWebView)
+ if (APPLE)
+ target_compile_definitions(TestNavigationDownloads PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")
+ endif()
+
add_executable(TestCrashOverlay TestCrashOverlay.cpp)
add_dependencies(TestCrashOverlay ladybird_build_resource_files ${ladybird_helper_processes})
target_link_libraries(TestCrashOverlay PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)
@@ -445,6 +452,9 @@ if (BUILD_TESTING AND NOT WIN32)
add_test(NAME TestFileDownloader COMMAND $<TARGET_FILE:TestFileDownloader>)
set_tests_properties(TestFileDownloader PROPERTIES TIMEOUT 120 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
+ add_test(NAME TestNavigationDownloads COMMAND $<TARGET_FILE:TestNavigationDownloads>)
+ set_tests_properties(TestNavigationDownloads PROPERTIES TIMEOUT 120 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
+
add_test(NAME TestCrashOverlay COMMAND $<TARGET_FILE:TestCrashOverlay>)
set_tests_properties(TestCrashOverlay PROPERTIES TIMEOUT 60 ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
diff --git a/Tests/LibWebView/TestNavigationDownloads.cpp b/Tests/LibWebView/TestNavigationDownloads.cpp
new file mode 100644
index 00000000000..0f70acf4e2c
--- /dev/null
+++ b/Tests/LibWebView/TestNavigationDownloads.cpp
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/Atomic.h>
+#include <AK/LexicalPath.h>
+#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
+#include <AK/StringBuilder.h>
+#include <LibCore/Directory.h>
+#include <LibCore/EventLoop.h>
+#include <LibCore/File.h>
+#include <LibCore/StandardPaths.h>
+#include <LibCore/System.h>
+#include <LibCore/Timer.h>
+#include <LibFileSystem/FileSystem.h>
+#include <LibGfx/SystemTheme.h>
+#include <LibMain/Main.h>
+#include <LibThreading/Thread.h>
+#include <LibURL/Parser.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/FileDownloader.h>
+#include <LibWebView/HeadlessWebView.h>
+#include <LibWebView/Utilities.h>
+#include <netinet/in.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+
+namespace {
+
+class TestApplication : public WebView::Application {
+ WEB_VIEW_APPLICATION(TestApplication)
+
+public:
+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)
+ : WebView::Application(move(ladybird_binary_path))
+ {
+ }
+
+ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options) override
+ {
+ browser_options.headless_mode = WebView::HeadlessMode::Test;
+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;
+ web_content_options.is_test_mode = WebView::IsTestMode::Yes;
+ }
+
+ virtual bool should_coordinate_browser_process() const override { return false; }
+};
+
+// Answers a request for its page with a small document, and every other request with the same response.
+class TestHttpServer {
+public:
+ TestHttpServer(ByteString headers, ByteBuffer body)
+ : m_headers(move(headers))
+ , m_body(move(body))
+ {
+ m_socket = MUST(Core::System::socket(AF_INET, SOCK_STREAM, 0));
+
+ int reuse_address = 1;
+ MUST(Core::System::setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_address, sizeof(reuse_address)));
+
+ sockaddr_in address {};
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ MUST(Core::System::bind(m_socket, reinterpret_cast<sockaddr*>(&address), sizeof(address)));
+ MUST(Core::System::listen(m_socket, 16));
+
+ socklen_t address_size = sizeof(address);
+ VERIFY(::getsockname(m_socket, reinterpret_cast<sockaddr*>(&address), &address_size) == 0);
+ m_port = ntohs(address.sin_port);
+
+ m_thread = Threading::Thread::construct("TestHttpServer"sv, [this] -> intptr_t {
+ run();
+ return 0;
+ });
+ m_thread->start();
+ }
+
+ ~TestHttpServer()
+ {
+ m_shutting_down.store(true);
+ wake_server();
+ (void)m_thread->join();
+ (void)Core::System::close(m_socket);
+ }
+
+ URL::URL page_url() const
+ {
+ return URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/page", m_port)).release_value();
+ }
+
+ URL::URL url() const
+ {
+ return URL::Parser::basic_parse(ByteString::formatted("http://127.0.0.1:{}/file", m_port)).release_value();
+ }
+
+ // The number of requests for url(), not counting the page.
+ size_t request_count() const { return m_request_count.load(); }
+
+private:
+ void run()
+ {
+ while (!m_shutting_down.load()) {
+ auto client = ::accept(m_socket, nullptr, nullptr);
+ if (client < 0)
+ return;
+ respond(client);
+ (void)Core::System::close(client);
+ }
+ }
+
+ void wake_server()
+ {
+ auto socket = Core::System::socket(AF_INET, SOCK_STREAM, 0);
+ if (socket.is_error())
+ return;
+
+ sockaddr_in address {};
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ address.sin_port = htons(m_port);
+ (void)::connect(socket.value(), reinterpret_cast<sockaddr*>(&address), sizeof(address));
+ (void)Core::System::close(socket.value());
+ }
+
+ void respond(int client)
+ {
+ StringBuilder request;
+ Array<u8, 4096> buffer;
+ while (!request.string_view().contains("\r\n\r\n"sv)) {
+ auto read = Core::System::read(client, buffer);
+ if (read.is_error() || read.value() == 0)
+ return;
+ request.append(StringView { buffer.span().trim(read.value()) });
+ }
+
+ if (request.string_view().starts_with("GET /page "sv)) {
+ auto page = "<!DOCTYPE html><title>Downloads</title>"sv;
+ auto response = ByteString::formatted("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", page.length(), page);
+ (void)write_all(client, response.bytes());
+ return;
+ }
+ m_request_count.fetch_add(1);
+
+ auto head = ByteString::formatted("HTTP/1.1 200 OK\r\n{}Content-Length: {}\r\nConnection: close\r\n\r\n", m_headers, m_body.size());
+ if (write_all(client, head.bytes()))
+ (void)write_all(client, m_body.bytes());
+ }
+
+ static bool write_all(int fd, ReadonlyBytes bytes)
+ {
+ while (!bytes.is_empty()) {
+ auto written = Core::System::write(fd, bytes);
+ if (written.is_error() || written.value() == 0)
+ return false;
+ bytes = bytes.slice(written.value());
+ }
+ return true;
+ }
+
+ ByteString m_headers;
+ ByteBuffer m_body;
+ int m_socket { -1 };
+ u16 m_port { 0 };
+ RefPtr<Threading::Thread> m_thread;
+ Atomic<bool> m_shutting_down { false };
+ Atomic<size_t> m_request_count { 0 };
+};
+
+class FinishedDownloadRecorder final : public WebView::FileDownloaderObserver {
+public:
+ virtual void download_updated(WebView::FileDownloader::Download const& download) override
+ {
+ if (!WebView::FileDownloader::status_is_active(download.status))
+ m_finished = download;
+ }
+
+ Optional<WebView::FileDownloader::Download> const& finished() const { return m_finished; }
+
+private:
+ Optional<WebView::FileDownloader::Download> m_finished;
+};
+
+ByteBuffer make_body(size_t size)
+{
+ auto body = MUST(ByteBuffer::create_uninitialized(size));
+ for (size_t i = 0; i < size; ++i)
+ body[i] = static_cast<u8>((i * 31 + (i >> 8) * 17) & 0xff);
+ return body;
+}
+
+void load_page(WebView::HeadlessWebView& view, URL::URL const& url)
+{
+ IGNORE_USE_IN_ESCAPING_LAMBDA bool loaded = false;
+ view.on_load_finish = [&](URL::URL const&) { loaded = true; };
+ view.load(url);
+
+ auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(30), [] { });
+ deadline->start();
+ Core::EventLoop::current().spin_until([&] { return loaded || !deadline->is_active(); });
+ view.on_load_finish = nullptr;
+ if (!loaded) {
+ warnln("FAIL: the page did not load within 30 seconds");
+ VERIFY_NOT_REACHED();
+ }
+}
+
+WebView::FileDownloader::Download download_navigation_response(WebView::HeadlessWebView& view, URL::URL const& url)
+{
+ FinishedDownloadRecorder recorder;
+
+ view.load(url);
+
+ // A download that never finishes fails here, after 30 seconds.
+ auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(30), [] { });
+ deadline->start();
+ Core::EventLoop::current().spin_until([&] { return recorder.finished().has_value() || !deadline->is_active(); });
+ if (!recorder.finished().has_value()) {
+ warnln("FAIL: no download finished within 30 seconds");
+ VERIFY_NOT_REACHED();
+ }
+ return *recorder.finished();
+}
+
+void expect_download_holds_body(StringView what, WebView::FileDownloader::Download const& download, ByteBuffer const& body)
+{
+ if (download.status != WebView::FileDownloader::DownloadStatus::Completed) {
+ warnln("FAIL: {}: the download ended with status {}", what, to_underlying(download.status));
+ VERIFY_NOT_REACHED();
+ }
+
+ auto file = MUST(Core::File::open(download.destination.string(), Core::File::OpenMode::Read));
+ auto contents = MUST(file->read_until_eof());
+ if (contents.bytes() != body.bytes()) {
+ warnln("FAIL: {}: the file holds {} bytes, not the {} the server sent", what, contents.size(), body.size());
+ VERIFY_NOT_REACHED();
+ }
+}
+
+void expect_navigation_downloads_body(Core::AnonymousBuffer const& theme, StringView what, ByteString headers, ByteBuffer const& body)
+{
+ TestHttpServer server { move(headers), body };
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ expect_download_holds_body(what, download_navigation_response(*view, server.url()), body);
+}
+
+void expect_navigation_downloads_cached_body(Core::AnonymousBuffer const& theme, StringView what, ByteString headers, ByteBuffer const& body)
+{
+ TestHttpServer server { move(headers), body };
+
+ // Both downloads start from a document of the server's site, whose process reads and writes that site's cache.
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ load_page(*view, server.page_url());
+ expect_download_holds_body(what, download_navigation_response(*view, server.url()), body);
+
+ // The first download completes only after RequestServer has written its cache entry.
+ auto request_count = server.request_count();
+ expect_download_holds_body(what, download_navigation_response(*view, server.url()), body);
+ if (server.request_count() != request_count) {
+ warnln("FAIL: {}: the second download did not come from the disk cache", what);
+ VERIFY_NOT_REACHED();
+ }
+}
+
+}
+
+ErrorOr<int> ladybird_main(Main::Arguments arguments)
+{
+ auto test_directory = ByteString::formatted("{}/Ladybird-TestNavigationDownloads-{}", Core::StandardPaths::tempfile_directory(), generate_random_uuid());
+ TRY(Core::Directory::create(test_directory, Core::Directory::CreateDirectories::Yes));
+ auto cleanup_test_directory = ScopeGuard([&] {
+ MUST(FileSystem::remove(test_directory, FileSystem::RecursionMode::Allowed));
+ });
+ VERIFY(setenv("XDG_CONFIG_HOME", test_directory.characters(), 1) == 0);
+ VERIFY(setenv("XDG_CACHE_HOME", test_directory.characters(), 1) == 0);
+ VERIFY(setenv("XDG_DOWNLOAD_DIR", test_directory.characters(), 1) == 0);
+
+ signal(SIGPIPE, SIG_IGN);
+
+#if defined(LADYBIRD_BINARY_PATH)
+ auto app = TRY(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));
+#else
+ auto app = TRY(TestApplication::create(arguments, OptionalNone {}));
+#endif
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY(Gfx::load_system_theme(theme_path.string()));
+
+ auto body = make_body(1 * MiB);
+ expect_navigation_downloads_body(theme, "an attachment"sv, "Content-Disposition: attachment; filename=\"attachment.bin\"\r\n"sv, body);
+ expect_navigation_downloads_body(theme, "a response sniffed as unrenderable"sv, "Content-Type: application/octet-stream\r\n"sv, body);
+ expect_navigation_downloads_cached_body(theme, "a response sniffed from the disk cache"sv, "Cache-Control: max-age=3600\r\nContent-Type: application/octet-stream\r\n"sv, body);
+ expect_navigation_downloads_cached_body(theme, "an attachment from the disk cache"sv, "Cache-Control: max-age=3600\r\nContent-Disposition: attachment; filename=\"attachment.bin\"\r\n"sv, body);
+
+ outln("PASS: navigation responses download byte for byte");
+ return 0;
+}