Skip to main content

script/dom/xmlhttprequest/
xmlhttprequest.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::borrow::ToOwned;
6use std::cell::Cell;
7use std::cmp;
8use std::default::Default;
9use std::str::{self, FromStr};
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12
13use atomic_refcell::AtomicRefCell;
14use bytes::{Bytes, BytesMut};
15use crossbeam_channel::RecvTimeoutError;
16use data_url::mime::Mime;
17use dom_struct::dom_struct;
18use encoding_rs::{Encoding, UTF_8};
19use headers::{ContentLength, ContentType, HeaderMapExt};
20use html5ever::serialize;
21use html5ever::serialize::SerializeOpts;
22use http::Method;
23use http::header::{self, HeaderMap, HeaderName, HeaderValue};
24use hyper_serde::Serde;
25use js::context::{JSContext, NoGC};
26use js::conversions::ToJSValConvertible;
27use js::jsapi::Heap;
28use js::jsval::{JSVal, NullValue};
29use js::rust::wrappers2::{JS_ClearPendingException, JS_ParseJSON};
30use js::rust::{HandleObject, MutableHandleValue};
31use js::typedarray::{ArrayBufferU8, HeapArrayBuffer};
32use net_traits::blob_url_store::UrlWithBlobClaim;
33use net_traits::fetch::fetch_controller::FetchController;
34use net_traits::fetch::headers::extract_mime_type_as_dataurl_mime;
35use net_traits::http_status::HttpStatus;
36use net_traits::request::{CredentialsMode, Referrer, RequestBuilder, RequestId, RequestMode};
37use net_traits::{
38    FetchMetadata, FilteredMetadata, NetworkError, ReferrerPolicy, ResourceFetchTiming,
39    trim_http_whitespace,
40};
41use script_bindings::cell::DomRefCell;
42use script_bindings::num::Finite;
43use script_bindings::reflector::reflect_dom_object_with_proto;
44use script_bindings::trace::RootedTraceableBox;
45use script_traits::DocumentActivity;
46use servo_constellation_traits::BlobImpl;
47use servo_url::ServoUrl;
48use stylo_atoms::Atom;
49use url::Position;
50
51use crate::dom::bindings::buffer_source::{HeapBufferSource, get_buffer_source_copy};
52use crate::dom::bindings::cell::AtomicSafeBorrowMut;
53use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
54use crate::dom::bindings::codegen::Bindings::XMLHttpRequestBinding::{
55    XMLHttpRequestMethods, XMLHttpRequestResponseType,
56};
57use crate::dom::bindings::codegen::UnionTypes::DocumentOrBlobOrArrayBufferViewOrArrayBufferOrFormDataOrStringOrURLSearchParams as DocumentOrXMLHttpRequestBodyInit;
58use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
59use crate::dom::bindings::inheritance::Castable;
60use crate::dom::bindings::refcounted::Trusted;
61use crate::dom::bindings::reflector::DomGlobal;
62use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
63use crate::dom::bindings::str::{ByteString, DOMString, USVString, is_token};
64use crate::dom::blob::{Blob, normalize_type_string};
65use crate::dom::csp::{GlobalCspReporting, Violation};
66use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
67use crate::dom::event::{Event, EventBubbles, EventCancelable};
68use crate::dom::eventtarget::EventTarget;
69use crate::dom::globalscope::GlobalScope;
70use crate::dom::headers::is_forbidden_request_header;
71use crate::dom::node::Node;
72use crate::dom::performance::performanceresourcetiming::InitiatorType;
73use crate::dom::progressevent::ProgressEvent;
74use crate::dom::servoparser::ServoParser;
75use crate::dom::servoparser::html::HtmlSerialize;
76use crate::dom::stream::readablestream::ReadableStream;
77use crate::dom::window::Window;
78use crate::dom::workerglobalscope::WorkerGlobalScope;
79use crate::dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget;
80use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload;
81use crate::event_loop::document_loader::DocumentLoader;
82use crate::event_loop::timers::{OneshotTimerCallback, OneshotTimerHandle};
83use crate::fetch::body::{
84    BodySource, Extractable, ExtractedBody, decode_to_utf16_with_bom_removal,
85};
86use crate::fetch::fetch::RequestWithGlobalScope;
87use crate::fetch::network_listener::{self, FetchResponseListener, ResourceTimingListener};
88use crate::mime::{APPLICATION, CHARSET, HTML, MimeExt, TEXT, XML};
89use crate::tasks::task_source::{SendableTaskSource, TaskSourceName};
90use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
91
92#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
93enum XMLHttpRequestState {
94    Unsent = 0,
95    Opened = 1,
96    HeadersReceived = 2,
97    Loading = 3,
98    Done = 4,
99}
100
101#[derive(Clone, Copy)]
102enum ErrorType {
103    Abort,
104    Timeout,
105    Network,
106}
107
108#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
109pub(crate) struct GenerationId(u32);
110
111/// Closure of required data for each async network event that comprises the
112/// XHR's response.
113struct XHRContext {
114    xhr: TrustedXHRAddress,
115    gen_id: GenerationId,
116    sync_status: Arc<AtomicRefCell<Option<ErrorResult>>>,
117    url: ServoUrl,
118}
119
120impl FetchResponseListener for XHRContext {
121    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
122
123    fn process_response(
124        &mut self,
125        cx: &mut JSContext,
126        _: &GlobalScope,
127        _: RequestId,
128        metadata: Result<FetchMetadata, NetworkError>,
129    ) {
130        let xhr = self.xhr.root();
131        let rv = xhr.process_headers_available(cx, self.gen_id, metadata);
132        if rv.is_err() {
133            *self.sync_status.safe_borrow_mut(cx.no_gc()) = Some(rv);
134        }
135    }
136
137    fn process_response_chunk(
138        &mut self,
139        cx: &mut JSContext,
140        _: &GlobalScope,
141        _: RequestId,
142        chunk: Bytes,
143    ) {
144        self.xhr
145            .root()
146            .process_data_available(cx, self.gen_id, chunk);
147    }
148
149    fn process_response_eof(
150        self,
151        cx: &mut JSContext,
152        global: &GlobalScope,
153        _: RequestId,
154        response: Result<(), NetworkError>,
155        timing: ResourceFetchTiming,
156    ) {
157        network_listener::submit_timing(cx, global, &self, &response, &timing);
158
159        let rv = self
160            .xhr
161            .root()
162            .process_response_complete(cx, self.gen_id, response.map(|_| ()));
163        *self.sync_status.safe_borrow_mut(cx.no_gc()) = Some(rv);
164    }
165
166    fn process_csp_violations(
167        &mut self,
168        cx: &mut js::context::JSContext,
169        global: &GlobalScope,
170        _request_id: RequestId,
171        violations: Vec<Violation>,
172    ) {
173        global.report_csp_violations(cx, violations, None, None);
174    }
175
176    fn should_invoke(&self) -> bool {
177        self.xhr.root().generation_id.get() == self.gen_id
178    }
179}
180
181impl ResourceTimingListener for XHRContext {
182    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
183        (InitiatorType::XMLHttpRequest, self.url.clone())
184    }
185}
186
187#[derive(Clone)]
188enum XHRProgress {
189    /// Notify that headers have been received
190    HeadersReceived(GenerationId, Option<HeaderMap>, HttpStatus),
191    /// Partial progress (after receiving headers), containing portion of the response
192    Loading(GenerationId, Bytes),
193    /// Loading is done
194    Done(GenerationId),
195    /// There was an error
196    Errored(GenerationId, ErrorType),
197}
198
199impl XHRProgress {
200    fn generation_id(&self) -> GenerationId {
201        match *self {
202            XHRProgress::HeadersReceived(id, _, _) |
203            XHRProgress::Loading(id, _) |
204            XHRProgress::Done(id) |
205            XHRProgress::Errored(id, _) => id,
206        }
207    }
208}
209
210#[dom_struct]
211pub(crate) struct XMLHttpRequest {
212    eventtarget: XMLHttpRequestEventTarget,
213    ready_state: Cell<XMLHttpRequestState>,
214    timeout: Cell<Duration>,
215    with_credentials: Cell<bool>,
216    upload: Dom<XMLHttpRequestUpload>,
217    response_url: DomRefCell<String>,
218    #[no_trace]
219    status: DomRefCell<HttpStatus>,
220    #[no_trace]
221    response: DomRefCell<BytesMut>,
222    response_type: Cell<XMLHttpRequestResponseType>,
223    response_xml: MutNullableDom<Document>,
224    response_blob: MutNullableDom<Blob>,
225    #[ignore_malloc_size_of = "mozjs"]
226    response_arraybuffer: HeapBufferSource<ArrayBufferU8>,
227    #[ignore_malloc_size_of = "Defined in rust-mozjs"]
228    response_json: Heap<JSVal>,
229    #[no_trace]
230    response_headers: DomRefCell<HeaderMap>,
231    #[no_trace]
232    override_mime_type: DomRefCell<Option<Mime>>,
233
234    // Associated concepts
235    #[no_trace]
236    request_method: DomRefCell<Method>,
237    #[no_trace]
238    request_url: DomRefCell<Option<UrlWithBlobClaim>>,
239    #[no_trace]
240    request_headers: DomRefCell<HeaderMap>,
241    request_body_len: Cell<usize>,
242    sync: Cell<bool>,
243    upload_complete: Cell<bool>,
244    upload_listener: Cell<bool>,
245    send_flag: Cell<bool>,
246
247    timeout_cancel: DomRefCell<Option<OneshotTimerHandle>>,
248    fetch_time: Cell<Instant>,
249    generation_id: Cell<GenerationId>,
250    response_status: Cell<Result<(), ()>>,
251    #[no_trace]
252    referrer: Referrer,
253    #[no_trace]
254    referrer_policy: ReferrerPolicy,
255    #[no_trace]
256    controller: DomRefCell<FetchController>,
257}
258
259impl XMLHttpRequest {
260    fn new_inherited(global: &GlobalScope, upload: &XMLHttpRequestUpload) -> XMLHttpRequest {
261        XMLHttpRequest {
262            eventtarget: XMLHttpRequestEventTarget::new_inherited(),
263            ready_state: Cell::new(XMLHttpRequestState::Unsent),
264            timeout: Cell::new(Duration::ZERO),
265            with_credentials: Cell::new(false),
266            upload: Dom::from_ref(upload),
267            response_url: DomRefCell::new(String::new()),
268            status: DomRefCell::new(HttpStatus::new_error()),
269            response: DomRefCell::new(BytesMut::new()),
270            response_type: Cell::new(XMLHttpRequestResponseType::_empty),
271            response_xml: Default::default(),
272            response_blob: Default::default(),
273            response_arraybuffer: HeapBufferSource::default(),
274            response_json: Heap::default(),
275            response_headers: DomRefCell::new(HeaderMap::new()),
276            override_mime_type: DomRefCell::new(None),
277
278            request_method: DomRefCell::new(Method::GET),
279            request_url: DomRefCell::new(None),
280            request_headers: DomRefCell::new(HeaderMap::new()),
281            request_body_len: Cell::new(0),
282            sync: Cell::new(false),
283            upload_complete: Cell::new(false),
284            upload_listener: Cell::new(false),
285            send_flag: Cell::new(false),
286
287            timeout_cancel: DomRefCell::new(None),
288            fetch_time: Cell::new(Instant::now()),
289            generation_id: Cell::new(GenerationId(0)),
290            response_status: Cell::new(Ok(())),
291            referrer: global.get_referrer(),
292            referrer_policy: global.get_referrer_policy(),
293            controller: DomRefCell::new(Default::default()),
294        }
295    }
296
297    fn new(
298        cx: &mut JSContext,
299        global: &GlobalScope,
300        proto: Option<HandleObject>,
301    ) -> DomRoot<XMLHttpRequest> {
302        let upload = XMLHttpRequestUpload::new(cx, global);
303        reflect_dom_object_with_proto(
304            cx,
305            Box::new(XMLHttpRequest::new_inherited(global, &upload)),
306            global,
307            proto,
308        )
309    }
310
311    fn sync_in_window(&self) -> bool {
312        self.sync.get() && self.global().is::<Window>()
313    }
314}
315
316impl XMLHttpRequestMethods<crate::DomTypeHolder> for XMLHttpRequest {
317    /// <https://xhr.spec.whatwg.org/#constructors>
318    fn Constructor(
319        cx: &mut JSContext,
320        global: &GlobalScope,
321        proto: Option<HandleObject>,
322    ) -> Fallible<DomRoot<XMLHttpRequest>> {
323        Ok(XMLHttpRequest::new(cx, global, proto))
324    }
325
326    // https://xhr.spec.whatwg.org/#handler-xhr-onreadystatechange
327    event_handler!(
328        readystatechange,
329        GetOnreadystatechange,
330        SetOnreadystatechange
331    );
332
333    /// <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate>
334    fn ReadyState(&self) -> u16 {
335        self.ready_state.get() as u16
336    }
337
338    /// <https://xhr.spec.whatwg.org/#the-open()-method>
339    fn Open(&self, cx: &mut JSContext, method: ByteString, url: USVString) -> ErrorResult {
340        // Step 8
341        self.Open_(cx, method, url, true, None, None)
342    }
343
344    /// <https://xhr.spec.whatwg.org/#the-open()-method>
345    fn Open_(
346        &self,
347        cx: &mut JSContext,
348        method: ByteString,
349        url: USVString,
350        asynch: bool,
351        username: Option<USVString>,
352        password: Option<USVString>,
353    ) -> ErrorResult {
354        // Step 1. If this’s relevant global object is a Window object and its associated
355        // Document is not fully active, then throw an "InvalidStateError" DOMException.
356        let global = self.global();
357        if let Some(window) = global.downcast::<Window>() &&
358            !window.Document().is_fully_active()
359        {
360            return Err(Error::InvalidState(Some(
361                "Document is not fully active".into(),
362            )));
363        }
364
365        // Step 5
366        // FIXME(seanmonstar): use a Trie instead?
367        let maybe_method = method.as_str().and_then(|s| {
368            // Note: hyper tests against the uppercase versions
369            // Since we want to pass methods not belonging to the short list above
370            // without changing capitalization, this will actually sidestep rust-http's type system
371            // since methods like "patch" or "PaTcH" will be considered extension methods
372            // despite the there being a rust-http method variant for them
373            let upper = s.to_ascii_uppercase();
374            match &*upper {
375                "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "CONNECT" | "TRACE" |
376                "TRACK" => upper.parse().ok(),
377                _ => s.parse().ok(),
378            }
379        });
380
381        match maybe_method {
382            // Step 4
383            Some(Method::CONNECT) | Some(Method::TRACE) => {
384                Err(Error::Security(Some("Method is forbidden".into())))
385            },
386            Some(ref t) if t.as_str() == "TRACK" => {
387                Err(Error::Security(Some("Method is forbidden".into())))
388            },
389            Some(parsed_method) => {
390                // Step 3
391                if !is_token(&method) {
392                    return Err(Error::Syntax(Some("Invalid method".into())));
393                }
394
395                // Step 5. Let parsedURL be the result of encoding-parsing a URL url, relative to this’s
396                // relevant settings object.
397                let mut parsed_url = match self
398                    .global()
399                    .encoding_parse_a_url(&url.0)
400                    .map(|url| ensure_blob_referenced_by_url_is_kept_alive(&global, url))
401                {
402                    Ok(parsed) => parsed,
403                    Err(_) => {
404                        // Step 6. If parsedURL is failure, then throw a "SyntaxError" DOMException.
405                        return Err(Error::Syntax(Some("Invalid URL".into())));
406                    },
407                };
408
409                // Step 8. If parsedURL’s host is non-null, then:
410                if parsed_url.host().is_some() {
411                    // Step 8.1 If the username argument is not null, set the username given parsedURL and username.
412                    if let Some(user_str) = username &&
413                        let Err(error) = parsed_url.set_username(&user_str.0)
414                    {
415                        warn!("Could not set username on XMLHttpRequest: {error:?}");
416                    }
417
418                    // Step 8.2 If the password argument is not null, set the password given parsedURL and password.
419                    if let Some(pass_str) = password &&
420                        let Err(error) = parsed_url.set_password(Some(&pass_str.0))
421                    {
422                        warn!("Could not set password on XMLHttpRequest: {error:?}");
423                    }
424                }
425
426                // Step 9. If async is false, the current global object is a Window object, and
427                // either this’s timeout is not 0 or this’s response type is not the empty string,
428                // then throw an "InvalidAccessError" DOMException.
429                if !asynch && self.global().is::<Window>() {
430                    if !self.timeout.get().is_zero() {
431                        return Err(Error::InvalidAccess(Some(
432                            "Nonzero timeout for synchronous request".into(),
433                        )));
434                    }
435                    if self.response_type.get() != XMLHttpRequestResponseType::_empty {
436                        return Err(Error::InvalidAccess(Some(
437                            "Nonempty response type for synchronous request".into(),
438                        )));
439                    }
440                }
441
442                // Step 10. Terminate this’s fetch controller.
443                self.terminate_ongoing_fetch(cx.no_gc());
444
445                // FIXME(#13767): In the WPT test: FileAPI/blob/Blob-XHR-revoke.html,
446                // the xhr.open(url) is expected to hold a reference to the URL,
447                // thus renders following revocations invalid. Though we won't
448                // implement this for now, if ever needed, we should check blob
449                // scheme and trigger corresponding actions here.
450
451                // Step 12
452                *self.request_method.safe_borrow_mut(cx.no_gc()) = parsed_method;
453                *self.request_url.safe_borrow_mut(cx.no_gc()) = Some(parsed_url);
454                self.sync.set(!asynch);
455                *self.request_headers.safe_borrow_mut(cx.no_gc()) = HeaderMap::new();
456                self.send_flag.set(false);
457                self.upload_listener.set(false);
458                *self.status.safe_borrow_mut(cx.no_gc()) = HttpStatus::new_error();
459
460                // Step 13
461                if self.ready_state.get() != XMLHttpRequestState::Opened {
462                    self.change_ready_state(cx, XMLHttpRequestState::Opened);
463                }
464                Ok(())
465            },
466            // Step 3
467            // This includes cases where as_str() returns None, and when is_token() returns false,
468            // both of which indicate invalid extension method names
469            _ => Err(Error::Syntax(Some("Invalid method".into()))),
470        }
471    }
472
473    /// <https://xhr.spec.whatwg.org/#the-setrequestheader()-method>
474    fn SetRequestHeader(&self, no_gc: &NoGC, name: ByteString, value: ByteString) -> ErrorResult {
475        // Step 1: If this’s state is not opened, then throw an "InvalidStateError" DOMException.
476        if self.ready_state.get() != XMLHttpRequestState::Opened {
477            return Err(Error::InvalidState(Some("Request not yet open".into())));
478        }
479        // Step 2: If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
480        if self.send_flag.get() {
481            return Err(Error::InvalidState(Some("Request already sent".into())));
482        }
483
484        // Step 3: Normalize value.
485        let value = trim_http_whitespace(&value);
486
487        // Step 4: If name is not a header name or value is not a header value, then throw a
488        // "SyntaxError" DOMException.
489        if !is_token(&name) {
490            return Err(Error::Syntax(Some("Invalid header name".into())));
491        }
492        if !is_field_value(value) {
493            return Err(Error::Syntax(Some("Invalid header value".into())));
494        }
495
496        // FIXME: This looks wrong. We should use HeaderName::from_bytes instead.
497        let name_str = name
498            .as_str()
499            .ok_or(Error::Syntax(Some("Non-UTF8 header name".into())))?;
500
501        // Step 5: If (name, value) is a forbidden request-header, then return.
502        if is_forbidden_request_header(name_str, value) {
503            return Ok(());
504        }
505
506        debug!(
507            "SetRequestHeader: name={:?}, value={:?}",
508            name_str,
509            str::from_utf8(value).ok()
510        );
511        let mut headers = self.request_headers.safe_borrow_mut(no_gc);
512
513        // Step 6: Combine (name, value) in this’s author request headers.
514        // https://fetch.spec.whatwg.org/#concept-header-list-combine
515        let value = match headers.get(name_str).map(HeaderValue::as_bytes) {
516            Some(raw) => {
517                let mut buf = raw.to_vec();
518                buf.extend_from_slice(b", ");
519                buf.extend_from_slice(value);
520                buf
521            },
522            None => value.into(),
523        };
524
525        if let (Ok(header_name), Ok(header_value)) = (
526            HeaderName::from_str(name_str),
527            HeaderValue::from_bytes(&value),
528        ) {
529            headers.insert(header_name, header_value);
530        } else {
531            warn!("Not setting header in XMLHttpRequest {name_str:?}: {value:?}");
532        }
533
534        Ok(())
535    }
536
537    /// <https://xhr.spec.whatwg.org/#the-timeout-attribute>
538    fn Timeout(&self) -> u32 {
539        self.timeout.get().as_millis() as u32
540    }
541
542    /// <https://xhr.spec.whatwg.org/#the-timeout-attribute>
543    fn SetTimeout(&self, no_gc: &NoGC, timeout: u32) -> ErrorResult {
544        // Step 1
545        if self.sync_in_window() {
546            return Err(Error::InvalidAccess(Some(
547                "Timeouts are not allowed for synchronous requests".into(),
548            )));
549        }
550
551        // Step 2
552        let timeout = Duration::from_millis(timeout as u64);
553        self.timeout.set(timeout);
554
555        if self.send_flag.get() {
556            if timeout.is_zero() {
557                self.cancel_timeout(no_gc);
558                return Ok(());
559            }
560            let progress = Instant::now() - self.fetch_time.get();
561            if timeout > progress {
562                self.set_timeout(no_gc, timeout - progress);
563            } else {
564                // Immediately execute the timeout steps
565                self.set_timeout(no_gc, Duration::ZERO);
566            }
567        }
568        Ok(())
569    }
570
571    /// <https://xhr.spec.whatwg.org/#the-withcredentials-attribute>
572    fn WithCredentials(&self) -> bool {
573        self.with_credentials.get()
574    }
575
576    /// <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials>
577    fn SetWithCredentials(&self, with_credentials: bool) -> ErrorResult {
578        match self.ready_state.get() {
579            // Step 1
580            XMLHttpRequestState::HeadersReceived |
581            XMLHttpRequestState::Loading |
582            XMLHttpRequestState::Done => {
583                Err(Error::InvalidState(Some("Response in progress".into())))
584            },
585            // Step 2
586            _ if self.send_flag.get() => {
587                Err(Error::InvalidState(Some("Request has been sent".into())))
588            },
589            // Step 3
590            _ => {
591                self.with_credentials.set(with_credentials);
592                Ok(())
593            },
594        }
595    }
596
597    /// <https://xhr.spec.whatwg.org/#the-upload-attribute>
598    fn Upload(&self) -> DomRoot<XMLHttpRequestUpload> {
599        DomRoot::from_ref(&*self.upload)
600    }
601
602    /// <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send>
603    fn Send(
604        &self,
605        cx: &mut JSContext,
606        data: Option<DocumentOrXMLHttpRequestBodyInit>,
607    ) -> ErrorResult {
608        // Step 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
609        // Step 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
610        if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
611            return Err(Error::InvalidState(Some(
612                "XMLHttpRequest not open or already sent".into(),
613            )));
614        }
615        let Some(url) = self.request_url.borrow().clone() else {
616            return Err(Error::InvalidState(Some("XMLHttpRequest not open".into())));
617        };
618
619        // Step 3. If this’s request method is `GET` or `HEAD`, then set body to null.
620        let data = match *self.request_method.borrow() {
621            Method::GET | Method::HEAD => None,
622            _ => data,
623        };
624
625        // Step 4 (first half)
626        let mut extracted_or_serialized = match data {
627            Some(DocumentOrXMLHttpRequestBodyInit::Document(ref doc)) => {
628                let bytes = Vec::from(&*serialize_document(doc)?.as_bytes(cx.no_gc()));
629                let content_type = if doc.is_html_document() {
630                    "text/html;charset=UTF-8"
631                } else {
632                    "application/xml;charset=UTF-8"
633                };
634                let total_bytes = bytes.len();
635                let global = self.global();
636                let stream = ReadableStream::new_from_bytes(cx, &global, bytes)?;
637                Some(ExtractedBody {
638                    stream,
639                    total_bytes: Some(total_bytes),
640                    content_type: Some(DOMString::from(content_type)),
641                    source: BodySource::Object,
642                })
643            },
644            Some(DocumentOrXMLHttpRequestBodyInit::Blob(ref b)) => {
645                let extracted_body = b
646                    .extract(cx, &self.global(), false)
647                    .expect("Couldn't extract body.");
648                if !extracted_body.in_memory() && self.sync.get() {
649                    warn!("Sync XHR with not in-memory Blob as body not supported");
650                    None
651                } else {
652                    Some(extracted_body)
653                }
654            },
655            Some(DocumentOrXMLHttpRequestBodyInit::FormData(ref formdata)) => Some(
656                formdata
657                    .extract(cx, &self.global(), false)
658                    .expect("Couldn't extract body."),
659            ),
660            Some(DocumentOrXMLHttpRequestBodyInit::String(ref str)) => Some(
661                str.extract(cx, &self.global(), false)
662                    .expect("Couldn't extract body."),
663            ),
664            Some(DocumentOrXMLHttpRequestBodyInit::URLSearchParams(ref urlsp)) => Some(
665                urlsp
666                    .extract(cx, &self.global(), false)
667                    .expect("Couldn't extract body."),
668            ),
669            Some(DocumentOrXMLHttpRequestBodyInit::ArrayBuffer(ref typedarray)) => {
670                let bytes = get_buffer_source_copy(typedarray.into());
671                let total_bytes = bytes.len();
672                let global = self.global();
673                let stream = ReadableStream::new_from_bytes(cx, &global, bytes)?;
674                Some(ExtractedBody {
675                    stream,
676                    total_bytes: Some(total_bytes),
677                    content_type: None,
678                    source: BodySource::Object,
679                })
680            },
681            Some(DocumentOrXMLHttpRequestBodyInit::ArrayBufferView(ref typedarray)) => {
682                let bytes = get_buffer_source_copy(typedarray.into());
683                let total_bytes = bytes.len();
684                let global = self.global();
685                let stream = ReadableStream::new_from_bytes(cx, &global, bytes)?;
686                Some(ExtractedBody {
687                    stream,
688                    total_bytes: Some(total_bytes),
689                    content_type: None,
690                    source: BodySource::Object,
691                })
692            },
693            None => None,
694        };
695
696        self.request_body_len.set(
697            extracted_or_serialized
698                .as_ref()
699                .map_or(0, |e| e.total_bytes.unwrap_or(0)),
700        );
701
702        // Step 5. If one or more event listeners are registered on this’s upload object,
703        // then set this’s upload listener flag.
704        // If we dont have data to upload, we dont want to emit events
705        let has_handlers = self.upload.upcast::<EventTarget>().has_handlers();
706        self.upload_listener.set(has_handlers && data.is_some());
707
708        // todo preserved headers?
709
710        // Step 7. Unset this’s upload complete flag.
711        self.upload_complete.set(false);
712
713        // Step 8. Unset this’s timed out flag.
714        // FIXME handle the 'timed out flag'
715
716        // Step 9. If req’s body is null, then set this’s upload complete flag.
717        self.upload_complete.set(extracted_or_serialized.is_none());
718
719        // Step 10. Set this’s send() flag.
720        self.send_flag.set(true);
721
722        // Step 11. If this’s synchronous flag is unset, then:
723        if !self.sync.get() {
724            // If one of the event handlers below aborts the fetch by calling
725            // abort or open we will need the current generation id to detect it.
726            let gen_id = self.generation_id.get();
727
728            // Step 11.1 Fire a progress event named loadstart at this with 0 and 0.
729            self.dispatch_response_progress_event(cx, atom!("loadstart"));
730            if self.generation_id.get() != gen_id {
731                return Ok(());
732            }
733
734            // Step 11.2 If this’s upload complete flag is unset and this’s upload listener flag is set,
735            // then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted
736            // and requestBodyLength.
737            if !self.upload_complete.get() && self.upload_listener.get() {
738                self.dispatch_upload_progress_event(cx, atom!("loadstart"), Ok(Some(0)));
739                if self.generation_id.get() != gen_id {
740                    return Ok(());
741                }
742            }
743        }
744
745        // Step 6
746        // TODO - set referrer_policy/referrer_url in request
747        let credentials_mode = if self.with_credentials.get() {
748            CredentialsMode::Include
749        } else {
750            CredentialsMode::CredentialsSameOrigin
751        };
752        let use_url_credentials = !url.username().is_empty() || url.password().is_some();
753
754        let content_type = match extracted_or_serialized.as_mut() {
755            Some(body) => body.content_type.take(),
756            None => None,
757        };
758
759        let global = self.global();
760        let mut request = RequestBuilder::new(global.webview_id(), url, self.referrer.clone())
761            .method(self.request_method.borrow().clone())
762            .headers((*self.request_headers.borrow()).clone())
763            .unsafe_request(true)
764            // XXXManishearth figure out how to avoid this clone
765            .body(extracted_or_serialized.map(|e| e.into_net_request_body(cx).0))
766            .synchronous(self.sync.get())
767            .mode(RequestMode::CorsMode)
768            .use_cors_preflight(self.upload_listener.get())
769            .credentials_mode(credentials_mode)
770            .use_url_credentials(use_url_credentials)
771            .with_global_scope(&global)
772            .referrer_policy(self.referrer_policy);
773
774        // step 4 (second half)
775        if let Some(content_type) = content_type {
776            let encoding = match data {
777                Some(DocumentOrXMLHttpRequestBodyInit::String(_)) |
778                Some(DocumentOrXMLHttpRequestBodyInit::Document(_)) =>
779                // XHR spec differs from http, and says UTF-8 should be in capitals,
780                // instead of "utf-8", which is what Hyper defaults to. So not
781                // using content types provided by Hyper.
782                {
783                    Some("UTF-8")
784                },
785                _ => None,
786            };
787
788            // We cannot use typed header insertion with `mime::Mime` parsing here,
789            // since it lowercases `charset=UTF-8`: https://github.com/hyperium/mime/issues/116
790            let mut content_type_set = false;
791            if !request.headers.contains_key(header::CONTENT_TYPE) &&
792                let Ok(content_type_value) = HeaderValue::from_str(&content_type.str())
793            {
794                request
795                    .headers
796                    .insert(header::CONTENT_TYPE, content_type_value);
797                content_type_set = true;
798            }
799
800            if !content_type_set {
801                let content_type = request.headers.typed_get::<ContentType>();
802                if let Some(content_type) = content_type &&
803                    let Some(encoding) = encoding &&
804                    let Ok(mime) = content_type.to_string().parse::<Mime>()
805                {
806                    for param in mime.parameters.iter() {
807                        if param.0 == CHARSET && !param.1.as_str().eq_ignore_ascii_case(encoding) {
808                            let new_params: Vec<_> =
809                                mime.parameters.iter().filter(|p| p.0 != CHARSET).collect();
810
811                            let new_mime = format!(
812                                "{}/{};charset={encoding}{}{}",
813                                mime.type_,
814                                mime.subtype,
815                                if new_params.is_empty() { "" } else { "; " },
816                                new_params
817                                    .iter()
818                                    .map(|param| format!("{}={}", param.0, param.1))
819                                    .collect::<Vec<String>>()
820                                    .join("; ")
821                            );
822
823                            if let Ok(content_type_header) = HeaderValue::from_str(&new_mime) {
824                                request
825                                    .headers
826                                    .insert(header::CONTENT_TYPE, content_type_header);
827                            }
828                        }
829                    }
830                }
831            }
832        }
833
834        self.fetch_time.set(Instant::now());
835
836        let rv = self.fetch(cx, request, &self.global());
837        // Step 10
838        if self.sync.get() {
839            return rv;
840        }
841
842        let timeout = self.timeout.get();
843        if timeout > Duration::ZERO {
844            self.set_timeout(cx.no_gc(), timeout);
845        }
846        Ok(())
847    }
848
849    /// <https://xhr.spec.whatwg.org/#the-abort()-method>
850    fn Abort(&self, cx: &mut JSContext) {
851        // Step 1
852        self.terminate_ongoing_fetch(cx.no_gc());
853        // Step 2
854        let state = self.ready_state.get();
855        if (state == XMLHttpRequestState::Opened && self.send_flag.get()) ||
856            state == XMLHttpRequestState::HeadersReceived ||
857            state == XMLHttpRequestState::Loading
858        {
859            let gen_id = self.generation_id.get();
860            self.process_partial_response(cx, XHRProgress::Errored(gen_id, ErrorType::Abort));
861            // If open was called in one of the handlers invoked by the
862            // above call then we should terminate the abort sequence
863            if self.generation_id.get() != gen_id {
864                return;
865            }
866        }
867        // Step 3
868        if self.ready_state.get() == XMLHttpRequestState::Done {
869            self.change_ready_state(cx, XMLHttpRequestState::Unsent);
870            self.response_status.set(Err(()));
871            *self.status.safe_borrow_mut(cx.no_gc()) = HttpStatus::new_error();
872            self.response.safe_borrow_mut(cx.no_gc()).clear();
873            self.response_headers.safe_borrow_mut(cx.no_gc()).clear();
874        }
875    }
876
877    /// <https://xhr.spec.whatwg.org/#the-responseurl-attribute>
878    fn ResponseURL(&self) -> USVString {
879        USVString(self.response_url.borrow().clone())
880    }
881
882    /// <https://xhr.spec.whatwg.org/#the-status-attribute>
883    fn Status(&self) -> u16 {
884        self.status.borrow().raw_code()
885    }
886
887    /// <https://xhr.spec.whatwg.org/#the-statustext-attribute>
888    fn StatusText(&self) -> ByteString {
889        ByteString::new(self.status.borrow().message().to_vec())
890    }
891
892    /// <https://xhr.spec.whatwg.org/#the-getresponseheader()-method>
893    fn GetResponseHeader(&self, name: ByteString) -> Option<ByteString> {
894        let headers = self.filter_response_headers();
895        // > All custom header names are lower cased upon conversion to a HeaderName value.
896        // https://docs.rs/http/latest/http/header/struct.HeaderName.html#representation
897        let headers = headers.get_all(HeaderName::from_str(name.as_str()?).ok()?);
898        let mut first = true;
899        let s = headers.iter().fold(Vec::new(), |mut vec, value| {
900            if !first {
901                vec.extend(", ".as_bytes());
902            }
903            if let Ok(v) = str::from_utf8(value.as_bytes()).map(|s| s.trim().as_bytes()) {
904                vec.extend(v);
905                first = false;
906            }
907            vec
908        });
909
910        // There was no header with that name so we never got to change that value
911        if first {
912            None
913        } else {
914            Some(ByteString::new(s))
915        }
916    }
917
918    /// <https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method>
919    fn GetAllResponseHeaders(&self) -> ByteString {
920        let headers = self.filter_response_headers();
921        let keys = headers.keys();
922        let v = keys.fold(Vec::new(), |mut vec, k| {
923            let values = headers.get_all(k);
924            vec.extend(k.as_str().as_bytes());
925            vec.extend(": ".as_bytes());
926            let mut first = true;
927            for value in values {
928                if !first {
929                    vec.extend(", ".as_bytes());
930                    first = false;
931                }
932                vec.extend(value.as_bytes());
933            }
934            vec.extend("\r\n".as_bytes());
935            vec
936        });
937
938        ByteString::new(v)
939    }
940
941    /// <https://xhr.spec.whatwg.org/#the-overridemimetype()-method>
942    fn OverrideMimeType(&self, no_gc: &NoGC, mime: DOMString) -> ErrorResult {
943        // 1. If this’s state is loading or done, then throw an "InvalidStateError"
944        //   DOMException.
945        match self.ready_state.get() {
946            XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
947                return Err(Error::InvalidState(Some("Request already started".into())));
948            },
949            _ => {},
950        }
951
952        // 2. Set this’s override MIME type to the result of parsing mime.
953        // 3. If this’s override MIME type is failure, then set this’s override MIME type
954        //    to application/octet-stream.
955        let override_mime = match mime.parse::<Mime>() {
956            Ok(mime) => mime,
957            Err(_) => "application/octet-stream"
958                .parse::<Mime>()
959                .expect("Fallback MIME type must always parse"),
960        };
961
962        *self.override_mime_type.safe_borrow_mut(no_gc) = Some(override_mime);
963        Ok(())
964    }
965
966    /// <https://xhr.spec.whatwg.org/#the-responsetype-attribute>
967    fn ResponseType(&self) -> XMLHttpRequestResponseType {
968        self.response_type.get()
969    }
970
971    /// <https://xhr.spec.whatwg.org/#the-responsetype-attribute>
972    fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult {
973        // Step 1
974        if self.global().is::<WorkerGlobalScope>() &&
975            response_type == XMLHttpRequestResponseType::Document
976        {
977            return Ok(());
978        }
979        match self.ready_state.get() {
980            // Step 2
981            XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
982                Err(Error::InvalidState(Some("Request already started".into())))
983            },
984            _ => {
985                if self.sync_in_window() {
986                    // Step 3
987                    Err(Error::InvalidAccess(Some(
988                        "Cannot set response type for synchronous requests".into(),
989                    )))
990                } else {
991                    // Step 4
992                    self.response_type.set(response_type);
993                    Ok(())
994                }
995            },
996        }
997    }
998
999    /// <https://xhr.spec.whatwg.org/#the-response-attribute>
1000    fn Response(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
1001        match self.response_type.get() {
1002            XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => {
1003                let ready_state = self.ready_state.get();
1004                // Step 2
1005                if ready_state == XMLHttpRequestState::Done ||
1006                    ready_state == XMLHttpRequestState::Loading
1007                {
1008                    self.text_response().to_jsval(cx, rval);
1009                } else {
1010                    // Step 1
1011                    "".to_jsval(cx, rval);
1012                }
1013            },
1014            // Step 1
1015            _ if self.ready_state.get() != XMLHttpRequestState::Done => {
1016                rval.set(NullValue());
1017            },
1018            // Step 2
1019            XMLHttpRequestResponseType::Document => self.document_response(cx).to_jsval(cx, rval),
1020            XMLHttpRequestResponseType::Json => self.json_response(cx, rval),
1021            XMLHttpRequestResponseType::Blob => self.blob_response(cx).to_jsval(cx, rval),
1022            XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) {
1023                Some(array_buffer) => array_buffer.to_jsval(cx, rval),
1024                None => rval.set(NullValue()),
1025            },
1026        }
1027    }
1028
1029    /// <https://xhr.spec.whatwg.org/#the-responsetext-attribute>
1030    fn GetResponseText(&self) -> Fallible<USVString> {
1031        match self.response_type.get() {
1032            XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => {
1033                Ok(USVString(match self.ready_state.get() {
1034                    // Step 3
1035                    XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
1036                        self.text_response()
1037                    },
1038                    // Step 2
1039                    _ => String::new(),
1040                }))
1041            },
1042            // Step 1
1043            _ => Err(Error::InvalidState(Some(
1044                "Response type does not match".into(),
1045            ))),
1046        }
1047    }
1048
1049    /// <https://xhr.spec.whatwg.org/#the-responsexml-attribute>
1050    fn GetResponseXML(&self, cx: &mut JSContext) -> Fallible<Option<DomRoot<Document>>> {
1051        match self.response_type.get() {
1052            XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Document => {
1053                // Step 3
1054                if let XMLHttpRequestState::Done = self.ready_state.get() {
1055                    Ok(self.document_response(cx))
1056                } else {
1057                    // Step 2
1058                    Ok(None)
1059                }
1060            },
1061            // Step 1
1062            _ => Err(Error::InvalidState(Some(
1063                "Response type does not match".into(),
1064            ))),
1065        }
1066    }
1067}
1068
1069pub(crate) type TrustedXHRAddress = Trusted<XMLHttpRequest>;
1070
1071impl XMLHttpRequest {
1072    fn change_ready_state(&self, cx: &mut JSContext, rs: XMLHttpRequestState) {
1073        assert_ne!(self.ready_state.get(), rs);
1074        self.ready_state.set(rs);
1075        if rs != XMLHttpRequestState::Unsent {
1076            let event = Event::new(
1077                cx,
1078                &self.global(),
1079                atom!("readystatechange"),
1080                EventBubbles::DoesNotBubble,
1081                EventCancelable::Cancelable,
1082            );
1083            event.fire(cx, self.upcast());
1084        }
1085    }
1086
1087    fn process_headers_available(
1088        &self,
1089        cx: &mut JSContext,
1090        gen_id: GenerationId,
1091        metadata: Result<FetchMetadata, NetworkError>,
1092    ) -> Result<(), Error> {
1093        let (headers, status, final_url) = match metadata {
1094            Ok(meta) => match meta {
1095                FetchMetadata::Unfiltered(m) => (m.headers, m.status, m.final_url),
1096                FetchMetadata::Filtered { filtered, .. } => match filtered {
1097                    FilteredMetadata::Basic(m) => (Some(m.headers), m.status, m.final_url),
1098                    FilteredMetadata::Cors(m) => (Some(m.headers), m.status, m.final_url),
1099                    FilteredMetadata::Opaque => return Err(Error::Network(None)),
1100                    FilteredMetadata::OpaqueRedirect(_) => return Err(Error::Network(None)),
1101                },
1102            },
1103            Err(_) => {
1104                self.process_partial_response(cx, XHRProgress::Errored(gen_id, ErrorType::Network));
1105                return Err(Error::Network(None));
1106            },
1107        };
1108
1109        final_url[..Position::AfterQuery]
1110            .clone_into(&mut self.response_url.safe_borrow_mut(cx.no_gc()));
1111
1112        // XXXManishearth Clear cache entries in case of a network error
1113        self.process_partial_response(
1114            cx,
1115            XHRProgress::HeadersReceived(gen_id, headers.map(Serde::into_inner), status),
1116        );
1117        Ok(())
1118    }
1119
1120    fn process_data_available(&self, cx: &mut JSContext, gen_id: GenerationId, payload: Bytes) {
1121        self.process_partial_response(cx, XHRProgress::Loading(gen_id, payload));
1122    }
1123
1124    fn process_response_complete(
1125        &self,
1126        cx: &mut JSContext,
1127        gen_id: GenerationId,
1128        status: Result<(), NetworkError>,
1129    ) -> ErrorResult {
1130        match status {
1131            Ok(()) => {
1132                self.process_partial_response(cx, XHRProgress::Done(gen_id));
1133                Ok(())
1134            },
1135            Err(_) => {
1136                self.process_partial_response(cx, XHRProgress::Errored(gen_id, ErrorType::Network));
1137                Err(Error::Network(None))
1138            },
1139        }
1140    }
1141
1142    fn process_partial_response(&self, cx: &mut JSContext, progress: XHRProgress) {
1143        let msg_id = progress.generation_id();
1144
1145        // Aborts processing if abort() or open() was called
1146        // (including from one of the event handlers called below)
1147        macro_rules! return_if_fetch_was_terminated(
1148            () => (
1149                if msg_id != self.generation_id.get() {
1150                    return
1151                }
1152            );
1153        );
1154
1155        // Ignore message if it belongs to a terminated fetch
1156        return_if_fetch_was_terminated!();
1157
1158        // Ignore messages coming from previously-errored responses or requests that have timed out
1159        if self.response_status.get().is_err() {
1160            return;
1161        }
1162
1163        match progress {
1164            XHRProgress::HeadersReceived(_, headers, status) => {
1165                assert!(self.ready_state.get() == XMLHttpRequestState::Opened);
1166                // For synchronous requests, this should not fire any events, and just store data
1167                // XXXManishearth Find a way to track partial progress of the send (onprogresss for XHRUpload)
1168
1169                // Part of step 13, send() (processing request end of file)
1170                // Substep 1
1171                self.upload_complete.set(true);
1172                // Substeps 2-4
1173                if !self.sync.get() && self.upload_listener.get() {
1174                    self.dispatch_upload_progress_event(cx, atom!("progress"), Ok(None));
1175                    return_if_fetch_was_terminated!();
1176                    self.dispatch_upload_progress_event(cx, atom!("load"), Ok(None));
1177                    return_if_fetch_was_terminated!();
1178                    self.dispatch_upload_progress_event(cx, atom!("loadend"), Ok(None));
1179                    return_if_fetch_was_terminated!();
1180                }
1181                // Part of step 13, send() (processing response)
1182                // XXXManishearth handle errors, if any (substep 1)
1183                // Substep 2
1184                if !status.is_error() {
1185                    *self.status.safe_borrow_mut(cx.no_gc()) = status;
1186                }
1187                if let Some(h) = headers.as_ref() {
1188                    *self.response_headers.safe_borrow_mut(cx.no_gc()) = h.clone();
1189                }
1190                {
1191                    let len = headers.and_then(|h| h.typed_get::<ContentLength>());
1192                    let mut response = self.response.safe_borrow_mut(cx.no_gc());
1193                    response.clear();
1194                    if let Some(len) = len {
1195                        // don't attempt to prereserve more than 4 MB of memory,
1196                        // to avoid giving servers the ability to DOS the client by
1197                        // providing arbitrarily large content-lengths.
1198                        //
1199                        // this number is arbitrary, it's basically big enough that most
1200                        // XHR requests won't hit it, but not so big that it allows for DOS
1201                        let size = cmp::min(0b100_0000000000_0000000000, len.0 as usize);
1202
1203                        // preallocate the buffer
1204                        response.reserve(size);
1205                    }
1206                }
1207                // Substep 3
1208                if !self.sync.get() {
1209                    self.change_ready_state(cx, XMLHttpRequestState::HeadersReceived);
1210                }
1211            },
1212            XHRProgress::Loading(_, partial_response) => {
1213                // For synchronous requests, this should not fire any events, and just store data
1214                // Part of step 11, send() (processing response body)
1215                // XXXManishearth handle errors, if any (substep 2)
1216
1217                self.response
1218                    .safe_borrow_mut(cx.no_gc())
1219                    .extend_from_slice(&partial_response);
1220                if !self.sync.get() {
1221                    if self.ready_state.get() == XMLHttpRequestState::HeadersReceived {
1222                        self.ready_state.set(XMLHttpRequestState::Loading);
1223                    }
1224                    let event = Event::new(
1225                        cx,
1226                        &self.global(),
1227                        atom!("readystatechange"),
1228                        EventBubbles::DoesNotBubble,
1229                        EventCancelable::Cancelable,
1230                    );
1231                    event.fire(cx, self.upcast());
1232                    return_if_fetch_was_terminated!();
1233                    self.dispatch_response_progress_event(cx, atom!("progress"));
1234                }
1235            },
1236            XHRProgress::Done(_) => {
1237                assert!(
1238                    self.ready_state.get() == XMLHttpRequestState::HeadersReceived ||
1239                        self.ready_state.get() == XMLHttpRequestState::Loading ||
1240                        self.sync.get()
1241                );
1242
1243                self.cancel_timeout(cx.no_gc());
1244                self.controller.safe_borrow_mut(cx.no_gc()).ignore();
1245
1246                // Part of step 11, send() (processing response end of file)
1247                // XXXManishearth handle errors, if any (substep 2)
1248
1249                // Subsubsteps 6-8
1250                self.send_flag.set(false);
1251
1252                self.change_ready_state(cx, XMLHttpRequestState::Done);
1253                return_if_fetch_was_terminated!();
1254                // Subsubsteps 11-12
1255                self.dispatch_response_progress_event(cx, atom!("load"));
1256                return_if_fetch_was_terminated!();
1257                self.dispatch_response_progress_event(cx, atom!("loadend"));
1258            },
1259            XHRProgress::Errored(_, e) => {
1260                self.cancel_timeout(cx.no_gc());
1261                self.controller.safe_borrow_mut(cx.no_gc()).ignore();
1262
1263                self.discard_subsequent_responses();
1264                self.send_flag.set(false);
1265                *self.status.safe_borrow_mut(cx.no_gc()) = HttpStatus::new_error();
1266                self.response_headers.safe_borrow_mut(cx.no_gc()).clear();
1267                // XXXManishearth set response to NetworkError
1268                self.change_ready_state(cx, XMLHttpRequestState::Done);
1269                return_if_fetch_was_terminated!();
1270
1271                let errormsg = match e {
1272                    ErrorType::Abort => "abort",
1273                    ErrorType::Timeout => "timeout",
1274                    ErrorType::Network => "error",
1275                };
1276
1277                let upload_complete = &self.upload_complete;
1278                if !upload_complete.get() {
1279                    upload_complete.set(true);
1280                    if self.upload_listener.get() {
1281                        self.dispatch_upload_progress_event(cx, Atom::from(errormsg), Err(()));
1282                        return_if_fetch_was_terminated!();
1283                        self.dispatch_upload_progress_event(cx, atom!("loadend"), Err(()));
1284                        return_if_fetch_was_terminated!();
1285                    }
1286                }
1287                self.dispatch_response_progress_event(cx, Atom::from(errormsg));
1288                return_if_fetch_was_terminated!();
1289                self.dispatch_response_progress_event(cx, atom!("loadend"));
1290            },
1291        }
1292    }
1293
1294    fn terminate_ongoing_fetch(&self, no_gc: &NoGC) {
1295        self.controller.safe_borrow_mut(no_gc).abort();
1296        let GenerationId(prev_id) = self.generation_id.get();
1297        self.generation_id.set(GenerationId(prev_id + 1));
1298        self.response_status.set(Ok(()));
1299    }
1300
1301    fn dispatch_progress_event(
1302        &self,
1303        cx: &mut JSContext,
1304        upload: bool,
1305        type_: Atom,
1306        loaded: u64,
1307        total: Option<u64>,
1308    ) {
1309        let (total_length, length_computable) = if self
1310            .response_headers
1311            .borrow()
1312            .contains_key(header::CONTENT_ENCODING)
1313        {
1314            (0, false)
1315        } else {
1316            (total.unwrap_or(0), total.is_some())
1317        };
1318        let progressevent = ProgressEvent::new(
1319            cx,
1320            &self.global(),
1321            type_,
1322            EventBubbles::DoesNotBubble,
1323            EventCancelable::NotCancelable,
1324            length_computable,
1325            Finite::wrap(loaded as f64),
1326            Finite::wrap(total_length as f64),
1327        );
1328        let target = if upload {
1329            self.upload.upcast()
1330        } else {
1331            self.upcast()
1332        };
1333        progressevent.upcast::<Event>().fire(cx, target);
1334    }
1335
1336    fn dispatch_upload_progress_event(
1337        &self,
1338        cx: &mut JSContext,
1339        type_: Atom,
1340        partial_load: Result<Option<u64>, ()>,
1341    ) {
1342        // If partial_load is Ok(None), loading has completed and we can just use the value from the request body
1343        // If an error occurred, we pass 0 for both loaded and total
1344
1345        let request_body_len = self.request_body_len.get() as u64;
1346        let (loaded, total) = match partial_load {
1347            Ok(l) => match l {
1348                Some(loaded) => (loaded, Some(request_body_len)),
1349                None => (request_body_len, Some(request_body_len)),
1350            },
1351            Err(()) => (0, None),
1352        };
1353        self.dispatch_progress_event(cx, true, type_, loaded, total);
1354    }
1355
1356    fn dispatch_response_progress_event(&self, cx: &mut JSContext, type_: Atom) {
1357        let len = self.response.borrow().len() as u64;
1358        let total = self
1359            .response_headers
1360            .borrow()
1361            .typed_get::<ContentLength>()
1362            .map(|v| v.0);
1363        self.dispatch_progress_event(cx, false, type_, len, total);
1364    }
1365
1366    fn set_timeout(&self, no_gc: &NoGC, duration: Duration) {
1367        // Sets up the object to timeout in a given number of milliseconds
1368        // This will cancel all previous timeouts
1369        let callback = OneshotTimerCallback::XhrTimeout(XHRTimeoutCallback {
1370            xhr: Trusted::new(self),
1371            generation_id: self.generation_id.get(),
1372        });
1373        *self.timeout_cancel.safe_borrow_mut(no_gc) =
1374            Some(self.global().schedule_callback(callback, duration));
1375    }
1376
1377    fn cancel_timeout(&self, no_gc: &NoGC) {
1378        if let Some(handle) = self.timeout_cancel.safe_borrow_mut(no_gc).take() {
1379            self.global().unschedule_callback(handle);
1380        }
1381    }
1382
1383    /// <https://xhr.spec.whatwg.org/#text-response>
1384    fn text_response(&self) -> String {
1385        // Step 3, 5
1386        let charset = self.final_charset().unwrap_or(UTF_8);
1387        // TODO: Step 4 - add support for XML encoding guess stuff using XML spec
1388
1389        // According to Simon, decode() should never return an error, so unwrap()ing
1390        // the result should be fine. XXXManishearth have a closer look at this later
1391        // Step 1, 2, 6
1392        let response = self.response.borrow();
1393        let (text, _, _) = charset.decode(&response);
1394        text.into_owned()
1395    }
1396
1397    /// <https://xhr.spec.whatwg.org/#blob-response>
1398    fn blob_response(&self, cx: &mut JSContext) -> DomRoot<Blob> {
1399        // Step 1
1400        if let Some(response) = self.response_blob.get() {
1401            return response;
1402        }
1403        // Step 2
1404        let mime = normalize_type_string(&self.final_mime_type().to_string());
1405
1406        // Step 3, 4
1407        let bytes = self.response.borrow().to_vec();
1408        let blob = Blob::new(cx, &self.global(), BlobImpl::new_from_bytes(bytes, mime));
1409        self.response_blob.set(Some(&blob));
1410        blob
1411    }
1412
1413    /// <https://xhr.spec.whatwg.org/#arraybuffer-response>
1414    fn arraybuffer_response(
1415        &self,
1416        cx: &mut JSContext,
1417    ) -> Option<RootedTraceableBox<HeapArrayBuffer>> {
1418        // Step 5: Set the response object to a new ArrayBuffer with the received bytes
1419        // For caching purposes, skip this step if the response is already created
1420        if !self.response_arraybuffer.is_initialized() {
1421            let bytes = self.response.borrow();
1422
1423            // If this is not successful, the response won't be set and the function will return None
1424            self.response_arraybuffer.set_data(cx, &bytes).ok()?;
1425        }
1426
1427        // Return the correct ArrayBuffer
1428        self.response_arraybuffer.get_typed_array().ok()
1429    }
1430
1431    /// <https://xhr.spec.whatwg.org/#document-response>
1432    fn document_response(&self, cx: &mut JSContext) -> Option<DomRoot<Document>> {
1433        // Caching: if we have existing response xml, redirect it directly
1434        let response = self.response_xml.get();
1435        if response.is_some() {
1436            return response;
1437        }
1438
1439        // Step 1: If xhr’s response’s body is null, then return.
1440        if self.response_status.get().is_err() {
1441            return None;
1442        }
1443
1444        // Step 2: Let finalMIME be the result of get a final MIME type for xhr.
1445        let final_mime = self.final_mime_type();
1446
1447        // Step 3: If finalMIME is not an HTML MIME type or an XML MIME type, then return.
1448        let is_xml_mime_type = final_mime.matches(TEXT, XML) ||
1449            final_mime.matches(APPLICATION, XML) ||
1450            final_mime.has_suffix(XML);
1451        if !final_mime.matches(TEXT, HTML) && !is_xml_mime_type {
1452            return None;
1453        }
1454
1455        // Step 4: If xhr’s response type is the empty string and finalMIME is an HTML MIME
1456        //         type, then return.
1457        let charset;
1458        let temp_doc;
1459        if final_mime.matches(TEXT, HTML) {
1460            if self.response_type.get() == XMLHttpRequestResponseType::_empty {
1461                return None;
1462            }
1463
1464            // Step 5: If finalMIME is an HTML MIME type, then:
1465            // Step 5.1: Let charset be the result of get a final encoding for xhr.
1466            // Step 5.2: If charset is null, prescan the first 1024 bytes of xhr’s received bytes
1467            // and if that does not terminate unsuccessfully then let charset be the return value.
1468            // TODO: This isn't happening right now.
1469            // Step 5.3. If charset is null, then set charset to UTF-8.
1470            charset = Some(self.final_charset().unwrap_or(UTF_8));
1471
1472            // Step 5.4: Let document be a document that represents the result parsing xhr’s
1473            // received bytes following the rules set forth in the HTML Standard for an HTML parser
1474            // with scripting disabled and a known definite encoding charset. [HTML]
1475            temp_doc = self.document_text_html(cx);
1476        } else {
1477            assert!(is_xml_mime_type);
1478
1479            // Step 6: Otherwise, let document be a document that represents the result of running
1480            // the XML parser with XML scripting support disabled on xhr’s received bytes. If that
1481            // fails (unsupported character encoding, namespace well-formedness error, etc.), then
1482            // return null. [HTML]
1483            //
1484            // TODO: The spec seems to suggest the charset should come from the XML parser here.
1485            temp_doc = self.handle_xml(cx);
1486            charset = self.final_charset();
1487
1488            // Not sure it the parser should throw an error for this case
1489            // The specification does not indicates this test,
1490            // but for now we check the document has no child nodes
1491            let has_no_child_nodes = temp_doc.upcast::<Node>().children().next().is_none();
1492            if has_no_child_nodes {
1493                return None;
1494            }
1495        }
1496
1497        // Step 7: If charset is null, then set charset to UTF-8.
1498        let charset = charset.unwrap_or(UTF_8);
1499
1500        // Step 8: Set document’s encoding to charset.
1501        temp_doc.set_encoding(charset);
1502
1503        // Step 9: Set document’s content type to finalMIME.
1504        // Step 10: Set document’s URL to xhr’s response’s URL.
1505        // Step 11: Set document’s origin to xhr’s relevant settings object’s origin.
1506        //
1507        // Done by `handle_text_html()` and `handle_xml()`.
1508
1509        // Step 12: Set xhr’s response object to document.
1510        self.response_xml.set(Some(&temp_doc));
1511        self.response_xml.get()
1512    }
1513
1514    #[expect(unsafe_code)]
1515    /// <https://xhr.spec.whatwg.org/#json-response>
1516    fn json_response(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
1517        // Step 1
1518        let response_json = self.response_json.get();
1519        if !response_json.is_null_or_undefined() {
1520            return rval.set(response_json);
1521        }
1522        // Step 2
1523        let bytes = self.response.borrow();
1524        // Step 3
1525        if bytes.is_empty() {
1526            return rval.set(NullValue());
1527        }
1528        // Step 4
1529        // https://xhr.spec.whatwg.org/#json-response refers to
1530        // https://infra.spec.whatwg.org/#parse-json-from-bytes which refers to
1531        // https://encoding.spec.whatwg.org/#utf-8-decode which means
1532        // that the encoding is always UTF-8 and the UTF-8 BOM is removed,
1533        // if present, but UTF-16BE/LE BOM must not be honored.
1534        let json_text = decode_to_utf16_with_bom_removal(&bytes, UTF_8);
1535        // Step 5
1536        unsafe {
1537            if !JS_ParseJSON(
1538                cx,
1539                json_text.as_ptr(),
1540                json_text.len() as u32,
1541                rval.reborrow(),
1542            ) {
1543                JS_ClearPendingException(cx);
1544                return rval.set(NullValue());
1545            }
1546        }
1547        // Step 6
1548        self.response_json.set(rval.get());
1549    }
1550
1551    fn document_text_html(&self, cx: &mut JSContext) -> DomRoot<Document> {
1552        let charset = self.final_charset().unwrap_or(UTF_8);
1553        let wr = self.global();
1554        let response = self.response.borrow();
1555        let (decoded, _, _) = charset.decode(&response);
1556        let document = self.new_doc(cx, IsHTMLDocument::HTMLDocument);
1557        // TODO: Disable scripting while parsing
1558        ServoParser::parse_html_document(
1559            cx,
1560            &document,
1561            Some(DOMString::from(decoded)),
1562            wr.get_url(),
1563            None,
1564            None,
1565        );
1566        document
1567    }
1568
1569    fn handle_xml(&self, cx: &mut JSContext) -> DomRoot<Document> {
1570        let charset = self.final_charset().unwrap_or(UTF_8);
1571        let wr = self.global();
1572        let response = self.response.borrow();
1573        let (decoded, _, _) = charset.decode(&response);
1574        let document = self.new_doc(cx, IsHTMLDocument::NonHTMLDocument);
1575        // TODO: Disable scripting while parsing
1576        ServoParser::parse_xml_document(
1577            cx,
1578            &document,
1579            Some(DOMString::from(decoded)),
1580            wr.get_url(),
1581            None,
1582        );
1583        document
1584    }
1585
1586    fn new_doc(&self, cx: &mut JSContext, is_html_document: IsHTMLDocument) -> DomRoot<Document> {
1587        let wr = self.global();
1588        let win = wr.as_window();
1589        let doc = win.Document();
1590        let docloader = DocumentLoader::new(&doc.loader());
1591        let base = wr.get_url();
1592        let parsed_url = base.join(&self.ResponseURL().0).ok();
1593        let content_type = Some(self.final_mime_type());
1594        Document::new(
1595            cx,
1596            win,
1597            HasBrowsingContext::No,
1598            parsed_url,
1599            None,
1600            doc.origin().clone(),
1601            is_html_document,
1602            content_type,
1603            None,
1604            DocumentActivity::Inactive,
1605            docloader,
1606            None,
1607            None,
1608            false,
1609            false,
1610            Some(doc.insecure_requests_policy()),
1611            doc.has_trustworthy_ancestor_origin(),
1612            doc.custom_element_reaction_stack(),
1613            doc.creation_sandboxing_flag_set(),
1614            doc.pipeline_id(),
1615            doc.image_cache(),
1616        )
1617    }
1618
1619    fn filter_response_headers(&self) -> HeaderMap {
1620        // https://fetch.spec.whatwg.org/#concept-response-header-list
1621        let mut headers = self.response_headers.borrow().clone();
1622        headers.remove(header::SET_COOKIE);
1623        headers.remove(HeaderName::from_static("set-cookie2"));
1624        // XXXManishearth additional CORS filtering goes here
1625        headers
1626    }
1627
1628    fn discard_subsequent_responses(&self) {
1629        self.response_status.set(Err(()));
1630    }
1631
1632    fn fetch(
1633        &self,
1634        cx: &mut JSContext,
1635        request_builder: RequestBuilder,
1636        global: &GlobalScope,
1637    ) -> ErrorResult {
1638        let xhr = Trusted::new(self);
1639
1640        let sync_status = Arc::new(AtomicRefCell::new(None));
1641        let context = XHRContext {
1642            xhr,
1643            gen_id: self.generation_id.get(),
1644            sync_status: sync_status.clone(),
1645            url: request_builder.url.url(),
1646        };
1647
1648        let (task_source, script_port) = if self.sync.get() {
1649            let (sender, receiver) = global.new_script_pair();
1650            (
1651                SendableTaskSource {
1652                    sender,
1653                    pipeline_id: global.pipeline_id(),
1654                    name: TaskSourceName::Networking,
1655                    canceller: Default::default(),
1656                },
1657                Some(receiver),
1658            )
1659        } else {
1660            (
1661                global.task_manager().networking_task_source().to_sendable(),
1662                None,
1663            )
1664        };
1665
1666        *self.controller.safe_borrow_mut(cx.no_gc()) =
1667            FetchController::new(request_builder.id, false, global.core_resource_thread());
1668
1669        global.fetch(request_builder, context, task_source);
1670
1671        if let Some(script_port) = script_port {
1672            // The timer scheduled by `set_timeout` cannot fire while this loop blocks the event
1673            // loop, so the timeout of a synchronous request has to be enforced here instead.
1674            let timeout = self.timeout.get();
1675            let deadline = (!timeout.is_zero()).then(|| self.fetch_time.get() + timeout);
1676            loop {
1677                let message = match deadline {
1678                    None => script_port.recv().unwrap(),
1679                    Some(deadline) => match script_port.recv_deadline(deadline) {
1680                        Err(RecvTimeoutError::Timeout) => {
1681                            // <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send>
1682                            // Step 12.6. If processedResponse is false, then set this’s timed out
1683                            // to true and terminate this’s fetch controller.
1684                            self.controller.safe_borrow_mut(cx.no_gc()).terminate();
1685                            self.process_partial_response(
1686                                cx,
1687                                XHRProgress::Errored(self.generation_id.get(), ErrorType::Timeout),
1688                            );
1689                            return Err(Error::Timeout(Some(
1690                                "Synchronous request timed out".into(),
1691                            )));
1692                        },
1693                        message => message.unwrap(),
1694                    },
1695                };
1696                if !global.process_event(cx, message) {
1697                    // We're exiting.
1698                    return Err(Error::Abort(None));
1699                }
1700                if let Some(ref status) = *sync_status.borrow() {
1701                    return status.clone();
1702                }
1703            }
1704        }
1705        Ok(())
1706    }
1707
1708    /// <https://xhr.spec.whatwg.org/#final-charset>
1709    fn final_charset(&self) -> Option<&'static Encoding> {
1710        // 1. Let label be null.
1711        // 2. Let responseMIME be the result of get a response MIME type for xhr.
1712        // 3. If responseMIME’s parameters["charset"] exists, then set label to it.
1713        let response_charset = self
1714            .response_mime_type()
1715            .get_parameter(CHARSET)
1716            .map(ToString::to_string);
1717
1718        // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
1719        let override_charset = self
1720            .override_mime_type
1721            .borrow()
1722            .as_ref()
1723            .and_then(|mime| mime.get_parameter(CHARSET))
1724            .map(ToString::to_string);
1725
1726        // 5. If label is null, then return null.
1727        // 6. Let encoding be the result of getting an encoding from label.
1728        // 7. If encoding is failure, then return null.
1729        // 8. Return encoding.
1730        override_charset
1731            .or(response_charset)
1732            .and_then(|charset| Encoding::for_label(charset.as_bytes()))
1733    }
1734
1735    /// <https://xhr.spec.whatwg.org/#response-mime-type>
1736    fn response_mime_type(&self) -> Mime {
1737        // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s
1738        //    header list.
1739        // 2. If mimeType is failure, then set mimeType to text/xml.
1740        // 3. Return mimeType.
1741        extract_mime_type_as_dataurl_mime(&self.response_headers.borrow())
1742            .unwrap_or_else(|| Mime::new(TEXT, XML))
1743    }
1744
1745    /// <https://xhr.spec.whatwg.org/#final-mime-type>
1746    fn final_mime_type(&self) -> Mime {
1747        self.override_mime_type
1748            .borrow()
1749            .as_ref()
1750            .map(MimeExt::clone)
1751            .unwrap_or_else(|| self.response_mime_type())
1752    }
1753}
1754
1755#[derive(JSTraceable, MallocSizeOf)]
1756pub(crate) struct XHRTimeoutCallback {
1757    #[ignore_malloc_size_of = "Because it is non-owning"]
1758    xhr: Trusted<XMLHttpRequest>,
1759    generation_id: GenerationId,
1760}
1761
1762impl XHRTimeoutCallback {
1763    pub(crate) fn invoke(self, cx: &mut JSContext) {
1764        let xhr = self.xhr.root();
1765        if xhr.ready_state.get() != XMLHttpRequestState::Done {
1766            xhr.process_partial_response(
1767                cx,
1768                XHRProgress::Errored(self.generation_id, ErrorType::Timeout),
1769            );
1770        }
1771    }
1772}
1773
1774fn serialize_document(doc: &Document) -> Fallible<DOMString> {
1775    let mut writer = vec![];
1776    if serialize(
1777        &mut writer,
1778        &HtmlSerialize::new(doc.upcast::<Node>()),
1779        SerializeOpts::default(),
1780    )
1781    .is_err()
1782    {
1783        return Err(Error::InvalidState(Some(
1784            "Could not serialize document".into(),
1785        )));
1786    };
1787    let Ok(string) = String::from_utf8(writer) else {
1788        return Err(Error::InvalidState(Some(
1789            "Could not serialize document".into(),
1790        )));
1791    };
1792    Ok(DOMString::from(string))
1793}
1794
1795/// Returns whether `bs` is a `field-value`, as defined by
1796/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-32).
1797pub(crate) fn is_field_value(slice: &[u8]) -> bool {
1798    // Classifications of characters necessary for the [CRLF] (SP|HT) rule
1799    #[derive(PartialEq)]
1800    #[expect(clippy::upper_case_acronyms)]
1801    enum PreviousCharacter {
1802        Other,
1803        CR,
1804        LF,
1805        SPHT, // SP or HT
1806    }
1807    let mut prev = PreviousCharacter::Other; // The previous character
1808    slice.iter().all(|&x| {
1809        // http://tools.ietf.org/html/rfc2616#section-2.2
1810        match x {
1811            13 if (prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT) => {
1812                // CR
1813                prev = PreviousCharacter::CR;
1814                true
1815            },
1816            10 if prev == PreviousCharacter::CR => {
1817                // LF
1818                prev = PreviousCharacter::LF;
1819                true
1820            },
1821            10 => false,
1822            32 => {
1823                // SP
1824                if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT {
1825                    prev = PreviousCharacter::SPHT;
1826                    true
1827                } else if prev == PreviousCharacter::Other {
1828                    // Counts as an Other here, since it's not preceded by a CRLF
1829                    // SP is not a CTL, so it can be used anywhere
1830                    // though if used immediately after a CR the CR is invalid
1831                    // We don't change prev since it's already Other
1832                    true
1833                } else {
1834                    false
1835                }
1836            },
1837            9 if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT => {
1838                // HT
1839                prev = PreviousCharacter::SPHT;
1840                true
1841            },
1842            9 => false,
1843            0..=31 | 127 => false, // CTLs
1844            x if x > 127 => false, // non ASCII
1845            _ if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT => {
1846                prev = PreviousCharacter::Other;
1847                true
1848            },
1849            _ => false, // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule
1850        }
1851    })
1852}