Skip to main content

script/fetch/
fetch.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::Cell;
8use std::rc::Rc;
9use std::time::Duration;
10
11use bytes::Bytes;
12use js::context::JSContext;
13use js::gc::Rootable;
14use js::jsapi::ExceptionStackBehavior;
15use js::jsval::UndefinedValue;
16use js::realm::CurrentRealm;
17use js::rust::HandleValue;
18use net_traits::blob_url_store::UrlWithBlobClaim;
19use net_traits::fetch::fetch_controller::FetchController;
20use net_traits::request::{
21    CorsSettings, CredentialsMode, Destination, Referrer, Request as NetTraitsRequest,
22    RequestBuilder, RequestId, RequestMode, ServiceWorkersMode,
23};
24use net_traits::{
25    CoreResourceMsg, CoreResourceThread, ExposedMetadata, FetchChannels, FetchMetadata,
26    FetchResponseMsg, FilteredMetadata, Metadata, NetworkError, ResourceFetchTiming, fetch_async,
27};
28use pixels::CorsStatus;
29use rustc_hash::FxHashMap;
30use script_bindings::cformat;
31use script_bindings::js::{JS_IsExceptionPending, JS_SetPendingException};
32use script_bindings::root::Dom;
33use serde::{Deserialize, Serialize};
34use servo_base::generic_channel::GenericCallback;
35use servo_base::id::WebViewId;
36use servo_url::ServoUrl;
37use timers::TimerEventRequest;
38use uuid::Uuid;
39
40use crate::dom::TracedPromise;
41use crate::dom::abortsignal::AbortAlgorithm;
42use crate::dom::bindings::codegen::Bindings::AbortSignalBinding::AbortSignalMethods;
43use crate::dom::bindings::codegen::Bindings::RequestBinding::{
44    RequestInfo, RequestInit, RequestMethods,
45};
46use crate::dom::bindings::codegen::Bindings::ResponseBinding::Response_Binding::ResponseMethods;
47use crate::dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType;
48use crate::dom::bindings::codegen::Bindings::WindowBinding::{DeferredRequestInit, WindowMethods};
49use crate::dom::bindings::error::{Error, Fallible};
50use crate::dom::bindings::inheritance::Castable;
51use crate::dom::bindings::num::Finite;
52use crate::dom::bindings::refcounted::Trusted;
53use crate::dom::bindings::root::DomRoot;
54use crate::dom::bindings::trace::NoTrace;
55use crate::dom::csp::{GlobalCspReporting, Violation};
56use crate::dom::fetchlaterresult::FetchLaterResult;
57use crate::dom::globalscope::GlobalScope;
58use crate::dom::headers::Guard;
59use crate::dom::performance::performanceresourcetiming::InitiatorType;
60use crate::dom::promise::{Promise, RootedPromise};
61use crate::dom::request::Request;
62use crate::dom::response::Response;
63use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
64use crate::dom::window::Window;
65use crate::fetch::body::BodyMixin;
66use crate::fetch::network_listener::{
67    self, FetchResponseListener, NetworkListener, ResourceTimingListener, submit_timing_data,
68};
69use crate::realms::enter_auto_realm;
70
71/// An id to differentiate one deferred fetch record from another.
72#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
73pub(crate) struct DeferredFetchRecordId(Uuid);
74
75impl Default for DeferredFetchRecordId {
76    fn default() -> Self {
77        Self(Uuid::new_v4())
78    }
79}
80
81pub(crate) type QueuedDeferredFetchRecord = Rc<DeferredFetchRecord>;
82
83/// <https://fetch.spec.whatwg.org/#fetch-record>
84#[derive(JSTraceable, MallocSizeOf)]
85#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
86pub(crate) struct FetchRecord {
87    /// <https://fetch.spec.whatwg.org/#concept-fetch-record-fetch>
88    #[no_trace]
89    controller: Option<FetchController>,
90    /// If this record was created by a call to `fetch()`, this holds the [`Request`]
91    /// that started this operation.
92    request: Option<Dom<Request>>,
93    /// Whether canceling this fetch when aborting a document should mark
94    /// the document as unsalvageable for the back-forward cache (BFCache).
95    cancelling_invalidates_salvageability: bool,
96}
97
98/// <https://fetch.spec.whatwg.org/#concept-fetch-group>
99#[derive(JSTraceable, MallocSizeOf)]
100#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
101pub(crate) struct FetchGroup {
102    /// The [`CoreResourceThread`] for this [`FetchGroup`].
103    #[no_trace]
104    core_resource_thread: CoreResourceThread,
105    /// <https://fetch.spec.whatwg.org/#fetch-group-deferred-fetch-records>
106    #[conditional_malloc_size_of]
107    #[no_trace]
108    pub(crate) deferred_fetch_records: FxHashMap<DeferredFetchRecordId, QueuedDeferredFetchRecord>,
109    /// <https://fetch.spec.whatwg.org/#concept-fetch-record>
110    pub(crate) fetch_records: FxHashMap<NoTrace<RequestId>, FetchRecord>,
111}
112
113impl FetchGroup {
114    pub(crate) fn new(core_resource_thread: CoreResourceThread) -> Self {
115        Self {
116            core_resource_thread,
117            deferred_fetch_records: Default::default(),
118            fetch_records: Default::default(),
119        }
120    }
121
122    pub(crate) fn fetch<Listener: FetchResponseListener>(
123        &mut self,
124        request: RequestBuilder,
125        listener: NetworkListener<Listener>,
126        request_object: Option<&Request>,
127    ) {
128        self.fetch_with_options(request, listener, request_object, true);
129    }
130
131    pub(crate) fn fetch_with_options<Listener: FetchResponseListener>(
132        &mut self,
133        request: RequestBuilder,
134        listener: NetworkListener<Listener>,
135        request_object: Option<&Request>,
136        cancelling_invalidates_salvageability: bool,
137    ) {
138        self.fetch_records.insert(
139            NoTrace(request.id),
140            FetchRecord {
141                controller: Some(FetchController::new(
142                    request.id,
143                    request.keep_alive,
144                    self.core_resource_thread.clone(),
145                )),
146                request: request_object.map(Dom::from_ref),
147                cancelling_invalidates_salvageability,
148            },
149        );
150        fetch_async(
151            &self.core_resource_thread,
152            request,
153            None,
154            listener.into_callback(),
155        );
156    }
157
158    pub(crate) fn deferred_fetches(&self) -> Vec<QueuedDeferredFetchRecord> {
159        self.deferred_fetch_records.values().cloned().collect()
160    }
161
162    fn append_deferred_fetch(
163        &mut self,
164        deferred_record: DeferredFetchRecord,
165    ) -> DeferredFetchRecordId {
166        let deferred_fetch_record_id = DeferredFetchRecordId::default();
167        self.deferred_fetch_records
168            .insert(deferred_fetch_record_id, Rc::new(deferred_record));
169        deferred_fetch_record_id
170    }
171
172    pub(crate) fn deferred_fetch_record_for_id(
173        &self,
174        deferred_fetch_record_id: &DeferredFetchRecordId,
175    ) -> QueuedDeferredFetchRecord {
176        self.deferred_fetch_records
177            .get(deferred_fetch_record_id)
178            .expect("Should always use a generated fetch_record_id instead of passing your own")
179            .clone()
180    }
181
182    pub(crate) fn fetch_controller(
183        &mut self,
184        request_id: &RequestId,
185    ) -> Option<&mut FetchController> {
186        self.fetch_records
187            .get_mut(&NoTrace(*request_id))?
188            .controller
189            .as_mut()
190    }
191
192    pub(crate) fn fetch_call_request(&self, request_id: &RequestId) -> Option<DomRoot<Request>> {
193        let fetch_record = self.fetch_records.get(&NoTrace(*request_id))?;
194        let request = fetch_record.request.as_ref()?;
195        Some(request.as_rooted())
196    }
197
198    /// <https://fetch.spec.whatwg.org/#concept-fetch-group-terminate>
199    ///
200    /// Returns `true` if any fetches were cancelled and `false` otherwise.
201    pub(crate) fn terminate(&mut self, global: &GlobalScope) -> bool {
202        // Step 1. For each fetch record record of fetchGroup’s fetch records,
203        // if record’s controller is non-null and record’s request’s done flag
204        // is unset and keepalive is false, terminate record’s controller.
205        //
206        // Fetches that are done are removed from our set of fetch records as soon as they finish,
207        // so they do not need to be skipped here. This approach differs from the specification
208        // text, but is behaviorally identical.
209        let mut cancelled_any = false;
210        self.fetch_records.retain(|_, fetch_record| {
211            let Some(controller) = fetch_record.controller.as_mut() else {
212                return false;
213            };
214            if !controller.keep_alive() {
215                controller.terminate();
216                if fetch_record.cancelling_invalidates_salvageability {
217                    cancelled_any = true;
218                }
219                return false;
220            }
221            true
222        });
223
224        // Step 2. Process deferred fetches for fetchGroup.
225        self.process_deferred_fetches(global);
226
227        cancelled_any
228    }
229
230    /// <https://fetch.spec.whatwg.org/#process-deferred-fetches>
231    pub(crate) fn process_deferred_fetches(&mut self, global: &GlobalScope) {
232        // Step 1. For each deferred fetch record deferredRecord of fetchGroup’s
233        // deferred fetch records, process a deferred fetch deferredRecord.
234        for deferred_fetch in self.deferred_fetches() {
235            self.process_a_deferred_fetch(global, &deferred_fetch);
236        }
237    }
238
239    /// <https://fetch.spec.whatwg.org/#process-a-deferred-fetch>
240    pub(crate) fn process_a_deferred_fetch(
241        &mut self,
242        global: &GlobalScope,
243        deferred_fetch: &DeferredFetchRecord,
244    ) {
245        // Step 1. If deferredRecord’s invoke state is not "pending", then return.
246        if deferred_fetch.invoke_state.get() != DeferredFetchRecordInvokeState::Pending {
247            return;
248        }
249        // Step 2. Set deferredRecord’s invoke state to "sent".
250        deferred_fetch
251            .invoke_state
252            .set(DeferredFetchRecordInvokeState::Sent);
253        // Step 3. Fetch deferredRecord’s request.
254        let fetch_later_listener = FetchLaterListener {
255            url: deferred_fetch.request.url(),
256        };
257        let task_source = global.task_manager().networking_task_source().to_sendable();
258        self.fetch(
259            request_init_from_request(deferred_fetch.request.clone(), global),
260            NetworkListener::new(fetch_later_listener, task_source),
261            None, /* state */
262        );
263        // Step 4 is handled by caller
264    }
265
266    pub(crate) fn mark_fetch_request_as_done(&mut self, request_id: &RequestId) {
267        self.fetch_records.remove(&NoTrace(*request_id));
268    }
269}
270
271fn request_init_from_request(request: NetTraitsRequest, global: &GlobalScope) -> RequestBuilder {
272    let mut builder = RequestBuilder::new(
273        request.target_webview_id,
274        request.url_with_blob_claim(),
275        request.referrer,
276    )
277    .method(request.method)
278    .headers(request.headers)
279    .unsafe_request(request.unsafe_request)
280    .body(request.body)
281    .destination(request.destination)
282    .synchronous(request.synchronous)
283    .mode(request.mode)
284    .cache_mode(request.cache_mode)
285    .use_cors_preflight(request.use_cors_preflight)
286    .credentials_mode(request.credentials_mode)
287    .use_url_credentials(request.use_url_credentials)
288    .referrer_policy(request.referrer_policy)
289    .pipeline_id(request.pipeline_id)
290    .redirect_mode(request.redirect_mode)
291    .integrity_metadata(request.integrity_metadata)
292    .cryptographic_nonce_metadata(request.cryptographic_nonce_metadata)
293    .parser_metadata(request.parser_metadata)
294    .initiator(request.initiator)
295    .client(global.request_client(None))
296    .response_tainting(request.response_tainting);
297    builder.id = request.id;
298    builder.reload_navigation = request.reload_navigation;
299    builder.history_navigation = request.history_navigation;
300    builder
301}
302
303/// <https://fetch.spec.whatwg.org/#abort-fetch>
304fn abort_fetch_call(
305    promise: &RootedPromise,
306    request: &Request,
307    response_object: Option<&Response>,
308    abort_reason: HandleValue,
309    global: &GlobalScope,
310    cx: &mut JSContext,
311) {
312    // Step 1. Reject promise with error.
313    promise.reject(cx, abort_reason);
314    // Step 2. If request’s body is non-null and is readable, then cancel request’s body with error.
315    if let Some(body) = request.body() &&
316        body.is_readable()
317    {
318        body.cancel(cx, global, abort_reason);
319    }
320    // Step 3. If responseObject is null, then return.
321    // Step 4. Let response be responseObject’s response.
322    let Some(response) = response_object else {
323        return;
324    };
325    // Step 5. If response’s body is non-null and is readable, then error response’s body with error.
326    if let Some(body) = response.body() &&
327        body.is_readable()
328    {
329        body.error(cx, abort_reason);
330    }
331}
332
333/// <https://fetch.spec.whatwg.org/#dom-global-fetch>
334#[expect(non_snake_case)]
335pub(crate) fn Fetch(
336    global: &GlobalScope,
337    input: RequestInfo,
338    init: &RequestInit,
339    cx: &mut CurrentRealm,
340) -> RootedPromise {
341    // Step 1. Let p be a new promise.
342    let promise = Promise::new_in_realm(cx);
343
344    // Step 7. Let responseObject be null.
345    // NOTE: We do initialize the object earlier so we can use it to track errors.
346    let response = Response::new_fetch_response(cx, global);
347    response.Headers(cx).set_guard(Guard::Immutable);
348
349    // Step 2. Let requestObject be the result of invoking the initial value of Request as constructor
350    //         with input and init as arguments. If this throws an exception, reject p with it and return p.
351    rooted!(&in(cx) let mut fetch_call_state = FetchCallState {
352        promise: promise.to_traced(),
353        response: response.as_traced(),
354        locally_aborted: Cell::new(false),
355    });
356    let request_object =
357        match Request::constructor(cx, global, None, input, init, Some(&fetch_call_state)) {
358            Err(error) => {
359                response.error_stream(cx, error.clone());
360                promise.reject_error(cx, error);
361                return promise;
362            },
363            Ok(request) => request,
364        };
365    // Step 3. Let request be requestObject’s request.
366    let request = request_object.request().clone();
367    let request_id = request.id;
368
369    // Step 4. If requestObject’s signal is aborted, then:
370    let signal = request_object.Signal();
371    if signal.aborted() {
372        // Step 4.1. Abort the fetch() call with p, request, null, and requestObject’s signal’s abort reason.
373        rooted!(&in(cx) let mut abort_reason = UndefinedValue());
374        signal.Reason(abort_reason.handle_mut());
375        abort_fetch_call(
376            &promise,
377            &request_object,
378            None,
379            abort_reason.handle(),
380            global,
381            cx,
382        );
383        // Step 4.2. Return p.
384        return promise;
385    }
386
387    // Step 5. Let globalObject be request’s client’s global object.
388    // NOTE:   We already get the global object as an argument
389    let mut request_builder = request_init_from_request(request, global);
390
391    // Step 6. If globalObject is a ServiceWorkerGlobalScope object, then set request’s
392    //         service-workers mode to "none".
393    if global.is::<ServiceWorkerGlobalScope>() {
394        request_builder.service_workers_mode = ServiceWorkersMode::None;
395    }
396
397    // Step 8. Let relevantRealm be this’s relevant realm.
398    //
399    // Is `comp` as argument
400
401    // Step 9. Let locallyAborted be false.
402    // Step 10. Let controller be null.
403    let fetch_context = FetchContext {
404        request_id,
405        url: request_builder.url.url(),
406    };
407    let network_listener = NetworkListener::new(
408        fetch_context,
409        global.task_manager().networking_task_source().to_sendable(),
410    );
411
412    // Step 11. Add the following abort steps to requestObject’s signal:
413    signal.add(&AbortAlgorithm::Fetch(request_object.as_traced()));
414
415    // Step 12. Set controller to the result of calling fetch given request and
416    // processResponse given response being these steps:
417    global
418        .fetch_group_mut()
419        .fetch(request_builder, network_listener, Some(&request_object));
420
421    // Step 13. Return p.
422    promise
423}
424
425/// <https://fetch.spec.whatwg.org/#queue-a-deferred-fetch>
426fn queue_deferred_fetch(
427    request: NetTraitsRequest,
428    activate_after: Finite<f64>,
429    global: &GlobalScope,
430) -> DeferredFetchRecordId {
431    let trusted_global = Trusted::new(global);
432    let mut request = request;
433    // Step 1. Populate request from client given request.
434    request.client = Some(global.request_client(None));
435    request.populate_request_from_client();
436    // Step 2. Set request’s service-workers mode to "none".
437    request.service_workers_mode = ServiceWorkersMode::None;
438    // Step 3. Set request’s keepalive to true.
439    request.keep_alive = true;
440    // Step 4. Let deferredRecord be a new deferred fetch record whose request is request, and whose notify invoked is onActivatedWithoutTermination.
441    let deferred_record = DeferredFetchRecord {
442        request,
443        invoke_state: Cell::new(DeferredFetchRecordInvokeState::Pending),
444        activated: Cell::new(false),
445    };
446
447    // Step 5. Append deferredRecord to request’s client’s fetch group’s deferred fetch records.
448    let deferred_fetch_record_id = global
449        .fetch_group_mut()
450        .append_deferred_fetch(deferred_record);
451
452    // Step 6. If activateAfter is non-null, then run the following steps in parallel:
453    global.schedule_timer(TimerEventRequest {
454        callback: Box::new(move || {
455            // Step 6.2. Process deferredRecord.
456            let global = trusted_global.root();
457            let mut fetch_group = global.fetch_group_mut();
458            let deferred_fetch_record =
459                fetch_group.deferred_fetch_record_for_id(&deferred_fetch_record_id);
460            fetch_group.process_a_deferred_fetch(&global, &deferred_fetch_record);
461
462            // Last step of https://fetch.spec.whatwg.org/#process-a-deferred-fetch
463            //
464            // Step 4. Queue a global task on the deferred fetch task source with
465            // deferredRecord’s request’s client’s global object to run deferredRecord’s notify invoked.
466            let trusted_global = trusted_global.clone();
467            global.task_manager().deferred_fetch_task_source().queue(
468                task!(notify_deferred_record: move || {
469                    trusted_global.root().fetch_group().deferred_fetch_record_for_id(&deferred_fetch_record_id).activate();
470                }),
471            );
472        }),
473        // Step 6.1. The user agent should wait until any of the following conditions is met:
474        duration: Duration::from_millis(*activate_after as u64),
475    });
476    // Step 7. Return deferredRecord.
477    deferred_fetch_record_id
478}
479
480/// <https://fetch.spec.whatwg.org/#dom-window-fetchlater>
481#[expect(non_snake_case)]
482pub(crate) fn FetchLater(
483    cx: &mut JSContext,
484    window: &Window,
485    input: RequestInfo,
486    init: &DeferredRequestInit,
487) -> Fallible<DomRoot<FetchLaterResult>> {
488    let global_scope = window.upcast();
489    let document = window.Document();
490    // Step 1. Let requestObject be the result of invoking the initial value
491    // of Request as constructor with input and init as arguments.
492    let request_object = Request::constructor(
493        cx,
494        global_scope,
495        None,
496        input,
497        &init.parent,
498        None, /* state */
499    )?;
500    // Step 2. If requestObject’s signal is aborted, then throw signal’s abort reason.
501    let signal = request_object.Signal();
502    if signal.aborted() {
503        rooted!(&in(cx) let mut abort_reason = UndefinedValue());
504        signal.Reason(abort_reason.handle_mut());
505        assert!(!JS_IsExceptionPending(cx));
506        JS_SetPendingException(cx, abort_reason.handle(), ExceptionStackBehavior::Capture);
507        return Err(Error::JSFailed);
508    }
509    // Step 3. Let request be requestObject’s request.
510    let request = request_object.request();
511    // Step 4. Let activateAfter be null.
512    let mut activate_after = Finite::wrap(0_f64);
513    // Step 5. If init is given and init["activateAfter"] exists, then set
514    // activateAfter to init["activateAfter"].
515    if let Some(init_activate_after) = init.activateAfter.as_ref() {
516        activate_after = *init_activate_after;
517    }
518    // Step 6. If activateAfter is less than 0, then throw a RangeError.
519    if *activate_after < 0.0 {
520        return Err(Error::Range(c"activateAfter must be at least 0".to_owned()));
521    }
522    // Step 7. If this’s relevant global object’s associated document is not fully active, then throw a TypeError.
523    if !document.is_fully_active() {
524        return Err(Error::Type(c"Document is not fully active".to_owned()));
525    }
526    let url = request.url();
527    // Step 8. If request’s URL’s scheme is not an HTTP(S) scheme, then throw a TypeError.
528    if !matches!(url.scheme(), "http" | "https") {
529        return Err(Error::Type(c"URL is not http(s)".to_owned()));
530    }
531    // Step 9. If request’s URL is not a potentially trustworthy URL, then throw a SecurityError.
532    if !url.is_potentially_trustworthy() {
533        return Err(Error::Type(c"URL is not trustworthy".to_owned()));
534    }
535    // Step 10. If request’s body is not null, and request’s body length is null, then throw a TypeError.
536    if request
537        .body
538        .as_ref()
539        .is_some_and(|body| body.len().is_none())
540    {
541        return Err(Error::Type(c"Body is empty".to_owned()));
542    }
543    // Step 11. If the available deferred-fetch quota given request’s client and request’s URL’s
544    // origin is less than request’s total request length, then throw a "QuotaExceededError" DOMException.
545    let quota = document.available_deferred_fetch_quota(request.url().origin());
546    let requested = request.total_request_length() as isize;
547    if quota < requested {
548        return Err(Error::QuotaExceeded {
549            quota: Some(Finite::wrap(quota as f64)),
550            requested: Some(Finite::wrap(requested as f64)),
551        });
552    }
553    // Step 12. Let activated be false.
554    // Step 13. Let deferredRecord be the result of calling queue a deferred fetch given request,
555    // activateAfter, and the following step: set activated to true.
556    let deferred_record_id = queue_deferred_fetch(request.clone(), activate_after, global_scope);
557    // Step 14. Add the following abort steps to requestObject’s signal: Set deferredRecord’s invoke state to "aborted".
558    signal.add(&AbortAlgorithm::FetchLater(deferred_record_id));
559    // Step 15. Return a new FetchLaterResult whose activated getter steps are to return activated.
560    Ok(FetchLaterResult::new(cx, window, deferred_record_id))
561}
562
563/// <https://fetch.spec.whatwg.org/#deferred-fetch-record-invoke-state>
564#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
565pub(crate) enum DeferredFetchRecordInvokeState {
566    Pending,
567    Sent,
568    Aborted,
569}
570
571/// <https://fetch.spec.whatwg.org/#deferred-fetch-record>
572#[derive(MallocSizeOf)]
573pub(crate) struct DeferredFetchRecord {
574    /// <https://fetch.spec.whatwg.org/#deferred-fetch-record-request>
575    pub(crate) request: NetTraitsRequest,
576    /// <https://fetch.spec.whatwg.org/#deferred-fetch-record-invoke-state>
577    pub(crate) invoke_state: Cell<DeferredFetchRecordInvokeState>,
578    activated: Cell<bool>,
579}
580
581impl DeferredFetchRecord {
582    /// Part of step 13 of <https://fetch.spec.whatwg.org/#dom-window-fetchlater>
583    fn activate(&self) {
584        // and the following step: set activated to true.
585        self.activated.set(true);
586    }
587    /// Part of step 14 of <https://fetch.spec.whatwg.org/#dom-window-fetchlater>
588    pub(crate) fn abort(&self) {
589        // Set deferredRecord’s invoke state to "aborted".
590        self.invoke_state
591            .set(DeferredFetchRecordInvokeState::Aborted);
592    }
593    /// Part of step 15 of <https://fetch.spec.whatwg.org/#dom-window-fetchlater>
594    pub(crate) fn activated_getter_steps(&self) -> bool {
595        // whose activated getter steps are to return activated.
596        self.activated.get()
597    }
598}
599
600/// The captured state that is kept during a fetch operation.
601#[derive(Clone, JSTraceable, MallocSizeOf)]
602#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
603pub(crate) struct FetchCallState {
604    pub promise: TracedPromise,
605    pub response: Dom<Response>,
606    pub locally_aborted: Cell<bool>,
607}
608
609impl Rootable for FetchCallState {}
610
611impl FetchCallState {
612    /// Step 11 of <https://fetch.spec.whatwg.org/#dom-global-fetch>
613    pub(crate) fn abort_fetch(
614        &self,
615        cx: &mut JSContext,
616        request: &Request,
617        abort_reason: HandleValue,
618        global: &GlobalScope,
619    ) {
620        // Step 11.1. Set locallyAborted to true.
621        self.locally_aborted.set(true);
622
623        // Step 11.2. Assert: controller is non-null.
624        //
625        // Note: We currently prune fetch records that have finished (behaviorally
626        // equivalent to the specification and better for memory usage), so it might be
627        // the case that the `FetchRecord` is gone and the controller inaccessible.
628
629        // Step 11.3. Abort controller with requestObject’s signal’s abort reason.
630        if let Some(controller) = global
631            .fetch_group_mut()
632            .fetch_controller(&request.request().id)
633        {
634            controller.abort();
635        }
636
637        // Step 11.4. Abort the fetch() call with p, request, responseObject,
638        // and requestObject’s signal’s abort reason.
639        let promise = self.promise.root(cx);
640        abort_fetch_call(
641            &promise,
642            request,
643            Some(&self.response),
644            abort_reason,
645            global,
646            cx,
647        );
648    }
649
650    pub(crate) fn process_response(
651        &self,
652        cx: &mut JSContext,
653        fetch_metadata: Result<FetchMetadata, NetworkError>,
654    ) {
655        // Step 12.1. If locallyAborted is true, then abort these steps.
656        if self.locally_aborted.get() {
657            return;
658        }
659        let mut realm = enter_auto_realm(cx, &*self.promise);
660        let cx = &mut realm.current_realm();
661        match fetch_metadata {
662            // Step 12.3. If response is a network error, then reject
663            // p with a TypeError and abort these steps.
664            Err(error) => {
665                self.promise
666                    .reject_error(cx, Error::Type(cformat!("Network error: {:?}", error)));
667                self.response.set_type(cx, DOMResponseType::Error);
668                self.response
669                    .error_stream(cx, Error::Type(c"Network error occurred".to_owned()));
670                return;
671            },
672            // Step 12.4. Set responseObject to the result of creating a Response object,
673            // given response, "immutable", and relevantRealm.
674            Ok(metadata) => match metadata {
675                FetchMetadata::Unfiltered(m) => {
676                    fill_headers_with_metadata(cx, &self.response, m.into());
677                    self.response.set_type(cx, DOMResponseType::Default);
678                },
679                FetchMetadata::Filtered { filtered, .. } => match filtered {
680                    FilteredMetadata::Basic(m) => {
681                        fill_headers_with_metadata(cx, &self.response, m);
682                        self.response.set_type(cx, DOMResponseType::Basic);
683                    },
684                    FilteredMetadata::Cors(m) => {
685                        fill_headers_with_metadata(cx, &self.response, m);
686                        self.response.set_type(cx, DOMResponseType::Cors);
687                    },
688                    FilteredMetadata::Opaque => {
689                        self.response.set_type(cx, DOMResponseType::Opaque);
690                    },
691                    FilteredMetadata::OpaqueRedirect(url) => {
692                        self.response.set_type(cx, DOMResponseType::Opaqueredirect);
693                        self.response.set_final_url(url);
694                    },
695                },
696            },
697        }
698
699        // Step 12.5. Resolve p with responseObject.
700        self.promise.resolve_native(cx, &*self.response);
701    }
702
703    pub(crate) fn process_response_chunk(&self, cx: &mut JSContext, chunk: Bytes) {
704        self.response.stream_chunk(cx, chunk);
705    }
706
707    pub(crate) fn process_response_eof(
708        &self,
709        cx: &mut JSContext,
710        response: &Result<(), NetworkError>,
711    ) {
712        let mut realm = enter_auto_realm(cx, &*self.response);
713        let cx = &mut realm.current_realm();
714        if let Err(NetworkError::DecompressionError) = response {
715            self.response
716                .error_stream(cx, Error::Type(c"Network error occurred".to_owned()));
717        }
718        self.response.finish(cx);
719        // TODO
720        // ... trailerObject is not supported in Servo yet.
721    }
722}
723
724#[derive(JSTraceable, MallocSizeOf)]
725pub(crate) struct FetchContext {
726    #[no_trace]
727    request_id: RequestId,
728    #[no_trace]
729    url: ServoUrl,
730}
731
732/// Step 12 of <https://fetch.spec.whatwg.org/#dom-global-fetch>
733impl FetchResponseListener for FetchContext {
734    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {
735        // TODO
736    }
737
738    fn process_response(
739        &mut self,
740        cx: &mut JSContext,
741        global: &GlobalScope,
742        request_id: RequestId,
743        fetch_metadata: Result<FetchMetadata, NetworkError>,
744    ) {
745        let Some(request) = global.fetch_group().fetch_call_request(&request_id) else {
746            return;
747        };
748        request.process_response(cx, fetch_metadata);
749    }
750
751    fn process_response_chunk(
752        &mut self,
753        cx: &mut JSContext,
754        global: &GlobalScope,
755        request_id: RequestId,
756        chunk: Bytes,
757    ) {
758        let Some(call_state) = global.fetch_group().fetch_call_request(&request_id) else {
759            return;
760        };
761        call_state.process_response_chunk(cx, chunk);
762    }
763
764    fn process_response_eof(
765        self,
766        cx: &mut JSContext,
767        global: &GlobalScope,
768        request_id: RequestId,
769        response: Result<(), NetworkError>,
770        timing: ResourceFetchTiming,
771    ) {
772        let call_state = global.fetch_group().fetch_call_request(&request_id);
773        if let Some(call_state) = call_state {
774            call_state.process_response_eof(cx, &response);
775        };
776
777        // navigation submission is handled in servoparser/mod.rs
778        network_listener::submit_timing(cx, global, &self, &response, &timing);
779    }
780
781    fn process_csp_violations(
782        &mut self,
783        cx: &mut JSContext,
784        global: &GlobalScope,
785        _request_id: RequestId,
786        violations: Vec<Violation>,
787    ) {
788        global.report_csp_violations(cx, violations, None, None);
789    }
790}
791
792impl ResourceTimingListener for FetchContext {
793    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
794        (InitiatorType::Fetch, self.url.clone())
795    }
796}
797
798struct FetchLaterListener {
799    /// URL of this request.
800    url: ServoUrl,
801}
802
803impl FetchResponseListener for FetchLaterListener {
804    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
805
806    fn process_response(
807        &mut self,
808        _: &mut JSContext,
809        _: &GlobalScope,
810        _: RequestId,
811        fetch_metadata: Result<FetchMetadata, NetworkError>,
812    ) {
813        _ = fetch_metadata;
814    }
815
816    fn process_response_chunk(
817        &mut self,
818        _: &mut JSContext,
819        _: &GlobalScope,
820        _: RequestId,
821        chunk: Bytes,
822    ) {
823        _ = chunk;
824    }
825
826    fn process_response_eof(
827        self,
828        cx: &mut JSContext,
829        global: &GlobalScope,
830        _: RequestId,
831        response: Result<(), NetworkError>,
832        timing: ResourceFetchTiming,
833    ) {
834        network_listener::submit_timing(cx, global, &self, &response, &timing);
835    }
836
837    fn process_csp_violations(
838        &mut self,
839        cx: &mut JSContext,
840        global: &GlobalScope,
841        _request_id: RequestId,
842        violations: Vec<Violation>,
843    ) {
844        global.report_csp_violations(cx, violations, None, None);
845    }
846}
847
848impl ResourceTimingListener for FetchLaterListener {
849    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
850        (InitiatorType::Fetch, self.url.clone())
851    }
852}
853
854fn fill_headers_with_metadata(cx: &mut JSContext, r: &Response, m: ExposedMetadata) {
855    r.set_headers(cx, Some(m.headers));
856    r.set_status(&m.status);
857    r.set_final_url(m.final_url);
858    r.set_redirected(m.redirected);
859}
860
861pub(crate) trait CspViolationsProcessor {
862    fn process_csp_violations(&self, cx: &mut JSContext, violations: Vec<Violation>);
863}
864
865/// Convenience function for synchronously loading a whole resource.
866pub(crate) fn load_whole_resource(
867    request: RequestBuilder,
868    core_resource_thread: &CoreResourceThread,
869    global: &GlobalScope,
870    csp_violations_processor: &dyn CspViolationsProcessor,
871    cx: &mut JSContext,
872) -> Result<(Metadata, Vec<u8>, bool), NetworkError> {
873    let (action_sender, action_receiver) = GenericCallback::new_blocking().unwrap();
874    let url = request.url.url();
875    core_resource_thread
876        .send(CoreResourceMsg::Fetch(
877            request,
878            FetchChannels::ResponseMsg(action_sender),
879        ))
880        .unwrap();
881
882    let mut buf = vec![];
883    let mut metadata = None;
884    let mut muted_errors = false;
885    loop {
886        match action_receiver.recv().unwrap() {
887            FetchResponseMsg::ProcessRequestBody(..) => {},
888            FetchResponseMsg::ProcessResponse(_, Ok(m)) => {
889                muted_errors = m.cors_status() == CorsStatus::Unsafe;
890                metadata = Some(m.into());
891            },
892            FetchResponseMsg::ProcessResponseChunk(_, data) => buf.extend_from_slice(&data),
893            FetchResponseMsg::ProcessResponseEOF(_, Ok(_), _) => {
894                let metadata: Metadata = metadata.unwrap();
895                if let Some(timing) = &metadata.timing {
896                    submit_timing_data(cx, global, url, InitiatorType::Other, timing);
897                }
898                return Ok((metadata, buf, muted_errors));
899            },
900            FetchResponseMsg::ProcessResponse(_, Err(e)) |
901            FetchResponseMsg::ProcessResponseEOF(_, Err(e), _) => return Err(e),
902            FetchResponseMsg::ProcessCspViolations(_, violations) => {
903                csp_violations_processor.process_csp_violations(cx, violations);
904            },
905            FetchResponseMsg::ProcessContentLength(_request_id, size) => {
906                buf.reserve(size.saturating_sub(buf.len()))
907            },
908        }
909    }
910}
911
912pub(crate) trait RequestWithGlobalScope {
913    fn with_global_scope(self, global: &GlobalScope) -> Self;
914}
915
916impl RequestWithGlobalScope for RequestBuilder {
917    fn with_global_scope(self, global: &GlobalScope) -> Self {
918        self.client(global.request_client(None))
919            .pipeline_id(Some(global.pipeline_id()))
920    }
921}
922
923/// <https://html.spec.whatwg.org/multipage/#create-a-potential-cors-request>
924/// This function is temporary, since it does not ensure that blob URLs are claimed
925/// appropriately. All callers must migrate to create_a_potential_cors_request_with_claim.
926#[allow(clippy::too_many_arguments)]
927pub(crate) fn create_a_potential_cors_request(
928    webview_id: Option<WebViewId>,
929    url: ServoUrl,
930    destination: Destination,
931    cors_setting: Option<CorsSettings>,
932    same_origin_fallback: Option<bool>,
933    referrer: Referrer,
934) -> RequestBuilder {
935    create_a_potential_cors_request_with_claim(
936        webview_id,
937        UrlWithBlobClaim::from_url_without_having_claimed_blob(url),
938        destination,
939        cors_setting,
940        same_origin_fallback,
941        referrer,
942    )
943}
944
945/// <https://html.spec.whatwg.org/multipage/#create-a-potential-cors-request>
946#[allow(clippy::too_many_arguments)]
947pub(crate) fn create_a_potential_cors_request_with_claim(
948    webview_id: Option<WebViewId>,
949    url: UrlWithBlobClaim,
950    destination: Destination,
951    cors_setting: Option<CorsSettings>,
952    same_origin_fallback: Option<bool>,
953    referrer: Referrer,
954) -> RequestBuilder {
955    RequestBuilder::new(webview_id, url, referrer)
956        // Step 1. Let mode be "no-cors" if corsAttributeState is No CORS, and "cors" otherwise.
957        .mode(match cors_setting {
958            Some(_) => RequestMode::CorsMode,
959            // Step 2. If same-origin fallback flag is set and mode is "no-cors", set mode to "same-origin".
960            None if same_origin_fallback == Some(true) => RequestMode::SameOrigin,
961            None => RequestMode::NoCors,
962        })
963        .credentials_mode(match cors_setting {
964            // Step 4. If corsAttributeState is Anonymous, set credentialsMode to "same-origin".
965            Some(CorsSettings::Anonymous) => CredentialsMode::CredentialsSameOrigin,
966            // Step 3. Let credentialsMode be "include".
967            _ => CredentialsMode::Include,
968        })
969        // Step 5. Return a new request whose URL is url, destination is destination,
970        // mode is mode, credentials mode is credentialsMode, and whose use-URL-credentials flag is set.
971        .destination(destination)
972        .use_url_credentials(true)
973}