1use 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 #[no_trace]
52 url: DomRefCell<Option<ServoUrl>>,
53 #[no_trace]
54 url_list: DomRefCell<Vec<ServoUrl>>,
55 body_stream: MutNullableDom<ReadableStream>,
57 fetch_body_stream: MutNullableDom<ReadableStream>,
60 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 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 pub(crate) fn new_fetch_response(
95 cx: &mut js::context::JSContext,
96 global: &GlobalScope,
97 ) -> DomRoot<Response> {
98 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
157fn is_redirect_status(status: u16) -> bool {
159 status == 301 || status == 302 || status == 303 || status == 307 || status == 308
160}
161
162fn is_valid_status_text(status_text: &ByteString) -> bool {
164 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
173fn 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 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 let response = Response::new_with_proto(cx, global, proto);
190
191 response.Headers(cx).set_guard(Guard::Response);
194
195 let body_with_type = match body_init {
198 Some(body) => Some(body.extract(cx, global, false)?),
199 None => None,
200 };
201
202 initialize_response(cx, body_with_type, init, response)
204 }
205
206 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 fn Redirect(
217 cx: &mut js::context::JSContext,
218 global: &GlobalScope,
219 url: USVString,
220 status: u16,
221 ) -> Fallible<DomRoot<Response>> {
222 let base_url = global.api_base_url();
224 let parsed_url = base_url.join(&url.0);
225
226 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 if !is_redirect_status(status) {
234 return Err(Error::Range(c"status is not a redirect status".to_owned()));
235 }
236
237 let response = Response::new(cx, global);
240
241 *response.status.borrow_mut() = HttpStatus::new_raw(status, vec![]);
243
244 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 response.Headers(cx).set_guard(Guard::Immutable);
254
255 Ok(response)
257 }
258
259 fn CreateFromJson(
261 cx: &mut js::context::JSContext,
262 global: &GlobalScope,
263 data: HandleValue,
264 init: &ResponseBinding::ResponseInit,
265 ) -> Fallible<DomRoot<Response>> {
266 let json_str = serialize_jsval_to_json_utf8(cx, data)?;
268
269 let body_init = BodyInit::String(json_str);
273 let mut body = body_init.extract(cx, global, false)?;
274
275 let response = Response::new(cx, global);
278 response.Headers(cx).set_guard(Guard::Response);
279
280 body.content_type = Some(DOMString::from_static("application/json"));
282 initialize_response(cx, Some(body), init, response)
283 }
284
285 fn Type(&self) -> DOMResponseType {
287 *self.response_type.borrow() }
289
290 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 fn Redirected(&self) -> bool {
307 self.redirected.get()
308 }
309
310 fn Status(&self) -> u16 {
312 self.status.borrow().raw_code()
313 }
314
315 fn Ok(&self) -> bool {
317 self.status.borrow().is_success()
318 }
319
320 fn StatusText(&self) -> ByteString {
322 ByteString::new(self.status.borrow().message().to_vec())
323 }
324
325 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 fn Clone(&self, cx: &mut js::context::JSContext) -> Fallible<DomRoot<Response>> {
333 if self.is_unusable() {
335 return Err(Error::Type(c"cannot clone a disturbed response".to_owned()));
336 }
337
338 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 clone_body_stream_for_dom_body(cx, &self.body_stream, &new_response.body_stream)?;
361 new_response.fetch_body_stream.set(None);
363
364 Ok(new_response)
365 }
366
367 fn BodyUsed(&self) -> bool {
369 self.is_body_used()
370 }
371
372 fn GetBody(&self) -> Option<DomRoot<ReadableStream>> {
374 self.body()
375 }
376
377 fn Text(&self, cx: &mut js::context::JSContext) -> RootedPromise {
379 consume_body(cx, self, BodyType::Text)
380 }
381
382 fn Blob(&self, cx: &mut js::context::JSContext) -> RootedPromise {
384 consume_body(cx, self, BodyType::Blob)
385 }
386
387 fn FormData(&self, cx: &mut js::context::JSContext) -> RootedPromise {
389 consume_body(cx, self, BodyType::FormData)
390 }
391
392 fn Json(&self, cx: &mut js::context::JSContext) -> RootedPromise {
394 consume_body(cx, self, BodyType::Json)
395 }
396
397 fn ArrayBuffer(&self, cx: &mut js::context::JSContext) -> RootedPromise {
399 consume_body(cx, self, BodyType::ArrayBuffer)
400 }
401
402 fn Bytes(&self, cx: &mut js::context::JSContext) -> RootedPromise {
404 consume_body(cx, self, BodyType::Bytes)
405 }
406
407 fn TextStream(&self, cx: &mut js::context::JSContext) -> Fallible<DomRoot<ReadableStream>> {
409 body_text_stream(cx, self)
410 }
411}
412
413fn 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 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 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 *response.status.borrow_mut() =
440 HttpStatus::new_raw(init.status, init.statusText.clone().into());
441
442 if let Some(ref headers_member) = init.headers {
444 response.Headers(cx).fill(Some(headers_member))?;
445 }
446
447 if let Some(ref body) = body {
449 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 response.body_stream.set(Some(&*body.stream));
458 response.fetch_body_stream.set(Some(&*body.stream));
459
460 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}