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