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