Truly independent web browser
LibWeb+LibWebView+Services: Give every top-level site a RequestServer
Ali Mohammad Pur2fc639198224
diff --git a/Libraries/LibHTTP/Cache/CacheIndex.cpp b/Libraries/LibHTTP/Cache/CacheIndex.cppindex 463445d55ec..94ad698e705 100644--- a/Libraries/LibHTTP/Cache/CacheIndex.cpp+++ b/Libraries/LibHTTP/Cache/CacheIndex.cpp@@ -196,6 +196,11 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPathWHERE last_access_time >= ?RETURNING cache_key, vary_key, MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);)#"sv));+ statements.remove_entries_accessed_before = TRY(database.prepare_statement(R"#(+ DELETE FROM CacheIndex+ WHERE last_access_time < ?+ RETURNING cache_key, vary_key, MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers);+ )#"sv));statements.remove_all_entries = TRY(database.prepare_statement(R"#(DELETE FROM CacheIndexRETURNING cache_key, vary_key;@@ -235,6 +240,13 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPathFROM CacheIndex;)#"sv));+ statements.select_access_profile = TRY(database.prepare_statement(R"#(+ SELECT last_access_time / ?1 * ?1 AS bucket, SUM(MAX(data_size, 0) + MAX(associated_data_size, 0) + OCTET_LENGTH(request_headers) + OCTET_LENGTH(response_headers))+ FROM CacheIndex+ GROUP BY bucket+ ORDER BY bucket DESC;+ )#"sv));+auto disk_space = TRY(FileSystem::compute_disk_space(cache_directory));auto maximum_disk_cache_size = compute_maximum_disk_cache_size(disk_space.free_bytes);@@ -435,6 +447,8 @@ void CacheIndex::remove_entries_accessed_since(UnixDateTime since, Function<voidm_entries.clear();m_total_estimated_size = 0;+ if (on_total_estimated_size_change)+ on_total_estimated_size_change();return;}@@ -454,6 +468,24 @@ void CacheIndex::remove_entries_accessed_since(UnixDateTime since, Function<voidsince);}+void CacheIndex::remove_entries_accessed_before(UnixDateTime before, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed)+{+ m_database->execute_statement(+ m_statements.remove_entries_accessed_before,+ [&](auto statement_id) -> ErrorOr<void> {+ auto cache_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 0));+ auto vary_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 1));+ auto removed_size = m_database->result_column<i64>(statement_id, 2);+ adjust_total_estimated_size(-removed_size);+ delete_entry(cache_key, vary_key);++ if (on_entry_removed)+ on_entry_removed(cache_key, vary_key);+ return {};+ },+ before);+}+void CacheIndex::remove_entries_for_cache_key(u64 cache_key, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed){Vector<u64> vary_keys;@@ -599,6 +631,9 @@ void CacheIndex::adjust_total_estimated_size(i64 delta)m_total_estimated_size = delta > 0 ? NumericLimits<i64>::max() : 0;elsem_total_estimated_size = max<i64>(total.value(), 0);++ if (on_total_estimated_size_change)+ on_total_estimated_size_change();}void CacheIndex::delete_entry(u64 cache_key, u64 vary_key)@@ -630,6 +665,27 @@ Requests::CacheSizes CacheIndex::estimate_cache_size_accessed_since(UnixDateTimereturn sizes;}+Vector<Requests::CacheAccessBucket> CacheIndex::access_profile(AK::Duration granularity)+{+ Vector<Requests::CacheAccessBucket> buckets;++ auto result = m_database->try_execute_statement(+ m_statements.select_access_profile,+ [&](auto statement_id) -> ErrorOr<void> {+ buckets.append({+ .last_access_time = m_database->result_column<UnixDateTime>(statement_id, 0),+ .size = static_cast<u64>(max<i64>(m_database->result_column<i64>(statement_id, 1), 0)),+ });+ return {};+ },+ max<i64>(granularity.to_milliseconds(), 1));++ if (result.is_error())+ dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1mUnable to profile cache accesses:\033[0m {}", result.error());++ return buckets;+}+void CacheIndex::set_maximum_disk_cache_size(u64 maximum_disk_cache_size){auto new_maximum_disk_cache_size = compute_maximum_disk_cache_size(m_limits.free_disk_space, maximum_disk_cache_size);diff --git a/Libraries/LibHTTP/Cache/CacheIndex.h b/Libraries/LibHTTP/Cache/CacheIndex.hindex 7a9cc969a7f..ebb3c68a119 100644--- a/Libraries/LibHTTP/Cache/CacheIndex.h+++ b/Libraries/LibHTTP/Cache/CacheIndex.h@@ -51,6 +51,7 @@ public:void remove_entries_exceeding_cache_limit(Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);void remove_variants_exceeding_limit(u64 cache_key, u64 vary_key_to_keep, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);void remove_entries_accessed_since(UnixDateTime, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);+ void remove_entries_accessed_before(UnixDateTime, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);void remove_entries_for_cache_key(u64 cache_key, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);Optional<Entry const&> find_entry(u64 cache_key, HeaderList const& request_headers);@@ -61,6 +62,10 @@ public:void update_last_access_time(u64 cache_key, u64 vary_key);Requests::CacheSizes estimate_cache_size_accessed_since(UnixDateTime since);+ Vector<Requests::CacheAccessBucket> access_profile(AK::Duration granularity);+ u64 total_estimated_size() const { return static_cast<u64>(m_total_estimated_size); }++ Function<void()> on_total_estimated_size_change;void set_maximum_disk_cache_size(u64 maximum_disk_cache_size);u64 maximum_disk_cache_entry_size() const { return static_cast<u64>(m_limits.maximum_disk_cache_entry_size); }@@ -71,6 +76,7 @@ private:Database::StatementID remove_entry { 0 };Database::StatementID remove_entries_exceeding_cache_limit { 0 };Database::StatementID remove_entries_accessed_since { 0 };+ Database::StatementID remove_entries_accessed_before { 0 };Database::StatementID remove_all_entries { 0 };Database::StatementID select_entries { 0 };Database::StatementID update_response_headers { 0 };@@ -78,6 +84,7 @@ private:Database::StatementID update_last_access_time { 0 };Database::StatementID estimate_cache_size_accessed_since { 0 };Database::StatementID select_total_estimated_size { 0 };+ Database::StatementID select_access_profile { 0 };};struct Limits {diff --git a/Libraries/LibHTTP/Cache/DiskCache.cpp b/Libraries/LibHTTP/Cache/DiskCache.cppindex 028f0fa7071..6eca9f1289d 100644--- a/Libraries/LibHTTP/Cache/DiskCache.cpp+++ b/Libraries/LibHTTP/Cache/DiskCache.cpp@@ -464,6 +464,13 @@ void DiskCache::remove_entries_accessed_since(UnixDateTime since)});}+void DiskCache::remove_entries_accessed_before(UnixDateTime before)+{+ m_index.remove_entries_accessed_before(before, [&](auto cache_key, auto vary_key) {+ delete_entry(cache_key, vary_key);+ });+}+// https://httpwg.org/specs/rfc9111.html#invalidationvoid DiskCache::invalidate(Utf16String const& partition, URL::URL const& url){diff --git a/Libraries/LibHTTP/Cache/DiskCache.h b/Libraries/LibHTTP/Cache/DiskCache.hindex d00ccd0dde0..be64e7ad6cc 100644--- a/Libraries/LibHTTP/Cache/DiskCache.h+++ b/Libraries/LibHTTP/Cache/DiskCache.h@@ -66,6 +66,12 @@ public:Requests::CacheSizes estimate_cache_size_accessed_since(UnixDateTime since);void remove_entries_accessed_since(UnixDateTime since);+ // Supports least-recently-used eviction across disk caches sharing one size limit.+ Vector<Requests::CacheAccessBucket> access_profile(AK::Duration granularity) { return m_index.access_profile(granularity); }+ void remove_entries_accessed_before(UnixDateTime before);+ u64 estimated_size() const { return m_index.total_estimated_size(); }+ void set_on_estimated_size_change(Function<void()> callback) { m_index.on_total_estimated_size_change = move(callback); }+void invalidate(Utf16String const& partition, URL::URL const&);LexicalPath const& cache_directory() const { return m_cache_directory; }diff --git a/Libraries/LibRequests/CacheSizes.cpp b/Libraries/LibRequests/CacheSizes.cppindex 9049b2155c1..a4d9e5b4770 100644--- a/Libraries/LibRequests/CacheSizes.cpp+++ b/Libraries/LibRequests/CacheSizes.cpp@@ -28,4 +28,22 @@ ErrorOr<Requests::CacheSizes> decode(Decoder& decoder)return Requests::CacheSizes { since_requested_time, total };}+template<>+ErrorOr<void> encode(Encoder& encoder, Requests::CacheAccessBucket const& bucket)+{+ TRY(encoder.encode(bucket.last_access_time));+ TRY(encoder.encode(bucket.size));++ return {};+}++template<>+ErrorOr<Requests::CacheAccessBucket> decode(Decoder& decoder)+{+ auto last_access_time = TRY(decoder.decode<UnixDateTime>());+ auto size = TRY(decoder.decode<u64>());++ return Requests::CacheAccessBucket { last_access_time, size };+}+}diff --git a/Libraries/LibRequests/CacheSizes.h b/Libraries/LibRequests/CacheSizes.hindex 8ed45418a85..7128d40fc19 100644--- a/Libraries/LibRequests/CacheSizes.h+++ b/Libraries/LibRequests/CacheSizes.h@@ -6,6 +6,7 @@#pragma once+#include <AK/Time.h>#include <AK/Types.h>#include <LibIPC/Forward.h>@@ -16,6 +17,12 @@ struct CacheSizes {u64 total { 0 };};+// Total bytes of entries last accessed in the time bucket starting at last_access_time.+struct CacheAccessBucket {+ UnixDateTime last_access_time;+ u64 size { 0 };+};+}namespace IPC {@@ -26,4 +33,10 @@ ErrorOr<void> encode(Encoder&, Requests::CacheSizes const&);template<>ErrorOr<Requests::CacheSizes> decode(Decoder&);+template<>+ErrorOr<void> encode(Encoder&, Requests::CacheAccessBucket const&);++template<>+ErrorOr<Requests::CacheAccessBucket> decode(Decoder&);+}diff --git a/Libraries/LibRequests/RequestControlClient.cpp b/Libraries/LibRequests/RequestControlClient.cppindex 2cf0e0c14fe..5d04bcb336d 100644--- a/Libraries/LibRequests/RequestControlClient.cpp+++ b/Libraries/LibRequests/RequestControlClient.cpp@@ -22,9 +22,12 @@ void RequestControlClient::die()promise->reject(Error::from_string_literal("RequestServer process died"));for (auto& [id, promise] : m_pending_clear_cache_requests)promise->reject(Error::from_string_literal("RequestServer process died"));+ for (auto& [id, promise] : m_pending_cache_access_profile_requests)+ promise->reject(Error::from_string_literal("RequestServer process died"));m_pending_cache_size_estimations.clear();m_pending_clear_cache_requests.clear();+ m_pending_cache_access_profile_requests.clear();if (auto request_server_died_callback = move(on_request_server_died)) {Core::deferred_invoke([request_server_died_callback = move(request_server_died_callback)]() mutable {@@ -99,4 +102,28 @@ void RequestControlClient::removed_cache_entries(u64 clear_cache_request_id)(*promise)->resolve({});}+NonnullRefPtr<Core::Promise<Vector<CacheAccessBucket>>> RequestControlClient::retrieve_cache_access_profile(AK::Duration granularity)+{+ auto promise = Core::Promise<Vector<CacheAccessBucket>>::construct();++ auto access_profile_request_id = m_next_cache_access_profile_request_id++;+ m_pending_cache_access_profile_requests.set(access_profile_request_id, promise);++ async_retrieve_cache_access_profile(access_profile_request_id, granularity);++ return promise;+}++void RequestControlClient::retrieved_cache_access_profile(u64 access_profile_request_id, Vector<CacheAccessBucket> buckets)+{+ if (auto promise = m_pending_cache_access_profile_requests.take(access_profile_request_id); promise.has_value())+ (*promise)->resolve(move(buckets));+}++void RequestControlClient::disk_cache_size_changed(u64 size)+{+ if (on_disk_cache_size_changed)+ on_disk_cache_size_changed(size);+}+}diff --git a/Libraries/LibRequests/RequestControlClient.h b/Libraries/LibRequests/RequestControlClient.hindex 72b9d308ecc..a0072fecf65 100644--- a/Libraries/LibRequests/RequestControlClient.h+++ b/Libraries/LibRequests/RequestControlClient.h@@ -32,12 +32,14 @@ public:NonnullRefPtr<Core::Promise<CacheSizes>> estimate_cache_size_accessed_since(UnixDateTime since);NonnullRefPtr<Core::Promise<Empty>> clear_cache(UnixDateTime since);+ NonnullRefPtr<Core::Promise<Vector<CacheAccessBucket>>> retrieve_cache_access_profile(AK::Duration granularity);Function<void(Vector<NetworkUsage>, u64 interval_microseconds)> on_network_usage;Function<void(int client_id)> on_client_disconnected;Function<String(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&)> on_retrieve_http_cookie;Function<void(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&, Vector<HTTP::Cookie::ParsedCookie> const&, Optional<HTTP::HSTS::ParsedHSTSPolicy> const&)> on_store_response_cookies_and_hsts_policy;Function<void()> on_request_server_died;+ Function<void(u64 size)> on_disk_cache_size_changed;private:virtual void die() override;@@ -48,12 +50,17 @@ private:virtual void store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) override;virtual void estimated_cache_size(u64 cache_size_estimation_id, CacheSizes sizes) override;virtual void removed_cache_entries(u64 clear_cache_request_id) override;+ virtual void disk_cache_size_changed(u64 size) override;+ virtual void retrieved_cache_access_profile(u64 access_profile_request_id, Vector<CacheAccessBucket> buckets) override;HashMap<u64, NonnullRefPtr<Core::Promise<CacheSizes>>> m_pending_cache_size_estimations;u64 m_next_cache_size_estimation_id { 0 };HashMap<u64, NonnullRefPtr<Core::Promise<Empty>>> m_pending_clear_cache_requests;u64 m_next_clear_cache_request_id { 0 };++ HashMap<u64, NonnullRefPtr<Core::Promise<Vector<CacheAccessBucket>>>> m_pending_cache_access_profile_requests;+ u64 m_next_cache_access_profile_request_id { 0 };};}diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cppindex 16a4d573d31..a37575e68a4 100644--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp@@ -77,6 +77,7 @@ static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch:body = NavigationResponseBodyHandle {.request_server_client_id = request->client_id,.request_server_request_id = request->request_id,+ .request_server_top_level_site = {},};}@@ -251,12 +252,17 @@ static GC::Ptr<Fetch::Infrastructure::Request> create_navigation_request_from_destatic GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, LocalNavigable& navigable, NavigationResponseBodyHandle handle, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Optional<JsonObject> network_response, RefPtr<NavigationResponseNetworkEventState> network_response_state){- if (!ResourceLoader::is_initialized() || !ResourceLoader::the().request_client())+ if (!ResourceLoader::is_initialized())+ return {};++ // The UI process moved the response to the RequestServer for the handle's site.+ auto request_client = ResourceLoader::the().request_client_for_top_level_site(handle.request_server_top_level_site);+ if (!request_client)return {};// Preserve the original RequestServer identity while WebContent decides whether this response will become a// document or a download. A download is adopted by the UI process using that identity.- auto request = ResourceLoader::the().request_client()->adopt_request(+ auto request = request_client->adopt_request(handle.request_server_client_id,handle.request_server_request_id,Requests::RequestClient::TransferLease::Yes);diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cppindex 7430189d055..bfe7e907f5f 100644--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp@@ -143,7 +143,8 @@ static Optional<BytecodeCacheContext> bytecode_cache_context_for_request(Fetch::if (!Fetch::Infrastructure::is_http_or_https_scheme(response_url.scheme()))return {};- if (!ResourceLoader::is_initialized() || !ResourceLoader::the().request_client())+ auto network_isolation_key = Fetch::Infrastructure::determine_the_network_partition_key(request);+ if (!ResourceLoader::is_initialized() || !ResourceLoader::the().request_client_for(network_isolation_key))return {};auto vary_key = response.javascript_bytecode_cache_vary_key();@@ -160,7 +161,7 @@ static Optional<BytecodeCacheContext> bytecode_cache_context_for_request(Fetch::.request_headers = HTTP::HeaderList::create(request.header_list()->headers()),.memory_cache_request_headers = move(memory_cache_request_headers),.vary_key = *vary_key,- .network_isolation_key = Fetch::Infrastructure::determine_the_network_partition_key(request),+ .network_isolation_key = move(network_isolation_key),};}@@ -194,7 +195,8 @@ static void schedule_bytecode_cache_generation(JS::ParsedProgram cache_parse, Noreturn heap_blob;};- if (!ResourceLoader::is_initialized() || !ResourceLoader::the().request_client()) {+ auto request_client = ResourceLoader::is_initialized() ? ResourceLoader::the().request_client_for(cache_context.network_isolation_key) : nullptr;+ if (!request_client) {install_heap_copy();return;}@@ -204,7 +206,7 @@ static void schedule_bytecode_cache_generation(JS::ParsedProgram cache_parse, No// of the script, exactly as they are when a later load reads the blob back from the cache. The shared// buffer the blob arrived in goes to RequestServer as it is, and is unmapped once the store returns.Core::ImmutableBytes installed_blob;- auto stored_blob = ResourceLoader::the().request_client()->store_cache_associated_data(cache_context.network_isolation_key, cache_context.url, cache_context.method, *cache_context.request_headers, cache_context.vary_key, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, *blob);+ auto stored_blob = request_client->store_cache_associated_data(cache_context.network_isolation_key, cache_context.url, cache_context.method, *cache_context.request_headers, cache_context.vary_key, HTTP::CacheEntryAssociatedData::JavaScriptBytecode, *blob);if (!stored_blob.is_error() && stored_blob.value().has_value()) {installed_blob = stored_blob.release_value().release_value();install_target.install_generated_bytecode_cache(type, original_source_code, source_hash, installed_blob);diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex eaf80c409f3..6013a70eee8 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -1221,18 +1221,24 @@ bool Internals::set_disk_cache_enabled_for_navigations(bool enabled)void Internals::simulate_request_server_connection_loss(){- auto disconnected_client = move(ResourceLoader::the().request_client());- auto request_server_died_callback = move(disconnected_client->on_request_server_died);- disconnected_client = nullptr;-- // Synchronously obtain a replacement connection from the UI process, so that this process is not left unable to- // load resources.- page().client().page_did_lose_request_server_connection();-- // A real connection loss defers this callback. Exercise the case where the replacement connection arrives before- // that deferred callback runs.- if (request_server_died_callback)- request_server_died_callback();+ Vector<Optional<Utf16String>> top_level_sites { OptionalNone {} };+ for (auto& top_level_site : ResourceLoader::the().top_level_sites())+ top_level_sites.append(move(top_level_site));++ for (auto const& top_level_site : top_level_sites) {+ auto disconnected_client = ResourceLoader::the().take_client_for_testing(top_level_site);+ if (!disconnected_client)+ continue;+ auto request_server_died_callback = move(disconnected_client->on_request_server_died);+ disconnected_client = nullptr;++ // Replace the connection synchronously so resource loading can continue.+ page().client().page_did_lose_request_server_connection(top_level_site);++ // Exercise reconnection before the deferred connection-loss callback runs.+ if (request_server_died_callback)+ request_server_died_callback();+ }}void Internals::simulate_worker_request_server_connection_loss()diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cppindex 3367c1a87ea..451e2b0ac3d 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp@@ -20,6 +20,7 @@#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>+#include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>#include <LibWeb/Loader/ContentBlocker.h>#include <LibWeb/Loader/GeneratedPagesLoader.h>#include <LibWeb/Loader/LoadRequest.h>@@ -53,9 +54,9 @@ Optional<URL::URL> const& ResourceLoader::proxy_autoconfig_url()return proxy_autoconfig_url_storage();}-void ResourceLoader::initialize(GC::Heap& heap, NonnullRefPtr<Requests::RequestClient> request_client)+void ResourceLoader::initialize(GC::Heap& heap){- resource_loader() = adopt_ref(*new ResourceLoader(heap, move(request_client)));+ resource_loader() = adopt_ref(*new ResourceLoader(heap));}bool ResourceLoader::is_initialized()@@ -72,13 +73,12 @@ ResourceLoader& ResourceLoader::the()return *resource_loader();}-ResourceLoader::ResourceLoader(GC::Heap& heap, NonnullRefPtr<Requests::RequestClient> request_client)+ResourceLoader::ResourceLoader(GC::Heap& heap): m_heap(heap), m_user_agent(MUST(String::from_utf8(default_user_agent))), m_platform(MUST(String::from_utf8(default_platform))), m_preferred_languages(default_preferred_languages()){- set_client(move(request_client));}NavigatorCompatibilityMode ResourceLoader::s_navigator_compatibility_mode = default_navigator_compatibility_mode;@@ -96,13 +96,58 @@ void ResourceLoader::set_navigator_compatibility_mode(NavigatorCompatibilityModevm.set_source_text_syntaxes(JS::VM::StackFrameSyntax::AtSign, JS::VM::NativeFunctionSourceSyntax::MultiLine);}-void ResourceLoader::set_client(NonnullRefPtr<Requests::RequestClient> request_client)+void ResourceLoader::set_client(Optional<Utf16String> const& top_level_site, NonnullRefPtr<Requests::RequestClient> request_client){- m_request_client = move(request_client);- m_request_client->on_request_server_died = [this, disconnected_client = m_request_client->make_weak_ptr<Requests::RequestClient>()]() {- if (m_request_client.ptr() == disconnected_client.ptr())- m_request_client = nullptr;+ request_client->on_request_server_died = [this, top_level_site, disconnected_client = request_client->make_weak_ptr<Requests::RequestClient>()]() {+ auto& client = ensure_client_for(top_level_site);+ if (client.ptr() == disconnected_client.ptr())+ client = nullptr;};+ ensure_client_for(top_level_site) = move(request_client);+}++RefPtr<Requests::RequestClient> ResourceLoader::request_client_for(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key) const+{+ if (!network_isolation_key.has_value())+ return m_request_client;+ return request_client_for_top_level_site(network_isolation_key->top_level_site);+}++RefPtr<Requests::RequestClient> ResourceLoader::request_client_for_top_level_site(Optional<Utf16String> const& top_level_site) const+{+ if (top_level_site.has_value()) {+ if (auto it = m_site_request_clients.find(*top_level_site); it != m_site_request_clients.end())+ return it->value;+ }+ return m_request_client;+}++RefPtr<Requests::RequestClient>& ResourceLoader::ensure_client_for(Optional<Utf16String> const& top_level_site)+{+ if (!top_level_site.has_value())+ return m_request_client;+ return m_site_request_clients.ensure(*top_level_site);+}++Vector<Utf16String> ResourceLoader::top_level_sites() const+{+ Vector<Utf16String> top_level_sites;+ for (auto const& entry : m_site_request_clients)+ top_level_sites.append(entry.key);+ return top_level_sites;+}++RefPtr<Requests::RequestClient> ResourceLoader::take_client_for_testing(Optional<Utf16String> const& top_level_site)+{+ return move(ensure_client_for(top_level_site));+}++// Speculation warms up the RequestServer that the document's requests go through.+static Optional<HTTP::NetworkIsolationKey> speculative_network_isolation_key(GC::Ptr<DOM::Document> document)+{+ if (!document)+ return {};+ return Fetch::Infrastructure::determine_the_network_partition_key(document->relevant_settings_object());}void ResourceLoader::prefetch_dns(GC::Ptr<DOM::Document> document, URL::URL const& url, URL::URL const& source_url)@@ -122,8 +167,8 @@ void ResourceLoader::prefetch_dns(GC::Ptr<DOM::Document> document, URL::URL consreturn;// FIXME: We could put this request in a queue until the client connection is re-established.- if (m_request_client)- m_request_client->ensure_connection(url, RequestServer::CacheLevel::ResolveOnly);+ if (auto request_client = request_client_for(speculative_network_isolation_key(document)))+ request_client->ensure_connection(url, RequestServer::CacheLevel::ResolveOnly);}void ResourceLoader::preconnect(GC::Ptr<DOM::Document> document, URL::URL const& url, URL::URL const& source_url)@@ -143,8 +188,8 @@ void ResourceLoader::preconnect(GC::Ptr<DOM::Document> document, URL::URL const&return;// FIXME: We could put this request in a queue until the client connection is re-established.- if (m_request_client)- m_request_client->ensure_connection(url, RequestServer::CacheLevel::CreateConnection);+ if (auto request_client = request_client_for(speculative_network_isolation_key(document)))+ request_client->ensure_connection(url, RequestServer::CacheLevel::CreateConnection);}static ByteString sanitized_url_for_logging(URL::URL const& url)@@ -527,7 +572,8 @@ static NonnullRefPtr<HTTP::HeaderList const> headers_with_normalized_values(HTTPRefPtr<Requests::Request> ResourceLoader::start_network_request(LoadRequest const& request, Requests::RequestClient::TransferLease transfer_lease){// FIXME: We could put this request in a queue until the client connection is re-established.- if (!m_request_client) {+ auto request_client = request_client_for(request.network_isolation_key());+ if (!request_client) {log_failure(request, "RequestServer is currently unavailable"sv);return nullptr;}@@ -539,7 +585,7 @@ RefPtr<Requests::Request> ResourceLoader::start_network_request(LoadRequest cons// requests are attributed through the worker process's browser-level owners.auto originating_page_id = request.page() && request.page()->has_top_level_traversable() ? request.page()->client().id().value() : 0;auto headers = headers_with_normalized_values(request.headers());- auto protocol_request = m_request_client->start_request(request.method(), request.url().value(), *headers, request.body(), request.cache_mode(), request.include_credentials(), transfer_lease, {}, cache_miss_notification, originating_page_id, request.network_isolation_key());+ auto protocol_request = request_client->start_request(request.method(), request.url().value(), *headers, request.body(), request.cache_mode(), request.include_credentials(), transfer_lease, {}, cache_miss_notification, originating_page_id, request.network_isolation_key());if (!protocol_request) {log_failure(request, "Failed to initiate load"sv);return nullptr;diff --git a/Libraries/LibWeb/Loader/ResourceLoader.h b/Libraries/LibWeb/Loader/ResourceLoader.hindex 3ed2ff284cf..b3f89ccfb1a 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.h+++ b/Libraries/LibWeb/Loader/ResourceLoader.h@@ -8,7 +8,9 @@#pragma once#include <AK/ByteString.h>+#include <AK/HashMap.h>#include <AK/HashTable.h>+#include <AK/Utf16String.h>#include <LibCore/EventReceiver.h>#include <LibCore/ImmutableBytes.h>#include <LibGC/Function.h>@@ -29,14 +31,16 @@ class WEB_API ResourceLoader : public Core::EventReceiver {C_OBJECT_ABSTRACT(ResourceLoader)public:- static void initialize(GC::Heap&, NonnullRefPtr<Requests::RequestClient>);+ static void initialize(GC::Heap&);static bool is_initialized();static ResourceLoader& the();static void set_proxy_autoconfig_url(URL::URL);static Optional<URL::URL> const& proxy_autoconfig_url();- void set_client(NonnullRefPtr<Requests::RequestClient>);+ // Route requests through their top-level site's client, falling back to the server with no site+ // for requests without a site or without a client for that site.+ void set_client(Optional<Utf16String> const& top_level_site, NonnullRefPtr<Requests::RequestClient>);using OnHeadersReceived = GC::Function<void(Requests::Request*, 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)>;using OnDataReceived = GC::Function<void(Requests::ResponseData data)>;@@ -45,7 +49,12 @@ public:RefPtr<Requests::Request> load(LoadRequest&, GC::Root<OnHeadersReceived>, GC::Root<OnDataReceived>, GC::Root<OnCachedBodyAvailable>, GC::Root<OnComplete>, Requests::RequestClient::TransferLease = Requests::RequestClient::TransferLease::No);- RefPtr<Requests::RequestClient>& request_client() { return m_request_client; }+ RefPtr<Requests::RequestClient> request_client_for(Optional<HTTP::NetworkIsolationKey> const&) const;+ RefPtr<Requests::RequestClient> request_client_for_top_level_site(Optional<Utf16String> const&) const;++ // Sites with clients, excluding the server with no site.+ Vector<Utf16String> top_level_sites() const;+ RefPtr<Requests::RequestClient> take_client_for_testing(Optional<Utf16String> const& top_level_site);void prefetch_dns(GC::Ptr<DOM::Document>, URL::URL const&, URL::URL const& source_url);void preconnect(GC::Ptr<DOM::Document>, URL::URL const&, URL::URL const& source_url);@@ -78,7 +87,9 @@ public:void set_enable_global_privacy_control(bool enable) { m_enable_global_privacy_control = enable; }private:- explicit ResourceLoader(GC::Heap&, NonnullRefPtr<Requests::RequestClient>);+ explicit ResourceLoader(GC::Heap&);++ RefPtr<Requests::RequestClient>& ensure_client_for(Optional<Utf16String> const& top_level_site);struct FileLoadResult {ReadonlyBytes data;@@ -97,6 +108,7 @@ private:GC::Heap& m_heap;RefPtr<Requests::RequestClient> m_request_client;+ HashMap<Utf16String, RefPtr<Requests::RequestClient>> m_site_request_clients;HashTable<NonnullRefPtr<Requests::Request>> m_active_requests;String m_user_agent;diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex a9a99a3aec7..6971b8a5cf5 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -813,7 +813,7 @@ public:virtual void page_did_update_cookie(HTTP::Cookie::Cookie const&) { }virtual void page_did_expire_cookies_with_time_offset(AK::Duration) { }virtual void page_did_delete_all_cookies(URL::URL const&, GC::Ref<WebIDL::Promise>) { }- virtual void page_did_lose_request_server_connection() { }+ virtual void page_did_lose_request_server_connection([[maybe_unused]] Optional<Utf16String> const& top_level_site) { }virtual void page_did_simulate_worker_request_server_connection_loss() { }virtual void page_did_store_hsts_policy_for_testing(String const&, HTTP::HSTS::ParsedHSTSPolicy const&) { }virtual void page_did_request_clear_storage_for_testing(StorageAPI::StorageEndpointType, HTML::EnvironmentSettingsObject const&) { }diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cppindex b3d3181de53..dfd67e92356 100644--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp@@ -234,13 +234,14 @@ ErrorOr<void> WebSocket::establish_web_socket_connection(URL::URL const& url_recreturn Error::from_string_literal("PAC proxy configurations are not supported");}- auto request_client = ResourceLoader::the().request_client();+ auto network_isolation_key = Fetch::Infrastructure::determine_the_network_partition_key(client);+ auto request_client = ResourceLoader::the().request_client_for(network_isolation_key);// FIXME: We could put this request in a queue until the client connection is re-established.if (!request_client)return Error::from_string_literal("RequestServer is currently unavailable");- m_websocket = request_client->websocket_connect(connection_url, Fetch::Infrastructure::determine_the_network_partition_key(client), origin_string, protocol_byte_strings, {}, additional_headers);+ m_websocket = request_client->websocket_connect(connection_url, move(network_isolation_key), origin_string, protocol_byte_strings, {}, additional_headers);m_websocket->on_open = GC::weak_callback(*this, [](auto& self) {self.on_open();diff --git a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cppindex 99a2e435ed3..9deed6996b4 100644--- a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cpp+++ b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cpp@@ -95,6 +95,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::NavigationResponseBodyHandle c{TRY(encoder.encode(handle.request_server_client_id));TRY(encoder.encode(handle.request_server_request_id));+ TRY(encoder.encode(handle.request_server_top_level_site));return {};}@@ -104,6 +105,7 @@ ErrorOr<Web::HTML::NavigationResponseBodyHandle> decode(Decoder& decoder)return Web::HTML::NavigationResponseBodyHandle {.request_server_client_id = TRY(decoder.decode<int>()),.request_server_request_id = TRY(decoder.decode<u64>()),+ .request_server_top_level_site = TRY(decoder.decode<Optional<Utf16String>>()),};}diff --git a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.hindex 093f63dae25..ddc4012d9c5 100644--- a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h+++ b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h@@ -66,6 +66,9 @@ struct NavigationResponseBodyHandle {// response moves from the fetch worker through the UI process to the document host.int request_server_client_id { -1 };u64 request_server_request_id { 0 };+ // Selects the document host's client for adoption; empty selects the RequestServer with no site.+ // The UI process sets this when moving the response to the host's RequestServer.+ Optional<Utf16String> request_server_top_level_site;};using NavigationResponseBody = Variant<Empty, NavigationResponseBodyHandle, ByteBuffer>;diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 938fda09fc4..580f2fc1225 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -1127,7 +1127,7 @@ void Application::open_bookmark_in_new_window(String const& bookmark_id, IsPrivaErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(IsPrivate is_private, Web::PageId initial_page_id, Optional<Web::HTML::CrossProcessId> navigable_to_adopt, Optional<Web::HTML::CrossProcessId> initial_document_state_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables, Optional<Web::HTML::SessionHistoryEntryDescriptor> canonical_initial_history_entry, Web::HTML::VisibilityState system_visibility_state){// The client's WebContentClient picks up this same session when it is created.- auto request_server_connection = TRY(connect_new_request_server_client(session_for_new_view(is_private), RequestServer::SiteBinding::Bound));+ auto session = session_for_new_view(is_private);auto image_decoder = TRY(launch_image_decoder_process());auto cross_process_id_allocator = allocate_cross_process_id_allocator();@@ -1155,8 +1155,7 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(if (!navigable_to_adopt.has_value())client->set_initial_top_level_history_entry({}, move(initial_history_entry), initial_document_id);- client->request_server_site_bindings().did_connect(request_server_connection.client_id);- client->async_connect_to_request_server(move(request_server_connection.handle), request_server_connection.client_id);+ TRY(client->request_server_site_bindings().connect(session));client->async_set_site_compatibility_data(m_site_compatibility_data);connect_to_image_decoder(*client, move(image_decoder));@@ -1239,9 +1238,9 @@ bool Application::request_server_client_may_use_cookies_in(int client_id, URL::Ubool may_use_cookies = false;auto check_bindings = [&](RequestServerSiteBindings& bindings) {- if (bindings.client_id() != client_id)+ if (!bindings.has_client(client_id))return IterationDecision::Continue;- may_use_cookies = bindings.may_use_cookies_under(context->top_level_site, url);+ may_use_cookies = bindings.may_use_cookies_under(client_id, context->top_level_site, url);return IterationDecision::Break;};WebContentClient::for_each_client([&](WebContentClient& client) { return check_bindings(client.request_server_site_bindings()); });diff --git a/Libraries/LibWebView/CanonicalDocument.cpp b/Libraries/LibWebView/CanonicalDocument.cppindex e9778121c7c..f08caef7128 100644--- a/Libraries/LibWebView/CanonicalDocument.cpp+++ b/Libraries/LibWebView/CanonicalDocument.cpp@@ -4,13 +4,11 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibURL/Site.h>#include <LibWebView/BlobURLStore.h>#include <LibWebView/CanonicalBrowsingContext.h>#include <LibWebView/CanonicalBrowsingContextGroup.h>#include <LibWebView/CanonicalDocument.h>#include <LibWebView/CanonicalWindow.h>-#include <LibWebView/RequestServerManager.h>#include <LibWebView/WebContentClient.h>#include <LibWebView/WebContentPage.h>#include <LibWebView/WebUI.h>@@ -70,10 +68,6 @@ void CanonicalDocument::set_host(RefPtr<WebContentPage> host)if (m_host) {m_relevant_global_object->agent().set_hosting_process_if_unset(m_host->client());// The process makes the document's requests through the RequestServer of the document's top-level site.- if (auto top_level_origin = this->top_level_origin(); top_level_origin.has_value()) {- if (auto top_level_site = URL::Site::serialize_for_partitioning(*top_level_origin); top_level_site.has_value())- RequestServerManager::the().assign_site(m_host->client(), *top_level_site);- }m_host->client().request_server_site_bindings().bind_sites_of(*this);}}diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cppindex 995c08ae837..8d043834966 100644--- a/Libraries/LibWebView/CanonicalTraversable.cpp+++ b/Libraries/LibWebView/CanonicalTraversable.cpp@@ -9,6 +9,7 @@#include <AK/StringBuilder.h>#include <AK/TemporaryChange.h>#include <LibCore/EventLoop.h>+#include <LibURL/Site.h>#include <LibWebCommon/WebView/SiteIsolation.h>#include <LibWebView/Application.h>#include <LibWebView/CanonicalBrowsingContext.h>@@ -1408,13 +1409,7 @@ void CanonicalTraversable::continue_history_navigation_population(HistoryOperatiendpoint->async_continue_history_navigation_population(operation_id, changing_navigable->target_entry_descriptor(), operation->algorithm->navigation_type(),changing_navigable->navigable().ongoing_navigation().has<CanonicalNavigable::Traversal>(), Web::HTML::HistoryNavigationPopulation { loader.request(), loader.take_result() });};- if (auto client_id = endpoint->client().request_server_site_bindings().client_id(); client_id.has_value()) {- if (auto request_server = RequestServerManager::the().instance_for_client(*client_id)) {- changing_navigable.population_loader->move_response_body_to(*request_server, move(finish_handoff));- return;- }- }- finish_handoff(false);+ changing_navigable.population_loader->move_response_body_to(endpoint->client().request_server_site_bindings(), move(finish_handoff));}bool CanonicalTraversable::run_changing_navigable_history_step_job(ApplyHistoryStep& run, ChangingNavigable& changing_navigable)@@ -1764,6 +1759,23 @@ bool CanonicalTraversable::is_handing_navigable_to_another_page(CanonicalNavigabreturn false;}+bool CanonicalTraversable::client_populates_a_history_entry_for_site(WebContentClient const& client, Utf16String const& site) const+{+ for (auto const& [operation_id, operation] : m_history_operations) {+ if (!operation->algorithm)+ continue;+ for (auto const& changing_navigable : operation->algorithm->changing_navigables()) {+ if (!changing_navigable->has_pending_job() || !changing_navigable->navigable().is_top_level_traversable())+ continue;+ auto endpoint = changing_job_endpoint(*changing_navigable);+ if (&endpoint->client() == &client+ && URL::Site::serialize_for_partitioning(changing_navigable->target_entry->url.origin()) == site)+ return true;+ }+ }+ return false;+}+// A history step's changing job populates its target entry's document in the process hosting the navigable, which need// not have hosted local file content. For an entry whose document state held local file content, that process reads the// file the entry's file: URL names.diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.hindex 65dda1f9ea3..8f6cb69c2a9 100644--- a/Libraries/LibWebView/CanonicalTraversable.h+++ b/Libraries/LibWebView/CanonicalTraversable.h@@ -118,6 +118,7 @@ public:bool hosts(CanonicalNavigable const&, WebContentPage const&) const;bool represents(CanonicalNavigable const&, WebContentPage const&) const;bool page_hosts_any(WebContentPage const&) const;+ bool client_populates_a_history_entry_for_site(WebContentClient const&, Utf16String const&) const;bool page_populates_a_history_entry_for_local_file(WebContentPage const&, ByteString const& path) const;void stop_hosting_in_page(CanonicalNavigable&, NonnullRefPtr<WebContentPage>);void release_page_if_unused(NonnullRefPtr<WebContentPage>);diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex b5218376db6..4d2dafdfb47 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -595,7 +595,7 @@ void apply_dns_settings(Requests::RequestControlClient& client)});}-ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode http_disk_cache_mode)+ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, bool sites_have_their_own, HTTPDiskCacheMode http_disk_cache_mode){auto const& browser_options = Application::browser_options();auto const& request_server_options = Application::request_server_options();@@ -608,6 +608,8 @@ ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_proif (site.has_value()) {arguments.append("--site"sv);arguments.append(site->to_byte_string());+ } else if (sites_have_their_own) {+ arguments.append("--sites-have-their-own"sv);}if (browser_options.disable_sandbox == DisableSandbox::Yes)diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.hindex 900f12be412..43461588360 100644--- a/Libraries/LibWebView/HelperProcess.h+++ b/Libraries/LibWebView/HelperProcess.h@@ -31,7 +31,9 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_videoWEBVIEW_API void shut_down_video_decoder_servers();WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::CompositorClient>> launch_compositor_process();WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebWorkerClient>> launch_web_worker_process(Web::HTML::AgentType, IsPrivate, Web::HTML::WorkerAgentId);-WEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode);+// Serves the given site's partitions, or all partitions if site is empty. With sites_have_their_own,+// the server with no site only handles site requests in transit to their site's RequestServer.+WEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, bool sites_have_their_own, HTTPDiskCacheMode);WEBVIEW_API void apply_dns_settings(Requests::RequestControlClient&);struct ImageDecoderConnection {diff --git a/Libraries/LibWebView/NavigationLoader.cpp b/Libraries/LibWebView/NavigationLoader.cppindex 3c4d5ba4f03..27e62dbe417 100644--- a/Libraries/LibWebView/NavigationLoader.cpp+++ b/Libraries/LibWebView/NavigationLoader.cpp@@ -8,6 +8,7 @@#include <LibHTTP/HeaderList.h>#include <LibRequests/Request.h>#include <LibRequests/RequestClient.h>+#include <LibURL/Site.h>#include <LibWebCommon/Fetch/Infrastructure/URL.h>#include <LibWebCommon/HTML/BrowsingContext.h>#include <LibWebCommon/HTML/CrossOrigin/OpenerPolicyEnforcement.h>@@ -24,6 +25,7 @@#include <LibWebView/CanonicalWindow.h>#include <LibWebView/NavigationLoader.h>#include <LibWebView/RequestServerManager.h>+#include <LibWebView/RequestServerSiteBindings.h>namespace WebView {@@ -371,11 +373,27 @@ void NavigationLoader::set_response_body_callbacks(Requests::Request& request)});}-void NavigationLoader::move_response_body_to(RequestServerInstance& request_server, Function<void(bool)> completion_steps)+void NavigationLoader::move_response_body_to(RequestServerSiteBindings const& host_bindings, Function<void(bool)> completion_steps){VERIFY(!m_completion_steps);m_completion_steps = move(completion_steps);+ // The host adopts the response through its client of the RequestServer of the document's top-level site.+ auto top_level_site = m_top_level_site;+ auto client_id = host_bindings.client_id_for(top_level_site);+ if (!client_id.has_value()) {+ top_level_site = {};+ client_id = host_bindings.client_id();+ }+ auto request_server_or_null = client_id.has_value() ? RequestServerManager::the().instance_for_client(*client_id) : nullptr;+ if (!request_server_or_null) {+ did_acquire(false);+ return;+ }+ auto& request_server = *request_server_or_null;+ if (auto* body_handle = response_body_handle(*m_result))+ body_handle->request_server_top_level_site = top_level_site;+if (request_server.is_retired() || (m_response_body_request_server && m_response_body_request_server->is_retired())) {did_acquire(false);return;@@ -450,6 +468,8 @@ void NavigationLoader::set_document(CanonicalDocument const& document, Canonical{VERIFY(m_result.has_value());m_result->document_id = document.id();+ if (auto top_level_origin = document.top_level_origin(); top_level_origin.has_value())+ m_top_level_site = URL::Site::serialize_for_partitioning(*top_level_origin);auto* navigation_params = m_result->navigation_params.get_pointer<Web::HTML::NavigationParamsDescriptor>();if (!navigation_params)diff --git a/Libraries/LibWebView/NavigationLoader.h b/Libraries/LibWebView/NavigationLoader.hindex 37413672cee..20fd814438e 100644--- a/Libraries/LibWebView/NavigationLoader.h+++ b/Libraries/LibWebView/NavigationLoader.h@@ -11,6 +11,7 @@#include <AK/OwnPtr.h>#include <AK/RefCounted.h>#include <AK/RefPtr.h>+#include <AK/Utf16String.h>#include <AK/Weakable.h>#include <LibHTTP/Forward.h>#include <LibRequests/Forward.h>@@ -63,8 +64,8 @@ public:void acquire_response_body(Function<void(bool)> completion_steps);void obtain_the_response_policies(CanonicalNavigable const&);void check_the_responses_adherence_to_its_embedder_policy(CanonicalNavigable const&);- // Moves the response over to the RequestServer of the process that will host the document, if that is another one.- void move_response_body_to(RequestServerInstance&, Function<void(bool)> completion_steps);+ // Moves the response to the document host's RequestServer for its top-level site, if different.+ void move_response_body_to(RequestServerSiteBindings const& host_bindings, Function<void(bool)> completion_steps);bool response_body_matches(int request_server_client_id, u64 request_server_request_id) const;Web::HTML::NavigationPopulationRequest const& request() const { return m_request; }Web::HTML::NavigationPopulationResult const& result() const;@@ -93,6 +94,8 @@ private:RefPtr<RequestServerInstance> m_response_body_request_server;Optional<int> m_response_body_request_server_client_id;Optional<u64> m_response_body_request_server_request_id;+ // The top-level site of the document the response creates.+ Optional<Utf16String> m_top_level_site;bool m_response_body_was_handed_off { false };Function<void(bool)> m_completion_steps;};diff --git a/Libraries/LibWebView/Options.h b/Libraries/LibWebView/Options.hindex 33356f8f671..be5d20dce77 100644--- a/Libraries/LibWebView/Options.h+++ b/Libraries/LibWebView/Options.h@@ -7,6 +7,7 @@#pragma once#include <AK/ByteString.h>+#include <AK/NumericLimits.h>#include <AK/Optional.h>#include <AK/String.h>#include <AK/Vector.h>@@ -124,8 +125,9 @@ struct RequestServerOptions {HTTPDiskCacheMode http_disk_cache_mode { HTTPDiskCacheMode::Disabled };Optional<ByteString> resource_substitution_map_path;HTTP::ProxyConfiguration proxy_configuration;- // Per-session limit, excluding the RequestServer with no site. Zero makes every process share that server.- size_t maximum_site_request_servers { 16 };+ // Per-session limit, excluding the RequestServer with no site. Sites beyond the limit share that server;+ // zero makes every process share it.+ size_t maximum_site_request_servers { NumericLimits<size_t>::max() };};enum class IsTestMode {diff --git a/Libraries/LibWebView/RequestServerManager.cpp b/Libraries/LibWebView/RequestServerManager.cppindex 2d2b691327e..eb32abc331e 100644--- a/Libraries/LibWebView/RequestServerManager.cpp+++ b/Libraries/LibWebView/RequestServerManager.cpp@@ -5,11 +5,13 @@*/#include <AK/LexicalPath.h>+#include <AK/QuickSort.h>#include <AK/StringBuilder.h>#include <LibCore/DirIterator.h>#include <LibCore/EventLoop.h>#include <LibCore/File.h>#include <LibFileSystem/FileSystem.h>+#include <LibHTTP/Cache/Utilities.h>#include <LibWebView/Application.h>#include <LibWebView/HelperProcess.h>#include <LibWebView/RequestServerManager.h>@@ -21,8 +23,13 @@ namespace WebView {static constexpr int idle_request_server_timeout_ms = 60'000;-// A site's RequestServer gets this share of the cache size the user allows.-static constexpr u64 site_cache_size_divisor = 8;+// Entries last accessed in the same time bucket are evicted together.+static constexpr auto cache_access_granularity = AK::Duration::from_seconds(1);++// Leave room for new writes to avoid evicting after every write.+static constexpr u64 cache_eviction_target_percent = 90;++static constexpr auto cache_eviction_timeout = AK::Duration::from_seconds(10);RequestServerInstance::RequestServerInstance(NonnullRefPtr<BrowsingSession> session, Optional<Utf16String> site, ByteString cache_path): m_session(move(session))@@ -39,10 +46,8 @@ RequestServerManager& RequestServerManager::the()}RequestServerManager::RequestServerManager()+ : m_maximum_site_instances(Application::request_server_options().maximum_site_request_servers){- // Without top-level site isolation, one process could need RequestServers for multiple top-level sites.- if (Application::web_content_options().site_isolation_mode == SiteIsolationMode::TopLevel)- m_maximum_site_instances = Application::request_server_options().maximum_site_request_servers;}RequestServerManager::~RequestServerManager() = default;@@ -66,15 +71,19 @@ ErrorOr<NonnullRefPtr<RequestServerInstance>> RequestServerManager::instance_forreturn instance;}- retire_idle_instances();-- size_t site_instance_count = 0;- for (auto const& instance : m_instances) {- if (instance->m_session.ptr() == &session && instance->site().has_value())- ++site_instance_count;+ auto site_instance_count = [&] {+ size_t count = 0;+ for (auto const& instance : m_instances) {+ if (instance->m_session.ptr() == &session && instance->site().has_value())+ ++count;+ }+ return count;+ };+ if (site_instance_count() >= m_maximum_site_instances) {+ retire_idle_instances();+ if (site_instance_count() >= m_maximum_site_instances)+ return browser_instance(session);}- if (site_instance_count >= m_maximum_site_instances)- return browser_instance(session);return launch(session, top_level_site);}@@ -104,6 +113,8 @@ ErrorOr<NonnullRefPtr<RequestServerInstance>> RequestServerManager::launch(Nonnuauto instance = adopt_ref(*new RequestServerInstance(session, move(site), move(cache_path)));TRY(launch_process(*instance));m_instances.append(instance);+ if (m_dormant_site_caches.has_value() && is_live_cache_path(instance->cache_path()))+ m_dormant_site_caches->remove(instance->cache_path());return instance;}@@ -111,7 +122,7 @@ ErrorOr<void> RequestServerManager::launch_process(RequestServerInstance& instan{// Private sessions keep nothing on disk. Every RequestServer of a session would open the same cache otherwise.auto disk_cache_mode = instance.session().is_private() == IsPrivate::Yes ? HTTPDiskCacheMode::Disabled : Application::request_server_options().http_disk_cache_mode;- auto control_client = TRY(launch_request_server_process(instance.cache_path(), instance.site(), disk_cache_mode));+ auto control_client = TRY(launch_request_server_process(instance.cache_path(), instance.site(), uses_site_request_servers(), disk_cache_mode));auto weak_instance = instance.make_weak_ptr();control_client->on_client_disconnected = [weak_instance](int client_id) {@@ -122,17 +133,15 @@ ErrorOr<void> RequestServerManager::launch_process(RequestServerInstance& instanif (auto instance = weak_instance.strong_ref())the().did_lose_process(*instance);};+ control_client->on_disk_cache_size_changed = [weak_instance](u64 size) {+ if (auto instance = weak_instance.strong_ref())+ the().disk_cache_size_changed(*instance, size);+ };Application::the().configure_request_server_control_client(*control_client);instance.m_control_client = move(control_client);instance.m_ui_client = nullptr;- if (instance.site().has_value()) {- auto settings = Application::settings().browsing_data_settings().disk_cache_settings;- settings.maximum_size /= site_cache_size_divisor;- instance.m_control_client->async_set_disk_cache_settings(settings);- }-auto connection = TRY(connect_new_client(instance, instance.session(), RequestServer::SiteBinding::Unrestricted));auto transport = TRY(connection.handle.create_transport());auto ui_client = make_ref_counted<Requests::RequestClient>(move(transport));@@ -165,41 +174,6 @@ ErrorOr<RequestServerClientConnection> RequestServerManager::connect_new_client(return Error::from_string_literal("RequestServer keeps handing out client IDs that are in use");}-void RequestServerManager::assign_site(WebContentClient& client, Utf16String const& top_level_site)-{- if (!uses_site_request_servers())- return;-- auto& bindings = client.request_server_site_bindings();- RefPtr<RequestServerInstance> current;- if (bindings.client_id().has_value())- current = instance_for_client(*bindings.client_id());-- // Top-level site isolation keeps a process on its first site's RequestServer.- if (current && current->site().has_value()) {- if (current->site() != top_level_site)- dbgln("RequestServer: process {} hosting {} also hosts a document under {}", client.pid(), *current->site(), top_level_site);- return;- }-- auto target = instance_for_site(client.session(), top_level_site);- if (target.is_error()) {- warnln("Unable to launch a RequestServer for {}: {}", top_level_site, target.error());- return;- }- if (target.value().ptr() == current.ptr())- return;-- auto connection = connect_new_client(*target.value(), client.session(), RequestServer::SiteBinding::Bound);- if (connection.is_error()) {- warnln("Unable to connect a process to the RequestServer for {}: {}", top_level_site, connection.error());- return;- }-- bindings.did_connect(connection.value().client_id);- client.async_connect_to_request_server(move(connection.value().handle), connection.value().client_id);-}-void RequestServerManager::client_disconnected(RequestServerInstance& instance, int client_id){Application::the().did_disconnect_request_server_client(client_id);@@ -239,29 +213,15 @@ void RequestServerManager::did_lose_process(RequestServerInstance& instance)VERIFY_NOT_REACHED();}- // Every process that was served by the RequestServer gets a replacement client, bound to the same sites.- WebContentClient::for_each_client([&](WebContentClient& client) {- auto& bindings = client.request_server_site_bindings();- if (!bindings.client_id().has_value() || !lost_client_ids.contains(*bindings.client_id()))- return IterationDecision::Continue;-- auto connection = connect_new_client(instance, client.session(), RequestServer::SiteBinding::Bound);- if (connection.is_error()) {- warnln("Unable to reconnect a process to its RequestServer: {}", connection.error());+ auto reconnect = [&](RequestServerSiteBindings& bindings) {+ if (auto result = bindings.reconnect_lost_clients(instance, lost_client_ids); result.is_error()) {+ warnln("Unable to reconnect a process to its RequestServer: {}", result.error());VERIFY_NOT_REACHED();}- bindings.did_connect(connection.value().client_id);- client.async_connect_to_request_server(move(connection.value().handle), connection.value().client_id);return IterationDecision::Continue;- });-- auto result = WorkerProcessManager::the().reconnect_to_request_server(instance, [&](RequestServerSiteBindings const& bindings) {- return bindings.client_id().has_value() && lost_client_ids.contains(*bindings.client_id());- });- if (result.is_error()) {- warnln("Unable to reconnect WebWorker processes to RequestServer: {}", result.error());- VERIFY_NOT_REACHED();- }+ };+ WebContentClient::for_each_client([&](WebContentClient& client) { return reconnect(client.request_server_site_bindings()); });+ WorkerProcessManager::the().for_each_request_server_site_bindings([&](RequestServerSiteBindings& bindings) { return reconnect(bindings); });}void RequestServerManager::retire(RequestServerInstance& instance)@@ -269,6 +229,9 @@ void RequestServerManager::retire(RequestServerInstance& instance)instance.m_retired = true;// The process exits once its last client is gone; dropping the control connection and the UI client sees to that.m_instances.remove_first_matching([&](auto const& candidate) { return candidate.ptr() == &instance; });++ if (m_dormant_site_caches.has_value() && instance.site().has_value() && instance.session().is_private() == IsPrivate::No && !is_live_cache_path(instance.cache_path()))+ m_dormant_site_caches->set(instance.cache_path(), { .last_use = UnixDateTime::now(), .size = instance.m_disk_cache_size });}void RequestServerManager::retire_idle_instances()@@ -282,12 +245,10 @@ void RequestServerManager::retire_idle_instances()void RequestServerManager::disk_cache_settings_changed(){auto const& settings = Application::settings().browsing_data_settings().disk_cache_settings;- for (auto& instance : m_instances) {- auto instance_settings = settings;- if (instance->site().has_value())- instance_settings.maximum_size /= site_cache_size_divisor;- instance->control_client().async_set_disk_cache_settings(instance_settings);- }+ for (auto& instance : m_instances)+ instance->control_client().async_set_disk_cache_settings(settings);++ evict_least_recently_used_cache_entries_if_needed();}void RequestServerManager::dns_settings_changed()@@ -317,14 +278,21 @@ ByteString RequestServerManager::cache_path_for_site(ByteString const& sites_dirreturn LexicalPath::join(sites_directory, name.string_view()).string();}+// Private sessions keep nothing in the cache directories of their RequestServers.+bool RequestServerManager::is_live_cache_path(ByteString const& path) const+{+ return any_of(m_instances, [&](auto const& instance) {+ return instance->session().is_private() == IsPrivate::No && instance->cache_path() == path;+ });+}+Vector<ByteString> RequestServerManager::dormant_site_cache_paths(){Vector<ByteString> paths;Core::DirIterator iterator(sites_directory(), Core::DirIterator::SkipParentAndBaseDir);while (iterator.has_next()) {auto path = iterator.next_full_path();- auto is_live = any_of(m_instances, [&](auto const& instance) { return instance->cache_path() == path; });- if (!is_live)+ if (!is_live_cache_path(path))paths.append(move(path));}return paths;@@ -403,6 +371,7 @@ NonnullRefPtr<Core::Promise<Empty>> RequestServerManager::clear_cache(UnixDateTiif (last_use_of_site_cache(path) >= since)(void)FileSystem::remove(path, FileSystem::RecursionMode::Allowed);}+ m_dormant_site_caches.clear();auto settle = [clearing] {if (--clearing->pending == 0)@@ -418,4 +387,114 @@ NonnullRefPtr<Core::Promise<Empty>> RequestServerManager::clear_cache(UnixDateTireturn clearing->promise;}+HashMap<ByteString, RequestServerManager::DormantSiteCache>& RequestServerManager::dormant_site_caches()+{+ if (!m_dormant_site_caches.has_value()) {+ HashMap<ByteString, DormantSiteCache> caches;+ for (auto const& path : dormant_site_cache_paths()) {+ DormantSiteCache cache;+ for_each_file_under(path, [&](auto const&, struct stat const& stat) {+ cache.last_use = max(cache.last_use, UnixDateTime::from_seconds_since_epoch(stat.st_mtime));+ cache.size += stat.st_size;+ });+ caches.set(path, cache);+ }+ m_dormant_site_caches = move(caches);+ }+ return *m_dormant_site_caches;+}++u64 RequestServerManager::maximum_disk_cache_size() const+{+ // Apply the per-server free-space limit to the combined caches too.+ auto maximum_size = Application::settings().browsing_data_settings().disk_cache_settings.maximum_size;+ auto disk_space = FileSystem::compute_disk_space(LexicalPath { Application::request_server_options().cache_path });+ if (disk_space.is_error())+ return maximum_size;+ return static_cast<u64>(HTTP::compute_maximum_disk_cache_size(disk_space.value().free_bytes, maximum_size));+}++void RequestServerManager::disk_cache_size_changed(RequestServerInstance& instance, u64 size)+{+ instance.m_disk_cache_size = size;+ evict_least_recently_used_cache_entries_if_needed();+}++void RequestServerManager::evict_least_recently_used_cache_entries_if_needed()+{+ // Size reports after eviction trigger another pass if needed.+ if (Application::request_server_options().http_disk_cache_mode == HTTPDiskCacheMode::Disabled)+ return;+ if (m_cache_eviction_start_time.has_value() && MonotonicTime::now() - *m_cache_eviction_start_time < cache_eviction_timeout)+ return;++ auto maximum_size = maximum_disk_cache_size();++ u64 total_size = 0;+ for (auto const& [path, cache] : dormant_site_caches())+ total_size += cache.size;+ for (auto const& instance : m_instances)+ total_size += instance->m_disk_cache_size;+ if (total_size <= maximum_size)+ return;++ struct Eviction : public RefCounted<Eviction> {+ u64 id { 0 };+ Vector<Requests::CacheAccessBucket> buckets;+ size_t pending { 0 };+ u64 target_size { 0 };+ };+ auto eviction = adopt_ref(*new Eviction);+ eviction->id = ++m_cache_eviction_id;+ eviction->target_size = maximum_size / 100 * cache_eviction_target_percent;+ m_cache_eviction_start_time = MonotonicTime::now();++ auto settle = [eviction] {+ if (--eviction->pending > 0)+ return;++ auto& manager = the();+ if (manager.m_cache_eviction_id != eviction->id)+ return;+ manager.m_cache_eviction_start_time.clear();++ auto& dormant_caches = manager.dormant_site_caches();+ for (auto const& [path, cache] : dormant_caches)+ eviction->buckets.append({ .last_access_time = cache.last_use, .size = cache.size });+ if (eviction->buckets.is_empty())+ return;++ // Keep the most recently used buckets that fit, and at least the most recent one.+ quick_sort(eviction->buckets, [](auto const& a, auto const& b) { return a.last_access_time > b.last_access_time; });+ auto cutoff = eviction->buckets.first().last_access_time;+ u64 kept_size = 0;+ for (auto const& bucket : eviction->buckets) {+ kept_size += bucket.size;+ if (kept_size > eviction->target_size)+ break;+ cutoff = bucket.last_access_time;+ }++ for (auto& instance : manager.m_instances)+ instance->control_client().async_remove_cache_entries_accessed_before(cutoff);++ dormant_caches.remove_all_matching([&](auto const& path, auto const& cache) {+ if (cache.last_use >= cutoff)+ return false;+ (void)FileSystem::remove(path, FileSystem::RecursionMode::Allowed);+ return true;+ });+ };++ eviction->pending = m_instances.size() + 1;+ for (auto& instance : m_instances) {+ instance->control_client().retrieve_cache_access_profile(cache_access_granularity)->when_resolved([eviction, settle](Vector<Requests::CacheAccessBucket> buckets) {+ eviction->buckets.extend(move(buckets));+ settle();+ })+ .when_rejected([settle](Error&) { settle(); });+ }+ settle();+}+}diff --git a/Libraries/LibWebView/RequestServerManager.h b/Libraries/LibWebView/RequestServerManager.hindex 48128291b4f..b7134c33cf8 100644--- a/Libraries/LibWebView/RequestServerManager.h+++ b/Libraries/LibWebView/RequestServerManager.h@@ -34,7 +34,7 @@ public:~RequestServerInstance();// The top-level site whose requests this RequestServer makes, or nothing for the one that serves the UI process and- // processes that have no site yet.+ // requests under no site.Optional<Utf16String> const& site() const { return m_site; }BrowsingSession& session() const { return *m_session; }ByteString const& cache_path() const { return m_cache_path; }@@ -61,13 +61,16 @@ private:HashTable<int> m_client_ids;RefPtr<Core::Timer> m_idle_timer;bool m_retired { false };++ // As last reported by the RequestServer.+ u64 m_disk_cache_size { 0 };};struct RequestServerClientConnection;-// The RequestServers of the UI process: one for each top-level site that a process hosts documents of, within each-// browsing session, plus one with no site for the UI process itself and for processes that host no site yet. A site's-// RequestServer caches only that site's responses, in a directory of its own that its sandbox confines it to.+// Manages RequestServers per browsing session and top-level site, plus one with no site for the UI process+// and requests under no site. Each site's server only makes and caches requests for that site's partitions;+// its sandbox confines the cache to that site's directory.class WEBVIEW_API RequestServerManager {public:AK_ALLOC_WITH_KMALLOC;@@ -80,8 +83,8 @@ public:// The RequestServer with no site of the session. The default session's is launched with the browser.ErrorOr<NonnullRefPtr<RequestServerInstance>> browser_instance(BrowsingSession&);- // The RequestServer of a site, launched when first asked for. Once there are as many as allowed, further sites share- // the RequestServer with no site.+ // The RequestServer of a site, launched when first asked for. Once there are as many as allowed and none is idle,+ // further sites share the RequestServer with no site.ErrorOr<NonnullRefPtr<RequestServerInstance>> instance_for_site(BrowsingSession&, Utf16String const& top_level_site);RefPtr<RequestServerInstance> instance_for_client(int client_id);@@ -89,9 +92,6 @@ public:ErrorOr<RequestServerClientConnection> connect_new_client(RequestServerInstance&, BrowsingSession&, RequestServer::SiteBinding);- // Moves a process to its site's RequestServer, the first time it is about to host a document of a site.- void assign_site(WebContentClient&, Utf16String const& top_level_site);-void disk_cache_settings_changed();void dns_settings_changed();@@ -111,10 +111,28 @@ private:ByteString sites_directory() const;static ByteString cache_path_for_site(ByteString const& sites_directory, Utf16String const& site);+ bool is_live_cache_path(ByteString const&) const;Vector<ByteString> dormant_site_cache_paths();+ // Enforce the user's combined cache size limit with least-recently-used eviction.+ // Caches of sites without a RequestServer are evicted whole.+ void disk_cache_size_changed(RequestServerInstance&, u64 size);+ void evict_least_recently_used_cache_entries_if_needed();+ u64 maximum_disk_cache_size() const;++ struct DormantSiteCache {+ UnixDateTime last_use;+ u64 size { 0 };+ };+ HashMap<ByteString, DormantSiteCache>& dormant_site_caches();+Vector<NonnullRefPtr<RequestServerInstance>> m_instances;size_t m_maximum_site_instances { 0 };++ Optional<HashMap<ByteString, DormantSiteCache>> m_dormant_site_caches;+ // Time out evictions if a RequestServer disappears before answering.+ Optional<MonotonicTime> m_cache_eviction_start_time;+ u64 m_cache_eviction_id { 0 };};}diff --git a/Libraries/LibWebView/RequestServerSiteBindings.cpp b/Libraries/LibWebView/RequestServerSiteBindings.cppindex 0c24c412491..97680b85f70 100644--- a/Libraries/LibWebView/RequestServerSiteBindings.cpp+++ b/Libraries/LibWebView/RequestServerSiteBindings.cpp@@ -8,6 +8,7 @@#include <LibURL/Site.h>#include <LibWebView/Application.h>#include <LibWebView/CanonicalDocument.h>+#include <LibWebView/HelperProcess.h>#include <LibWebView/RequestServerManager.h>#include <LibWebView/RequestServerSiteBindings.h>@@ -21,11 +22,38 @@ unsigned RequestServerSiteBindings::SiteTraits::hash(Site const& site)return hash;}-void RequestServerSiteBindings::did_connect(int client_id)+RequestServerSiteBindings::RequestServerSiteBindings(ConnectionHandler connection_handler)+ : m_connection_handler(move(connection_handler)){- m_client_id = client_id;- for (auto const& site : m_sites)- send(site);+}++RequestServerSiteBindings::~RequestServerSiteBindings() = default;++ErrorOr<void> RequestServerSiteBindings::connect(BrowsingSession& session)+{+ m_session = session.make_weak_ptr();++ auto instance = TRY(RequestServerManager::the().browser_instance(session));+ auto connection = TRY(connect_client(*instance, {}));+ m_connection_handler(connection, {});++ for (auto const& top_level_site : top_level_sites_to_connect())+ TRY(connect_to_site(top_level_site));+ return {};+}++Optional<int> RequestServerSiteBindings::client_id_for(Optional<Utf16String> const& top_level_site) const+{+ if (!top_level_site.has_value())+ return m_client_id;+ return m_site_client_ids.get(*top_level_site);+}++bool RequestServerSiteBindings::has_client(int client_id) const+{+ if (m_client_id == client_id)+ return true;+ return any_of(m_site_client_ids, [&](auto const& entry) { return entry.value == client_id; });}void RequestServerSiteBindings::bind_sites_of(CanonicalDocument const& document)@@ -48,8 +76,14 @@ void RequestServerSiteBindings::bind_sites_of(RequestServerSiteBindings const& obind(site);}-bool RequestServerSiteBindings::may_use_cookies_under(Utf16String const& top_level_site, URL::URL const& url) const+bool RequestServerSiteBindings::may_use_cookies_under(int client_id, Utf16String const& top_level_site, URL::URL const& url) const{+ // A client of a site's RequestServer makes requests under that site alone.+ for (auto const& [client_top_level_site, site_client_id] : m_site_client_ids) {+ if (site_client_id == client_id && client_top_level_site != top_level_site)+ return false;+ }+// FIXME: The process of the document that starts a navigation makes the navigation's requests. Until the UI process// makes navigation requests itself, a client may use the cookies of a navigation to the request's URL.if (URL::Site::serialize_for_partitioning(url.origin()) == top_level_site)@@ -58,22 +92,125 @@ bool RequestServerSiteBindings::may_use_cookies_under(Utf16String const& top_levreturn any_of(m_sites, [&](Site const& site) { return site.top_level_site == top_level_site; });}+ErrorOr<void> RequestServerSiteBindings::reconnect_lost_clients(RequestServerInstance& instance, HashTable<int> const& lost_client_ids)+{+ // A process whose session is gone has nothing left to fetch for.+ if (!m_session)+ return {};++ if (m_client_id.has_value() && lost_client_ids.contains(*m_client_id)) {+ auto connection = TRY(connect_client(instance, {}));+ m_connection_handler(connection, {});+ }++ for (auto const& top_level_site : top_level_sites()) {+ auto client_id = m_site_client_ids.get(top_level_site);+ if (!client_id.has_value() || !lost_client_ids.contains(*client_id))+ continue;+ auto connection = TRY(connect_client(instance, top_level_site));+ m_connection_handler(connection, top_level_site);+ }+ return {};+}++ErrorOr<RequestServerClientConnection> RequestServerSiteBindings::replace_client(Optional<Utf16String> const& top_level_site, bool navigation_authorized)+{+ if (!client_id_for(top_level_site).has_value() && !navigation_authorized)+ return Error::from_string_literal("No existing client or authorized navigation for this site");++ auto session = m_session.strong_ref();+ if (!session)+ return Error::from_string_literal("The process's browsing session is gone");++ RefPtr<RequestServerInstance> instance;+ if (auto client_id = client_id_for(top_level_site); client_id.has_value())+ instance = RequestServerManager::the().instance_for_client(*client_id);+ if (!instance) {+ instance = top_level_site.has_value()+ ? TRY(RequestServerManager::the().instance_for_site(*session, *top_level_site))+ : TRY(RequestServerManager::the().browser_instance(*session));+ }+ return connect_client(*instance, top_level_site);+}++Vector<Utf16String> RequestServerSiteBindings::top_level_sites() const+{+ Vector<Utf16String> top_level_sites;+ for (auto const& entry : m_site_client_ids)+ top_level_sites.append(entry.key);+ return top_level_sites;+}++Vector<Utf16String> RequestServerSiteBindings::top_level_sites_to_connect() const+{+ HashTable<Utf16String> top_level_sites;+ for (auto const& site : m_sites)+ top_level_sites.set(site.top_level_site);++ Vector<Utf16String> result;+ for (auto const& top_level_site : top_level_sites)+ result.append(top_level_site);+ return result;+}++ErrorOr<RequestServerClientConnection> RequestServerSiteBindings::connect_client(RequestServerInstance& instance, Optional<Utf16String> const& top_level_site)+{+ auto session = m_session.strong_ref();+ VERIFY(session);++ auto connection = TRY(RequestServerManager::the().connect_new_client(instance, *session, RequestServer::SiteBinding::Bound));+ if (top_level_site.has_value()) {+ m_site_client_ids.set(*top_level_site, connection.client_id);+ for (auto const& site : m_sites) {+ if (site.top_level_site == *top_level_site)+ send(site);+ }+ } else {+ m_client_id = connection.client_id;+ }+ return connection;+}++ErrorOr<void> RequestServerSiteBindings::connect_to_site(Utf16String const& top_level_site)+{+ auto session = m_session.strong_ref();+ VERIFY(session);++ auto instance = TRY(RequestServerManager::the().instance_for_site(*session, top_level_site));+ auto connection = TRY(connect_client(*instance, top_level_site));+ m_connection_handler(connection, top_level_site);+ return {};+}+void RequestServerSiteBindings::bind(Site site){- if (m_sites.set(site) == HashSetResult::InsertedNewEntry)+ if (m_sites.set(site) != HashSetResult::InsertedNewEntry)+ return;++ // NB: connect() handles sites bound before the process connects.+ if (!m_session || !m_client_id.has_value())+ return;++ if (m_site_client_ids.contains(site.top_level_site)) {send(site);+ return;+ }++ if (auto result = connect_to_site(site.top_level_site); result.is_error())+ warnln("Unable to connect a process to the RequestServer for {}: {}", site.top_level_site, result.error());}void RequestServerSiteBindings::send(Site const& site) const{- // NB: A client that has not connected yet, or whose RequestServer has died, is bound to every site when it connects.- if (!m_client_id.has_value())+ // NB: Replacement clients regain their site bindings when they connect.+ auto client_id = m_site_client_ids.get(site.top_level_site);+ if (!client_id.has_value())return;- auto instance = RequestServerManager::the().instance_for_client(*m_client_id);+ auto instance = RequestServerManager::the().instance_for_client(*client_id);if (!instance)return;- (void)instance->control_client().send_sync_but_allow_failure<Messages::RequestServerControl::BindClientToSite>(*m_client_id, site.top_level_site, site.frame_site);+ (void)instance->control_client().send_sync_but_allow_failure<Messages::RequestServerControl::BindClientToSite>(*client_id, site.top_level_site, site.frame_site);}}diff --git a/Libraries/LibWebView/RequestServerSiteBindings.h b/Libraries/LibWebView/RequestServerSiteBindings.hindex 75e8e0f3e06..e2aaaa6d894 100644--- a/Libraries/LibWebView/RequestServerSiteBindings.h+++ b/Libraries/LibWebView/RequestServerSiteBindings.h@@ -6,16 +6,23 @@#pragma once+#include <AK/Function.h>+#include <AK/HashMap.h>#include <AK/HashTable.h>#include <AK/Optional.h>#include <AK/Utf16String.h>+#include <AK/WeakPtr.h>#include <LibURL/Forward.h>#include <LibWebView/Forward.h>namespace WebView {-// The sites that the RequestServer client of one process is bound to. RequestServer refuses a bound client the network-// isolation keys of any other sites, so a compromised process cannot reach another site's cache entries.+struct RequestServerClientConnection;++// One process's RequestServer clients and site bindings. Each top-level site's client is bound to the sites of+// documents hosted under it; other requests use the server with no site through a client bound to no site.+// RequestServer rejects other sites' network isolation keys, preventing a compromised process from reaching+// their cache entries and restricting each site's RequestServer to that top-level site's requests.//// NB: Bindings last for the life of the process and are never revoked. A process that has hosted a site's document may// have kept anything that document could reach, so leaving the site grants it nothing it lacked.@@ -24,21 +31,39 @@ class RequestServerSiteBindings {AK_MAKE_NONMOVABLE(RequestServerSiteBindings);public:- RequestServerSiteBindings() = default;+ // Hands the process a new client, for the RequestServer of the given top-level site or the one with no site.+ using ConnectionHandler = Function<void(RequestServerClientConnection&, Optional<Utf16String> const& top_level_site)>;- Optional<int> client_id() const { return m_client_id; }+ explicit RequestServerSiteBindings(ConnectionHandler);+ ~RequestServerSiteBindings();- // The process has a new RequestServer client. It is bound to every site the previous client was bound to.- void did_connect(int client_id);+ // Connects to the server with no site and the servers of all bound top-level sites.+ // The session supplies cookies and must be the process's session.+ ErrorOr<void> connect(BrowsingSession&);++ // The process's client of the RequestServer of a top-level site, or of the one with no site.+ Optional<int> client_id() const { return m_client_id; }+ Optional<int> client_id_for(Optional<Utf16String> const& top_level_site) const;+ bool has_client(int client_id) const;- // Binds the client to the sites of a document, before the process is told to host it.+ // Binds the process to the sites of a document, before it is told to host it.void bind_sites_of(CanonicalDocument const&);- // Binds the client to every site that another process's client is bound to, as for a worker that process starts.+ // Binds the process to every site that another process is bound to, as for a worker that process starts.void bind_sites_of(RequestServerSiteBindings const&);// Whether the client may use the cookies of top_level_site's partition for a request for url.- bool may_use_cookies_under(Utf16String const& top_level_site, URL::URL const& url) const;+ bool may_use_cookies_under(int client_id, Utf16String const& top_level_site, URL::URL const& url) const;++ ErrorOr<void> reconnect_lost_clients(RequestServerInstance&, HashTable<int> const& lost_client_ids);++ // Replaces the client for top_level_site (empty for the server with no site).+ // A new site requires navigation authorization authenticated by the UI process.+ // Returns the connection without calling the connection handler.+ ErrorOr<RequestServerClientConnection> replace_client(Optional<Utf16String> const& top_level_site, bool navigation_authorized = false);++ // Sites with clients, excluding the server with no site.+ Vector<Utf16String> top_level_sites() const;private:struct Site {@@ -51,10 +76,16 @@ private:static unsigned hash(Site const&);};+ ErrorOr<RequestServerClientConnection> connect_client(RequestServerInstance&, Optional<Utf16String> const& top_level_site);+ ErrorOr<void> connect_to_site(Utf16String const& top_level_site);+ Vector<Utf16String> top_level_sites_to_connect() const;void bind(Site);void send(Site const&) const;+ ConnectionHandler m_connection_handler;+ WeakPtr<BrowsingSession> m_session;Optional<int> m_client_id;+ HashMap<Utf16String, int> m_site_client_ids;HashTable<Site, SiteTraits> m_sites;};diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 7666e216bd0..90e7c15a8e8 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -18,6 +18,7 @@#include <LibIPC/Transport.h>#include <LibIPC/TransportHandle.h>#include <LibRequests/Request.h>+#include <LibURL/Site.h>#include <LibWebCommon/HTML/BrowsingContext.h>#include <LibWebCommon/Page/InputEvent.h>#include <LibWebCommon/WebDriver/Error.h>@@ -123,6 +124,9 @@ WebContentClient::WebContentClient(NonnullOwnPtr<IPC::Transport> transport, IsPr: IPC::ConnectionToServer<WebContentClientEndpoint, WebContentServerEndpoint, WebContentClientPageRoutingStub>(*this, move(transport)), m_is_private(is_private), m_session(Application::existing_session(is_private))+ , m_request_server_site_bindings([this](RequestServerClientConnection& connection, Optional<Utf16String> const& top_level_site) {+ async_connect_to_request_server(move(connection.handle), connection.client_id, top_level_site);+ }), m_unassigned_initial_page_id(initial_page_id), m_root_navigable_id(root_navigable_id), m_audio_tab_id(allocate_audio_tab_id())@@ -808,21 +812,34 @@ Messages::WebContentClient::DidIsKnownHstsHostResponse WebContentClient::did_is_return m_session->hsts_store->is_known_hsts_host(domain);}-Messages::WebContentClient::DidLoseRequestServerConnectionResponse WebContentClient::did_lose_request_server_connection()-{- // The replacement client is on the RequestServer the process was using.- RefPtr<RequestServerInstance> instance;- if (auto client_id = m_request_server_site_bindings.client_id(); client_id.has_value())- instance = RequestServerManager::the().instance_for_client(*client_id);- auto connection = instance- ? RequestServerManager::the().connect_new_client(*instance, *m_session, RequestServer::SiteBinding::Bound)- : connect_new_request_server_client(*m_session, RequestServer::SiteBinding::Bound);+Messages::WebContentClient::DidLoseRequestServerConnectionResponse WebContentClient::did_lose_request_server_connection(Optional<Utf16String> top_level_site)+{+ bool navigation_authorized = false;+ if (top_level_site.has_value() && !m_request_server_site_bindings.client_id_for(top_level_site).has_value()) {+ ViewImplementation::for_each_view([&](ViewImplementation& view) {+ if (!view.has_traversable())+ return IterationDecision::Continue;+ auto& traversable = view.traversable();+ auto navigation = traversable.uncommitted_navigation();+ if (navigation && navigation->state.has<CanonicalNavigation::CreatingNavigationParams>()+ && navigation->worker() && &navigation->worker()->client() == this+ && URL::Site::serialize_for_partitioning(navigation->url.origin()) == *top_level_site)+ navigation_authorized = true;+ if (traversable.client_populates_a_history_entry_for_site(*this, *top_level_site))+ navigation_authorized = true;+ return navigation_authorized ? IterationDecision::Break : IterationDecision::Continue;+ });+ }+ if (!m_request_server_site_bindings.client_id_for(top_level_site).has_value() && !navigation_authorized) {+ did_misbehave("did_lose_request_server_connection"sv, "site has neither an existing client nor an authorized navigation"sv);+ return OptionalNone {};+ }++ auto connection = m_request_server_site_bindings.replace_client(top_level_site, navigation_authorized);if (connection.is_error()) {warnln("Unable to connect a replacement RequestServer client: {}", connection.error());return OptionalNone {};}-- m_request_server_site_bindings.did_connect(connection.value().client_id);return move(connection.value().handle);}diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 944ae7b5a52..055582d426c 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -205,7 +205,7 @@ private:virtual Messages::WebContentClient::StartWorkerAgentResponse start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) override;virtual void did_update_cookie(HTTP::Cookie::Cookie) override;virtual Messages::WebContentClient::DidIsKnownHstsHostResponse did_is_known_hsts_host(String) override;- virtual Messages::WebContentClient::DidLoseRequestServerConnectionResponse did_lose_request_server_connection() override;+ virtual Messages::WebContentClient::DidLoseRequestServerConnectionResponse did_lose_request_server_connection(Optional<Utf16String> top_level_site) override;virtual Messages::WebContentClient::RequestMediaServerConnectionResponse request_media_server_connection() override;virtual Messages::WebContentClient::RequestAudioServerConnectionResponse request_audio_server_connection() override;virtual void request_video_presentation_channel() override;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 6dba807a17d..a4dcf936c83 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -357,13 +357,7 @@ bool WebContentPage::continue_navigation_population_in_selected_process(Web::HTMhost->async_populate_navigation(weak_loader->request(), weak_loader->take_result());};// Wait for the destination RequestServer to acknowledge the import before the host adopts it.- if (auto client_id = host->client().request_server_site_bindings().client_id(); client_id.has_value()) {- if (auto request_server = RequestServerManager::the().instance_for_client(*client_id)) {- weak_loader->move_response_body_to(*request_server, move(finish_handoff));- return true;- }- }- finish_handoff(false);+ weak_loader->move_response_body_to(host->client().request_server_site_bindings(), move(finish_handoff));return true;}diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cppindex c65509a873a..b0f9d2cdced 100644--- a/Libraries/LibWebView/WebWorkerClient.cpp+++ b/Libraries/LibWebView/WebWorkerClient.cpp@@ -20,6 +20,9 @@ namespace WebView {WebWorkerClient::WebWorkerClient(NonnullOwnPtr<IPC::Transport> transport, IsPrivate is_private, Web::HTML::WorkerAgentId agent_id): IPC::ConnectionToServer<WebWorkerClientEndpoint, WebWorkerServerEndpoint>(*this, move(transport)), m_is_private(is_private)+ , m_request_server_site_bindings([this](RequestServerClientConnection& connection, Optional<Utf16String> const& top_level_site) {+ async_connect_to_request_server(move(connection.handle), connection.client_id, top_level_site);+ }), m_agent_id(agent_id), m_audio_tab_id(allocate_audio_tab_id()){diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex aaece7f1b2f..e7b0d210a70 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -205,24 +205,10 @@ Web::HTML::WorkerAgentId WorkerProcessManager::start_worker_agent(Owner owner, Oclient->request_server_site_bindings().bind_sites_of(web_worker_owner.client->request_server_site_bindings());});- // The worker's requests go through the RequestServer of its owner's site.- auto request_server_instance = [&]() -> RefPtr<RequestServerInstance> {- Optional<int> owner_client_id = owner.client.visit(- [&](WebContentOwner const& web_content_owner) { return web_content_owner.client ? web_content_owner.client->request_server_site_bindings().client_id() : Optional<int> {}; },- [&](WebWorkerOwner const& web_worker_owner) { return web_worker_owner.client->request_server_site_bindings().client_id(); });- if (owner_client_id.has_value()) {- if (auto instance = RequestServerManager::the().instance_for_client(*owner_client_id))- return instance;- }- return nullptr;- }();- if (!request_server_instance)- request_server_instance = TRY(RequestServerManager::the().browser_instance(*session));- auto request_server_connection = TRY(RequestServerManager::the().connect_new_client(*request_server_instance, *session, RequestServer::SiteBinding::Bound));auto image_decoder = TRY(launch_image_decoder_process());- client->request_server_site_bindings().did_connect(request_server_connection.client_id);- client->async_connect_to_request_server(move(request_server_connection.handle), request_server_connection.client_id);+ // The worker's requests go through the RequestServers of its owner's sites.+ TRY(client->request_server_site_bindings().connect(*session));client->async_set_site_compatibility_data(Application::the().site_compatibility_data());// The User-Agent string, the navigator compatibility mode, and the preferred languages live in this process.// Pages get them through their view; a worker gets the same values here, so its navigator never contradicts@@ -445,25 +431,6 @@ void WorkerProcessManager::for_each_request_server_site_bindings(Function<Iterat}}-ErrorOr<void> WorkerProcessManager::reconnect_to_request_server(RequestServerInstance& instance, Function<bool(RequestServerSiteBindings const&)> should_reconnect)-{- for (auto& entry : m_agents) {- auto& agent = entry.value;- if (!agent.client->is_open() || !should_reconnect(agent.client->request_server_site_bindings()))- continue;-- // A worker whose session is gone has nothing left to fetch for.- auto session = agent.client->session();- if (!session)- continue;-- auto request_server_connection = TRY(RequestServerManager::the().connect_new_client(instance, *session, RequestServer::SiteBinding::Bound));- agent.client->request_server_site_bindings().did_connect(request_server_connection.client_id);- agent.client->async_connect_to_request_server(move(request_server_connection.handle), request_server_connection.client_id);- }- return {};-}-ErrorOr<void> WorkerProcessManager::simulate_request_server_connection_loss_for_testing(WebContentClient& owner, Web::PageId page_id){auto is_owned_by_page = [&](WorkerAgent const& agent) {@@ -481,18 +448,17 @@ ErrorOr<void> WorkerProcessManager::simulate_request_server_connection_loss_for_}for (auto& client : clients) {- auto session = client->session();- VERIFY(session);- RefPtr<RequestServerInstance> instance;- if (auto client_id = client->request_server_site_bindings().client_id(); client_id.has_value())- instance = RequestServerManager::the().instance_for_client(*client_id);- if (!instance)- instance = TRY(RequestServerManager::the().browser_instance(*session));- auto request_server_connection = TRY(RequestServerManager::the().connect_new_client(*instance, *session, RequestServer::SiteBinding::Bound));- client->request_server_site_bindings().did_connect(request_server_connection.client_id);- auto response = client->send_sync_but_allow_failure<Messages::WebWorkerServer::SimulateRequestServerConnectionLossAndReconnectForTesting>(move(request_server_connection.handle), request_server_connection.client_id);- if (!response)- return Error::from_string_literal("WebWorker disconnected while reconnecting to RequestServer");+ auto& bindings = client->request_server_site_bindings();+ Vector<Optional<Utf16String>> top_level_sites { OptionalNone {} };+ for (auto& top_level_site : bindings.top_level_sites())+ top_level_sites.append(move(top_level_site));++ for (auto const& top_level_site : top_level_sites) {+ auto request_server_connection = TRY(bindings.replace_client(top_level_site));+ auto response = client->send_sync_but_allow_failure<Messages::WebWorkerServer::SimulateRequestServerConnectionLossAndReconnectForTesting>(move(request_server_connection.handle), request_server_connection.client_id, top_level_site);+ if (!response)+ return Error::from_string_literal("WebWorker disconnected while reconnecting to RequestServer");+ }}return {};diff --git a/Libraries/LibWebView/WorkerProcessManager.h b/Libraries/LibWebView/WorkerProcessManager.hindex ef9ecc8b5a7..536654621a0 100644--- a/Libraries/LibWebView/WorkerProcessManager.h+++ b/Libraries/LibWebView/WorkerProcessManager.h@@ -65,8 +65,6 @@ public:void remove_web_worker_owner(WebWorkerClient&);void post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage, CanonicalEnvironmentSettingsObject const& source_settings, pid_t source_process_id, IsPrivate);- // Reconnects the workers whose RequestServer client the predicate picks out to the given RequestServer.- ErrorOr<void> reconnect_to_request_server(RequestServerInstance&, Function<bool(RequestServerSiteBindings const&)> should_reconnect);void for_each_request_server_site_bindings(Function<IterationDecision(RequestServerSiteBindings&)> const&);ErrorOr<void> simulate_request_server_connection_loss_for_testing(WebContentClient&, Web::PageId page_id);diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cppindex b2ac2ddcf22..5b5d1fce24c 100644--- a/Services/RequestServer/ConnectionFromClient.cpp+++ b/Services/RequestServer/ConnectionFromClient.cpp@@ -229,6 +229,10 @@ bool ConnectionFromClient::may_use_network_isolation_key(HTTP::NetworkIsolationKif (m_site_binding == SiteBinding::Unrestricted)return true;+ // A site's RequestServer makes no requests under any other top-level site.+ if (auto const& site = process_top_level_site(); site.has_value() && key.top_level_site != *site)+ return false;+// FIXME: The process of the document that starts a navigation makes the navigation's requests, not the process that// will host the new document. Until the UI process makes navigation requests itself, a client may make a// request whose key is that of a navigation to the request's URL. Such keys only reach the partitions of@@ -810,6 +814,14 @@ void ConnectionFromClient::ensure_connection(u64 request_id, URL::URL url, ::Reqm_active_requests.set(request_id, move(request));}+// The partition of this RequestServer's disk cache that a key reaches, if any.+static Optional<Utf16String> disk_cache_partition_for(Optional<HTTP::NetworkIsolationKey> const& network_isolation_key)+{+ if (!network_isolation_key.has_value() || !process_keeps_responses_under(network_isolation_key->top_level_site))+ return {};+ return network_isolation_key->disk_cache_partition();+}+Messages::RequestServer::StoreCacheAssociatedDataResponse ConnectionFromClient::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){if (!is_valid_associated_data(associated_data)) {@@ -825,7 +837,7 @@ Messages::RequestServer::StoreCacheAssociatedDataResponse ConnectionFromClient::if (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key))return { Optional<IPC::File> {}, 0 };- auto partition = network_isolation_key.has_value() ? network_isolation_key->disk_cache_partition() : OptionalNone {};+ auto partition = disk_cache_partition_for(network_isolation_key);if (!m_disk_cache.has_value() || !partition.has_value() || !data.is_valid())return { Optional<IPC::File> {}, 0 };@@ -855,7 +867,7 @@ Messages::RequestServer::RetrieveCacheAssociatedDataResponse ConnectionFromClienif (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key))return Optional<Core::AnonymousBuffer> {};- auto partition = network_isolation_key.has_value() ? network_isolation_key->disk_cache_partition() : OptionalNone {};+ auto partition = disk_cache_partition_for(network_isolation_key);if (!m_disk_cache.has_value() || !partition.has_value())return Optional<Core::AnonymousBuffer> {};diff --git a/Services/RequestServer/ControlConnectionFromClient.cpp b/Services/RequestServer/ControlConnectionFromClient.cppindex e4415a4eb13..4db4705cd2f 100644--- a/Services/RequestServer/ControlConnectionFromClient.cpp+++ b/Services/RequestServer/ControlConnectionFromClient.cpp@@ -16,6 +16,8 @@ namespace RequestServer {static ControlConnectionFromClient* s_control_connection = nullptr;+static constexpr auto disk_cache_size_report_delay = AK::Duration::from_seconds(2);+ControlConnectionFromClient::ControlConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, RequestServer::ConnectionFromClient::ConnectionMap& connections, RequestServer::ConnectionFromClient::RequestTransferLeaseMap& request_transfer_leases, Optional<HTTP::DiskCache&> disk_cache): IPC::ConnectionFromClient<RequestServerControlClientEndpoint, RequestServerControlEndpoint>(*this, move(transport), 0), m_connections(connections)@@ -25,10 +27,26 @@ ControlConnectionFromClient::ControlConnectionFromClient(NonnullOwnPtr<IPC::Tran{VERIFY(s_control_connection == nullptr);s_control_connection = this;++ if (m_disk_cache.has_value()) {+ // Coalesce the size changes of a burst of cache writes into one report.+ m_disk_cache_size_report_timer = Core::Timer::create_single_shot(disk_cache_size_report_delay, [this] {+ async_disk_cache_size_changed(m_disk_cache->estimated_size());+ });+ m_disk_cache->set_on_estimated_size_change([this] {+ if (!m_disk_cache_size_report_timer->is_active())+ m_disk_cache_size_report_timer->start();+ });++ // The cache may have been on disk before this process started.+ m_disk_cache_size_report_timer->start();+ }}ControlConnectionFromClient::~ControlConnectionFromClient(){+ if (m_disk_cache.has_value())+ m_disk_cache->set_on_estimated_size_change(nullptr);if (s_control_connection == this)s_control_connection = nullptr;}@@ -45,6 +63,10 @@ void ControlConnectionFromClient::die()m_performance_timer = nullptr;Request::set_performance_monitor_enabled(false);+ if (m_disk_cache.has_value())+ m_disk_cache->set_on_estimated_size_change(nullptr);+ m_disk_cache_size_report_timer = nullptr;+if (s_control_connection == this)s_control_connection = nullptr;@@ -209,6 +231,22 @@ void ControlConnectionFromClient::remove_cache_entries_accessed_since(u64 clear_async_removed_cache_entries(clear_cache_request_id);}+void ControlConnectionFromClient::retrieve_cache_access_profile(u64 access_profile_request_id, AK::Duration granularity)+{+ Vector<Requests::CacheAccessBucket> buckets;++ if (m_disk_cache.has_value())+ buckets = m_disk_cache->access_profile(granularity);++ async_retrieved_cache_access_profile(access_profile_request_id, move(buckets));+}++void ControlConnectionFromClient::remove_cache_entries_accessed_before(UnixDateTime before)+{+ if (m_disk_cache.has_value())+ m_disk_cache->remove_entries_accessed_before(before);+}+void ControlConnectionFromClient::retrieved_http_cookie(int client_id, u64 request_id, RequestType request_type, u64 cookie_request_id, String cookie){note_event_tick("ipc-retrieved-cookie"sv);diff --git a/Services/RequestServer/ControlConnectionFromClient.h b/Services/RequestServer/ControlConnectionFromClient.hindex 60af7871e23..f5631640583 100644--- a/Services/RequestServer/ControlConnectionFromClient.h+++ b/Services/RequestServer/ControlConnectionFromClient.h@@ -51,6 +51,8 @@ private:virtual void estimate_cache_size_accessed_since(u64 cache_size_estimation_id, UnixDateTime since) override;virtual void remove_cache_entries_accessed_since(u64 clear_cache_request_id, UnixDateTime since) override;+ virtual void retrieve_cache_access_profile(u64 access_profile_request_id, AK::Duration granularity) override;+ virtual void remove_cache_entries_accessed_before(UnixDateTime before) override;virtual void retrieved_http_cookie(int client_id, u64 request_id, RequestType request_type, u64 cookie_request_id, String cookie) override;virtual void stored_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id) override;@@ -68,6 +70,8 @@ private:NonnullRefPtr<Resolver> m_resolver;+ RefPtr<Core::Timer> m_disk_cache_size_report_timer;+RefPtr<Core::Timer> m_performance_timer;Optional<MonotonicTime> m_last_performance_push;};diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cppindex 2ddb8ab9eba..652ab840789 100644--- a/Services/RequestServer/Request.cpp+++ b/Services/RequestServer/Request.cpp@@ -543,7 +543,7 @@ Request::Request(, m_transfer_lease(move(transfer_lease)){// A response for another site is only passing through this RequestServer on its way to that site's.- if (auto const& site = process_top_level_site(); site.has_value() && m_disk_cache.has_value() && m_network_isolation_key->top_level_site != *site)+ if (m_disk_cache.has_value() && !process_keeps_responses_under(m_network_isolation_key->top_level_site))m_disk_cache.clear();if constexpr (REQUESTSERVER_WIRE_DEBUG)diff --git a/Services/RequestServer/RequestServerControl.ipc b/Services/RequestServer/RequestServerControl.ipcindex 321e419c70f..9c7964e1699 100644--- a/Services/RequestServer/RequestServerControl.ipc+++ b/Services/RequestServer/RequestServerControl.ipc@@ -30,6 +30,10 @@ endpoint RequestServerControlestimate_cache_size_accessed_since(u64 cache_size_estimation_id, UnixDateTime since) =|remove_cache_entries_accessed_since(u64 clear_cache_request_id, UnixDateTime since) =|+ // Supports the UI process's least-recently-used eviction across all RequestServer disk caches.+ retrieve_cache_access_profile(u64 access_profile_request_id, AK::Duration granularity) =|+ remove_cache_entries_accessed_before(UnixDateTime before) =|+retrieved_http_cookie(int client_id, u64 request_id, ::RequestServer::RequestType request_type, u64 cookie_request_id, String cookie) =|stored_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id) =|}diff --git a/Services/RequestServer/RequestServerControlClient.ipc b/Services/RequestServer/RequestServerControlClient.ipcindex 4a2913c96a2..2a5798b21b3 100644--- a/Services/RequestServer/RequestServerControlClient.ipc+++ b/Services/RequestServer/RequestServerControlClient.ipc@@ -20,4 +20,8 @@ endpoint RequestServerControlClientestimated_cache_size(u64 cache_size_estimation_id, Requests::CacheSizes sizes) =|removed_cache_entries(u64 clear_cache_request_id) =|++ // Sent once the disk cache's size settles after changing.+ disk_cache_size_changed(u64 size) =|+ retrieved_cache_access_profile(u64 access_profile_request_id, Vector<Requests::CacheAccessBucket> buckets) =|}diff --git a/Services/RequestServer/Resolver.cpp b/Services/RequestServer/Resolver.cppindex 1b0a3c00967..8fb73a87ef7 100644--- a/Services/RequestServer/Resolver.cpp+++ b/Services/RequestServer/Resolver.cpp@@ -25,6 +25,7 @@ void set_default_certificate_path(ByteString default_certificate_path)static HTTP::ProxyConfiguration g_proxy_configuration;static Optional<Utf16String> g_process_top_level_site;+static bool g_process_sites_have_their_own { false };HTTP::ProxyConfiguration const& proxy_configuration(){@@ -46,6 +47,18 @@ void set_process_top_level_site(Optional<Utf16String> site)g_process_top_level_site = move(site);}+void set_process_sites_have_their_own()+{+ g_process_sites_have_their_own = true;+}++bool process_keeps_responses_under(Utf16String const& top_level_site)+{+ if (g_process_top_level_site.has_value())+ return top_level_site == *g_process_top_level_site;+ return !g_process_sites_have_their_own;+}+DNSInfo& DNSInfo::the(){static DNSInfo g_dns_info;diff --git a/Services/RequestServer/Resolver.h b/Services/RequestServer/Resolver.hindex 52a65b630be..6056a909002 100644--- a/Services/RequestServer/Resolver.h+++ b/Services/RequestServer/Resolver.h@@ -57,9 +57,15 @@ void set_default_certificate_path(ByteString);HTTP::ProxyConfiguration const& proxy_configuration();void set_proxy_configuration(HTTP::ProxyConfiguration);-// The top-level site this RequestServer serves, when there is one per site. Only responses for that site go into its-// disk cache; a response it fetches for another site is on its way to that site's RequestServer.+// The top-level site this RequestServer serves, when there is one per site.Optional<Utf16String> const& process_top_level_site();void set_process_top_level_site(Optional<Utf16String>);+// Sites have RequestServers of their own, and this one has no site.+void set_process_sites_have_their_own();++// Cache only this server's site's responses. A server with no site caches all sites unless they have+// their own RequestServers; other sites' responses are only in transit to their site's server.+bool process_keeps_responses_under(Utf16String const& top_level_site);+}diff --git a/Services/RequestServer/main.cpp b/Services/RequestServer/main.cppindex 6777b8258a9..a7a01084925 100644--- a/Services/RequestServer/main.cpp+++ b/Services/RequestServer/main.cpp@@ -52,6 +52,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)StringView resource_map_path;StringView cache_path;StringView top_level_site;+ bool sites_have_their_own = false;bool wait_for_debugger = false;bool disable_sandbox = false;@@ -66,6 +67,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(resource_map_path, "Path to JSON file mapping URLs to local files", "resource-map", 0, "path");args_parser.add_option(cache_path, "Path to the profile cache", "cache-path", 0, "path");args_parser.add_option(top_level_site, "The top-level site this RequestServer serves", "site", 0, "site");+ args_parser.add_option(sites_have_their_own, "Sites have RequestServers of their own; keep none of their responses", "sites-have-their-own");args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.parse(arguments);@@ -131,6 +133,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)if (!top_level_site.is_empty())RequestServer::set_process_top_level_site(Utf16String::from_utf8(top_level_site));+ else if (sites_have_their_own)+ RequestServer::set_process_sites_have_their_own();TRY(RequestServer::initialize_libcurl());diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 33ff5a74f7a..9161953dfa5 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -475,10 +475,10 @@ void ConnectionFromClient::compositor_process_reconnected()m_page_host->compositor_process_reconnected();}-void ConnectionFromClient::connect_to_request_server(IPC::TransportHandle handle, int client_id)+void ConnectionFromClient::connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site){if (on_request_server_connection)- on_request_server_connection(handle, client_id);+ on_request_server_connection(handle, client_id, top_level_site);}ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_media_server_transport()diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex fb10aa51161..e52a9b7ecaa 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -71,7 +71,7 @@ public:Web::Compositor::CompositorConnection* compositor_process_connection() const;void did_destroy_compositor_context(Web::CompositorContextId);- Function<void(IPC::TransportHandle const&, Optional<int> client_id)> on_request_server_connection;+ Function<void(IPC::TransportHandle const&, Optional<int> client_id, Optional<Utf16String> const& top_level_site)> on_request_server_connection;Function<void(IPC::TransportHandle const&)> on_image_decoder_connection;// Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.@@ -113,7 +113,7 @@ private:virtual void run_webdriver_user_prompt_handling(Web::PageId page_id, u64 request_id) override;virtual void did_handle_webdriver_mouse_event(Web::PageId page_id, u64 request_id) override;virtual void connect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) override;- virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id) override;+ virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) override;virtual void connect_to_test_endpoint(IPC::TransportHandle handle) override;virtual void connect_to_image_decoder(IPC::TransportHandle handle) override;virtual void connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 81d3f94a1cf..05f014e630f 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1524,9 +1524,9 @@ void PageClient::did_delete_all_cookies(u64 request_id)Web::WebIDL::resolve_promise(realm, promise);}-void PageClient::page_did_lose_request_server_connection()+void PageClient::page_did_lose_request_server_connection(Optional<Utf16String> const& top_level_site){- auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidLoseRequestServerConnection>();+ auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidLoseRequestServerConnection>(top_level_site);if (!response)return;@@ -1535,7 +1535,7 @@ void PageClient::page_did_lose_request_server_connection()return;if (client().on_request_server_connection)- client().on_request_server_connection(*handle, {});+ client().on_request_server_connection(*handle, {}, top_level_site);}void PageClient::page_did_simulate_worker_request_server_connection_loss()diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex b346d696762..36503b5c05b 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -299,7 +299,7 @@ private:virtual void page_did_update_cookie(HTTP::Cookie::Cookie const&) override;virtual void page_did_expire_cookies_with_time_offset(AK::Duration) override;virtual void page_did_delete_all_cookies(URL::URL const&, GC::Ref<Web::WebIDL::Promise>) override;- virtual void page_did_lose_request_server_connection() override;+ virtual void page_did_lose_request_server_connection(Optional<Utf16String> const& top_level_site) override;virtual void page_did_simulate_worker_request_server_connection_loss() override;virtual void page_did_store_hsts_policy_for_testing(String const&, HTTP::HSTS::ParsedHSTSPolicy const&) override;virtual void page_did_request_clear_storage_for_testing(Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentSettingsObject const&) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 8fe0fe00601..302f0945680 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -193,7 +193,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_is_known_hsts_host(String domain) => (bool result)- did_lose_request_server_connection() => (Optional<IPC::TransportHandle> handle)+ did_lose_request_server_connection(Optional<Utf16String> top_level_site) => (Optional<IPC::TransportHandle> handle)request_media_server_connection() => (Optional<IPC::TransportHandle> handle)request_audio_server_connection() => (Optional<IPC::TransportHandle> handle)request_video_presentation_channel() =|diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex 8ae3b697112..e2fd68f3f6a 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -89,7 +89,7 @@ endpoint WebContentServer routed by Web::PageId page_idrun_webdriver_bidi_command(Web::PageId page_id, u64 command_id, Web::HTML::CrossProcessId navigable_id, String method, JsonValue params) =|set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState state) =|connect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) =|- connect_to_request_server(IPC::TransportHandle handle, int client_id) =|+ connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) =|connect_to_test_endpoint(IPC::TransportHandle handle) =|connect_to_image_decoder(IPC::TransportHandle handle) =|connect_to_compositor_process(IPC::TransportHandle handle, IPC::TransportHandle render_clock_handle) =|diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex 6a19e6d25fc..74ecedcc98b 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -157,7 +157,7 @@ static void install_crash_signal_handlers()}#endif-static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id);+static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site);static ErrorOr<void> connect_to_image_decoder(IPC::TransportHandle const& handle);ErrorOr<int> ladybird_main(Main::Arguments arguments)@@ -295,8 +295,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto webcontent_client = TRY(IPC::take_over_accepted_client_from_system_server<WebContent::ConnectionFromClient>(mach_server_name, enable_test_mode));auto& heap = Web::Bindings::main_thread_vm().heap();- webcontent_client->on_request_server_connection = [&heap](auto const& handle, auto client_id) {- if (auto result = connect_to_resource_loader(heap, handle, client_id); result.is_error())+ webcontent_client->on_request_server_connection = [&heap](auto const& handle, auto client_id, auto const& top_level_site) {+ if (auto result = connect_to_resource_loader(heap, handle, client_id, top_level_site); result.is_error())dbgln("Failed to connect to resource loader: {}", result.error());};webcontent_client->on_image_decoder_connection = [](auto const& handle) {@@ -323,17 +323,16 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)return event_loop.exec();}-ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id)+ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site){auto transport = TRY(handle.create_transport());// Querying the client ID runs the event loop and could dispatch a request before the client is ready.auto request_client = client_id.has_value()? TRY(try_make_ref_counted<Requests::RequestClient>(move(transport), *client_id)): TRY(try_make_ref_counted<Requests::RequestClient>(move(transport)));- if (Web::ResourceLoader::is_initialized())- Web::ResourceLoader::the().set_client(move(request_client));- else- Web::ResourceLoader::initialize(heap, move(request_client));+ if (!Web::ResourceLoader::is_initialized())+ Web::ResourceLoader::initialize(heap);+ Web::ResourceLoader::the().set_client(top_level_site, move(request_client));return {};}diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cppindex 5f74f53c356..f085f828667 100644--- a/Services/WebWorker/ConnectionFromClient.cpp+++ b/Services/WebWorker/ConnectionFromClient.cpp@@ -18,10 +18,10 @@namespace WebWorker {-void ConnectionFromClient::connect_to_request_server(IPC::TransportHandle handle, int client_id)+void ConnectionFromClient::connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site){if (on_request_server_connection)- on_request_server_connection(handle, client_id);+ on_request_server_connection(handle, client_id, top_level_site);// A real connection loss defers this callback. Exercise the case where the replacement connection arrives before// that deferred callback runs.@@ -29,13 +29,12 @@ void ConnectionFromClient::connect_to_request_server(IPC::TransportHandle handlerequest_server_died_callback();}-void ConnectionFromClient::simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id)+void ConnectionFromClient::simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id, Optional<Utf16String> top_level_site){- auto disconnected_client = move(Web::ResourceLoader::the().request_client());- m_request_server_died_callback_for_testing = move(disconnected_client->on_request_server_died);- disconnected_client = nullptr;+ if (auto disconnected_client = Web::ResourceLoader::the().take_client_for_testing(top_level_site))+ m_request_server_died_callback_for_testing = move(disconnected_client->on_request_server_died);- connect_to_request_server(move(replacement_handle), client_id);+ connect_to_request_server(move(replacement_handle), client_id, move(top_level_site));}void ConnectionFromClient::connect_to_image_decoder(IPC::TransportHandle handle)diff --git a/Services/WebWorker/ConnectionFromClient.h b/Services/WebWorker/ConnectionFromClient.hindex 6e26758ca0a..5567423d2ef 100644--- a/Services/WebWorker/ConnectionFromClient.h+++ b/Services/WebWorker/ConnectionFromClient.h@@ -42,7 +42,7 @@ public:Web::Compositor::CompositorConnection* compositor_process_connection() const;- Function<void(IPC::TransportHandle const&, Optional<int> client_id)> on_request_server_connection;+ Function<void(IPC::TransportHandle const&, Optional<int> client_id, Optional<Utf16String> const& top_level_site)> on_request_server_connection;Function<void(IPC::TransportHandle const&)> on_image_decoder_connection;// Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.@@ -54,8 +54,8 @@ private:Web::Page& page();Web::Page const& page() const;- virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id) override;- virtual void simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id) override;+ virtual void connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) override;+ virtual void simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id, Optional<Utf16String> top_level_site) override;virtual void connect_to_image_decoder(IPC::TransportHandle handle) override;virtual void connect_to_compositor(IPC::TransportHandle handle) override;virtual void set_site_compatibility_data(JsonValue data) override;diff --git a/Services/WebWorker/WebWorkerServer.ipc b/Services/WebWorker/WebWorkerServer.ipcindex af1e377d0a2..57b7a03ee20 100644--- a/Services/WebWorker/WebWorkerServer.ipc+++ b/Services/WebWorker/WebWorkerServer.ipc@@ -13,8 +13,8 @@endpoint WebWorkerServer {set_font_service(IPC::TransportHandle handle, IPC::File catalog, u64 catalog_size, u64 generation) =|- connect_to_request_server(IPC::TransportHandle handle, int client_id) =|- simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id) => ()+ connect_to_request_server(IPC::TransportHandle handle, int client_id, Optional<Utf16String> top_level_site) =|+ simulate_request_server_connection_loss_and_reconnect_for_testing(IPC::TransportHandle replacement_handle, int client_id, Optional<Utf16String> top_level_site) => ()connect_to_image_decoder(IPC::TransportHandle handle) =|connect_to_compositor(IPC::TransportHandle handle) =|set_site_compatibility_data(JsonValue data) =|diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cppindex 86df525081e..c1b4bb631bf 100644--- a/Services/WebWorker/main.cpp+++ b/Services/WebWorker/main.cpp@@ -36,7 +36,7 @@#include <openssl/thread.h>-static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id);+static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site);static ErrorOr<void> connect_to_image_decoder(IPC::TransportHandle const& handle);static ErrorOr<Web::HTML::AgentType> agent_type_from_string(StringView type)@@ -140,8 +140,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto client = TRY(IPC::take_over_accepted_client_from_system_server<WebWorker::ConnectionFromClient>(mach_server_name, enable_test_mode));auto& heap = Web::Bindings::main_thread_vm().heap();- client->on_request_server_connection = [&heap](auto const& handle, auto client_id) {- if (auto result = connect_to_resource_loader(heap, handle, client_id); result.is_error())+ client->on_request_server_connection = [&heap](auto const& handle, auto client_id, auto const& top_level_site) {+ if (auto result = connect_to_resource_loader(heap, handle, client_id, top_level_site); result.is_error())dbgln("Failed to connect to resource loader: {}", result.error());};client->on_image_decoder_connection = [](auto const& handle) {@@ -159,17 +159,16 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)return event_loop.exec();}-static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id)+static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site){auto transport = TRY(handle.create_transport());// Querying the client ID runs the event loop and could dispatch a request before the client is ready.auto request_client = client_id.has_value()? TRY(try_make_ref_counted<Requests::RequestClient>(move(transport), *client_id)): TRY(try_make_ref_counted<Requests::RequestClient>(move(transport)));- if (Web::ResourceLoader::is_initialized())- Web::ResourceLoader::the().set_client(move(request_client));- else- Web::ResourceLoader::initialize(heap, move(request_client));+ if (!Web::ResourceLoader::is_initialized())+ Web::ResourceLoader::initialize(heap);+ Web::ResourceLoader::the().set_client(top_level_site, move(request_client));return {};}diff --git a/Tests/LibHTTP/TestCacheIndex.cpp b/Tests/LibHTTP/TestCacheIndex.cppindex 5838bb6003b..5b886229476 100644--- a/Tests/LibHTTP/TestCacheIndex.cpp+++ b/Tests/LibHTTP/TestCacheIndex.cpp@@ -6,6 +6,7 @@#include <AK/LexicalPath.h>#include <AK/NumericLimits.h>+#include <AK/QuickSort.h>#include <LibCore/Directory.h>#include <LibCore/StandardPaths.h>#include <LibDatabase/Database.h>@@ -416,3 +417,41 @@ TEST_CASE(stored_vary_wildcard_does_not_match)auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));EXPECT(!reloaded_index.find_entry(1, *request_headers).has_value());}++TEST_CASE(access_profile_and_eviction_by_last_access_time)+{+ auto state = create_cache_index();++ size_t size_changes = 0;+ state.index.on_total_estimated_size_change = [&] { ++size_changes; };++ auto request_headers = HTTP::HeaderList::create();+ auto response_headers = HTTP::HeaderList::create();+ auto now = UnixDateTime::now();++ TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com/1"_string, request_headers, response_headers, 10, now, now));+ TRY_OR_FAIL(state.index.create_entry(2, 0, "https://example.com/2"_string, request_headers, response_headers, 20, now, now));+ TRY_OR_FAIL(state.index.create_entry(3, 0, "https://example.com/3"_string, request_headers, response_headers, 40, now, now));+ EXPECT_EQ(size_changes, 3u);++ // Entries 1 and 2 were last used in the same minute, entry 3 five minutes later.+ TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = 60000 WHERE cache_key = 1;"sv));+ TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = 119999 WHERE cache_key = 2;"sv));+ TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = 360000 WHERE cache_key = 3;"sv));++ auto buckets = state.index.access_profile(AK::Duration::from_seconds(60));+ EXPECT_EQ(buckets.size(), 2u);+ EXPECT_EQ(buckets[0].last_access_time, UnixDateTime::from_milliseconds_since_epoch(360000));+ EXPECT_EQ(buckets[0].size, 40u);+ EXPECT_EQ(buckets[1].last_access_time, UnixDateTime::from_milliseconds_since_epoch(60000));+ EXPECT_EQ(buckets[1].size, 30u);++ Vector<u64> removed_entries;+ state.index.remove_entries_accessed_before(UnixDateTime::from_milliseconds_since_epoch(360000), [&](auto cache_key, auto) { removed_entries.append(cache_key); });+ quick_sort(removed_entries);+ EXPECT_EQ(removed_entries, (Vector<u64> { 1, 2 }));+ EXPECT_EQ(state.index.total_estimated_size(), 40u);+ EXPECT(size_changes >= 5u);+ EXPECT(state.index.find_entry(3, *request_headers).has_value());+ EXPECT(!state.index.find_entry(1, *request_headers).has_value());+}diff --git a/Tests/LibWebView/TestRendererCookieAccess.cpp b/Tests/LibWebView/TestRendererCookieAccess.cppindex 8c902044504..8ddbc3d6e46 100644--- a/Tests/LibWebView/TestRendererCookieAccess.cpp+++ b/Tests/LibWebView/TestRendererCookieAccess.cpp@@ -17,6 +17,7 @@#include <LibHTTP/Cookie/ParsedCookie.h>#include <LibMain/Main.h>#include <LibURL/Parser.h>+#include <LibURL/Site.h>#include <LibWebCommon/FileAPI/SerializedBlobURLEntry.h>#include <LibWebView/Application.h>#include <LibWebView/BlobURLStore.h>@@ -163,6 +164,40 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)stub.did_update_cookie(move(cookie));});+ auto victim_site = URL::Site::serialize_for_partitioning(victim_url.origin()).release_value();+ expect_rejected("creating a RequestServer client for an unauthorized site"sv, [&](auto& stub, auto) {+ VERIFY(!stub.did_lose_request_server_connection(victim_site).handle().has_value());+ });++ // The UI's navigation record permits the destination client before any document is bound to it.+ auto navigation_view = create_view();+ auto& navigation_client = navigation_view->page().client();+ auto& navigation_stub = static_cast<WebContentClientStub&>(navigation_client);+ auto loader = WebView::NavigationLoader::create(navigation_client.is_private(), Web::HTML::NavigationPopulationRequest {+ .navigable_id = navigation_view->traversable().id(),+ .history_entry = {},+ .source_snapshot_params = Web::HTML::create_navigation_source_snapshot_without_a_source_document(),+ .target_snapshot_params = {},+ .csp_navigation_type = Web::ContentSecurityPolicy::Directives::NavigationType::Other,+ .history_handling = Web::Bindings::NavigationHistoryBehavior::Auto,+ .user_involvement = Web::HTML::UserNavigationInvolvement::None,+ .navigation_id = "authorized-navigation"_utf16,+ });+ navigation_view->traversable().set_ongoing_navigation({+ .url = victim_url,+ .navigation_id = "authorized-navigation"_utf16,+ .state = WebView::CanonicalNavigation::CreatingNavigationParams { loader },+ .page = &navigation_view->page(),+ });+ expect_rejected("using another renderer's navigation to create a RequestServer client"sv, [&](auto& stub, auto) {+ VERIFY(!stub.did_lose_request_server_connection(victim_site).handle().has_value());+ });+ auto authorized_connection = navigation_stub.did_lose_request_server_connection(victim_site);+ VERIFY(authorized_connection.handle().has_value());+ navigation_view->traversable().clear_ongoing_navigation();+ VERIFY(navigation_stub.did_lose_request_server_connection(victim_site).handle().has_value());+ VERIFY(navigation_stub.did_lose_request_server_connection({}).handle().has_value());+outln("PASS: renderers cannot read, store or update cookies the way HTTP responses and WebDriver do, nor reach another origin's cookies or blob URL entries");return 0;}diff --git a/UI/Android/src/main/cpp/WebContentService.cpp b/UI/Android/src/main/cpp/WebContentService.cppindex 1f554ec31b3..ae6d2bf8130 100644--- a/UI/Android/src/main/cpp/WebContentService.cpp+++ b/UI/Android/src/main/cpp/WebContentService.cpp@@ -50,7 +50,8 @@ ErrorOr<int> service_main(int ipc_socket)Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);auto request_server_client = TRY(bind_request_server_service());- Web::ResourceLoader::initialize(Web::Bindings::main_thread_vm().heap(), move(request_server_client));+ Web::ResourceLoader::initialize(Web::Bindings::main_thread_vm().heap());+ Web::ResourceLoader::the().set_client({}, move(request_server_client));bool is_test_mode = false;