Truly independent web browser
/*
* Copyright (c) 2018-2024, Andreas Kling <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AllOf.h>
#include <AK/IDAllocator.h>
#include <AK/Math.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/WeakPtr.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Socket.h>
#include <LibHTTP/Cache/DiskCache.h>
#include <LibHTTP/Header.h>
#include <LibHTTP/Method.h>
#include <LibHTTP/Port.h>
#include <LibIPC/Limits.h>
#include <LibIPC/TransportHandle.h>
#include <LibRequests/NetworkError.h>
#include <LibRequests/WebSocket.h>
#include <LibURL/Parser.h>
#include <LibURL/Site.h>
#include <LibWebSocket/ConnectionInfo.h>
#include <LibWebSocket/Message.h>
#include <RequestServer/AIA.h>
#include <RequestServer/AlternativeServices.h>
#include <RequestServer/CURL.h>
#include <RequestServer/ConnectionFromClient.h>
#include <RequestServer/ControlConnectionFromClient.h>
#include <RequestServer/Request.h>
#include <RequestServer/Resolver.h>
#include <RequestServer/WebSocketImplCurl.h>
namespace RequestServer {
static IDAllocator s_client_ids;
static size_t s_private_connection_count { 0 };
static constexpr size_t max_websockets_per_client = 256;
static constexpr size_t max_websockets = 1024;
static constexpr i64 TICK_GAP_THRESHOLD_MS = 100;
static Optional<MonotonicTime> s_last_tick_at;
static StringView s_last_tick_label;
// When libcurl asks us (via on_timeout_callback) to wake it up after N ms, we record when. If `curl-timer-fired`
// then runs close to that time the gap is by design (libcurl's heartbeat) and we suppress the wire-stall log.
static Optional<MonotonicTime> s_curl_timer_due_at;
static constexpr i64 CURL_TIMER_ON_TIME_TOLERANCE_MS = 50;
void note_event_tick(StringView label)
{
if constexpr (!REQUESTSERVER_WIRE_DEBUG)
return;
auto now = MonotonicTime::now();
if (s_last_tick_at.has_value()) {
auto gap = (now - *s_last_tick_at).to_milliseconds();
if (gap > TICK_GAP_THRESHOLD_MS) {
bool curl_timer_fired_on_schedule = false;
if (label == "curl-timer-fired"sv && s_curl_timer_due_at.has_value()) {
auto overshoot_ms = (now - *s_curl_timer_due_at).to_milliseconds();
if (overshoot_ms >= -CURL_TIMER_ON_TIME_TOLERANCE_MS && overshoot_ms <= CURL_TIMER_ON_TIME_TOLERANCE_MS)
curl_timer_fired_on_schedule = true;
}
if (!curl_timer_fired_on_schedule) {
dbgln("RequestServer wire-stall: {} ms event-loop gap before '{}' (previous handler: '{}')",
gap, label, s_last_tick_label);
}
}
}
s_last_tick_at = now;
s_last_tick_label = label;
}
static constexpr i64 CURL_CALL_THRESHOLD_MS = 50;
template<typename F>
static auto time_curl_call(StringView label, F&& f)
{
if constexpr (!REQUESTSERVER_WIRE_DEBUG)
return f();
auto start = MonotonicTime::now();
auto result = f();
auto elapsed_ms = (MonotonicTime::now() - start).to_milliseconds();
if (elapsed_ms > CURL_CALL_THRESHOLD_MS)
dbgln("RequestServer wire-stall: curl call '{}' took {} ms (synchronous in event loop)", label, elapsed_ms);
return result;
}
// Per-client burst-of-requests counter. Tracks how many `start_request` IPC
// calls land in a tight window, so we can see if WebContent is dumping a
// page worth of requests on us in one shot. State lives on ConnectionFromClient.
static constexpr i64 BURST_WINDOW_MS = 100;
static constexpr u64 BURST_REPORT_THRESHOLD = 5;
ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transport, IsPrivate is_private, SiteBinding site_binding, ConnectionMap& connections, RequestTransferLeaseMap& request_transfer_leases, Optional<HTTP::DiskCache&> disk_cache)
: IPC::ConnectionFromClient<RequestClientEndpoint, RequestServerEndpoint>(*this, move(transport), s_client_ids.allocate())
, m_is_private(is_private)
, m_site_binding(site_binding)
, m_connections(connections)
, m_request_transfer_leases(request_transfer_leases)
, m_disk_cache(disk_cache)
, m_resolver(is_private == IsPrivate::Yes ? Resolver::private_resolver() : Resolver::default_resolver())
{
if (m_is_private == IsPrivate::Yes)
++s_private_connection_count;
m_connections.set(client_id(), *this);
set_up_curl_multi(m_fetch_curl);
auto result = curl_multi_setopt(m_fetch_curl.handle, CURLMOPT_MAX_HOST_CONNECTIONS, 6L);
VERIFY(result == CURLM_OK);
set_up_curl_multi(m_websocket_curl);
}
void ConnectionFromClient::set_up_curl_multi(CurlMulti& multi)
{
multi.client = this;
multi.handle = curl_multi_init();
auto set_option = [&multi](auto option, auto value) {
auto result = curl_multi_setopt(multi.handle, option, value);
VERIFY(result == CURLM_OK);
};
set_option(CURLMOPT_SOCKETFUNCTION, &on_socket_callback);
set_option(CURLMOPT_SOCKETDATA, &multi);
set_option(CURLMOPT_TIMERFUNCTION, &on_timeout_callback);
set_option(CURLMOPT_TIMERDATA, &multi);
// https://curl.se/libcurl/c/CURLMOPT_TIMERFUNCTION.html
// Your callback function timer_callback should install a single non-repeating timer with an expire time of
// timeout_ms milliseconds.
multi.timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(0), [this, &multi] {
auto now = MonotonicTime::now();
if (multi.timer_due_at.has_value() && now < *multi.timer_due_at) {
multi.timer->restart(*multi.timer_due_at - now);
return;
}
multi.timer_due_at = {};
note_event_tick("curl-timer-fired"sv);
s_curl_timer_due_at = {};
// When that timer fires, call either curl_multi_socket_action or curl_multi_perform, depending on which
// interface you use.
auto result = time_curl_call("multi_socket_action(timeout)"sv, [&multi] {
return curl_multi_socket_action(multi.handle, CURL_SOCKET_TIMEOUT, 0, nullptr);
});
VERIFY(result == CURLM_OK);
check_active_requests();
});
}
ConnectionFromClient::~ConnectionFromClient()
{
cancel_owned_work();
curl_multi_cleanup(m_fetch_curl.handle);
m_fetch_curl.handle = nullptr;
curl_multi_cleanup(m_websocket_curl.handle);
m_websocket_curl.handle = nullptr;
if (m_is_private == IsPrivate::Yes && --s_private_connection_count == 0) {
clear_aia_state(IsPrivate::Yes);
AlternativeServiceCache::the().clear(IsPrivate::Yes);
}
if (auto connection = ControlConnectionFromClient::the(); connection.has_value())
connection->async_client_disconnected(client_id());
s_client_ids.deallocate(client_id());
}
void ConnectionFromClient::request_complete(Badge<Request>, Request const& request)
{
if (request.has_transfer_lease())
return;
Core::deferred_invoke([weak_self = make_weak_ptr<ConnectionFromClient>(), request_id = request.request_id(), type = request.type()] {
if (auto self = weak_self.strong_ref()) {
if (type == RequestType::BackgroundRevalidation)
self->m_active_revalidation_requests.remove(request_id);
else
self->m_active_requests.remove(request_id);
}
});
}
// Transferred requests may still need our curl multi handle.
void ConnectionFromClient::cancel_owned_work()
{
m_active_requests.clear();
m_active_revalidation_requests.clear();
m_pending_websockets.clear();
m_websocket_cookie_requests.clear();
m_websockets.clear();
for (auto& fetch : m_aia_fetches) {
curl_multi_remove_handle(m_fetch_curl.handle, fetch.key);
curl_easy_cleanup(fetch.key);
if (fetch.value->resolve_list)
curl_slist_free_all(fetch.value->resolve_list);
}
m_aia_fetches.clear();
m_pending_aia_lookups.clear();
}
void ConnectionFromClient::die()
{
Vector<Requests::RequestTransferLeaseKey> transfer_leases_to_cancel;
for (auto& entry : m_request_transfer_leases) {
if (entry.value.owner.ptr() == this)
transfer_leases_to_cancel.append(entry.key);
// A designation ends with the client it names.
if (entry.value.adopter_client_id == client_id())
entry.value.adopter_client_id = {};
}
for (auto const& transfer_lease : transfer_leases_to_cancel) {
auto lease = m_request_transfer_leases.take(transfer_lease);
if (lease.has_value())
m_active_requests.remove(lease->request_id);
}
// Transferred requests can keep this object alive after the client disconnects.
cancel_owned_work();
m_connections.remove(client_id());
if (m_connections.is_empty() && !ControlConnectionFromClient::the().has_value())
Core::EventLoop::current().quit(0);
}
void ConnectionFromClient::bind_to_site(Badge<ControlConnectionFromClient>, Utf16String const& top_level_site, Optional<Utf16String> const& frame_site)
{
m_bound_top_level_sites.set(top_level_site);
if (frame_site.has_value())
m_bound_sites.set({ top_level_site, *frame_site });
}
// A bound client may use only the network isolation keys of the documents that the UI process has its process host, so a
// compromised process cannot reach the cache entries of another site.
bool ConnectionFromClient::may_use_network_isolation_key(HTTP::NetworkIsolationKey const& key, URL::URL const* request_url) const
{
if (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
// navigations, never the one a site's own documents use for their subresources.
if (request_url) {
auto url_site = URL::Site::serialize_for_partitioning(request_url->origin());
if (url_site.has_value() && key.frame_site == url_site) {
if (!key.is_subframe_document && key.is_cross_site_main_frame_navigation && key.top_level_site == *url_site)
return true;
if (key.is_subframe_document && m_bound_top_level_sites.contains(key.top_level_site))
return true;
}
}
if (!key.frame_site.has_value())
return m_bound_top_level_sites.contains(key.top_level_site);
return m_bound_sites.contains(BoundSite { key.top_level_site, *key.frame_site });
}
static bool is_supported_protocol_name(StringView protocol)
{
return protocol.is_one_of("http"sv, "https"sv);
}
static bool is_fetchable_url(URL::URL const& url)
{
if (!is_supported_protocol_name(url.scheme()))
return false;
// https://fetch.spec.whatwg.org/#block-bad-port
// 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, then return blocked.
return !url.port().has_value() || !HTTP::is_bad_port(*url.port());
}
// Headers go verbatim on the wire; newlines would allow request injection.
static bool are_valid_headers(Vector<HTTP::Header> const& headers)
{
return all_of(headers, [](auto const& header) {
return HTTP::is_header_name(header.name) && HTTP::is_header_value(header.value);
});
}
Messages::RequestServer::IsSupportedProtocolResponse ConnectionFromClient::is_supported_protocol(ByteString protocol)
{
return is_supported_protocol_name(protocol);
}
Messages::RequestServer::GetClientIdResponse ConnectionFromClient::get_client_id()
{
return client_id();
}
// Transfer leases outlive request-map entries during handoff.
bool ConnectionFromClient::is_live_request_id(u64 request_id) const
{
return m_active_requests.contains(request_id) || m_request_transfer_leases.contains({ client_id(), request_id });
}
void ConnectionFromClient::start_request(u64 request_id, ByteString method, URL::URL url, Vector<HTTP::Header> request_headers, ByteBuffer request_body, HTTP::CacheMode cache_mode, Optional<HTTP::NetworkIsolationKey> network_isolation_key, HTTP::Cookie::IncludeCredentials include_credentials, bool create_transfer_lease, Optional<u32> address_selection_hint, bool notify_on_cache_miss, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context)
{
note_event_tick("ipc-start-request"sv);
dbgln_if(REQUESTSERVER_DEBUG, "RequestServer: start_request({}, {})", request_id, url);
if (is_live_request_id(request_id)) {
did_misbehave("reused live request ID");
return;
}
// https://fetch.spec.whatwg.org/#dom-request
// 25.2. If method is not a method or method is a forbidden method, then throw a TypeError.
if (!HTTP::is_method(method) || HTTP::is_forbidden_method(method)) {
did_misbehave("invalid or forbidden request method");
return;
}
if (!are_valid_headers(request_headers)) {
did_misbehave("invalid request header");
return;
}
// Validate again at the boundary that grants network access.
if (!is_fetchable_url(url)) {
async_request_finished(request_id, 0, {}, Requests::NetworkError::MalformedUrl);
return;
}
if (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key, &url)) {
dbgln("RequestServer: Client {} is not bound to the network isolation key of its request for {}", client_id(), url);
async_request_finished(request_id, 0, {}, Requests::NetworkError::Unknown);
return;
}
if constexpr (REQUESTSERVER_WIRE_DEBUG) {
auto now = MonotonicTime::now();
if (m_burst_window_started_at.has_value() && (now - *m_burst_window_started_at).to_milliseconds() < BURST_WINDOW_MS) {
++m_requests_in_burst_window;
} else {
if (m_requests_in_burst_window > BURST_REPORT_THRESHOLD) {
dbgln("RequestServer wire-burst: client {} sent {} requests in <{} ms",
client_id(), m_requests_in_burst_window, BURST_WINDOW_MS);
}
m_burst_window_started_at = now;
m_requests_in_burst_window = 1;
}
}
Requests::RequestTransferLeaseKey lease_key { client_id(), request_id };
auto transfer_lease = create_transfer_lease
? Optional<Requests::RequestTransferLeaseKey> { lease_key }
: Optional<Requests::RequestTransferLeaseKey> {};
auto request = Request::fetch(request_id, m_disk_cache, move(network_isolation_key), cache_mode, *this, m_fetch_curl.handle, m_resolver, move(url), move(method), HTTP::HeaderList::create(move(request_headers)), move(request_body), include_credentials, same_site_context, transfer_lease, address_selection_hint, notify_on_cache_miss);
request->set_performance_origin(client_id(), originating_page_id);
m_active_requests.set(request_id, move(request));
if (transfer_lease.has_value())
m_request_transfer_leases.set(*transfer_lease, RequestTransferLease { *this, request_id });
}
void ConnectionFromClient::adopt_request(int source_client_id, u64 source_request_id, u64 target_request_id, bool preserve_transfer_lease, Optional<int> owner_client_id)
{
if (is_live_request_id(target_request_id)) {
did_misbehave("reused live request ID");
return;
}
auto lease_key = Requests::RequestTransferLeaseKey { source_client_id, source_request_id };
auto transfer_lease = m_request_transfer_leases.get(lease_key);
auto may_adopt = [&] {
if (!transfer_lease.has_value())
return false;
// The UI process adopts from the owner it names, or from itself when it names the client it designated. A bound
// client adopts only what it was designated for.
if (m_site_binding == SiteBinding::Unrestricted) {
if (!owner_client_id.has_value())
return false;
if (*owner_client_id == transfer_lease->owner->client_id())
return true;
return transfer_lease->owner.ptr() == this && transfer_lease->adopter_client_id == *owner_client_id;
}
return transfer_lease->adopter_client_id == client_id();
}();
if (!may_adopt) {
async_request_finished(target_request_id, 0, {}, Requests::NetworkError::Unknown);
return;
}
auto source_connection = transfer_lease->owner;
auto current_request_id = transfer_lease->request_id;
auto request = source_connection->m_active_requests.take(current_request_id);
if (!request.has_value()) {
async_request_finished(target_request_id, 0, {}, Requests::NetworkError::Unknown);
return;
}
auto const& request_transfer_lease = (*request)->transfer_lease();
if (!request_transfer_lease.has_value() || *request_transfer_lease != lease_key) {
source_connection->m_active_requests.set(current_request_id, request.release_value());
async_request_finished(target_request_id, 0, {}, Requests::NetworkError::Unknown);
return;
}
auto transfer_lease_to_preserve = preserve_transfer_lease
? Optional<Requests::RequestTransferLeaseKey> { lease_key }
: Optional<Requests::RequestTransferLeaseKey> {};
auto transfer_result = (*request)->transfer_to_client(*this, target_request_id, move(transfer_lease_to_preserve));
if (transfer_result.is_error()) {
dbgln("RequestServer: Failed to transfer request {} from client {} to client {}: {}", source_request_id, source_client_id, client_id(), transfer_result.error());
source_connection->m_active_requests.set(current_request_id, request.release_value());
async_request_finished(target_request_id, 0, {}, Requests::NetworkError::Unknown);
return;
}
auto should_remove_after_transfer = (*request)->is_complete() && !preserve_transfer_lease;
m_active_requests.set(target_request_id, request.release_value());
if (preserve_transfer_lease) {
transfer_lease->owner = *this;
transfer_lease->request_id = target_request_id;
transfer_lease->adopter_client_id = {};
} else {
m_request_transfer_leases.remove(lease_key);
}
if (should_remove_after_transfer) {
Core::deferred_invoke([weak_self = make_weak_ptr<ConnectionFromClient>(), target_request_id] {
if (auto self = weak_self.strong_ref())
self->m_active_requests.remove(target_request_id);
});
}
}
void ConnectionFromClient::release_request_transfer_lease(int source_client_id, u64 source_request_id)
{
auto lease_key = Requests::RequestTransferLeaseKey { source_client_id, source_request_id };
auto lease = m_request_transfer_leases.get(lease_key);
if (!lease.has_value() || lease->owner.ptr() != this)
return;
auto owner = lease->owner;
auto request_id = lease->request_id;
m_request_transfer_leases.remove(lease_key);
auto request = owner->m_active_requests.get(request_id);
if (!request.has_value())
return;
(*request)->release_transfer_lease();
if ((*request)->is_complete()) {
Core::deferred_invoke([weak_owner = owner->make_weak_ptr<ConnectionFromClient>(), request_id] {
if (auto owner = weak_owner.strong_ref())
owner->m_active_requests.remove(request_id);
});
}
}
void ConnectionFromClient::start_revalidation_request(Badge<Request>, HTTP::NetworkIsolationKey network_isolation_key, ByteString method, URL::URL url, NonnullRefPtr<HTTP::HeaderList> request_headers, ByteBuffer request_body, HTTP::Cookie::IncludeCredentials include_credentials, HTTP::Cookie::SameSiteContext same_site_context)
{
note_event_tick("ipc-start-revalidation"sv);
auto request_id = m_next_revalidation_request_id++;
dbgln_if(REQUESTSERVER_DEBUG, "RequestServer: start_revalidation_request({}, {})", request_id, url);
auto request = Request::revalidate(request_id, m_disk_cache, move(network_isolation_key), *this, m_fetch_curl.handle, m_resolver, move(url), move(method), move(request_headers), move(request_body), include_credentials, same_site_context);
m_active_revalidation_requests.set(request_id, move(request));
}
int ConnectionFromClient::on_socket_callback(CURL*, int sockfd, int what, void* user_data, void*)
{
auto* multi = static_cast<CurlMulti*>(user_data);
auto* client = multi->client;
if (what == CURL_POLL_REMOVE) {
client->m_read_notifiers.remove(sockfd);
client->m_write_notifiers.remove(sockfd);
return 0;
}
auto update_notifier = [client, multi_handle = multi->handle, sockfd, what](auto& notifiers, Core::NotificationType type, int poll_flag, int select_flag) {
if (!(what & poll_flag)) {
if (auto notifier = notifiers.get(sockfd); notifier.has_value())
notifier.value()->set_enabled(false);
return;
}
auto& notifier = notifiers.ensure(sockfd, [client, sockfd, multi = multi_handle, type, select_flag] {
auto notifier = Core::Notifier::construct(sockfd, type);
notifier->on_activation = [client, sockfd, multi, select_flag] {
note_event_tick("curl-socket-ready"sv);
auto result = time_curl_call("multi_socket_action(socket)"sv, [&] {
return curl_multi_socket_action(multi, sockfd, select_flag, nullptr);
});
VERIFY(result == CURLM_OK);
client->check_active_requests();
};
return notifier;
});
notifier->set_enabled(true);
};
update_notifier(client->m_read_notifiers, Core::NotificationType::Read, CURL_POLL_IN, CURL_CSELECT_IN);
update_notifier(client->m_write_notifiers, Core::NotificationType::Write, CURL_POLL_OUT, CURL_CSELECT_OUT);
return 0;
}
int ConnectionFromClient::on_timeout_callback(void*, long timeout_ms, void* user_data)
{
auto* multi = static_cast<CurlMulti*>(user_data);
if (!multi->timer)
return 0;
// https://curl.se/libcurl/c/CURLMOPT_TIMERFUNCTION.html
// A timeout_ms value of -1 passed to this callback means you should delete the timer.
if (timeout_ms == -1) {
multi->timer->stop();
multi->timer_due_at = {};
s_curl_timer_due_at = {};
} else {
// All other values are valid expire times in number of milliseconds - including zero milliseconds.
VERIFY(timeout_ms >= 0);
auto due_at = MonotonicTime::now() + AK::Duration::from_milliseconds(timeout_ms);
multi->timer_due_at = due_at;
s_curl_timer_due_at = due_at;
// If this callback is called when a timer is already running, this new expire time replaces the former timeout.
// The application should then effectively cancel the old timeout and set a new timeout using this new expire time.
//
// WARNING: do not call libcurl directly from within the callback itself when the timeout_ms value is zero, since
// it risks triggering an unpleasant recursive behavior that immediately calls another call to the callback with
// a zero timeout...
multi->timer->restart(AK::Duration::from_milliseconds(timeout_ms));
}
// The timer callback should return 0 on success, and -1 on error.
return 0;
}
void ConnectionFromClient::check_active_requests()
{
note_event_tick("check-active-requests"sv);
int msgs_in_queue = 0;
u64 completions_drained = 0;
for (auto* multi_handle : { m_fetch_curl.handle, m_websocket_curl.handle }) {
while (auto* msg = curl_multi_info_read(multi_handle, &msgs_in_queue)) {
if (msg->msg != CURLMSG_DONE)
continue;
void* application_private = nullptr;
auto result = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &application_private);
VERIFY(result == CURLE_OK);
VERIFY(application_private != nullptr);
// FIXME: Come up with a unified way to track websockets and standard fetches instead of this nasty tagged pointer
if (reinterpret_cast<uintptr_t>(application_private) & websocket_private_tag) {
auto* websocket_impl = reinterpret_cast<WebSocketImplCurl*>(reinterpret_cast<uintptr_t>(application_private) & ~websocket_private_tag);
if (msg->data.result == CURLE_OK) {
if (!websocket_impl->did_connect())
websocket_impl->on_connection_error();
} else {
websocket_impl->on_connection_error();
}
continue;
}
if (reinterpret_cast<uintptr_t>(application_private) & aia_fetch_private_tag) {
complete_aia_fetch(msg->easy_handle, msg->data.result);
continue;
}
++completions_drained;
auto* request = static_cast<Request*>(application_private);
request->notify_fetch_complete({}, msg->data.result);
}
}
if (completions_drained > 1)
dbgln_if(REQUESTSERVER_WIRE_DEBUG, "RequestServer wire-batch: drained {} completions in one curl multi tick", completions_drained);
}
static size_t aia_write_body(char* data, size_t size, size_t count, void* user_data)
{
auto& fetch = *static_cast<AIAFetch*>(user_data);
auto const length = size * count;
if (fetch.body.size() + length > max_aia_response_size)
return 0;
if (fetch.body.try_append(data, length).is_error())
return 0;
return length;
}
void ConnectionFromClient::fetch_aia_intermediate(Badge<Request>, ByteString const& url, u64 for_request_id)
{
for (auto& in_flight : m_aia_fetches) {
if (in_flight.value->url == url) {
in_flight.value->request_ids.append(for_request_id);
return;
}
}
// The lookup below is async, so m_aia_fetches has no entry yet; this is what stops a second request for the
// same URL from starting a duplicate lookup in the meantime.
if (auto pending = m_pending_aia_lookups.get(url); pending.has_value()) {
m_pending_aia_lookups.ensure(url).append(for_request_id);
return;
}
m_pending_aia_lookups.set(url, { for_request_id });
auto parsed = URL::Parser::basic_parse(url);
if (!parsed.has_value() || !parsed->host().has_value() || !can_pin_host_in_curl_resolve_list(parsed->serialized_host()) || parsed->includes_credentials()) {
abandon_aia_lookup(url);
return;
}
auto host = parsed->serialized_host().to_byte_string();
auto port = parsed->port_or_default();
// Curl gets the same serialization the host and port above came from, so it cannot parse the authority differently.
auto fetch_url = parsed->serialize().to_byte_string();
auto weak_self = make_weak_ptr<ConnectionFromClient>();
auto proxy = proxy_configuration().proxy_for(*parsed).copy();
resolve_proxy_host(proxy, [weak_self, url, fetch_url, host, port, proxy](ErrorOr<void> result) mutable {
auto self = weak_self.strong_ref();
if (!self)
return;
if (result.is_error()) {
dbgln_if(REQUESTSERVER_DEBUG, "AIA: Proxy lookup failed for {}: {}", url, result.error());
self->abandon_aia_lookup(url);
return;
}
self->look_up_aia_host(url, fetch_url, host, port, move(proxy));
});
}
void ConnectionFromClient::look_up_aia_host(ByteString const& url, ByteString const& fetch_url, ByteString const& host, u16 port, Optional<HTTP::Proxy> proxy)
{
auto weak_self = make_weak_ptr<ConnectionFromClient>();
// Avoid leaking hostnames resolved by the proxy.
if (proxy.has_value() && proxy->resolves_hostnames()) {
start_aia_fetch(url, fetch_url, move(proxy), {});
return;
}
// Resolve through RequestServer's own resolver rather than letting curl do it, so the AIA fetch honors the
// same DNS configuration (DoH included) as every other request this process makes.
m_resolver->dns.lookup(host, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA }, { .validate_dnssec_locally = DNSInfo::the().validate_dnssec_locally })
->when_rejected([weak_self, url](auto const& error) {
if (auto self = weak_self.strong_ref()) {
dbgln_if(REQUESTSERVER_DEBUG, "AIA: DNS lookup failed for {}: {}", url, error);
self->abandon_aia_lookup(url);
}
})
.when_resolved([weak_self, url, fetch_url, host, port, proxy = move(proxy)](auto const& dns_result) mutable {
auto self = weak_self.strong_ref();
if (!self)
return;
if (dns_result->is_empty() || !dns_result->has_cached_addresses()) {
dbgln_if(REQUESTSERVER_DEBUG, "AIA: DNS lookup returned no addresses for {}", url);
self->abandon_aia_lookup(url);
return;
}
self->start_aia_fetch(url, fetch_url, move(proxy), build_curl_resolve_list(*dns_result, host, port));
});
}
// Nothing will arrive to wake the waiting requests, so release them to retry without the intermediate.
void ConnectionFromClient::abandon_aia_lookup(ByteString const& url)
{
auto waiting = m_pending_aia_lookups.take(url);
if (!waiting.has_value())
return;
for (auto request_id : *waiting) {
if (auto request = m_active_requests.get(request_id); request.has_value())
(*request)->retry_after_aia({});
}
}
void ConnectionFromClient::start_aia_fetch(ByteString const& url, ByteString const& fetch_url, Optional<HTTP::Proxy> proxy, Optional<ByteString> resolve_entry)
{
auto waiting = m_pending_aia_lookups.take(url);
if (!waiting.has_value() || waiting->is_empty())
return;
auto* easy_handle = curl_easy_init();
if (!easy_handle) {
for (auto request_id : *waiting) {
if (auto request = m_active_requests.get(request_id); request.has_value())
(*request)->retry_after_aia({});
}
return;
}
auto fetch = make<AIAFetch>();
fetch->url = url;
fetch->request_ids = move(*waiting);
auto set_option = [&](auto option, auto value) {
if (auto result = curl_easy_setopt(easy_handle, option, value); result != CURLE_OK)
dbgln("RequestServer: AIA fetch failed to set curl option: {}", curl_easy_strerror(result));
};
set_option(CURLOPT_PRIVATE, reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(fetch.ptr()) | aia_fetch_private_tag));
set_option(CURLOPT_URL, fetch_url.characters());
set_option(CURLOPT_PROTOCOLS_STR, "http");
// curl would resolve a redirect's host itself, bypassing our resolver.
set_option(CURLOPT_FOLLOWLOCATION, 0L);
set_option(CURLOPT_TIMEOUT, 10L);
set_option(CURLOPT_MAXFILESIZE_LARGE, static_cast<curl_off_t>(max_aia_response_size));
set_option(CURLOPT_NOSIGNAL, 1L);
set_option(CURLOPT_WRITEFUNCTION, aia_write_body);
set_option(CURLOPT_WRITEDATA, fetch.ptr());
set_option(CURLOPT_PROXY, proxy.has_value() ? proxy->to_curl_url().characters() : "");
curl_slist* resolve_list = nullptr;
for (auto const& entry : { move(resolve_entry), curl_resolve_entry_for_proxy(proxy) }) {
if (entry.has_value())
resolve_list = curl_slist_append(resolve_list, entry->characters());
}
if (resolve_list) {
set_option(CURLOPT_RESOLVE, resolve_list);
fetch->resolve_list = resolve_list;
}
auto result = curl_multi_add_handle(m_fetch_curl.handle, easy_handle);
VERIFY(result == CURLM_OK);
m_aia_fetches.set(easy_handle, move(fetch));
}
void ConnectionFromClient::complete_aia_fetch(void* easy_handle, int result_code)
{
long response_code = 0;
curl_easy_getinfo(easy_handle, CURLINFO_RESPONSE_CODE, &response_code);
auto fetch = m_aia_fetches.take(easy_handle);
curl_multi_remove_handle(m_fetch_curl.handle, easy_handle);
curl_easy_cleanup(easy_handle);
if (!fetch.has_value())
return;
// curl only reads the resolve list while the handle is attached, so it outlives the handle and is freed here.
if ((*fetch)->resolve_list)
curl_slist_free_all((*fetch)->resolve_list);
bool added = false;
if (result_code == CURLE_OK && response_code == 200) {
Vector<NonnullRefPtr<AIACollector>> collectors;
for (auto request_id : (*fetch)->request_ids) {
if (auto request = m_active_requests.get(request_id); request.has_value()) {
if (auto* collector = (*request)->aia_collector())
collectors.append(*collector);
}
}
added = add_fetched_aia_intermediates((*fetch)->body.bytes(), collectors);
}
if (!added) {
dbgln_if(REQUESTSERVER_DEBUG, "AIA: intermediate fetch from {} failed (curl={}, status={})", (*fetch)->url, result_code, response_code);
mark_aia_url_failed(m_is_private, (*fetch)->url);
}
for (auto request_id : (*fetch)->request_ids) {
if (auto request = m_active_requests.get(request_id); request.has_value())
(*request)->retry_after_aia({});
}
}
void ConnectionFromClient::fail_websocket(u64 websocket_id, Requests::WebSocket::Error error)
{
async_websocket_ready_state_changed(websocket_id, to_underlying(Requests::WebSocket::ReadyState::Closed));
async_websocket_errored(websocket_id, to_underlying(error));
async_websocket_closed(websocket_id, to_underlying(WebSocket::CloseStatusCode::AbnormalClosure), {}, false);
}
Messages::RequestServer::StopRequestResponse ConnectionFromClient::stop_request(u64 request_id)
{
auto request = m_active_requests.take(request_id);
if (!request.has_value()) {
dbgln("StopRequest: Request ID {} not found", request_id);
return false;
}
if ((*request)->transfer_lease().has_value())
m_request_transfer_leases.remove(*(*request)->transfer_lease());
return true;
}
Messages::RequestServer::ExportRequestResponse ConnectionFromClient::export_request(u64 request_id)
{
if (m_site_binding != SiteBinding::Unrestricted) {
did_misbehave("export of a request by a bound client");
return Optional<Requests::ExportedRequest> {};
}
auto request = m_active_requests.get(request_id);
if (!request.has_value())
return Optional<Requests::ExportedRequest> {};
auto transfer_lease = (*request)->transfer_lease();
auto exported = (*request)->export_response();
if (exported.is_error()) {
dbgln("RequestServer: Failed to export request {}: {}", request_id, exported.error());
return Optional<Requests::ExportedRequest> {};
}
if (transfer_lease.has_value())
m_request_transfer_leases.remove(*transfer_lease);
// A finished transfer has nothing left to do here once its outcome is on its way.
if ((*request)->is_complete()) {
Core::deferred_invoke([weak_self = make_weak_ptr<ConnectionFromClient>(), request_id] {
if (auto self = weak_self.strong_ref())
self->m_active_requests.remove(request_id);
});
}
return exported.release_value();
}
void ConnectionFromClient::import_request(u64 request_id, Requests::ExportedRequest exported_request, bool create_transfer_lease)
{
if (m_site_binding != SiteBinding::Unrestricted) {
did_misbehave("import of a request by a bound client");
return;
}
if (is_live_request_id(request_id)) {
did_misbehave("reused live request ID");
return;
}
Optional<Requests::RequestTransferLeaseKey> transfer_lease;
if (create_transfer_lease) {
transfer_lease = Requests::RequestTransferLeaseKey { client_id(), request_id };
m_request_transfer_leases.set(*transfer_lease, RequestTransferLease { *this, request_id });
}
auto request = Request::import(request_id, m_disk_cache, *this, m_resolver, move(exported_request), transfer_lease);
m_active_requests.set(request_id, move(request));
}
void ConnectionFromClient::resolve_host(u64 lookup_id, ByteString host)
{
// Whatever connects to the host would bypass a proxy, and a proxy that resolves names would never see this lookup,
// so nothing is looked up while one is configured.
if (!proxy_configuration().is_empty() || host.is_empty() || host.length() > 253) {
async_host_resolved(lookup_id, {});
return;
}
auto weak_self = make_weak_ptr<ConnectionFromClient>();
m_resolver->dns.lookup(host, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA }, { .validate_dnssec_locally = DNSInfo::the().validate_dnssec_locally })
->when_rejected([weak_self, lookup_id](auto const&) {
if (auto self = weak_self.strong_ref())
self->async_host_resolved(lookup_id, {});
})
.when_resolved([weak_self, lookup_id](auto const& dns_result) {
auto self = weak_self.strong_ref();
if (!self)
return;
Vector<ByteString> addresses;
for (auto const& address : dns_result->cached_addresses())
addresses.append(address.visit([](auto const& address) { return ByteString { MUST(address.to_string()) }; }));
self->async_host_resolved(lookup_id, move(addresses));
});
}
void ConnectionFromClient::ensure_connection(u64 request_id, URL::URL url, ::RequestServer::CacheLevel cache_level)
{
if (is_live_request_id(request_id)) {
did_misbehave("reused live request ID");
return;
}
if (!is_fetchable_url(url))
return;
auto request = Request::connect(request_id, *this, m_fetch_curl.handle, m_resolver, move(url), cache_level);
m_active_requests.set(request_id, move(request));
}
size_t ConnectionFromClient::websocket_count() const
{
return m_pending_websockets.size() + m_websockets.size();
}
size_t ConnectionFromClient::total_websocket_count() const
{
size_t count = 0;
for (auto const& connection : m_connections)
count += connection.value->websocket_count();
return count;
}
void ConnectionFromClient::websocket_connect(u64 websocket_id, URL::URL url, Optional<HTTP::NetworkIsolationKey> network_isolation_key, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, u64 originating_page_id, HTTP::Cookie::SameSiteContext same_site_context)
{
if (m_pending_websockets.contains(websocket_id) || m_websockets.contains(websocket_id)) {
did_misbehave("reused live WebSocket ID");
return;
}
// The origin, protocols and extensions all become header values in the handshake.
auto is_header_value = [](auto const& value) { return HTTP::is_header_value(value); };
if (!are_valid_headers(additional_request_headers)
|| !is_header_value(origin)
|| !all_of(protocols, is_header_value)
|| !all_of(extensions, is_header_value)) {
did_misbehave("invalid WebSocket handshake header");
return;
}
// https://websockets.spec.whatwg.org/#concept-websocket-establish
// 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s scheme is "ws"; otherwise to "https".
// The fetch of requestURL then blocks bad ports like any other.
if (!url.scheme().is_one_of("ws"sv, "wss"sv) || !url.host().has_value() || (url.port().has_value() && HTTP::is_bad_port(*url.port()))) {
fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
// Bound shared descriptor usage, including pending WebSockets.
if (websocket_count() >= max_websockets_per_client || total_websocket_count() >= max_websockets) {
dbgln("WebSocketConnect: Refusing WebSocket beyond the limit of {} per client and {} overall", max_websockets_per_client, max_websockets);
fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
if (network_isolation_key.has_value() && !may_use_network_isolation_key(*network_isolation_key)) {
dbgln("RequestServer: Client {} is not bound to the network isolation key of its WebSocket for {}", client_id(), url);
fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
// The handshake carries the user's cookies for the URL, which we retrieve from the UI process ourselves. The client
// does not get to choose them.
additional_request_headers.remove_all_matching([](auto const& header) {
return header.name.equals_ignoring_ascii_case("Cookie"sv);
});
m_pending_websockets.set(websocket_id);
auto control_connection = ControlConnectionFromClient::the();
if (!control_connection.has_value()) {
m_pending_websockets.remove(websocket_id);
fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
static u64 s_next_cookie_request_id = 0;
auto cookie_request_id = s_next_cookie_request_id++;
m_websocket_cookie_requests.set(websocket_id, {
.cookie_request_id = cookie_request_id,
.continuation = [this, websocket_id, originating_page_id, url, origin = move(origin), protocols = move(protocols), extensions = move(extensions), request_headers = move(additional_request_headers)](String cookie) mutable {
// Sent as UTF-8, like the Cookie header of a fetch.
if (!cookie.is_empty())
request_headers.append({ "Cookie"sv, cookie.to_byte_string() });
connect_websocket(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(request_headers));
},
});
Optional<HTTP::Cookie::PartitionContext> partition_context;
if (network_isolation_key.has_value())
partition_context = HTTP::Cookie::PartitionContext { network_isolation_key->top_level_site, network_isolation_key->has_cross_site_ancestor };
control_connection->async_retrieve_http_cookie(client_id(), websocket_id, RequestType::WebSocket, cookie_request_id, url, move(partition_context), same_site_context);
}
bool ConnectionFromClient::websocket_retrieved_http_cookie(Badge<ControlConnectionFromClient>, u64 websocket_id, u64 cookie_request_id, String cookie)
{
// The client may have closed the WebSocket while its cookies were being retrieved.
auto cookie_request = m_websocket_cookie_requests.get(websocket_id);
if (!cookie_request.has_value())
return true;
if (cookie_request->cookie_request_id != cookie_request_id)
return false;
auto taken_cookie_request = m_websocket_cookie_requests.take(websocket_id).release_value();
taken_cookie_request.continuation(move(cookie));
return true;
}
void ConnectionFromClient::connect_websocket(u64 websocket_id, u64 originating_page_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers)
{
auto host = url.serialized_host().to_byte_string();
auto weak_self = make_weak_ptr<ConnectionFromClient>();
if (!can_pin_host_in_curl_resolve_list(host)) {
m_pending_websockets.remove(websocket_id);
fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
auto proxy = proxy_configuration().proxy_for(url).copy();
resolve_proxy_host(proxy, [weak_self, websocket_id, originating_page_id, url = move(url), origin = move(origin), protocols = move(protocols), extensions = move(extensions), additional_request_headers = move(additional_request_headers), proxy](ErrorOr<void> result) mutable {
auto self = weak_self.strong_ref();
if (!self)
return;
if (result.is_error()) {
dbgln("WebSocketConnect: Proxy lookup failed: {}", result.error());
if (self->m_pending_websockets.remove(websocket_id))
self->fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
self->look_up_websocket_host(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy));
});
}
void ConnectionFromClient::look_up_websocket_host(u64 websocket_id, u64 originating_page_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy> proxy)
{
auto host = url.serialized_host().to_byte_string();
auto weak_self = make_weak_ptr<ConnectionFromClient>();
// Avoid leaking hostnames resolved by the proxy.
if (proxy.has_value() && proxy->resolves_hostnames()) {
if (m_pending_websockets.remove(websocket_id))
open_websocket(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy), nullptr);
return;
}
m_resolver->dns.lookup(host, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA }, { .validate_dnssec_locally = DNSInfo::the().validate_dnssec_locally })
->when_rejected([weak_self, websocket_id](auto const& error) {
auto self = weak_self.strong_ref();
if (!self)
return;
dbgln("WebSocketConnect: DNS lookup failed: {}", error);
if (!self->m_pending_websockets.remove(websocket_id))
return;
self->fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
})
.when_resolved([weak_self, websocket_id, originating_page_id, host = move(host), url = move(url), origin = move(origin), protocols = move(protocols), extensions = move(extensions), additional_request_headers = move(additional_request_headers), proxy = move(proxy)](auto const& dns_result) mutable {
auto self = weak_self.strong_ref();
if (!self)
return;
if (dns_result->is_empty() || !dns_result->has_cached_addresses()) {
dbgln("WebSocketConnect: DNS lookup failed for '{}'", host);
if (!self->m_pending_websockets.remove(websocket_id))
return;
self->fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
// Don't connect the websocket if we already requested to close it before the DNS lookup completed.
if (!self->m_pending_websockets.remove(websocket_id))
return;
self->open_websocket(websocket_id, originating_page_id, move(url), move(origin), move(protocols), move(extensions), move(additional_request_headers), move(proxy), dns_result);
});
}
void ConnectionFromClient::open_websocket(u64 websocket_id, u64 originating_page_id, URL::URL url, ByteString origin, Vector<ByteString> protocols, Vector<ByteString> extensions, Vector<HTTP::Header> additional_request_headers, Optional<HTTP::Proxy> proxy, RefPtr<DNS::LookupResult const> dns_result)
{
auto weak_self = make_weak_ptr<ConnectionFromClient>();
WebSocket::ConnectionInfo connection_info(move(url));
connection_info.set_origin(move(origin));
connection_info.set_protocols(move(protocols));
connection_info.set_extensions(move(extensions));
connection_info.set_headers(HTTP::HeaderList::create(move(additional_request_headers)));
if (dns_result)
connection_info.set_dns_result(dns_result.release_nonnull());
if (auto const& path = default_certificate_path(); !path.is_empty())
connection_info.set_root_certificates_path(path);
auto impl = WebSocketImplCurl::create(m_websocket_curl.handle, m_is_private);
impl->set_proxy(move(proxy));
impl->set_performance_origin(client_id(), originating_page_id);
auto connection = WebSocket::WebSocket::create(move(connection_info), move(impl));
connection->on_open = [self = weak_self, websocket_id]() {
if (auto strong_self = self.strong_ref())
strong_self->async_websocket_connected(websocket_id);
};
connection->on_message = [self = weak_self, websocket_id](WebSocket::Message message) {
auto strong_self = self.strong_ref();
if (!strong_self)
return;
auto const& data = message.data();
// NB: Large messages can exceed IPC::MAX_MESSAGE_PAYLOAD_SIZE and need shared memory.
if (data.size() >= Requests::WEBSOCKET_SHARED_MEMORY_THRESHOLD) {
auto buffer_or_error = Core::AnonymousBuffer::create_with_size(data.size());
if (buffer_or_error.is_error()) {
// NB: Inline fallback may exceed the IPC limit, and WebSocket messages cannot be skipped.
dbgln("WebSocket on_message: failed to allocate shared buffer for {} bytes: {}", data.size(), buffer_or_error.error());
strong_self->async_websocket_errored(websocket_id, to_underlying(Requests::WebSocket::Error::ServerClosedSocket));
if (auto* connection = strong_self->m_websockets.get(websocket_id).value_or({}))
connection->close(to_underlying(WebSocket::CloseStatusCode::MessageTooBig), "Message too big");
return;
}
auto buffer = buffer_or_error.release_value();
__builtin_memcpy(buffer.data<void>(), data.data(), data.size());
strong_self->async_websocket_received_shared(websocket_id, message.is_text(), move(buffer));
return;
}
strong_self->async_websocket_received(websocket_id, message.is_text(), data);
};
connection->on_message_bytes_transmitted = [self = weak_self, websocket_id](u64 byte_count) {
if (auto strong_self = self.strong_ref())
strong_self->async_websocket_transmitted(websocket_id, byte_count);
};
connection->on_error = [self = weak_self, websocket_id](auto message) {
if (auto strong_self = self.strong_ref())
strong_self->async_websocket_errored(websocket_id, (i32)message);
};
connection->on_close = [self = weak_self, websocket_id](u16 code, ByteString reason, bool was_clean) {
if (auto strong_self = self.strong_ref()) {
strong_self->async_websocket_closed(websocket_id, code, move(reason), was_clean);
Core::deferred_invoke([self, websocket_id] {
if (auto strong_self = self.strong_ref())
strong_self->m_websockets.remove(websocket_id);
});
}
};
connection->on_ready_state_change = [self = weak_self, websocket_id](auto state) {
if (auto strong_self = self.strong_ref())
strong_self->async_websocket_ready_state_changed(websocket_id, (u32)state);
};
connection->start();
m_websockets.set(websocket_id, move(connection));
}
void ConnectionFromClient::websocket_send(u64 websocket_id, bool is_text, ByteBuffer data)
{
if (auto* connection = m_websockets.get(websocket_id).value_or({}); connection && connection->ready_state() == WebSocket::ReadyState::Open)
connection->send(WebSocket::Message { move(data), is_text });
}
void ConnectionFromClient::websocket_send_shared(u64 websocket_id, bool is_text, Core::AnonymousBuffer data)
{
auto* connection = m_websockets.get(websocket_id).value_or({});
if (!connection || connection->ready_state() != WebSocket::ReadyState::Open)
return;
// Bound client-controlled allocations for copying and framing the message.
if (data.size() > IPC::MAX_MESSAGE_PAYLOAD_SIZE) {
dbgln("websocket_send_shared: refusing to send a {} byte message", data.size());
connection->close(to_underlying(WebSocket::CloseStatusCode::MessageTooBig), "Message too big");
return;
}
auto byte_buffer_or_error = ByteBuffer::copy(data.bytes());
if (byte_buffer_or_error.is_error()) {
dbgln("websocket_send_shared: failed to copy {} bytes from shared buffer: {}", data.size(), byte_buffer_or_error.error());
return;
}
connection->send(WebSocket::Message { byte_buffer_or_error.release_value(), is_text });
}
void ConnectionFromClient::websocket_close(u64 websocket_id, u16 code, ByteString reason)
{
m_websocket_cookie_requests.remove(websocket_id);
if (m_pending_websockets.remove(websocket_id)) {
fail_websocket(websocket_id, Requests::WebSocket::Error::CouldNotEstablishConnection);
return;
}
if (auto* connection = m_websockets.get(websocket_id).value_or({}); connection && connection->ready_state() != WebSocket::ReadyState::Closed)
connection->close(code, reason);
}
}