script/dom/
request.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
5use std::rc::Rc;
6use std::str::FromStr;
7
8use cssparser::match_ignore_ascii_case;
9use dom_struct::dom_struct;
10use http::Method as HttpMethod;
11use http::header::{HeaderName, HeaderValue};
12use http::method::InvalidMethod;
13use js::rust::HandleObject;
14use net_traits::ReferrerPolicy as MsgReferrerPolicy;
15use net_traits::fetch::headers::is_forbidden_method;
16use net_traits::request::{
17    CacheMode, CredentialsMode, Destination, Origin, RedirectMode, Referrer,
18    Request as NetTraitsRequest, RequestBuilder, RequestMode as NetTraitsRequestMode,
19    TraversableForUserPrompts,
20};
21use script_bindings::cformat;
22use servo_url::ServoUrl;
23
24use crate::body::{BodyMixin, BodyType, Extractable, clone_body_stream_for_dom_body, consume_body};
25use crate::conversions::Convert;
26use crate::dom::abortsignal::AbortSignal;
27use crate::dom::bindings::cell::DomRefCell;
28use crate::dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
29use crate::dom::bindings::codegen::Bindings::RequestBinding::{
30    ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestInfo, RequestInit,
31    RequestMethods, RequestMode, RequestRedirect,
32};
33use crate::dom::bindings::error::{Error, Fallible};
34use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object_with_proto};
35use crate::dom::bindings::root::{DomRoot, MutNullableDom};
36use crate::dom::bindings::str::{ByteString, DOMString, USVString};
37use crate::dom::bindings::trace::RootedTraceableBox;
38use crate::dom::globalscope::GlobalScope;
39use crate::dom::headers::{Guard, Headers};
40use crate::dom::promise::Promise;
41use crate::dom::stream::readablestream::ReadableStream;
42use crate::fetch::RequestWithGlobalScope;
43use crate::script_runtime::CanGc;
44use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
45
46#[dom_struct]
47pub(crate) struct Request {
48    reflector_: Reflector,
49    #[no_trace]
50    /// <https://fetch.spec.whatwg.org/#concept-request-request>
51    request: DomRefCell<NetTraitsRequest>,
52    /// <https://fetch.spec.whatwg.org/#concept-request-body>
53    body_stream: MutNullableDom<ReadableStream>,
54    /// <https://fetch.spec.whatwg.org/#request-headers>
55    headers: MutNullableDom<Headers>,
56    /// <https://fetch.spec.whatwg.org/#request-signal>
57    signal: MutNullableDom<AbortSignal>,
58}
59
60impl Request {
61    fn new_inherited(global: &GlobalScope, url: ServoUrl) -> Request {
62        Request {
63            reflector_: Reflector::new(),
64            request: DomRefCell::new(net_request_from_global(global, url)),
65            body_stream: MutNullableDom::new(None),
66            headers: Default::default(),
67            signal: MutNullableDom::new(None),
68        }
69    }
70
71    fn new(
72        global: &GlobalScope,
73        proto: Option<HandleObject>,
74        url: ServoUrl,
75        can_gc: CanGc,
76    ) -> DomRoot<Request> {
77        reflect_dom_object_with_proto(
78            Box::new(Request::new_inherited(global, url)),
79            global,
80            proto,
81            can_gc,
82        )
83    }
84
85    fn from_net_request(
86        global: &GlobalScope,
87        proto: Option<HandleObject>,
88        net_request: NetTraitsRequest,
89        can_gc: CanGc,
90    ) -> DomRoot<Request> {
91        let r = Request::new(global, proto, net_request.current_url(), can_gc);
92        *r.request.borrow_mut() = net_request;
93        r
94    }
95
96    // https://fetch.spec.whatwg.org/#dom-request
97    pub(crate) fn constructor(
98        cx: &mut js::context::JSContext,
99        global: &GlobalScope,
100        proto: Option<HandleObject>,
101        mut input: RequestInfo,
102        init: &RequestInit,
103    ) -> Fallible<DomRoot<Request>> {
104        // Step 1. Let request be null.
105        let temporary_request: NetTraitsRequest;
106
107        // Step 2. Let fallbackMode be null.
108        let mut fallback_mode: Option<NetTraitsRequestMode> = None;
109
110        // Step 3. Let baseURL be this’s relevant settings object’s API base URL.
111        let base_url = global.api_base_url();
112
113        // Step 4. Let signal be null.
114        let mut signal: Option<DomRoot<AbortSignal>> = None;
115
116        // Required later for step 41.1
117        let mut input_body_is_unusable = false;
118
119        match input {
120            // Step 5. If input is a string, then:
121            RequestInfo::USVString(USVString(ref usv_string)) => {
122                // Step 5.1. Let parsedURL be the result of parsing input with baseURL.
123                let parsed_url = base_url.join(usv_string);
124                // Step 5.2. If parsedURL is failure, then throw a TypeError.
125                if parsed_url.is_err() {
126                    return Err(Error::Type(c"Url could not be parsed".to_owned()));
127                }
128                // Step 5.3. If parsedURL includes credentials, then throw a TypeError.
129                let url = parsed_url.unwrap();
130                if includes_credentials(&url) {
131                    return Err(Error::Type(c"Url includes credentials".to_owned()));
132                }
133                // Step 5.4. Set request to a new request whose URL is parsedURL.
134                temporary_request = net_request_from_global(global, url);
135                // Step 5.5. Set fallbackMode to "cors".
136                fallback_mode = Some(NetTraitsRequestMode::CorsMode);
137            },
138            // Step 6. Otherwise:
139            // Step 6.1. Assert: input is a Request object.
140            RequestInfo::Request(ref input_request) => {
141                // Preparation for step 41.1
142                input_body_is_unusable = input_request.is_unusable();
143                // Step 6.2. Set request to input’s request.
144                temporary_request = input_request.request.borrow().clone();
145                // Step 6.3. Set signal to input’s signal.
146                signal = Some(input_request.Signal());
147            },
148        }
149
150        // Step 7. Let origin be this’s relevant settings object’s origin.
151        let origin = global.origin().immutable();
152
153        // Step 8. Let traversableForUserPrompts be "client".
154        let mut traversable_for_user_prompts = TraversableForUserPrompts::Client;
155
156        // Step 9. If request’s traversable for user prompts is an environment settings object
157        // and its origin is same origin with origin, then set traversableForUserPrompts
158        // to request’s traversable for user prompts.
159        // TODO: `environment settings object` is not implemented in Servo yet.
160
161        // Step 10. If init["window"] exists and is non-null, then throw a TypeError.
162        if !init.window.handle().is_null_or_undefined() {
163            return Err(Error::Type(c"Window is present and is not null".to_owned()));
164        }
165
166        // Step 11. If init["window"] exists, then set traversableForUserPrompts to "no-traversable".
167        if !init.window.handle().is_undefined() {
168            traversable_for_user_prompts = TraversableForUserPrompts::NoTraversable;
169        }
170
171        // Step 12. Set request to a new request with the following properties:
172        let mut request: NetTraitsRequest;
173        request = net_request_from_global(global, temporary_request.current_url());
174        request.method = temporary_request.method;
175        request.headers = temporary_request.headers.clone();
176        request.unsafe_request = true;
177        request.traversable_for_user_prompts = traversable_for_user_prompts;
178        // TODO: `entry settings object` is not implemented in Servo yet.
179        request.origin = Origin::Client;
180        request.referrer = temporary_request.referrer;
181        request.referrer_policy = temporary_request.referrer_policy;
182        request.mode = temporary_request.mode;
183        request.credentials_mode = temporary_request.credentials_mode;
184        request.cache_mode = temporary_request.cache_mode;
185        request.redirect_mode = temporary_request.redirect_mode;
186        request.integrity_metadata = temporary_request.integrity_metadata;
187
188        // Step 13. If init is not empty, then:
189        if init.body.is_some() ||
190            init.cache.is_some() ||
191            init.credentials.is_some() ||
192            init.integrity.is_some() ||
193            init.headers.is_some() ||
194            init.keepalive.is_some() ||
195            init.method.is_some() ||
196            init.mode.is_some() ||
197            init.redirect.is_some() ||
198            init.referrer.is_some() ||
199            init.referrerPolicy.is_some() ||
200            !init.window.handle().is_undefined()
201        {
202            // Step 13.1. If request’s mode is "navigate", then set it to "same-origin".
203            if request.mode == NetTraitsRequestMode::Navigate {
204                request.mode = NetTraitsRequestMode::SameOrigin;
205            }
206            // Step 13.2. Unset request’s reload-navigation flag.
207            // TODO
208            // Step 13.3. Unset request’s history-navigation flag.
209            // TODO
210            // Step 13.4. Set request’s origin to "client".
211            // TODO
212            // Step 13.5. Set request’s referrer to "client".
213            request.referrer = global.get_referrer();
214            // Step 13.6. Set request’s referrer policy to the empty string.
215            request.referrer_policy = MsgReferrerPolicy::EmptyString;
216            // Step 13.7. Set request’s URL to request’s current URL.
217            // TODO
218            // Step 13.8. Set request’s URL list to « request’s URL ».
219            // TODO
220        }
221
222        // Step 14. If init["referrer"] exists, then:
223        if let Some(init_referrer) = init.referrer.as_ref() {
224            // Step 14.1. Let referrer be init["referrer"].
225            let referrer = &init_referrer.0;
226            // Step 14.2. If referrer is the empty string, then set request’s referrer to "no-referrer".
227            if referrer.is_empty() {
228                request.referrer = Referrer::NoReferrer;
229            // Step 14.3. Otherwise:
230            } else {
231                // Step 14.3.1. Let parsedReferrer be the result of parsing referrer with baseURL.
232                let parsed_referrer = base_url.join(referrer);
233                // Step 14.3.2. If parsedReferrer is failure, then throw a TypeError.
234                if parsed_referrer.is_err() {
235                    return Err(Error::Type(c"Failed to parse referrer url".to_owned()));
236                }
237                // Step 14.3.3. If one of the following is true
238                // parsedReferrer’s scheme is "about" and path is the string "client"
239                // parsedReferrer’s origin is not same origin with origin
240                if let Ok(parsed_referrer) = parsed_referrer {
241                    if (parsed_referrer.cannot_be_a_base() &&
242                        parsed_referrer.scheme() == "about" &&
243                        parsed_referrer.path() == "client") ||
244                        parsed_referrer.origin() != *origin
245                    {
246                        // then set request’s referrer to "client".
247                        request.referrer = global.get_referrer();
248                    } else {
249                        // Step 14.3.4. Otherwise, set request’s referrer to parsedReferrer.
250                        request.referrer = Referrer::ReferrerUrl(parsed_referrer);
251                    }
252                }
253            }
254        }
255
256        // Step 15. If init["referrerPolicy"] exists, then set request’s referrer policy to it.
257        if let Some(init_referrerpolicy) = init.referrerPolicy.as_ref() {
258            let init_referrer_policy = (*init_referrerpolicy).convert();
259            request.referrer_policy = init_referrer_policy;
260        }
261
262        // Step 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
263        let mode = init.mode.as_ref().map(|m| (*m).convert()).or(fallback_mode);
264
265        // Step 17. If mode is "navigate", then throw a TypeError.
266        if let Some(NetTraitsRequestMode::Navigate) = mode {
267            return Err(Error::Type(c"Request mode is Navigate".to_owned()));
268        }
269
270        // Step 18. If mode is non-null, set request’s mode to mode.
271        if let Some(m) = mode {
272            request.mode = m;
273        }
274
275        // Step 19. If init["credentials"] exists, then set request’s credentials mode to it.
276        if let Some(init_credentials) = init.credentials.as_ref() {
277            let credentials = (*init_credentials).convert();
278            request.credentials_mode = credentials;
279        }
280
281        // Step 20. If init["cache"] exists, then set request’s cache mode to it.
282        if let Some(init_cache) = init.cache.as_ref() {
283            let cache = (*init_cache).convert();
284            request.cache_mode = cache;
285        }
286
287        // Step 21. If request’s cache mode is "only-if-cached" and request’s mode
288        // is not "same-origin", then throw a TypeError.
289        if request.cache_mode == CacheMode::OnlyIfCached &&
290            request.mode != NetTraitsRequestMode::SameOrigin
291        {
292            return Err(Error::Type(
293                c"Cache is 'only-if-cached' and mode is not 'same-origin'".to_owned(),
294            ));
295        }
296
297        // Step 22. If init["redirect"] exists, then set request’s redirect mode to it.
298        if let Some(init_redirect) = init.redirect.as_ref() {
299            let redirect = (*init_redirect).convert();
300            request.redirect_mode = redirect;
301        }
302
303        // Step 23. If init["integrity"] exists, then set request’s integrity metadata to it.
304        if let Some(init_integrity) = init.integrity.as_ref() {
305            let integrity = init_integrity.clone().to_string();
306            request.integrity_metadata = integrity;
307        }
308
309        // Step 24. If init["keepalive"] exists, then set request’s keepalive to it.
310        if let Some(init_keepalive) = init.keepalive {
311            request.keep_alive = init_keepalive;
312        }
313
314        // Step 25. If init["method"] exists, then:
315        // Step 25.1. Let method be init["method"].
316        if let Some(init_method) = init.method.as_ref() {
317            // Step 25.2. If method is not a method or method is a forbidden method, then throw a TypeError.
318            if !is_method(init_method) {
319                return Err(Error::Type(c"Method is not a method".to_owned()));
320            }
321            if is_forbidden_method(init_method) {
322                return Err(Error::Type(c"Method is forbidden".to_owned()));
323            }
324            // Step 25.3. Normalize method.
325            let method = match init_method.as_str() {
326                Some(s) => normalize_method(s)
327                    .map_err(|e| Error::Type(cformat!("Method is not valid: {:?}", e)))?,
328                None => return Err(Error::Type(c"Method is not a valid UTF8".to_owned())),
329            };
330            // Step 25.4. Set request’s method to method.
331            request.method = method;
332        }
333
334        // Step 26. If init["signal"] exists, then set signal to it.
335        if let Some(init_signal) = init.signal.as_ref() {
336            signal = init_signal.clone();
337        }
338        // Step 27. If init["priority"] exists, then:
339        // TODO
340        // Step 27.1. If request’s internal priority is not null,
341        // then update request’s internal priority in an implementation-defined manner.
342        // TODO
343        // Step 27.2. Otherwise, set request’s priority to init["priority"].
344        // TODO
345
346        // Step 28. Set this’s request to request.
347        let r = Request::from_net_request(global, proto, request, CanGc::from_cx(cx));
348
349        // Step 29. Let signals be « signal » if signal is non-null; otherwise « ».
350        let signals = signal.map_or(vec![], |s| vec![s]);
351        // Step 30. Set this’s signal to the result of creating a dependent
352        // abort signal from signals, using AbortSignal and this’s relevant realm.
353        r.signal
354            .set(Some(&AbortSignal::create_dependent_abort_signal(
355                signals,
356                global,
357                CanGc::from_cx(cx),
358            )));
359
360        // Step 31. Set this’s headers to a new Headers object with this’s relevant realm,
361        // whose header list is request’s header list and guard is "request".
362        //
363        // "or_init" looks unclear here, but it always enters the block since r
364        // hasn't had any other way to initialize its headers
365        r.headers
366            .or_init(|| Headers::for_request(&r.global(), CanGc::from_cx(cx)));
367
368        // Step 33. If init is not empty, then:
369        //
370        // but spec says this should only be when non-empty init?
371        let headers_copy = init
372            .headers
373            .as_ref()
374            .map(|possible_header| match possible_header {
375                HeadersInit::ByteStringSequenceSequence(init_sequence) => {
376                    HeadersInit::ByteStringSequenceSequence(init_sequence.clone())
377                },
378                HeadersInit::ByteStringByteStringRecord(init_map) => {
379                    HeadersInit::ByteStringByteStringRecord(init_map.clone())
380                },
381            });
382
383        // Step 33.3
384        // We cannot empty `r.Headers().header_list` because
385        // we would undo the Step 25 above.  One alternative is to set
386        // `headers_copy` as a deep copy of `r.Headers()`. However,
387        // `r.Headers()` is a `DomRoot<T>`, and therefore it is difficult
388        // to obtain a mutable reference to `r.Headers()`. Without the
389        // mutable reference, we cannot mutate `r.Headers()` to be the
390        // deep copied headers in Step 25.
391
392        // Step 32. If this’s request’s mode is "no-cors", then:
393        if r.request.borrow().mode == NetTraitsRequestMode::NoCors {
394            let borrowed_request = r.request.borrow();
395            // Step 32.1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
396            if !is_cors_safelisted_method(&borrowed_request.method) {
397                return Err(Error::Type(
398                    c"The mode is 'no-cors' but the method is not a cors-safelisted method"
399                        .to_owned(),
400                ));
401            }
402            // Step 32.2. Set this’s headers’s guard to "request-no-cors".
403            r.Headers(CanGc::from_cx(cx))
404                .set_guard(Guard::RequestNoCors);
405        }
406
407        match headers_copy {
408            None => {
409                // Step 33.4. If headers is a Headers object, then for each header of its header list, append header to this’s headers.
410                //
411                // This is equivalent to the specification's concept of
412                // "associated headers list". If an init headers is not given,
413                // but an input with headers is given, set request's
414                // headers as the input's Headers.
415                if let RequestInfo::Request(ref input_request) = input {
416                    r.Headers(CanGc::from_cx(cx))
417                        .copy_from_headers(input_request.Headers(CanGc::from_cx(cx)))?;
418                }
419            },
420            // Step 33.5. Otherwise, fill this’s headers with headers.
421            Some(headers_copy) => r.Headers(CanGc::from_cx(cx)).fill(Some(headers_copy))?,
422        }
423
424        // Step 33.5 depending on how we got here
425        // Copy the headers list onto the headers of net_traits::Request
426        r.request.borrow_mut().headers = r.Headers(CanGc::from_cx(cx)).get_headers_list();
427
428        // Step 34. Let inputBody be input’s request’s body if input is a Request object; otherwise null.
429        let input_body = if let RequestInfo::Request(ref mut input_request) = input {
430            let mut input_request_request = input_request.request.borrow_mut();
431            r.body_stream.set(input_request.body().as_deref());
432            input_request_request.body.take()
433        } else {
434            None
435        };
436
437        // Step 35. If either init["body"] exists and is non-null or inputBody is non-null,
438        // and request’s method is `GET` or `HEAD`, then throw a TypeError.
439        if init.body.as_ref().is_some_and(|body| body.is_some()) || input_body.is_some() {
440            let req = r.request.borrow();
441            let req_method = &req.method;
442            match *req_method {
443                HttpMethod::GET => {
444                    return Err(Error::Type(
445                        c"Init's body is non-null, and request method is GET".to_owned(),
446                    ));
447                },
448                HttpMethod::HEAD => {
449                    return Err(Error::Type(
450                        c"Init's body is non-null, and request method is HEAD".to_owned(),
451                    ));
452                },
453                _ => {},
454            }
455        }
456
457        // Step 36. Let initBody be null.
458        let mut init_body = None;
459        // Step 37. If init["body"] exists and is non-null, then:
460        if let Some(Some(ref input_init_body)) = init.body {
461            // Step 37.1. Let bodyWithType be the result of extracting init["body"], with keepalive set to request’s keepalive.
462            let mut body_with_type =
463                input_init_body.extract(cx, global, r.request.borrow().keep_alive)?;
464
465            // Step 37.3. Let type be bodyWithType’s type.
466            if let Some(contents) = body_with_type.content_type.take() {
467                let ct_header_name = b"Content-Type";
468                // Step 37.4. If type is non-null and this’s headers’s header list
469                // does not contain `Content-Type`, then append (`Content-Type`, type) to this’s headers.
470                if !r
471                    .Headers(CanGc::from_cx(cx))
472                    .Has(ByteString::new(ct_header_name.to_vec()))
473                    .unwrap()
474                {
475                    let ct_header_val = contents.as_bytes();
476                    r.Headers(CanGc::from_cx(cx)).Append(
477                        ByteString::new(ct_header_name.to_vec()),
478                        ByteString::new(ct_header_val.to_vec()),
479                    )?;
480
481                    // In Servo r.Headers's header list isn't a pointer to
482                    // the same actual list as r.request's, and so we need to
483                    // append to both lists to keep them in sync.
484                    if let Ok(v) = HeaderValue::from_bytes(&ct_header_val) {
485                        r.request
486                            .borrow_mut()
487                            .headers
488                            .insert(HeaderName::from_bytes(ct_header_name).unwrap(), v);
489                    }
490                }
491            }
492
493            // Step 37.2. Set initBody to bodyWithType’s body.
494            let (net_body, stream) = body_with_type.into_net_request_body();
495            r.body_stream.set(Some(&*stream));
496            init_body = Some(net_body);
497        }
498
499        // Step 38. Let inputOrInitBody be initBody if it is non-null; otherwise inputBody.
500        // Step 40. Let finalBody be inputOrInitBody.
501        // Step 41.2. Set finalBody to the result of creating a proxy for inputBody.
502        //
503        // There are multiple reassignments to similar values. In the end, all end up as
504        // final_body. Therefore, final_body is equivalent to inputOrInitBody
505        let final_body = init_body.or(input_body);
506
507        // Step 39. If inputOrInitBody is non-null and inputOrInitBody’s source is null, then:
508        if final_body
509            .as_ref()
510            .is_some_and(|body| body.source_is_null())
511        {
512            // Step 39.1. If initBody is non-null and init["duplex"] does not exist, then throw a TypeError.
513            // TODO
514            // Step 39.2. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
515            let request_mode = &r.request.borrow().mode;
516            if *request_mode != NetTraitsRequestMode::CorsMode &&
517                *request_mode != NetTraitsRequestMode::SameOrigin
518            {
519                return Err(Error::Type(
520                    c"Request mode must be Cors or SameOrigin".to_owned(),
521                ));
522            }
523            // Step 39.3. Set this’s request’s use-CORS-preflight flag.
524            // TODO
525        }
526
527        // Step 41. If initBody is null and inputBody is non-null, then:
528        // Step 41.1. If inputBody is unusable, then throw a TypeError.
529        //
530        // We only perform this check on input_body. However, we already
531        // processed the input body. Therefore, we check it all the way
532        // above and throw the error at the last possible moment
533        if input_body_is_unusable {
534            return Err(Error::Type(c"Input body is unusable".to_owned()));
535        }
536
537        // Step 42. Set this’s request’s body to finalBody.
538        r.request.borrow_mut().body = final_body;
539
540        Ok(r)
541    }
542
543    /// <https://fetch.spec.whatwg.org/#concept-request-clone>
544    fn clone_from(cx: &mut js::context::JSContext, r: &Request) -> Fallible<DomRoot<Request>> {
545        let req = r.request.borrow();
546        let url = req.url();
547        let headers_guard = r.Headers(CanGc::from_cx(cx)).get_guard();
548
549        // Step 1. Let newRequest be a copy of request, except for its body.
550        let mut new_req_inner = req.clone();
551        let body = new_req_inner.body.take();
552
553        let r_clone = Request::new(&r.global(), None, url, CanGc::from_cx(cx));
554        *r_clone.request.borrow_mut() = new_req_inner;
555
556        // Step 2. If request’s body is non-null, set newRequest’s body
557        // to the result of cloning request’s body.
558        if let Some(body) = body {
559            r_clone.request.borrow_mut().body = Some(body);
560        }
561
562        r_clone
563            .Headers(CanGc::from_cx(cx))
564            .copy_from_headers(r.Headers(CanGc::from_cx(cx)))?;
565        r_clone.Headers(CanGc::from_cx(cx)).set_guard(headers_guard);
566
567        clone_body_stream_for_dom_body(cx, &r.body_stream, &r_clone.body_stream)?;
568
569        // Step 3. Return newRequest.
570        Ok(r_clone)
571    }
572
573    pub(crate) fn get_request(&self) -> NetTraitsRequest {
574        self.request.borrow().clone()
575    }
576}
577
578fn net_request_from_global(global: &GlobalScope, url: ServoUrl) -> NetTraitsRequest {
579    let url = ensure_blob_referenced_by_url_is_kept_alive(global, url);
580    RequestBuilder::new(global.webview_id(), url, global.get_referrer())
581        .with_global_scope(global)
582        .build()
583}
584
585/// <https://fetch.spec.whatwg.org/#concept-method-normalize>
586fn normalize_method(m: &str) -> Result<HttpMethod, InvalidMethod> {
587    match_ignore_ascii_case! { m,
588        "delete" => return Ok(HttpMethod::DELETE),
589        "get" => return Ok(HttpMethod::GET),
590        "head" => return Ok(HttpMethod::HEAD),
591        "options" => return Ok(HttpMethod::OPTIONS),
592        "post" => return Ok(HttpMethod::POST),
593        "put" => return Ok(HttpMethod::PUT),
594        _ => (),
595    }
596    debug!("Method: {:?}", m);
597    HttpMethod::from_str(m)
598}
599
600/// <https://fetch.spec.whatwg.org/#concept-method>
601fn is_method(m: &ByteString) -> bool {
602    m.as_str().is_some()
603}
604
605/// <https://fetch.spec.whatwg.org/#cors-safelisted-method>
606fn is_cors_safelisted_method(m: &HttpMethod) -> bool {
607    m == HttpMethod::GET || m == HttpMethod::HEAD || m == HttpMethod::POST
608}
609
610/// <https://url.spec.whatwg.org/#include-credentials>
611fn includes_credentials(input: &ServoUrl) -> bool {
612    !input.username().is_empty() || input.password().is_some()
613}
614
615impl RequestMethods<crate::DomTypeHolder> for Request {
616    /// <https://fetch.spec.whatwg.org/#dom-request>
617    fn Constructor(
618        cx: &mut js::context::JSContext,
619        global: &GlobalScope,
620        proto: Option<HandleObject>,
621        input: RequestInfo,
622        init: RootedTraceableBox<RequestInit>,
623    ) -> Fallible<DomRoot<Request>> {
624        Self::constructor(cx, global, proto, input, &init)
625    }
626
627    /// <https://fetch.spec.whatwg.org/#dom-request-method>
628    fn Method(&self) -> ByteString {
629        let r = self.request.borrow();
630        ByteString::new(r.method.as_ref().as_bytes().into())
631    }
632
633    /// <https://fetch.spec.whatwg.org/#dom-request-url>
634    fn Url(&self) -> USVString {
635        let r = self.request.borrow();
636        USVString(r.url_list.first().map_or("", |u| u.as_str()).into())
637    }
638
639    /// <https://fetch.spec.whatwg.org/#dom-request-headers>
640    fn Headers(&self, can_gc: CanGc) -> DomRoot<Headers> {
641        self.headers
642            .or_init(|| Headers::new(&self.global(), can_gc))
643    }
644
645    /// <https://fetch.spec.whatwg.org/#dom-request-destination>
646    fn Destination(&self) -> RequestDestination {
647        self.request.borrow().destination.convert()
648    }
649
650    /// <https://fetch.spec.whatwg.org/#dom-request-referrer>
651    fn Referrer(&self) -> USVString {
652        let r = self.request.borrow();
653        USVString(match r.referrer {
654            Referrer::NoReferrer => String::from(""),
655            Referrer::Client(_) => String::from("about:client"),
656            Referrer::ReferrerUrl(ref u) => {
657                let u_c = u.clone();
658                u_c.into_string()
659            },
660        })
661    }
662
663    /// <https://fetch.spec.whatwg.org/#dom-request-referrerpolicy>
664    fn ReferrerPolicy(&self) -> ReferrerPolicy {
665        self.request.borrow().referrer_policy.convert()
666    }
667
668    /// <https://fetch.spec.whatwg.org/#dom-request-mode>
669    fn Mode(&self) -> RequestMode {
670        self.request.borrow().mode.clone().convert()
671    }
672
673    /// <https://fetch.spec.whatwg.org/#dom-request-credentials>
674    fn Credentials(&self) -> RequestCredentials {
675        let r = self.request.borrow().clone();
676        r.credentials_mode.convert()
677    }
678
679    /// <https://fetch.spec.whatwg.org/#dom-request-cache>
680    fn Cache(&self) -> RequestCache {
681        let r = self.request.borrow().clone();
682        r.cache_mode.convert()
683    }
684
685    /// <https://fetch.spec.whatwg.org/#dom-request-redirect>
686    fn Redirect(&self) -> RequestRedirect {
687        let r = self.request.borrow().clone();
688        r.redirect_mode.convert()
689    }
690
691    /// <https://fetch.spec.whatwg.org/#dom-request-integrity>
692    fn Integrity(&self) -> DOMString {
693        self.request.borrow().integrity_metadata.clone().into()
694    }
695
696    /// <https://fetch.spec.whatwg.org/#dom-request-keepalive>
697    fn Keepalive(&self) -> bool {
698        self.request.borrow().keep_alive
699    }
700
701    /// <https://fetch.spec.whatwg.org/#dom-body-body>
702    fn GetBody(&self) -> Option<DomRoot<ReadableStream>> {
703        self.body()
704    }
705
706    /// <https://fetch.spec.whatwg.org/#dom-body-bodyused>
707    fn BodyUsed(&self) -> bool {
708        self.is_body_used()
709    }
710
711    /// <https://fetch.spec.whatwg.org/#dom-request-signal>
712    fn Signal(&self) -> DomRoot<AbortSignal> {
713        self.signal
714            .get()
715            .expect("Should always be initialized in constructor and clone")
716    }
717
718    /// <https://fetch.spec.whatwg.org/#dom-request-clone>
719    fn Clone(&self, cx: &mut js::context::JSContext) -> Fallible<DomRoot<Request>> {
720        // Step 1. If this is unusable, then throw a TypeError.
721        if self.is_unusable() {
722            return Err(Error::Type(c"Request is unusable".to_owned()));
723        }
724
725        // Step 2. Let clonedRequest be the result of cloning this’s request.
726        let cloned_request = Request::clone_from(cx, self)?;
727        // Step 3. Assert: this’s signal is non-null.
728        let signal = self.signal.get().expect("Should always be initialized");
729        // Step 4. Let clonedSignal be the result of creating a dependent
730        // abort signal from « this’s signal », using AbortSignal and this’s relevant realm.
731        let cloned_signal = AbortSignal::create_dependent_abort_signal(
732            vec![signal],
733            &self.global(),
734            CanGc::from_cx(cx),
735        );
736        // Step 5. Let clonedRequestObject be the result of creating a Request object,
737        // given clonedRequest, this’s headers’s guard, clonedSignal and this’s relevant realm.
738        //
739        // These steps already happen in `clone_from`
740        cloned_request.signal.set(Some(&cloned_signal));
741        // Step 6. Return clonedRequestObject.
742        Ok(cloned_request)
743    }
744
745    /// <https://fetch.spec.whatwg.org/#dom-body-text>
746    fn Text(&self, can_gc: CanGc) -> Rc<Promise> {
747        consume_body(self, BodyType::Text, can_gc)
748    }
749
750    /// <https://fetch.spec.whatwg.org/#dom-body-blob>
751    fn Blob(&self, can_gc: CanGc) -> Rc<Promise> {
752        consume_body(self, BodyType::Blob, can_gc)
753    }
754
755    /// <https://fetch.spec.whatwg.org/#dom-body-formdata>
756    fn FormData(&self, can_gc: CanGc) -> Rc<Promise> {
757        consume_body(self, BodyType::FormData, can_gc)
758    }
759
760    /// <https://fetch.spec.whatwg.org/#dom-body-json>
761    fn Json(&self, can_gc: CanGc) -> Rc<Promise> {
762        consume_body(self, BodyType::Json, can_gc)
763    }
764
765    /// <https://fetch.spec.whatwg.org/#dom-body-arraybuffer>
766    fn ArrayBuffer(&self, can_gc: CanGc) -> Rc<Promise> {
767        consume_body(self, BodyType::ArrayBuffer, can_gc)
768    }
769
770    /// <https://fetch.spec.whatwg.org/#dom-body-bytes>
771    fn Bytes(&self, can_gc: CanGc) -> std::rc::Rc<Promise> {
772        consume_body(self, BodyType::Bytes, can_gc)
773    }
774}
775
776impl BodyMixin for Request {
777    fn is_body_used(&self) -> bool {
778        let body_stream = self.body_stream.get();
779        body_stream
780            .as_ref()
781            .is_some_and(|stream| stream.is_disturbed())
782    }
783
784    fn is_unusable(&self) -> bool {
785        let body_stream = self.body_stream.get();
786        body_stream
787            .as_ref()
788            .is_some_and(|stream| stream.is_disturbed() || stream.is_locked())
789    }
790
791    fn body(&self) -> Option<DomRoot<ReadableStream>> {
792        self.body_stream.get()
793    }
794
795    fn get_mime_type(&self, can_gc: CanGc) -> Vec<u8> {
796        let headers = self.Headers(can_gc);
797        headers.extract_mime_type()
798    }
799}
800
801impl Convert<CacheMode> for RequestCache {
802    fn convert(self) -> CacheMode {
803        match self {
804            RequestCache::Default => CacheMode::Default,
805            RequestCache::No_store => CacheMode::NoStore,
806            RequestCache::Reload => CacheMode::Reload,
807            RequestCache::No_cache => CacheMode::NoCache,
808            RequestCache::Force_cache => CacheMode::ForceCache,
809            RequestCache::Only_if_cached => CacheMode::OnlyIfCached,
810        }
811    }
812}
813
814impl Convert<RequestCache> for CacheMode {
815    fn convert(self) -> RequestCache {
816        match self {
817            CacheMode::Default => RequestCache::Default,
818            CacheMode::NoStore => RequestCache::No_store,
819            CacheMode::Reload => RequestCache::Reload,
820            CacheMode::NoCache => RequestCache::No_cache,
821            CacheMode::ForceCache => RequestCache::Force_cache,
822            CacheMode::OnlyIfCached => RequestCache::Only_if_cached,
823        }
824    }
825}
826
827impl Convert<CredentialsMode> for RequestCredentials {
828    fn convert(self) -> CredentialsMode {
829        match self {
830            RequestCredentials::Omit => CredentialsMode::Omit,
831            RequestCredentials::Same_origin => CredentialsMode::CredentialsSameOrigin,
832            RequestCredentials::Include => CredentialsMode::Include,
833        }
834    }
835}
836
837impl Convert<RequestCredentials> for CredentialsMode {
838    fn convert(self) -> RequestCredentials {
839        match self {
840            CredentialsMode::Omit => RequestCredentials::Omit,
841            CredentialsMode::CredentialsSameOrigin => RequestCredentials::Same_origin,
842            CredentialsMode::Include => RequestCredentials::Include,
843        }
844    }
845}
846
847impl Convert<Destination> for RequestDestination {
848    fn convert(self) -> Destination {
849        match self {
850            RequestDestination::_empty => Destination::None,
851            RequestDestination::Audio => Destination::Audio,
852            RequestDestination::Document => Destination::Document,
853            RequestDestination::Embed => Destination::Embed,
854            RequestDestination::Font => Destination::Font,
855            RequestDestination::Frame => Destination::Frame,
856            RequestDestination::Iframe => Destination::IFrame,
857            RequestDestination::Image => Destination::Image,
858            RequestDestination::Manifest => Destination::Manifest,
859            RequestDestination::Json => Destination::Json,
860            RequestDestination::Object => Destination::Object,
861            RequestDestination::Report => Destination::Report,
862            RequestDestination::Script => Destination::Script,
863            RequestDestination::Sharedworker => Destination::SharedWorker,
864            RequestDestination::Style => Destination::Style,
865            RequestDestination::Track => Destination::Track,
866            RequestDestination::Video => Destination::Video,
867            RequestDestination::Worker => Destination::Worker,
868            RequestDestination::Xslt => Destination::Xslt,
869        }
870    }
871}
872
873impl Convert<RequestDestination> for Destination {
874    fn convert(self) -> RequestDestination {
875        match self {
876            Destination::None => RequestDestination::_empty,
877            Destination::Audio => RequestDestination::Audio,
878            Destination::Document => RequestDestination::Document,
879            Destination::Embed => RequestDestination::Embed,
880            Destination::Font => RequestDestination::Font,
881            Destination::Frame => RequestDestination::Frame,
882            Destination::IFrame => RequestDestination::Iframe,
883            Destination::Image => RequestDestination::Image,
884            Destination::Manifest => RequestDestination::Manifest,
885            Destination::Json => RequestDestination::Json,
886            Destination::Object => RequestDestination::Object,
887            Destination::Report => RequestDestination::Report,
888            Destination::Script => RequestDestination::Script,
889            Destination::ServiceWorker | Destination::AudioWorklet | Destination::PaintWorklet => {
890                panic!("ServiceWorker request destination should not be exposed to DOM")
891            },
892            Destination::SharedWorker => RequestDestination::Sharedworker,
893            Destination::Style => RequestDestination::Style,
894            Destination::Track => RequestDestination::Track,
895            Destination::Video => RequestDestination::Video,
896            Destination::Worker => RequestDestination::Worker,
897            Destination::Xslt => RequestDestination::Xslt,
898            Destination::WebIdentity => RequestDestination::_empty,
899        }
900    }
901}
902
903impl Convert<NetTraitsRequestMode> for RequestMode {
904    fn convert(self) -> NetTraitsRequestMode {
905        match self {
906            RequestMode::Navigate => NetTraitsRequestMode::Navigate,
907            RequestMode::Same_origin => NetTraitsRequestMode::SameOrigin,
908            RequestMode::No_cors => NetTraitsRequestMode::NoCors,
909            RequestMode::Cors => NetTraitsRequestMode::CorsMode,
910        }
911    }
912}
913
914impl Convert<RequestMode> for NetTraitsRequestMode {
915    fn convert(self) -> RequestMode {
916        match self {
917            NetTraitsRequestMode::Navigate => RequestMode::Navigate,
918            NetTraitsRequestMode::SameOrigin => RequestMode::Same_origin,
919            NetTraitsRequestMode::NoCors => RequestMode::No_cors,
920            NetTraitsRequestMode::CorsMode => RequestMode::Cors,
921            NetTraitsRequestMode::WebSocket { .. } => {
922                unreachable!("Websocket request mode should never be exposed to Dom")
923            },
924        }
925    }
926}
927
928impl Convert<MsgReferrerPolicy> for ReferrerPolicy {
929    fn convert(self) -> MsgReferrerPolicy {
930        match self {
931            ReferrerPolicy::_empty => MsgReferrerPolicy::EmptyString,
932            ReferrerPolicy::No_referrer => MsgReferrerPolicy::NoReferrer,
933            ReferrerPolicy::No_referrer_when_downgrade => {
934                MsgReferrerPolicy::NoReferrerWhenDowngrade
935            },
936            ReferrerPolicy::Origin => MsgReferrerPolicy::Origin,
937            ReferrerPolicy::Origin_when_cross_origin => MsgReferrerPolicy::OriginWhenCrossOrigin,
938            ReferrerPolicy::Unsafe_url => MsgReferrerPolicy::UnsafeUrl,
939            ReferrerPolicy::Same_origin => MsgReferrerPolicy::SameOrigin,
940            ReferrerPolicy::Strict_origin => MsgReferrerPolicy::StrictOrigin,
941            ReferrerPolicy::Strict_origin_when_cross_origin => {
942                MsgReferrerPolicy::StrictOriginWhenCrossOrigin
943            },
944        }
945    }
946}
947
948impl Convert<ReferrerPolicy> for MsgReferrerPolicy {
949    fn convert(self) -> ReferrerPolicy {
950        match self {
951            MsgReferrerPolicy::EmptyString => ReferrerPolicy::_empty,
952            MsgReferrerPolicy::NoReferrer => ReferrerPolicy::No_referrer,
953            MsgReferrerPolicy::NoReferrerWhenDowngrade => {
954                ReferrerPolicy::No_referrer_when_downgrade
955            },
956            MsgReferrerPolicy::Origin => ReferrerPolicy::Origin,
957            MsgReferrerPolicy::OriginWhenCrossOrigin => ReferrerPolicy::Origin_when_cross_origin,
958            MsgReferrerPolicy::UnsafeUrl => ReferrerPolicy::Unsafe_url,
959            MsgReferrerPolicy::SameOrigin => ReferrerPolicy::Same_origin,
960            MsgReferrerPolicy::StrictOrigin => ReferrerPolicy::Strict_origin,
961            MsgReferrerPolicy::StrictOriginWhenCrossOrigin => {
962                ReferrerPolicy::Strict_origin_when_cross_origin
963            },
964        }
965    }
966}
967
968impl Convert<RedirectMode> for RequestRedirect {
969    fn convert(self) -> RedirectMode {
970        match self {
971            RequestRedirect::Follow => RedirectMode::Follow,
972            RequestRedirect::Error => RedirectMode::Error,
973            RequestRedirect::Manual => RedirectMode::Manual,
974        }
975    }
976}
977
978impl Convert<RequestRedirect> for RedirectMode {
979    fn convert(self) -> RequestRedirect {
980        match self {
981            RedirectMode::Follow => RequestRedirect::Follow,
982            RedirectMode::Error => RequestRedirect::Error,
983            RedirectMode::Manual => RequestRedirect::Manual,
984        }
985    }
986}