Skip to main content

script/dom/fetch/
response.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::cell::Cell;
6use std::str::FromStr;
7
8use bytes::Bytes;
9use dom_struct::dom_struct;
10use http::header::HeaderMap as HyperHeaders;
11use hyper_serde::Serde;
12use js::rust::{HandleObject, HandleValue};
13use net_traits::http_status::HttpStatus;
14use script_bindings::cell::DomRefCell;
15use script_bindings::cformat;
16use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
17use script_bindings::str::DOMString;
18use servo_url::ServoUrl;
19use url::Position;
20
21use crate::dom::RootedPromise;
22use crate::dom::bindings::codegen::Bindings::HeadersBinding::HeadersMethods;
23use crate::dom::bindings::codegen::Bindings::ResponseBinding;
24use crate::dom::bindings::codegen::Bindings::ResponseBinding::{
25    ResponseMethods, ResponseType as DOMResponseType,
26};
27use crate::dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
28use crate::dom::bindings::error::{Error, Fallible};
29use crate::dom::bindings::reflector::DomGlobal;
30use crate::dom::bindings::root::{DomRoot, MutNullableDom};
31use crate::dom::bindings::str::{ByteString, USVString, serialize_jsval_to_json_utf8};
32use crate::dom::globalscope::GlobalScope;
33use crate::dom::headers::{Guard, Headers, is_obs_text, is_vchar};
34use crate::dom::stream::readablestream::ReadableStream;
35use crate::dom::stream::underlyingsourcecontainer::UnderlyingSourceType;
36use crate::fetch::body::{
37    BodyMixin, BodyType, Extractable, ExtractedBody, body_text_stream,
38    clone_body_stream_for_dom_body, consume_body,
39};
40
41#[dom_struct]
42pub(crate) struct Response {
43    reflector_: Reflector,
44    headers_reflector: MutNullableDom<Headers>,
45    #[no_trace]
46    status: DomRefCell<HttpStatus>,
47    response_type: DomRefCell<DOMResponseType>,
48    /// <https://fetch.spec.whatwg.org/#concept-response-url>
49    /// FIXME: This should always point to the last entry of `url_list`.
50    /// Somehow we directly set it instead.
51    #[no_trace]
52    url: DomRefCell<Option<ServoUrl>>,
53    #[no_trace]
54    url_list: DomRefCell<Vec<ServoUrl>>,
55    /// The stream of <https://fetch.spec.whatwg.org/#body>.
56    body_stream: MutNullableDom<ReadableStream>,
57    /// The stream that receives network delivered bytes for Fetch responses.
58    /// This must remain stable even if `body_stream` is replaced by `tee()` branches during `clone()`.
59    fetch_body_stream: MutNullableDom<ReadableStream>,
60    /// FIXME: This should be removed.
61    redirected: Cell<bool>,
62}
63
64impl Response {
65    pub(crate) fn new_inherited(body_stream: Option<&ReadableStream>) -> Response {
66        Response {
67            reflector_: Reflector::new(),
68            headers_reflector: Default::default(),
69            status: DomRefCell::new(HttpStatus::default()),
70            response_type: DomRefCell::new(DOMResponseType::Default),
71            url: DomRefCell::new(None),
72            url_list: DomRefCell::new(vec![]),
73            body_stream: MutNullableDom::new(body_stream),
74            fetch_body_stream: MutNullableDom::new(body_stream),
75            redirected: Cell::new(false),
76        }
77    }
78
79    /// <https://fetch.spec.whatwg.org/#dom-response>
80    pub(crate) fn new(cx: &mut js::context::JSContext, global: &GlobalScope) -> DomRoot<Response> {
81        Self::new_with_proto(cx, global, None)
82    }
83
84    fn new_with_proto(
85        cx: &mut js::context::JSContext,
86        global: &GlobalScope,
87        proto: Option<HandleObject>,
88    ) -> DomRoot<Response> {
89        reflect_dom_object_with_proto(cx, Box::new(Response::new_inherited(None)), global, proto)
90    }
91
92    /// Create a `Response` whose body stream receives the chunks delivered by the network.
93    /// This is only for the fetch machinery; a JS-created `Response` is never network-backed.
94    pub(crate) fn new_fetch_response(
95        cx: &mut js::context::JSContext,
96        global: &GlobalScope,
97    ) -> DomRoot<Response> {
98        // Step 14. of https://fetch.spec.whatwg.org/#concept-http-network-fetch
99        // Set up stream with byte reading support with pullAlgorithm set to
100        // pullAlgorithm, cancelAlgorithm set to cancelAlgorithm.
101        let stream = ReadableStream::new_with_external_underlying_byte_source(
102            cx,
103            global,
104            UnderlyingSourceType::FetchResponse,
105        )
106        .expect("Failed to create ReadableStream with external underlying source");
107        reflect_dom_object_with_proto(
108            cx,
109            Box::new(Response::new_inherited(Some(&stream))),
110            global,
111            None,
112        )
113    }
114
115    pub(crate) fn error_stream(&self, cx: &mut js::context::JSContext, error: Error) {
116        if let Some(body) = self.fetch_body_stream.get() {
117            body.error_native(cx, error);
118        }
119    }
120
121    pub(crate) fn is_disturbed(&self) -> bool {
122        let body_stream = self.body_stream.get();
123        body_stream
124            .as_ref()
125            .is_some_and(|stream| stream.is_disturbed())
126    }
127
128    pub(crate) fn is_locked(&self) -> bool {
129        let body_stream = self.body_stream.get();
130        body_stream
131            .as_ref()
132            .is_some_and(|stream| stream.is_locked())
133    }
134}
135
136impl BodyMixin for Response {
137    fn is_body_used(&self) -> bool {
138        self.is_disturbed()
139    }
140
141    fn is_unusable(&self) -> bool {
142        self.body_stream
143            .get()
144            .is_some_and(|stream| stream.is_disturbed() || stream.is_locked())
145    }
146
147    fn body(&self) -> Option<DomRoot<ReadableStream>> {
148        self.body_stream.get()
149    }
150
151    fn get_mime_type(&self, cx: &mut js::context::JSContext) -> Vec<u8> {
152        let headers = self.Headers(cx);
153        headers.extract_mime_type()
154    }
155}
156
157/// <https://fetch.spec.whatwg.org/#redirect-status>
158fn is_redirect_status(status: u16) -> bool {
159    status == 301 || status == 302 || status == 303 || status == 307 || status == 308
160}
161
162/// <https://tools.ietf.org/html/rfc7230#section-3.1.2>
163fn is_valid_status_text(status_text: &ByteString) -> bool {
164    // reason-phrase  = *( HTAB / SP / VCHAR / obs-text )
165    for byte in status_text.iter() {
166        if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
167            return false;
168        }
169    }
170    true
171}
172
173/// <https://fetch.spec.whatwg.org/#null-body-status>
174fn is_null_body_status(status: u16) -> bool {
175    status == 101 || status == 204 || status == 205 || status == 304
176}
177
178impl ResponseMethods<crate::DomTypeHolder> for Response {
179    /// <https://fetch.spec.whatwg.org/#dom-response>
180    fn Constructor(
181        cx: &mut js::context::JSContext,
182        global: &GlobalScope,
183        proto: Option<HandleObject>,
184        body_init: Option<BodyInit>,
185        init: &ResponseBinding::ResponseInit,
186    ) -> Fallible<DomRoot<Response>> {
187        // 1. Set this’s response to a new response.
188        // Our Response/Body types don't actually hold onto an internal fetch Response.
189        let response = Response::new_with_proto(cx, global, proto);
190
191        // 2. Set this’s headers to a new Headers object with this’s relevant realm,
192        // whose header list is this’s response’s header list and guard is "response".
193        response.Headers(cx).set_guard(Guard::Response);
194
195        // 3. Let bodyWithType be null.
196        // 4. If body is non-null, then set bodyWithType to the result of extracting body.
197        let body_with_type = match body_init {
198            Some(body) => Some(body.extract(cx, global, false)?),
199            None => None,
200        };
201
202        // 5. Perform *initialize a response* given this, init, and bodyWithType.
203        initialize_response(cx, body_with_type, init, response)
204    }
205
206    /// <https://fetch.spec.whatwg.org/#dom-response-error>
207    fn Error(cx: &mut js::context::JSContext, global: &GlobalScope) -> DomRoot<Response> {
208        let response = Response::new(cx, global);
209        *response.response_type.borrow_mut() = DOMResponseType::Error;
210        response.Headers(cx).set_guard(Guard::Immutable);
211        *response.status.borrow_mut() = HttpStatus::new_error();
212        response
213    }
214
215    /// <https://fetch.spec.whatwg.org/#dom-response-redirect>
216    fn Redirect(
217        cx: &mut js::context::JSContext,
218        global: &GlobalScope,
219        url: USVString,
220        status: u16,
221    ) -> Fallible<DomRoot<Response>> {
222        // Step 1
223        let base_url = global.api_base_url();
224        let parsed_url = base_url.join(&url.0);
225
226        // Step 2
227        let url = match parsed_url {
228            Ok(url) => url,
229            Err(_) => return Err(Error::Type(c"ServoUrl could not be parsed".to_owned())),
230        };
231
232        // Step 3
233        if !is_redirect_status(status) {
234            return Err(Error::Range(c"status is not a redirect status".to_owned()));
235        }
236
237        // Step 4
238        // see Step 4 continued
239        let response = Response::new(cx, global);
240
241        // Step 5
242        *response.status.borrow_mut() = HttpStatus::new_raw(status, vec![]);
243
244        // Step 6
245        let url_bytestring =
246            ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
247        response
248            .Headers(cx)
249            .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?;
250
251        // Step 4 continued
252        // Headers Guard is set to Immutable here to prevent error in Step 6
253        response.Headers(cx).set_guard(Guard::Immutable);
254
255        // Step 7
256        Ok(response)
257    }
258
259    /// <https://fetch.spec.whatwg.org/#dom-response-json>
260    fn CreateFromJson(
261        cx: &mut js::context::JSContext,
262        global: &GlobalScope,
263        data: HandleValue,
264        init: &ResponseBinding::ResponseInit,
265    ) -> Fallible<DomRoot<Response>> {
266        // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
267        let json_str = serialize_jsval_to_json_utf8(cx, data)?;
268
269        // 2. Let body be the result of extracting bytes
270        // The spec's definition of JSON bytes is a UTF-8 encoding so using a DOMString here handles
271        // the encoding part.
272        let body_init = BodyInit::String(json_str);
273        let mut body = body_init.extract(cx, global, false)?;
274
275        // 3. Let responseObject be the result of creating a Response object, given a new response,
276        // "response", and the current realm.
277        let response = Response::new(cx, global);
278        response.Headers(cx).set_guard(Guard::Response);
279
280        // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
281        body.content_type = Some(DOMString::from_static("application/json"));
282        initialize_response(cx, Some(body), init, response)
283    }
284
285    /// <https://fetch.spec.whatwg.org/#dom-response-type>
286    fn Type(&self) -> DOMResponseType {
287        *self.response_type.borrow() // into()
288    }
289
290    /// <https://fetch.spec.whatwg.org/#dom-response-url>
291    fn Url(&self) -> USVString {
292        USVString(String::from(
293            (*self.url.borrow())
294                .as_ref()
295                .map(serialize_without_fragment)
296                .unwrap_or(""),
297        ))
298    }
299
300    /// <https://fetch.spec.whatwg.org/#dom-response-redirected>
301    /// TODO: The redirected getter steps are to return true if
302    /// this’s response’s URL list’s size is greater than 1; otherwise false.
303    ///
304    /// But if we do like spec says, test fails, probably because
305    /// we not fully set URL list in spec steps.
306    fn Redirected(&self) -> bool {
307        self.redirected.get()
308    }
309
310    /// <https://fetch.spec.whatwg.org/#dom-response-status>
311    fn Status(&self) -> u16 {
312        self.status.borrow().raw_code()
313    }
314
315    /// <https://fetch.spec.whatwg.org/#dom-response-ok>
316    fn Ok(&self) -> bool {
317        self.status.borrow().is_success()
318    }
319
320    /// <https://fetch.spec.whatwg.org/#dom-response-statustext>
321    fn StatusText(&self) -> ByteString {
322        ByteString::new(self.status.borrow().message().to_vec())
323    }
324
325    /// <https://fetch.spec.whatwg.org/#dom-response-headers>
326    fn Headers(&self, cx: &mut js::context::JSContext) -> DomRoot<Headers> {
327        self.headers_reflector
328            .or_init(|| Headers::for_response(cx, &self.global()))
329    }
330
331    /// <https://fetch.spec.whatwg.org/#dom-response-clone>
332    fn Clone(&self, cx: &mut js::context::JSContext) -> Fallible<DomRoot<Response>> {
333        // Step 1. If this is unusable, then throw a TypeError.
334        if self.is_unusable() {
335            return Err(Error::Type(c"cannot clone a disturbed response".to_owned()));
336        }
337
338        // Step 2. Let clonedResponse be the result of cloning this’s response.
339        let new_response = Response::new(cx, &self.global());
340        new_response
341            .Headers(cx)
342            .copy_from_headers(&self.Headers(cx))?;
343        new_response
344            .Headers(cx)
345            .set_guard(self.Headers(cx).get_guard());
346
347        *new_response.response_type.borrow_mut() = *self.response_type.borrow();
348        new_response
349            .status
350            .borrow_mut()
351            .clone_from(&self.status.borrow());
352        new_response.url.borrow_mut().clone_from(&self.url.borrow());
353        new_response
354            .url_list
355            .borrow_mut()
356            .clone_from(&self.url_list.borrow());
357
358        // Step 3. Return the result of creating a Response object,
359        // given clonedResponse, this’s headers’s guard, and this’s relevant realm.
360        clone_body_stream_for_dom_body(cx, &self.body_stream, &new_response.body_stream)?;
361        // The cloned response must not receive network chunks directly; it is fed via the tee branch.
362        new_response.fetch_body_stream.set(None);
363
364        Ok(new_response)
365    }
366
367    /// <https://fetch.spec.whatwg.org/#dom-body-bodyused>
368    fn BodyUsed(&self) -> bool {
369        self.is_body_used()
370    }
371
372    /// <https://fetch.spec.whatwg.org/#dom-body-body>
373    fn GetBody(&self) -> Option<DomRoot<ReadableStream>> {
374        self.body()
375    }
376
377    /// <https://fetch.spec.whatwg.org/#dom-body-text>
378    fn Text(&self, cx: &mut js::context::JSContext) -> RootedPromise {
379        consume_body(cx, self, BodyType::Text)
380    }
381
382    /// <https://fetch.spec.whatwg.org/#dom-body-blob>
383    fn Blob(&self, cx: &mut js::context::JSContext) -> RootedPromise {
384        consume_body(cx, self, BodyType::Blob)
385    }
386
387    /// <https://fetch.spec.whatwg.org/#dom-body-formdata>
388    fn FormData(&self, cx: &mut js::context::JSContext) -> RootedPromise {
389        consume_body(cx, self, BodyType::FormData)
390    }
391
392    /// <https://fetch.spec.whatwg.org/#dom-body-json>
393    fn Json(&self, cx: &mut js::context::JSContext) -> RootedPromise {
394        consume_body(cx, self, BodyType::Json)
395    }
396
397    /// <https://fetch.spec.whatwg.org/#dom-body-arraybuffer>
398    fn ArrayBuffer(&self, cx: &mut js::context::JSContext) -> RootedPromise {
399        consume_body(cx, self, BodyType::ArrayBuffer)
400    }
401
402    /// <https://fetch.spec.whatwg.org/#dom-body-bytes>
403    fn Bytes(&self, cx: &mut js::context::JSContext) -> RootedPromise {
404        consume_body(cx, self, BodyType::Bytes)
405    }
406
407    /// <https://fetch.spec.whatwg.org/#dom-body-textstream>
408    fn TextStream(&self, cx: &mut js::context::JSContext) -> Fallible<DomRoot<ReadableStream>> {
409        body_text_stream(cx, self)
410    }
411}
412
413/// <https://fetch.spec.whatwg.org/#initialize-a-response>
414fn initialize_response(
415    cx: &mut js::context::JSContext,
416    body: Option<ExtractedBody>,
417    init: &ResponseBinding::ResponseInit,
418    response: DomRoot<Response>,
419) -> Result<DomRoot<Response>, Error> {
420    // 1. If init["status"] is not in the range 200 to 599, inclusive, then throw a RangeError.
421    if init.status < 200 || init.status > 599 {
422        return Err(Error::Range(cformat!(
423            "init's status member should be in the range 200 to 599, inclusive, but is {}",
424            init.status
425        )));
426    }
427
428    // 2. If init["statusText"] is not the empty string and does not match the reason-phrase token production,
429    // then throw a TypeError.
430    if !is_valid_status_text(&init.statusText) {
431        return Err(Error::Type(
432            c"init's statusText member does not match the reason-phrase token production"
433                .to_owned(),
434        ));
435    }
436
437    // 3. Set response’s response’s status to init["status"].
438    // 4. Set response’s response’s status message to init["statusText"].
439    *response.status.borrow_mut() =
440        HttpStatus::new_raw(init.status, init.statusText.clone().into());
441
442    // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
443    if let Some(ref headers_member) = init.headers {
444        response.Headers(cx).fill(Some(headers_member))?;
445    }
446
447    // 6. If body is non-null, then:
448    if let Some(ref body) = body {
449        // 6.1 If response’s status is a null body status, then throw a TypeError.
450        if is_null_body_status(init.status) {
451            return Err(Error::Type(
452                c"Body is non-null but init's status member is a null body status".to_owned(),
453            ));
454        };
455
456        // 6.2 Set response’s body to body’s body.
457        response.body_stream.set(Some(&*body.stream));
458        response.fetch_body_stream.set(Some(&*body.stream));
459
460        // 6.3 If body’s type is non-null and response’s header list does not contain `Content-Type`,
461        // then append (`Content-Type`, body’s type) to response’s header list.
462        if let Some(content_type_contents) = &body.content_type &&
463            !response
464                .Headers(cx)
465                .Has(ByteString::new(b"Content-Type".to_vec()))
466                .unwrap()
467        {
468            response.Headers(cx).Append(
469                ByteString::new(b"Content-Type".to_vec()),
470                ByteString::new(content_type_contents.as_bytes(cx.no_gc()).to_vec()),
471            )?;
472        };
473    } else {
474        response.body_stream.set(None);
475        response.fetch_body_stream.set(None);
476    }
477
478    Ok(response)
479}
480
481fn serialize_without_fragment(url: &ServoUrl) -> &str {
482    &url[..Position::AfterQuery]
483}
484
485impl Response {
486    pub(crate) fn set_type(
487        &self,
488        cx: &mut js::context::JSContext,
489        new_response_type: DOMResponseType,
490    ) {
491        *self.response_type.borrow_mut() = new_response_type;
492        self.set_response_members_by_type(cx, new_response_type);
493    }
494
495    pub(crate) fn set_headers(
496        &self,
497        cx: &mut js::context::JSContext,
498        option_hyper_headers: Option<Serde<HyperHeaders>>,
499    ) {
500        self.Headers(cx).set_headers(match option_hyper_headers {
501            Some(hyper_headers) => hyper_headers.into_inner(),
502            None => HyperHeaders::new(),
503        });
504    }
505
506    pub(crate) fn set_status(&self, status: &HttpStatus) {
507        self.status.borrow_mut().clone_from(status);
508    }
509
510    pub(crate) fn set_final_url(&self, final_url: ServoUrl) {
511        *self.url.borrow_mut() = Some(final_url);
512    }
513
514    pub(crate) fn set_redirected(&self, is_redirected: bool) {
515        self.redirected.set(is_redirected);
516    }
517
518    fn set_response_members_by_type(
519        &self,
520        cx: &mut js::context::JSContext,
521        response_type: DOMResponseType,
522    ) {
523        match response_type {
524            DOMResponseType::Error => {
525                *self.status.borrow_mut() = HttpStatus::new_error();
526                self.set_headers(cx, None);
527            },
528            DOMResponseType::Opaque => {
529                *self.url_list.borrow_mut() = vec![];
530                *self.status.borrow_mut() = HttpStatus::new_error();
531                self.set_headers(cx, None);
532                self.body_stream.set(None);
533                self.fetch_body_stream.set(None);
534            },
535            DOMResponseType::Opaqueredirect => {
536                *self.status.borrow_mut() = HttpStatus::new_error();
537                self.set_headers(cx, None);
538                self.body_stream.set(None);
539                self.fetch_body_stream.set(None);
540            },
541            DOMResponseType::Default => {},
542            DOMResponseType::Basic => {},
543            DOMResponseType::Cors => {},
544        }
545    }
546
547    pub(crate) fn stream_chunk(&self, cx: &mut js::context::JSContext, chunk: Bytes) {
548        if let Some(body) = self.fetch_body_stream.get() {
549            body.enqueue_native(cx, chunk.to_vec());
550        }
551    }
552
553    pub(crate) fn finish(&self, cx: &mut js::context::JSContext) {
554        if let Some(body) = self.fetch_body_stream.get() {
555            body.controller_close_native(cx);
556        }
557    }
558}