Skip to main content

script/dom/xmlhttprequest/
xmlhttprequest.rs

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