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