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