Skip to content

Truly independent web browser

11.3 KB
Raw Blame
/*
 * Copyright (c) 2022-2023, Linus Groh <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Debug.h>
#include <AK/TypeCasts.h>
#include <AK/Utf16String.h>
#include <LibJS/Runtime/PromiseCapability.h>
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/AbortSignal.h>
#include <LibWeb/Fetch/FetchMethod.h>
#include <LibWeb/Fetch/Fetching/ClientContextSnapshots.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
#include <LibWeb/Fetch/Request.h>
#include <LibWeb/Fetch/Response.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/WebIDL/Promise.h>

namespace Web::Fetch {

struct ResponseObjectHolder final : public JS::Cell {
    GC_CELL(ResponseObjectHolder, JS::Cell);
    GC_DECLARE_ALLOCATOR(ResponseObjectHolder);

    virtual void visit_edges(JS::Cell::Visitor& visitor) override
    {
        Base::visit_edges(visitor);
        visitor.visit(response_object);
    }

    GC::Ptr<Response> response_object;
};

GC_DEFINE_ALLOCATOR(ResponseObjectHolder);

// https://fetch.spec.whatwg.org/#deserialize-a-serialized-abort-reason
static JS::Value deserialize_serialized_abort_reason(JS::Realm& realm, Infrastructure::FetchController const& controller)
{
    // 1. Let fallbackError be an "AbortError" DOMException.
    auto fallback_error = WebIDL::AbortError::create(realm, "Fetch was aborted"_utf16);
    auto fallback_error_value = throw_completion(realm, fallback_error).value();

    // 2. Let deserializedError be fallbackError.
    JS::Value deserialized_error = fallback_error_value;

    // 3. If abortReason is non-null, then set deserializedError to StructuredDeserialize(abortReason, realm).
    //    If that threw an exception or returned undefined, then set deserializedError to fallbackError.
    if (controller.serialized_abort_reason().has_value()) {
        auto deserialized_error_or_exception = HTML::structured_deserialize(realm.vm(), controller.serialized_abort_reason().value(), realm);
        if (!deserialized_error_or_exception.is_exception() && !deserialized_error_or_exception.value().is_undefined())
            deserialized_error = deserialized_error_or_exception.value();
    }

    // 4. Return deserializedError.
    return deserialized_error;
}

// https://fetch.spec.whatwg.org/#dom-global-fetch
GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindings::RequestInit const& init)
{
    auto& vm = realm.vm();

    // 1. Let p be a new promise.
    auto promise_capability = WebIDL::create_promise(realm);

    // 2. Let requestObject be the result of invoking the initial value of Request as constructor with input and init
    //    as arguments. If this throws an exception, reject p with it and return p.
    auto exception_or_request_object = Request::create_with_settings(HTML::principal_realm_settings_object(realm), input, init);
    if (exception_or_request_object.is_exception()) {
        WebIDL::reject_promise_with_exception(promise_capability, exception_or_request_object.release_error());
        return promise_capability;
    }
    auto request_object = exception_or_request_object.release_value();

    // 3. Let request be requestObject’s request.
    auto request = request_object->request();

    // 4. If requestObject’s signal is aborted, then:
    if (request_object->signal()->aborted()) {
        // 1. Abort the fetch() call with p, request, null, and requestObject’s signal’s abort reason.
        abort_fetch(*promise_capability, request_object, nullptr, request_object->signal()->reason());

        // 2. Return p.
        return promise_capability;
    }

    // 5. Let globalObject be request’s client’s global object.
    auto& global_object = Fetching::resolve_client(request)->global_object();

    // FIXME: 6. If globalObject is a ServiceWorkerGlobalScope object, then set request’s service-workers mode to "none".
    (void)global_object;

    // 7. Let responseObject be null.
    auto response_object_holder = GC::Heap::the().allocate<ResponseObjectHolder>();

    // 8. Let relevantRealm be this’s relevant Realm.
    // NOTE: This assumes that the running execution context is for the fetch() function call.
    auto& relevant_realm = HTML::relevant_realm(*vm.running_execution_context().function);

    // 9. Let locallyAborted be false.
    // NOTE: This lets us reject promises with predictable timing, when the request to abort comes from the same thread
    //       as the call to fetch.
    auto locally_aborted = Fetching::RefCountedFlag::create(false);

    // 10. Let controller be null.
    auto controller_holder = Infrastructure::FetchControllerHolder::create();

    // NOTE: Step 11 is done out of order so that the controller is non-null when we capture the GCPtr by copy in the abort algorithm lambda.
    //       This is not observable, AFAICT.

    // 12. Set controller to the result of calling fetch given request and processResponse given response being these
    //     steps:
    auto process_response = GC::create_function(GC::Heap::the(), GC::captures(locally_aborted, promise_capability, request_object, response_object_holder, controller_holder, relevant_realm), [](auto& locally_aborted, auto& promise_capability, auto& request_object, auto& response_object_holder, auto& controller_holder, auto& relevant_realm, GC::Ref<Infrastructure::ResponseView> response) {
        // 1. If locallyAborted is true, then abort these steps.
        if (locally_aborted->value())
            return;

        // AD-HOC: Promise reactions need an execution context and incumbent callback settings.
        HTML::TemporaryExecutionContext execution_context { relevant_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };

        // 2. If response’s aborted flag is set, then:
        if (response->aborted()) {
            // 1. Let deserializedError be the result of deserialize a serialized abort reason given controller’s
            //    serialized abort reason and relevantRealm.
            auto deserialized_error = deserialize_serialized_abort_reason(relevant_realm, *controller_holder->controller());

            // 2. Abort the fetch() call with p, request, responseObject, and deserializedError.
            abort_fetch(*promise_capability, request_object, response_object_holder->response_object, deserialized_error);

            // 3. Abort these steps.
            return;
        }

        // 3. If response is a network error, then reject p with a TypeError and abort these steps.
        if (response->is_network_error()) {
            auto message = response->network_error_message().value_or("Response is a network error"_string);
            WebIDL::reject_promise(relevant_realm, promise_capability, JS::TypeError::create(relevant_realm, Utf16String::from_utf8(message)));
            return;
        }

        // 4. Set responseObject to the result of creating a Response object, given response, "immutable", and
        //    relevantRealm.
        response_object_holder->response_object = Response::create(response, Headers::Guard::Immutable);

        // 5. Resolve p with responseObject.
        auto response_value = Bindings::wrap(
            Bindings::host_defined_wrapper_world(relevant_realm),
            relevant_realm,
            GC::Ref { *response_object_holder->response_object });
        WebIDL::resolve_promise(relevant_realm, promise_capability, response_value);
    });
    Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Engine::BodyIntent::DeliverStreamToConsumerAgent };
    fetch_algorithms_input.process_response = process_response;
    // AD-HOC: Request holds its body's source and length, and requestObject its stream, which fetching reads. Its
    //         reader is acquired here, not when fetching reads the stream, so that script cannot lock the stream first.
    if (auto body = request_object->body_impl())
        fetch_algorithms_input.request_body_reader = Infrastructure::FetchAlgorithms::RequestBodyReader { *body, MUST(body->stream()->get_a_reader()) };
    controller_holder->set_controller(Fetching::fetch(realm, request, Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input))));

    // 11. Add the following abort steps to requestObject’s signal:
    (void)request_object->signal()->add_abort_algorithm(GC::create_function(GC::Heap::the(), GC::captures(locally_aborted, controller_holder, promise_capability, request_object, response_object_holder, relevant_realm), [](auto& locally_aborted, auto& controller_holder, auto& promise_capability, auto& request_object, auto& response_object_holder, auto& relevant_realm) {
        dbgln_if(WEB_FETCH_DEBUG, "Fetch: Request object signal's abort algorithm called");

        // 1. Set locallyAborted to true.
        locally_aborted->set_value(true);

        // 2. Assert: controller is non-null.
        VERIFY(controller_holder->controller());

        // 3. Abort controller with requestObject’s signal’s abort reason.
        controller_holder->controller()->abort(relevant_realm, request_object->signal()->reason());

        // AD-HOC: An execution context is required for Promise functions.
        HTML::TemporaryExecutionContext execution_context { relevant_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };

        // 4. Abort the fetch() call with p, request, responseObject, and requestObject’s signal’s abort reason.
        abort_fetch(*promise_capability, request_object, response_object_holder->response_object, request_object->signal()->reason());
    }));

    // 13. Return p.
    return promise_capability;
}

// https://fetch.spec.whatwg.org/#abort-fetch
// NB: request is given as the Request object holding its body's stream.
void abort_fetch(WebIDL::Promise const& promise, GC::Ref<Request> request_object, GC::Ptr<Response> response_object, JS::Value error)
{
    dbgln_if(WEB_FETCH_DEBUG, "Fetch: Aborting fetch with: request @ {}, error = {}", request_object->request().ptr(), error);

    // 1. Reject promise with error.
    // NOTE: This is a no-op if promise has already fulfilled.
    WebIDL::reject_promise(promise, error);

    // 2. If request’s body is non-null and is readable, then cancel request’s body with error.
    if (auto body = request_object->body_impl(); body && body->stream()->is_readable()) {
        // NOTE: Cancel here is different than the cancel method of stream and refers to https://streams.spec.whatwg.org/#readablestream-cancel
        body->stream()->cancel(error);
    }

    // 3. If responseObject is null, then return.
    if (response_object == nullptr)
        return;

    // 4. Let response be responseObject’s response.
    auto response = response_object->response();

    // 5. If response’s body is non-null and is readable, then error response’s body with error.
    if (response->body()) {
        auto stream = response->body()->stream();
        if (stream->is_readable()) {
            stream->error(error);
        }
    }
}

}