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