Nacre/vendor/servo-script/dom/xmlhttprequest/xmlhttprequest.rs
astar76 0ecfd0f573 S031: root due timers in vendored servo-script (R5-01 SIGSEGV), crash-adblock regression smoke
fire_timer moved due timers into an unrooted Vec; a GC inside one callback swept
the functions of the timers still waiting. Heavy-web reruns and cargo test still pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 20:38:47 -06:00

1797 lines
69 KiB
Rust

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::borrow::ToOwned;
use std::cell::Cell;
use std::cmp;
use std::default::Default;
use std::str::{self, FromStr};
use std::sync::Arc;
use std::time::{Duration, Instant};
use atomic_refcell::AtomicRefCell;
use bytes::{Bytes, BytesMut};
use data_url::mime::Mime;
use dom_struct::dom_struct;
use encoding_rs::{Encoding, UTF_8};
use headers::{ContentLength, ContentType, HeaderMapExt};
use html5ever::serialize;
use html5ever::serialize::SerializeOpts;
use http::Method;
use http::header::{self, HeaderMap, HeaderName, HeaderValue};
use hyper_serde::Serde;
use js::context::{JSContext, NoGC};
use js::conversions::ToJSValConvertible;
use js::jsapi::Heap;
use js::jsval::{JSVal, NullValue};
use js::rust::wrappers2::{JS_ClearPendingException, JS_ParseJSON};
use js::rust::{HandleObject, MutableHandleValue};
use js::typedarray::{ArrayBufferU8, HeapArrayBuffer};
use net_traits::blob_url_store::UrlWithBlobClaim;
use net_traits::fetch::headers::extract_mime_type_as_dataurl_mime;
use net_traits::http_status::HttpStatus;
use net_traits::request::{CredentialsMode, Referrer, RequestBuilder, RequestId, RequestMode};
use net_traits::{
FetchMetadata, FilteredMetadata, NetworkError, ReferrerPolicy, ResourceFetchTiming,
trim_http_whitespace,
};
use script_bindings::cell::DomRefCell;
use script_bindings::num::Finite;
use script_bindings::reflector::reflect_dom_object_with_proto;
use script_bindings::trace::RootedTraceableBox;
use script_traits::DocumentActivity;
use servo_constellation_traits::BlobImpl;
use servo_url::ServoUrl;
use stylo_atoms::Atom;
use url::Position;
use crate::dom::bindings::buffer_source::{HeapBufferSource, get_buffer_source_copy};
use crate::dom::bindings::cell::AtomicSafeBorrowMut;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::codegen::Bindings::XMLHttpRequestBinding::{
XMLHttpRequestMethods, XMLHttpRequestResponseType,
};
use crate::dom::bindings::codegen::UnionTypes::DocumentOrBlobOrArrayBufferViewOrArrayBufferOrFormDataOrStringOrURLSearchParams as DocumentOrXMLHttpRequestBodyInit;
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::{ByteString, DOMString, USVString, is_token};
use crate::dom::blob::{Blob, normalize_type_string};
use crate::dom::csp::{GlobalCspReporting, Violation};
use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::headers::is_forbidden_request_header;
use crate::dom::node::Node;
use crate::dom::performance::performanceresourcetiming::InitiatorType;
use crate::dom::progressevent::ProgressEvent;
use crate::dom::servoparser::ServoParser;
use crate::dom::servoparser::html::HtmlSerialize;
use crate::dom::stream::readablestream::ReadableStream;
use crate::dom::window::Window;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget;
use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload;
use crate::event_loop::document_loader::DocumentLoader;
use crate::event_loop::timers::{OneshotTimerCallback, OneshotTimerHandle};
use crate::fetch::body::{
BodySource, Extractable, ExtractedBody, decode_to_utf16_with_bom_removal,
};
use crate::fetch::fetch::{FetchCanceller, RequestWithGlobalScope};
use crate::fetch::network_listener::{self, FetchResponseListener, ResourceTimingListener};
use crate::mime::{APPLICATION, CHARSET, HTML, MimeExt, TEXT, XML};
use crate::tasks::task_source::{SendableTaskSource, TaskSourceName};
use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum XMLHttpRequestState {
Unsent = 0,
Opened = 1,
HeadersReceived = 2,
Loading = 3,
Done = 4,
}
#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
pub(crate) struct GenerationId(u32);
/// Closure of required data for each async network event that comprises the
/// XHR's response.
struct XHRContext {
xhr: TrustedXHRAddress,
gen_id: GenerationId,
sync_status: Arc<AtomicRefCell<Option<ErrorResult>>>,
url: ServoUrl,
}
impl FetchResponseListener for XHRContext {
fn process_request_body(&mut self, _: RequestId) {
// todo
}
fn process_response(
&mut self,
cx: &mut JSContext,
_: RequestId,
metadata: Result<FetchMetadata, NetworkError>,
) {
let xhr = self.xhr.root();
let rv = xhr.process_headers_available(cx, self.gen_id, metadata);
if rv.is_err() {
*self.sync_status.safe_borrow_mut(cx.no_gc()) = Some(rv);
}
}
fn process_response_chunk(&mut self, cx: &mut JSContext, _: RequestId, chunk: Bytes) {
self.xhr
.root()
.process_data_available(cx, self.gen_id, chunk);
}
fn process_response_eof(
self,
cx: &mut JSContext,
_: RequestId,
response: Result<(), NetworkError>,
timing: ResourceFetchTiming,
) {
network_listener::submit_timing(cx, &self, &response, &timing);
let rv = self
.xhr
.root()
.process_response_complete(cx, self.gen_id, response.map(|_| ()));
*self.sync_status.safe_borrow_mut(cx.no_gc()) = Some(rv);
}
fn process_csp_violations(
&mut self,
cx: &mut js::context::JSContext,
_request_id: RequestId,
violations: Vec<Violation>,
) {
let global = &self.resource_timing_global();
global.report_csp_violations(cx, violations, None, None);
}
fn should_invoke(&self) -> bool {
self.xhr.root().generation_id.get() == self.gen_id
}
}
impl ResourceTimingListener for XHRContext {
fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
(InitiatorType::XMLHttpRequest, self.url.clone())
}
fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
self.xhr.root().global()
}
}
#[derive(Clone)]
pub(crate) enum XHRProgress {
/// Notify that headers have been received
HeadersReceived(GenerationId, Option<HeaderMap>, HttpStatus),
/// Partial progress (after receiving headers), containing portion of the response
Loading(GenerationId, Bytes),
/// Loading is done
Done(GenerationId),
/// There was an error (only Error::Abort(None), Error::Timeout(None) or Error::Network(None) is used)
Errored(GenerationId, Error),
}
impl XHRProgress {
fn generation_id(&self) -> GenerationId {
match *self {
XHRProgress::HeadersReceived(id, _, _) |
XHRProgress::Loading(id, _) |
XHRProgress::Done(id) |
XHRProgress::Errored(id, _) => id,
}
}
}
#[dom_struct]
pub(crate) struct XMLHttpRequest {
eventtarget: XMLHttpRequestEventTarget,
ready_state: Cell<XMLHttpRequestState>,
timeout: Cell<Duration>,
with_credentials: Cell<bool>,
upload: Dom<XMLHttpRequestUpload>,
response_url: DomRefCell<String>,
#[no_trace]
status: DomRefCell<HttpStatus>,
#[no_trace]
response: DomRefCell<BytesMut>,
response_type: Cell<XMLHttpRequestResponseType>,
response_xml: MutNullableDom<Document>,
response_blob: MutNullableDom<Blob>,
#[ignore_malloc_size_of = "mozjs"]
response_arraybuffer: HeapBufferSource<ArrayBufferU8>,
#[ignore_malloc_size_of = "Defined in rust-mozjs"]
response_json: Heap<JSVal>,
#[no_trace]
response_headers: DomRefCell<HeaderMap>,
#[no_trace]
override_mime_type: DomRefCell<Option<Mime>>,
// Associated concepts
#[no_trace]
request_method: DomRefCell<Method>,
#[no_trace]
request_url: DomRefCell<Option<UrlWithBlobClaim>>,
#[no_trace]
request_headers: DomRefCell<HeaderMap>,
request_body_len: Cell<usize>,
sync: Cell<bool>,
upload_complete: Cell<bool>,
upload_listener: Cell<bool>,
send_flag: Cell<bool>,
timeout_cancel: DomRefCell<Option<OneshotTimerHandle>>,
fetch_time: Cell<Instant>,
generation_id: Cell<GenerationId>,
response_status: Cell<Result<(), ()>>,
#[no_trace]
referrer: Referrer,
#[no_trace]
referrer_policy: ReferrerPolicy,
canceller: DomRefCell<FetchCanceller>,
}
impl XMLHttpRequest {
fn new_inherited(global: &GlobalScope, upload: &XMLHttpRequestUpload) -> XMLHttpRequest {
XMLHttpRequest {
eventtarget: XMLHttpRequestEventTarget::new_inherited(),
ready_state: Cell::new(XMLHttpRequestState::Unsent),
timeout: Cell::new(Duration::ZERO),
with_credentials: Cell::new(false),
upload: Dom::from_ref(upload),
response_url: DomRefCell::new(String::new()),
status: DomRefCell::new(HttpStatus::new_error()),
response: DomRefCell::new(BytesMut::new()),
response_type: Cell::new(XMLHttpRequestResponseType::_empty),
response_xml: Default::default(),
response_blob: Default::default(),
response_arraybuffer: HeapBufferSource::default(),
response_json: Heap::default(),
response_headers: DomRefCell::new(HeaderMap::new()),
override_mime_type: DomRefCell::new(None),
request_method: DomRefCell::new(Method::GET),
request_url: DomRefCell::new(None),
request_headers: DomRefCell::new(HeaderMap::new()),
request_body_len: Cell::new(0),
sync: Cell::new(false),
upload_complete: Cell::new(false),
upload_listener: Cell::new(false),
send_flag: Cell::new(false),
timeout_cancel: DomRefCell::new(None),
fetch_time: Cell::new(Instant::now()),
generation_id: Cell::new(GenerationId(0)),
response_status: Cell::new(Ok(())),
referrer: global.get_referrer(),
referrer_policy: global.get_referrer_policy(),
canceller: DomRefCell::new(Default::default()),
}
}
fn new(
cx: &mut JSContext,
global: &GlobalScope,
proto: Option<HandleObject>,
) -> DomRoot<XMLHttpRequest> {
let upload = XMLHttpRequestUpload::new(cx, global);
reflect_dom_object_with_proto(
cx,
Box::new(XMLHttpRequest::new_inherited(global, &upload)),
global,
proto,
)
}
fn sync_in_window(&self) -> bool {
self.sync.get() && self.global().is::<Window>()
}
}
impl XMLHttpRequestMethods<crate::DomTypeHolder> for XMLHttpRequest {
/// <https://xhr.spec.whatwg.org/#constructors>
fn Constructor(
cx: &mut JSContext,
global: &GlobalScope,
proto: Option<HandleObject>,
) -> Fallible<DomRoot<XMLHttpRequest>> {
Ok(XMLHttpRequest::new(cx, global, proto))
}
// https://xhr.spec.whatwg.org/#handler-xhr-onreadystatechange
event_handler!(
readystatechange,
GetOnreadystatechange,
SetOnreadystatechange
);
/// <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate>
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
/// <https://xhr.spec.whatwg.org/#the-open()-method>
fn Open(&self, cx: &mut JSContext, method: ByteString, url: USVString) -> ErrorResult {
// Step 8
self.Open_(cx, method, url, true, None, None)
}
/// <https://xhr.spec.whatwg.org/#the-open()-method>
fn Open_(
&self,
cx: &mut JSContext,
method: ByteString,
url: USVString,
asynch: bool,
username: Option<USVString>,
password: Option<USVString>,
) -> ErrorResult {
// Step 1. If this’s relevant global object is a Window object and its associated
// Document is not fully active, then throw an "InvalidStateError" DOMException.
let global = self.global();
if let Some(window) = global.downcast::<Window>() &&
!window.Document().is_fully_active()
{
return Err(Error::InvalidState(None));
}
// Step 5
// FIXME(seanmonstar): use a Trie instead?
let maybe_method = method.as_str().and_then(|s| {
// Note: hyper tests against the uppercase versions
// Since we want to pass methods not belonging to the short list above
// without changing capitalization, this will actually sidestep rust-http's type system
// since methods like "patch" or "PaTcH" will be considered extension methods
// despite the there being a rust-http method variant for them
let upper = s.to_ascii_uppercase();
match &*upper {
"DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "CONNECT" | "TRACE" |
"TRACK" => upper.parse().ok(),
_ => s.parse().ok(),
}
});
match maybe_method {
// Step 4
Some(Method::CONNECT) | Some(Method::TRACE) => Err(Error::Security(None)),
Some(ref t) if t.as_str() == "TRACK" => Err(Error::Security(None)),
Some(parsed_method) => {
// Step 3
if !is_token(&method) {
return Err(Error::Syntax(None));
}
// Step 5. Let parsedURL be the result of encoding-parsing a URL url, relative to this’s
// relevant settings object.
let mut parsed_url = match self
.global()
.encoding_parse_a_url(&url.0)
.map(|url| ensure_blob_referenced_by_url_is_kept_alive(&global, url))
{
Ok(parsed) => parsed,
Err(_) => {
// Step 6. If parsedURL is failure, then throw a "SyntaxError" DOMException.
return Err(Error::Syntax(None));
},
};
// Step 8. If parsedURL’s host is non-null, then:
if parsed_url.host().is_some() {
// Step 8.1 If the username argument is not null, set the username given parsedURL and username.
if let Some(user_str) = username &&
let Err(error) = parsed_url.set_username(&user_str.0)
{
warn!("Could not set username on XMLHttpRequest: {error:?}");
}
// Step 8.2 If the password argument is not null, set the password given parsedURL and password.
if let Some(pass_str) = password &&
let Err(error) = parsed_url.set_password(Some(&pass_str.0))
{
warn!("Could not set password on XMLHttpRequest: {error:?}");
}
}
// Step 9. If async is false, the current global object is a Window object, and
// either this’s timeout is not 0 or this’s response type is not the empty string,
// then throw an "InvalidAccessError" DOMException.
if !asynch {
// FIXME: This should only happen if the global environment is a document environment
if !self.timeout.get().is_zero() ||
self.response_type.get() != XMLHttpRequestResponseType::_empty
{
return Err(Error::InvalidAccess(None));
}
}
// Step 10. Terminate this’s fetch controller.
self.terminate_ongoing_fetch(cx.no_gc());
// FIXME(#13767): In the WPT test: FileAPI/blob/Blob-XHR-revoke.html,
// the xhr.open(url) is expected to hold a reference to the URL,
// thus renders following revocations invalid. Though we won't
// implement this for now, if ever needed, we should check blob
// scheme and trigger corresponding actions here.
// Step 12
*self.request_method.safe_borrow_mut(cx.no_gc()) = parsed_method;
*self.request_url.safe_borrow_mut(cx.no_gc()) = Some(parsed_url);
self.sync.set(!asynch);
*self.request_headers.safe_borrow_mut(cx.no_gc()) = HeaderMap::new();
self.send_flag.set(false);
self.upload_listener.set(false);
*self.status.safe_borrow_mut(cx.no_gc()) = HttpStatus::new_error();
// Step 13
if self.ready_state.get() != XMLHttpRequestState::Opened {
self.change_ready_state(cx, XMLHttpRequestState::Opened);
}
Ok(())
},
// Step 3
// This includes cases where as_str() returns None, and when is_token() returns false,
// both of which indicate invalid extension method names
_ => Err(Error::Syntax(None)),
}
}
/// <https://xhr.spec.whatwg.org/#the-setrequestheader()-method>
fn SetRequestHeader(&self, no_gc: &NoGC, name: ByteString, value: ByteString) -> ErrorResult {
// Step 1: If this’s state is not opened, then throw an "InvalidStateError" DOMException.
// Step 2: If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
return Err(Error::InvalidState(None));
}
// Step 3: Normalize value.
let value = trim_http_whitespace(&value);
// Step 4: If name is not a header name or value is not a header value, then throw a
// "SyntaxError" DOMException.
if !is_token(&name) || !is_field_value(value) {
return Err(Error::Syntax(None));
}
let name_str = name.as_str().ok_or(Error::Syntax(None))?;
// Step 5: If (name, value) is a forbidden request-header, then return.
if is_forbidden_request_header(name_str, value) {
return Ok(());
}
debug!(
"SetRequestHeader: name={:?}, value={:?}",
name_str,
str::from_utf8(value).ok()
);
let mut headers = self.request_headers.safe_borrow_mut(no_gc);
// Step 6: Combine (name, value) in this’s author request headers.
// https://fetch.spec.whatwg.org/#concept-header-list-combine
let value = match headers.get(name_str).map(HeaderValue::as_bytes) {
Some(raw) => {
let mut buf = raw.to_vec();
buf.extend_from_slice(b", ");
buf.extend_from_slice(value);
buf
},
None => value.into(),
};
if let (Ok(header_name), Ok(header_value)) = (
HeaderName::from_str(name_str),
HeaderValue::from_bytes(&value),
) {
headers.insert(header_name, header_value);
} else {
warn!("Not setting header in XMLHttpRequest {name_str:?}: {value:?}");
}
Ok(())
}
/// <https://xhr.spec.whatwg.org/#the-timeout-attribute>
fn Timeout(&self) -> u32 {
self.timeout.get().as_millis() as u32
}
/// <https://xhr.spec.whatwg.org/#the-timeout-attribute>
fn SetTimeout(&self, no_gc: &NoGC, timeout: u32) -> ErrorResult {
// Step 1
if self.sync_in_window() {
return Err(Error::InvalidAccess(None));
}
// Step 2
let timeout = Duration::from_millis(timeout as u64);
self.timeout.set(timeout);
if self.send_flag.get() {
if timeout.is_zero() {
self.cancel_timeout(no_gc);
return Ok(());
}
let progress = Instant::now() - self.fetch_time.get();
if timeout > progress {
self.set_timeout(no_gc, timeout - progress);
} else {
// Immediately execute the timeout steps
self.set_timeout(no_gc, Duration::ZERO);
}
}
Ok(())
}
/// <https://xhr.spec.whatwg.org/#the-withcredentials-attribute>
fn WithCredentials(&self) -> bool {
self.with_credentials.get()
}
/// <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials>
fn SetWithCredentials(&self, with_credentials: bool) -> ErrorResult {
match self.ready_state.get() {
// Step 1
XMLHttpRequestState::HeadersReceived |
XMLHttpRequestState::Loading |
XMLHttpRequestState::Done => Err(Error::InvalidState(None)),
// Step 2
_ if self.send_flag.get() => Err(Error::InvalidState(None)),
// Step 3
_ => {
self.with_credentials.set(with_credentials);
Ok(())
},
}
}
/// <https://xhr.spec.whatwg.org/#the-upload-attribute>
fn Upload(&self) -> DomRoot<XMLHttpRequestUpload> {
DomRoot::from_ref(&*self.upload)
}
/// <https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send>
fn Send(
&self,
cx: &mut JSContext,
data: Option<DocumentOrXMLHttpRequestBodyInit>,
) -> ErrorResult {
// Step 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.
// Step 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.
if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
return Err(Error::InvalidState(Some(
"XMLHttpRequest not open or already sent".into(),
)));
}
let Some(url) = self.request_url.borrow().clone() else {
return Err(Error::InvalidState(Some("XMLHttpRequest not open".into())));
};
// Step 3. If this’s request method is `GET` or `HEAD`, then set body to null.
let data = match *self.request_method.borrow() {
Method::GET | Method::HEAD => None,
_ => data,
};
// Step 4 (first half)
let mut extracted_or_serialized = match data {
Some(DocumentOrXMLHttpRequestBodyInit::Document(ref doc)) => {
let bytes = Vec::from(&*serialize_document(doc)?.as_bytes());
let content_type = if doc.is_html_document() {
"text/html;charset=UTF-8"
} else {
"application/xml;charset=UTF-8"
};
let total_bytes = bytes.len();
let global = self.global();
let stream = ReadableStream::new_from_bytes(cx, &global, bytes)?;
Some(ExtractedBody {
stream,
total_bytes: Some(total_bytes),
content_type: Some(DOMString::from(content_type)),
source: BodySource::Object,
})
},
Some(DocumentOrXMLHttpRequestBodyInit::Blob(ref b)) => {
let extracted_body = b
.extract(cx, &self.global(), false)
.expect("Couldn't extract body.");
if !extracted_body.in_memory() && self.sync.get() {
warn!("Sync XHR with not in-memory Blob as body not supported");
None
} else {
Some(extracted_body)
}
},
Some(DocumentOrXMLHttpRequestBodyInit::FormData(ref formdata)) => Some(
formdata
.extract(cx, &self.global(), false)
.expect("Couldn't extract body."),
),
Some(DocumentOrXMLHttpRequestBodyInit::String(ref str)) => Some(
str.extract(cx, &self.global(), false)
.expect("Couldn't extract body."),
),
Some(DocumentOrXMLHttpRequestBodyInit::URLSearchParams(ref urlsp)) => Some(
urlsp
.extract(cx, &self.global(), false)
.expect("Couldn't extract body."),
),
Some(DocumentOrXMLHttpRequestBodyInit::ArrayBuffer(ref typedarray)) => {
let bytes = get_buffer_source_copy(typedarray.into());
let total_bytes = bytes.len();
let global = self.global();
let stream = ReadableStream::new_from_bytes(cx, &global, bytes)?;
Some(ExtractedBody {
stream,
total_bytes: Some(total_bytes),
content_type: None,
source: BodySource::Object,
})
},
Some(DocumentOrXMLHttpRequestBodyInit::ArrayBufferView(ref typedarray)) => {
let bytes = get_buffer_source_copy(typedarray.into());
let total_bytes = bytes.len();
let global = self.global();
let stream = ReadableStream::new_from_bytes(cx, &global, bytes)?;
Some(ExtractedBody {
stream,
total_bytes: Some(total_bytes),
content_type: None,
source: BodySource::Object,
})
},
None => None,
};
self.request_body_len.set(
extracted_or_serialized
.as_ref()
.map_or(0, |e| e.total_bytes.unwrap_or(0)),
);
// Step 5. If one or more event listeners are registered on this’s upload object,
// then set this’s upload listener flag.
// If we dont have data to upload, we dont want to emit events
let has_handlers = self.upload.upcast::<EventTarget>().has_handlers();
self.upload_listener.set(has_handlers && data.is_some());
// todo preserved headers?
// Step 7. Unset this’s upload complete flag.
self.upload_complete.set(false);
// Step 8. Unset this’s timed out flag.
// FIXME handle the 'timed out flag'
// Step 9. If req’s body is null, then set this’s upload complete flag.
self.upload_complete.set(extracted_or_serialized.is_none());
// Step 10. Set this’s send() flag.
self.send_flag.set(true);
// Step 11. If this’s synchronous flag is unset, then:
if !self.sync.get() {
// If one of the event handlers below aborts the fetch by calling
// abort or open we will need the current generation id to detect it.
let gen_id = self.generation_id.get();
// Step 11.1 Fire a progress event named loadstart at this with 0 and 0.
self.dispatch_response_progress_event(cx, atom!("loadstart"));
if self.generation_id.get() != gen_id {
return Ok(());
}
// Step 11.2 If this’s upload complete flag is unset and this’s upload listener flag is set,
// then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted
// and requestBodyLength.
if !self.upload_complete.get() && self.upload_listener.get() {
self.dispatch_upload_progress_event(cx, atom!("loadstart"), Ok(Some(0)));
if self.generation_id.get() != gen_id {
return Ok(());
}
}
}
// Step 6
// TODO - set referrer_policy/referrer_url in request
let credentials_mode = if self.with_credentials.get() {
CredentialsMode::Include
} else {
CredentialsMode::CredentialsSameOrigin
};
let use_url_credentials = !url.username().is_empty() || url.password().is_some();
let content_type = match extracted_or_serialized.as_mut() {
Some(body) => body.content_type.take(),
None => None,
};
let global = self.global();
let mut request = RequestBuilder::new(global.webview_id(), url, self.referrer.clone())
.method(self.request_method.borrow().clone())
.headers((*self.request_headers.borrow()).clone())
.unsafe_request(true)
// XXXManishearth figure out how to avoid this clone
.body(extracted_or_serialized.map(|e| e.into_net_request_body(cx).0))
.synchronous(self.sync.get())
.mode(RequestMode::CorsMode)
.use_cors_preflight(self.upload_listener.get())
.credentials_mode(credentials_mode)
.use_url_credentials(use_url_credentials)
.with_global_scope(&global)
.referrer_policy(self.referrer_policy);
// step 4 (second half)
if let Some(content_type) = content_type {
let encoding = match data {
Some(DocumentOrXMLHttpRequestBodyInit::String(_)) |
Some(DocumentOrXMLHttpRequestBodyInit::Document(_)) =>
// XHR spec differs from http, and says UTF-8 should be in capitals,
// instead of "utf-8", which is what Hyper defaults to. So not
// using content types provided by Hyper.
{
Some("UTF-8")
},
_ => None,
};
// We cannot use typed header insertion with `mime::Mime` parsing here,
// since it lowercases `charset=UTF-8`: https://github.com/hyperium/mime/issues/116
let mut content_type_set = false;
if !request.headers.contains_key(header::CONTENT_TYPE) &&
let Ok(content_type_value) = HeaderValue::from_str(&content_type.str())
{
request
.headers
.insert(header::CONTENT_TYPE, content_type_value);
content_type_set = true;
}
if !content_type_set {
let content_type = request.headers.typed_get::<ContentType>();
if let Some(content_type) = content_type &&
let Some(encoding) = encoding &&
let Ok(mime) = content_type.to_string().parse::<Mime>()
{
for param in mime.parameters.iter() {
if param.0 == CHARSET && !param.1.as_str().eq_ignore_ascii_case(encoding) {
let new_params: Vec<_> =
mime.parameters.iter().filter(|p| p.0 != CHARSET).collect();
let new_mime = format!(
"{}/{};charset={encoding}{}{}",
mime.type_,
mime.subtype,
if new_params.is_empty() { "" } else { "; " },
new_params
.iter()
.map(|param| format!("{}={}", param.0, param.1))
.collect::<Vec<String>>()
.join("; ")
);
if let Ok(content_type_header) = HeaderValue::from_str(&new_mime) {
request
.headers
.insert(header::CONTENT_TYPE, content_type_header);
}
}
}
}
}
}
self.fetch_time.set(Instant::now());
let rv = self.fetch(cx, request, &self.global());
// Step 10
if self.sync.get() {
return rv;
}
let timeout = self.timeout.get();
if timeout > Duration::ZERO {
self.set_timeout(cx.no_gc(), timeout);
}
Ok(())
}
/// <https://xhr.spec.whatwg.org/#the-abort()-method>
fn Abort(&self, cx: &mut JSContext) {
// Step 1
self.terminate_ongoing_fetch(cx.no_gc());
// Step 2
let state = self.ready_state.get();
if (state == XMLHttpRequestState::Opened && self.send_flag.get()) ||
state == XMLHttpRequestState::HeadersReceived ||
state == XMLHttpRequestState::Loading
{
let gen_id = self.generation_id.get();
self.process_partial_response(cx, XHRProgress::Errored(gen_id, Error::Abort(None)));
// If open was called in one of the handlers invoked by the
// above call then we should terminate the abort sequence
if self.generation_id.get() != gen_id {
return;
}
}
// Step 3
if self.ready_state.get() == XMLHttpRequestState::Done {
self.change_ready_state(cx, XMLHttpRequestState::Unsent);
self.response_status.set(Err(()));
*self.status.safe_borrow_mut(cx.no_gc()) = HttpStatus::new_error();
self.response.safe_borrow_mut(cx.no_gc()).clear();
self.response_headers.safe_borrow_mut(cx.no_gc()).clear();
}
}
/// <https://xhr.spec.whatwg.org/#the-responseurl-attribute>
fn ResponseURL(&self) -> USVString {
USVString(self.response_url.borrow().clone())
}
/// <https://xhr.spec.whatwg.org/#the-status-attribute>
fn Status(&self) -> u16 {
self.status.borrow().raw_code()
}
/// <https://xhr.spec.whatwg.org/#the-statustext-attribute>
fn StatusText(&self) -> ByteString {
ByteString::new(self.status.borrow().message().to_vec())
}
/// <https://xhr.spec.whatwg.org/#the-getresponseheader()-method>
fn GetResponseHeader(&self, name: ByteString) -> Option<ByteString> {
let headers = self.filter_response_headers();
// > All custom header names are lower cased upon conversion to a HeaderName value.
// https://docs.rs/http/latest/http/header/struct.HeaderName.html#representation
let headers = headers.get_all(HeaderName::from_str(name.as_str()?).ok()?);
let mut first = true;
let s = headers.iter().fold(Vec::new(), |mut vec, value| {
if !first {
vec.extend(", ".as_bytes());
}
if let Ok(v) = str::from_utf8(value.as_bytes()).map(|s| s.trim().as_bytes()) {
vec.extend(v);
first = false;
}
vec
});
// There was no header with that name so we never got to change that value
if first {
None
} else {
Some(ByteString::new(s))
}
}
/// <https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method>
fn GetAllResponseHeaders(&self) -> ByteString {
let headers = self.filter_response_headers();
let keys = headers.keys();
let v = keys.fold(Vec::new(), |mut vec, k| {
let values = headers.get_all(k);
vec.extend(k.as_str().as_bytes());
vec.extend(": ".as_bytes());
let mut first = true;
for value in values {
if !first {
vec.extend(", ".as_bytes());
first = false;
}
vec.extend(value.as_bytes());
}
vec.extend("\r\n".as_bytes());
vec
});
ByteString::new(v)
}
/// <https://xhr.spec.whatwg.org/#the-overridemimetype()-method>
fn OverrideMimeType(&self, no_gc: &NoGC, mime: DOMString) -> ErrorResult {
// 1. If this’s state is loading or done, then throw an "InvalidStateError"
// DOMException.
match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
return Err(Error::InvalidState(None));
},
_ => {},
}
// 2. Set this’s override MIME type to the result of parsing mime.
// 3. If this’s override MIME type is failure, then set this’s override MIME type
// to application/octet-stream.
let override_mime = match mime.parse::<Mime>() {
Ok(mime) => mime,
Err(_) => "application/octet-stream"
.parse::<Mime>()
.map_err(|_| Error::Syntax(None))?,
};
*self.override_mime_type.safe_borrow_mut(no_gc) = Some(override_mime);
Ok(())
}
/// <https://xhr.spec.whatwg.org/#the-responsetype-attribute>
fn ResponseType(&self) -> XMLHttpRequestResponseType {
self.response_type.get()
}
/// <https://xhr.spec.whatwg.org/#the-responsetype-attribute>
fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult {
// Step 1
if self.global().is::<WorkerGlobalScope>() &&
response_type == XMLHttpRequestResponseType::Document
{
return Ok(());
}
match self.ready_state.get() {
// Step 2
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
Err(Error::InvalidState(None))
},
_ => {
if self.sync_in_window() {
// Step 3
Err(Error::InvalidAccess(None))
} else {
// Step 4
self.response_type.set(response_type);
Ok(())
}
},
}
}
/// <https://xhr.spec.whatwg.org/#the-response-attribute>
fn Response(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => {
let ready_state = self.ready_state.get();
// Step 2
if ready_state == XMLHttpRequestState::Done ||
ready_state == XMLHttpRequestState::Loading
{
self.text_response().to_jsval(cx, rval);
} else {
// Step 1
"".to_jsval(cx, rval);
}
},
// Step 1
_ if self.ready_state.get() != XMLHttpRequestState::Done => {
rval.set(NullValue());
},
// Step 2
XMLHttpRequestResponseType::Document => self.document_response(cx).to_jsval(cx, rval),
XMLHttpRequestResponseType::Json => self.json_response(cx, rval),
XMLHttpRequestResponseType::Blob => self.blob_response(cx).to_jsval(cx, rval),
XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) {
Some(array_buffer) => array_buffer.to_jsval(cx, rval),
None => rval.set(NullValue()),
},
}
}
/// <https://xhr.spec.whatwg.org/#the-responsetext-attribute>
fn GetResponseText(&self) -> Fallible<USVString> {
match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => {
Ok(USVString(match self.ready_state.get() {
// Step 3
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
self.text_response()
},
// Step 2
_ => String::new(),
}))
},
// Step 1
_ => Err(Error::InvalidState(None)),
}
}
/// <https://xhr.spec.whatwg.org/#the-responsexml-attribute>
fn GetResponseXML(&self, cx: &mut JSContext) -> Fallible<Option<DomRoot<Document>>> {
match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Document => {
// Step 3
if let XMLHttpRequestState::Done = self.ready_state.get() {
Ok(self.document_response(cx))
} else {
// Step 2
Ok(None)
}
},
// Step 1
_ => Err(Error::InvalidState(None)),
}
}
}
pub(crate) type TrustedXHRAddress = Trusted<XMLHttpRequest>;
impl XMLHttpRequest {
fn change_ready_state(&self, cx: &mut JSContext, rs: XMLHttpRequestState) {
assert_ne!(self.ready_state.get(), rs);
self.ready_state.set(rs);
if rs != XMLHttpRequestState::Unsent {
let event = Event::new(
cx,
&self.global(),
atom!("readystatechange"),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable,
);
event.fire(cx, self.upcast());
}
}
fn process_headers_available(
&self,
cx: &mut JSContext,
gen_id: GenerationId,
metadata: Result<FetchMetadata, NetworkError>,
) -> Result<(), Error> {
let metadata = match metadata {
Ok(meta) => match meta {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { filtered, .. } => match filtered {
FilteredMetadata::Basic(m) => m,
FilteredMetadata::Cors(m) => m,
FilteredMetadata::Opaque => return Err(Error::Network(None)),
FilteredMetadata::OpaqueRedirect(_) => return Err(Error::Network(None)),
},
},
Err(_) => {
self.process_partial_response(
cx,
XHRProgress::Errored(gen_id, Error::Network(None)),
);
return Err(Error::Network(None));
},
};
metadata.final_url[..Position::AfterQuery]
.clone_into(&mut self.response_url.safe_borrow_mut(cx.no_gc()));
// XXXManishearth Clear cache entries in case of a network error
self.process_partial_response(
cx,
XHRProgress::HeadersReceived(
gen_id,
metadata.headers.map(Serde::into_inner),
metadata.status,
),
);
Ok(())
}
fn process_data_available(&self, cx: &mut JSContext, gen_id: GenerationId, payload: Bytes) {
self.process_partial_response(cx, XHRProgress::Loading(gen_id, payload));
}
fn process_response_complete(
&self,
cx: &mut JSContext,
gen_id: GenerationId,
status: Result<(), NetworkError>,
) -> ErrorResult {
match status {
Ok(()) => {
self.process_partial_response(cx, XHRProgress::Done(gen_id));
Ok(())
},
Err(_) => {
self.process_partial_response(
cx,
XHRProgress::Errored(gen_id, Error::Network(None)),
);
Err(Error::Network(None))
},
}
}
fn process_partial_response(&self, cx: &mut JSContext, progress: XHRProgress) {
let msg_id = progress.generation_id();
// Aborts processing if abort() or open() was called
// (including from one of the event handlers called below)
macro_rules! return_if_fetch_was_terminated(
() => (
if msg_id != self.generation_id.get() {
return
}
);
);
// Ignore message if it belongs to a terminated fetch
return_if_fetch_was_terminated!();
// Ignore messages coming from previously-errored responses or requests that have timed out
if self.response_status.get().is_err() {
return;
}
match progress {
XHRProgress::HeadersReceived(_, headers, status) => {
assert!(self.ready_state.get() == XMLHttpRequestState::Opened);
// For synchronous requests, this should not fire any events, and just store data
// XXXManishearth Find a way to track partial progress of the send (onprogresss for XHRUpload)
// Part of step 13, send() (processing request end of file)
// Substep 1
self.upload_complete.set(true);
// Substeps 2-4
if !self.sync.get() && self.upload_listener.get() {
self.dispatch_upload_progress_event(cx, atom!("progress"), Ok(None));
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(cx, atom!("load"), Ok(None));
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(cx, atom!("loadend"), Ok(None));
return_if_fetch_was_terminated!();
}
// Part of step 13, send() (processing response)
// XXXManishearth handle errors, if any (substep 1)
// Substep 2
if !status.is_error() {
*self.status.safe_borrow_mut(cx.no_gc()) = status;
}
if let Some(h) = headers.as_ref() {
*self.response_headers.safe_borrow_mut(cx.no_gc()) = h.clone();
}
{
let len = headers.and_then(|h| h.typed_get::<ContentLength>());
let mut response = self.response.safe_borrow_mut(cx.no_gc());
response.clear();
if let Some(len) = len {
// don't attempt to prereserve more than 4 MB of memory,
// to avoid giving servers the ability to DOS the client by
// providing arbitrarily large content-lengths.
//
// this number is arbitrary, it's basically big enough that most
// XHR requests won't hit it, but not so big that it allows for DOS
let size = cmp::min(0b100_0000000000_0000000000, len.0 as usize);
// preallocate the buffer
response.reserve(size);
}
}
// Substep 3
if !self.sync.get() {
self.change_ready_state(cx, XMLHttpRequestState::HeadersReceived);
}
},
XHRProgress::Loading(_, partial_response) => {
// For synchronous requests, this should not fire any events, and just store data
// Part of step 11, send() (processing response body)
// XXXManishearth handle errors, if any (substep 2)
self.response
.safe_borrow_mut(cx.no_gc())
.extend_from_slice(&partial_response);
if !self.sync.get() {
if self.ready_state.get() == XMLHttpRequestState::HeadersReceived {
self.ready_state.set(XMLHttpRequestState::Loading);
}
let event = Event::new(
cx,
&self.global(),
atom!("readystatechange"),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable,
);
event.fire(cx, self.upcast());
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(cx, atom!("progress"));
}
},
XHRProgress::Done(_) => {
assert!(
self.ready_state.get() == XMLHttpRequestState::HeadersReceived ||
self.ready_state.get() == XMLHttpRequestState::Loading ||
self.sync.get()
);
self.cancel_timeout(cx.no_gc());
self.canceller.safe_borrow_mut(cx.no_gc()).ignore();
// Part of step 11, send() (processing response end of file)
// XXXManishearth handle errors, if any (substep 2)
// Subsubsteps 6-8
self.send_flag.set(false);
self.change_ready_state(cx, XMLHttpRequestState::Done);
return_if_fetch_was_terminated!();
// Subsubsteps 11-12
self.dispatch_response_progress_event(cx, atom!("load"));
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(cx, atom!("loadend"));
},
XHRProgress::Errored(_, e) => {
self.cancel_timeout(cx.no_gc());
self.canceller.safe_borrow_mut(cx.no_gc()).ignore();
self.discard_subsequent_responses();
self.send_flag.set(false);
*self.status.safe_borrow_mut(cx.no_gc()) = HttpStatus::new_error();
self.response_headers.safe_borrow_mut(cx.no_gc()).clear();
// XXXManishearth set response to NetworkError
self.change_ready_state(cx, XMLHttpRequestState::Done);
return_if_fetch_was_terminated!();
let errormsg = match e {
Error::Abort(None) => "abort",
Error::Timeout(None) => "timeout",
_ => "error",
};
let upload_complete = &self.upload_complete;
if !upload_complete.get() {
upload_complete.set(true);
if self.upload_listener.get() {
self.dispatch_upload_progress_event(cx, Atom::from(errormsg), Err(()));
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(cx, atom!("loadend"), Err(()));
return_if_fetch_was_terminated!();
}
}
self.dispatch_response_progress_event(cx, Atom::from(errormsg));
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(cx, atom!("loadend"));
},
}
}
fn terminate_ongoing_fetch(&self, no_gc: &NoGC) {
self.canceller.safe_borrow_mut(no_gc).abort();
let GenerationId(prev_id) = self.generation_id.get();
self.generation_id.set(GenerationId(prev_id + 1));
self.response_status.set(Ok(()));
}
fn dispatch_progress_event(
&self,
cx: &mut JSContext,
upload: bool,
type_: Atom,
loaded: u64,
total: Option<u64>,
) {
let (total_length, length_computable) = if self
.response_headers
.borrow()
.contains_key(header::CONTENT_ENCODING)
{
(0, false)
} else {
(total.unwrap_or(0), total.is_some())
};
let progressevent = ProgressEvent::new(
cx,
&self.global(),
type_,
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
length_computable,
Finite::wrap(loaded as f64),
Finite::wrap(total_length as f64),
);
let target = if upload {
self.upload.upcast()
} else {
self.upcast()
};
progressevent.upcast::<Event>().fire(cx, target);
}
fn dispatch_upload_progress_event(
&self,
cx: &mut JSContext,
type_: Atom,
partial_load: Result<Option<u64>, ()>,
) {
// If partial_load is Ok(None), loading has completed and we can just use the value from the request body
// If an error occurred, we pass 0 for both loaded and total
let request_body_len = self.request_body_len.get() as u64;
let (loaded, total) = match partial_load {
Ok(l) => match l {
Some(loaded) => (loaded, Some(request_body_len)),
None => (request_body_len, Some(request_body_len)),
},
Err(()) => (0, None),
};
self.dispatch_progress_event(cx, true, type_, loaded, total);
}
fn dispatch_response_progress_event(&self, cx: &mut JSContext, type_: Atom) {
let len = self.response.borrow().len() as u64;
let total = self
.response_headers
.borrow()
.typed_get::<ContentLength>()
.map(|v| v.0);
self.dispatch_progress_event(cx, false, type_, len, total);
}
fn set_timeout(&self, no_gc: &NoGC, duration: Duration) {
// Sets up the object to timeout in a given number of milliseconds
// This will cancel all previous timeouts
let callback = OneshotTimerCallback::XhrTimeout(XHRTimeoutCallback {
xhr: Trusted::new(self),
generation_id: self.generation_id.get(),
});
*self.timeout_cancel.safe_borrow_mut(no_gc) =
Some(self.global().schedule_callback(callback, duration));
}
fn cancel_timeout(&self, no_gc: &NoGC) {
if let Some(handle) = self.timeout_cancel.safe_borrow_mut(no_gc).take() {
self.global().unschedule_callback(handle);
}
}
/// <https://xhr.spec.whatwg.org/#text-response>
fn text_response(&self) -> String {
// Step 3, 5
let charset = self.final_charset().unwrap_or(UTF_8);
// TODO: Step 4 - add support for XML encoding guess stuff using XML spec
// According to Simon, decode() should never return an error, so unwrap()ing
// the result should be fine. XXXManishearth have a closer look at this later
// Step 1, 2, 6
let response = self.response.borrow();
let (text, _, _) = charset.decode(&response);
text.into_owned()
}
/// <https://xhr.spec.whatwg.org/#blob-response>
fn blob_response(&self, cx: &mut JSContext) -> DomRoot<Blob> {
// Step 1
if let Some(response) = self.response_blob.get() {
return response;
}
// Step 2
let mime = normalize_type_string(&self.final_mime_type().to_string());
// Step 3, 4
let bytes = self.response.borrow().to_vec();
let blob = Blob::new(cx, &self.global(), BlobImpl::new_from_bytes(bytes, mime));
self.response_blob.set(Some(&blob));
blob
}
/// <https://xhr.spec.whatwg.org/#arraybuffer-response>
fn arraybuffer_response(
&self,
cx: &mut JSContext,
) -> Option<RootedTraceableBox<HeapArrayBuffer>> {
// Step 5: Set the response object to a new ArrayBuffer with the received bytes
// For caching purposes, skip this step if the response is already created
if !self.response_arraybuffer.is_initialized() {
let bytes = self.response.borrow();
// If this is not successful, the response won't be set and the function will return None
self.response_arraybuffer.set_data(cx, &bytes).ok()?;
}
// Return the correct ArrayBuffer
self.response_arraybuffer.get_typed_array().ok()
}
/// <https://xhr.spec.whatwg.org/#document-response>
fn document_response(&self, cx: &mut JSContext) -> Option<DomRoot<Document>> {
// Caching: if we have existing response xml, redirect it directly
let response = self.response_xml.get();
if response.is_some() {
return response;
}
// Step 1: If xhr’s response’s body is null, then return.
if self.response_status.get().is_err() {
return None;
}
// Step 2: Let finalMIME be the result of get a final MIME type for xhr.
let final_mime = self.final_mime_type();
// Step 3: If finalMIME is not an HTML MIME type or an XML MIME type, then return.
let is_xml_mime_type = final_mime.matches(TEXT, XML) ||
final_mime.matches(APPLICATION, XML) ||
final_mime.has_suffix(XML);
if !final_mime.matches(TEXT, HTML) && !is_xml_mime_type {
return None;
}
// Step 4: If xhr’s response type is the empty string and finalMIME is an HTML MIME
// type, then return.
let charset;
let temp_doc;
if final_mime.matches(TEXT, HTML) {
if self.response_type.get() == XMLHttpRequestResponseType::_empty {
return None;
}
// Step 5: If finalMIME is an HTML MIME type, then:
// Step 5.1: Let charset be the result of get a final encoding for xhr.
// Step 5.2: If charset is null, prescan the first 1024 bytes of xhr’s received bytes
// and if that does not terminate unsuccessfully then let charset be the return value.
// TODO: This isn't happening right now.
// Step 5.3. If charset is null, then set charset to UTF-8.
charset = Some(self.final_charset().unwrap_or(UTF_8));
// Step 5.4: Let document be a document that represents the result parsing xhr’s
// received bytes following the rules set forth in the HTML Standard for an HTML parser
// with scripting disabled and a known definite encoding charset. [HTML]
temp_doc = self.document_text_html(cx);
} else {
assert!(is_xml_mime_type);
// Step 6: Otherwise, let document be a document that represents the result of running
// the XML parser with XML scripting support disabled on xhr’s received bytes. If that
// fails (unsupported character encoding, namespace well-formedness error, etc.), then
// return null. [HTML]
//
// TODO: The spec seems to suggest the charset should come from the XML parser here.
temp_doc = self.handle_xml(cx);
charset = self.final_charset();
// Not sure it the parser should throw an error for this case
// The specification does not indicates this test,
// but for now we check the document has no child nodes
let has_no_child_nodes = temp_doc.upcast::<Node>().children().next().is_none();
if has_no_child_nodes {
return None;
}
}
// Step 7: If charset is null, then set charset to UTF-8.
let charset = charset.unwrap_or(UTF_8);
// Step 8: Set document’s encoding to charset.
temp_doc.set_encoding(charset);
// Step 9: Set document’s content type to finalMIME.
// Step 10: Set document’s URL to xhr’s response’s URL.
// Step 11: Set document’s origin to xhr’s relevant settings object’s origin.
//
// Done by `handle_text_html()` and `handle_xml()`.
// Step 12: Set xhr’s response object to document.
self.response_xml.set(Some(&temp_doc));
self.response_xml.get()
}
#[expect(unsafe_code)]
/// <https://xhr.spec.whatwg.org/#json-response>
fn json_response(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
// Step 1
let response_json = self.response_json.get();
if !response_json.is_null_or_undefined() {
return rval.set(response_json);
}
// Step 2
let bytes = self.response.borrow();
// Step 3
if bytes.is_empty() {
return rval.set(NullValue());
}
// Step 4
// https://xhr.spec.whatwg.org/#json-response refers to
// https://infra.spec.whatwg.org/#parse-json-from-bytes which refers to
// https://encoding.spec.whatwg.org/#utf-8-decode which means
// that the encoding is always UTF-8 and the UTF-8 BOM is removed,
// if present, but UTF-16BE/LE BOM must not be honored.
let json_text = decode_to_utf16_with_bom_removal(&bytes, UTF_8);
// Step 5
unsafe {
if !JS_ParseJSON(
cx,
json_text.as_ptr(),
json_text.len() as u32,
rval.reborrow(),
) {
JS_ClearPendingException(cx);
return rval.set(NullValue());
}
}
// Step 6
self.response_json.set(rval.get());
}
fn document_text_html(&self, cx: &mut JSContext) -> DomRoot<Document> {
let charset = self.final_charset().unwrap_or(UTF_8);
let wr = self.global();
let response = self.response.borrow();
let (decoded, _, _) = charset.decode(&response);
let document = self.new_doc(cx, IsHTMLDocument::HTMLDocument);
// TODO: Disable scripting while parsing
ServoParser::parse_html_document(
cx,
&document,
Some(DOMString::from(decoded)),
wr.get_url(),
None,
None,
);
document
}
fn handle_xml(&self, cx: &mut JSContext) -> DomRoot<Document> {
let charset = self.final_charset().unwrap_or(UTF_8);
let wr = self.global();
let response = self.response.borrow();
let (decoded, _, _) = charset.decode(&response);
let document = self.new_doc(cx, IsHTMLDocument::NonHTMLDocument);
// TODO: Disable scripting while parsing
ServoParser::parse_xml_document(
cx,
&document,
Some(DOMString::from(decoded)),
wr.get_url(),
None,
);
document
}
fn new_doc(&self, cx: &mut JSContext, is_html_document: IsHTMLDocument) -> DomRoot<Document> {
let wr = self.global();
let win = wr.as_window();
let doc = win.Document();
let docloader = DocumentLoader::new(&doc.loader());
let base = wr.get_url();
let parsed_url = base.join(&self.ResponseURL().0).ok();
let content_type = Some(self.final_mime_type());
Document::new(
cx,
win,
HasBrowsingContext::No,
parsed_url,
None,
doc.origin().clone(),
is_html_document,
content_type,
None,
DocumentActivity::Inactive,
docloader,
None,
None,
Default::default(),
false,
false,
Some(doc.insecure_requests_policy()),
doc.has_trustworthy_ancestor_origin(),
doc.custom_element_reaction_stack(),
doc.creation_sandboxing_flag_set(),
doc.pipeline_id(),
doc.image_cache(),
)
}
fn filter_response_headers(&self) -> HeaderMap {
// https://fetch.spec.whatwg.org/#concept-response-header-list
let mut headers = self.response_headers.borrow().clone();
headers.remove(header::SET_COOKIE);
headers.remove(HeaderName::from_static("set-cookie2"));
// XXXManishearth additional CORS filtering goes here
headers
}
fn discard_subsequent_responses(&self) {
self.response_status.set(Err(()));
}
fn fetch(
&self,
cx: &mut JSContext,
request_builder: RequestBuilder,
global: &GlobalScope,
) -> ErrorResult {
let xhr = Trusted::new(self);
let sync_status = Arc::new(AtomicRefCell::new(None));
let context = XHRContext {
xhr,
gen_id: self.generation_id.get(),
sync_status: sync_status.clone(),
url: request_builder.url.url(),
};
let (task_source, script_port) = if self.sync.get() {
let (sender, receiver) = global.new_script_pair();
(
SendableTaskSource {
sender,
pipeline_id: global.pipeline_id(),
name: TaskSourceName::Networking,
canceller: Default::default(),
},
Some(receiver),
)
} else {
(
global.task_manager().networking_task_source().to_sendable(),
None,
)
};
*self.canceller.safe_borrow_mut(cx.no_gc()) =
FetchCanceller::new(request_builder.id, false, global.core_resource_thread());
global.fetch(request_builder, context, task_source);
if let Some(script_port) = script_port {
loop {
if !global.process_event(script_port.recv().unwrap(), cx) {
// We're exiting.
return Err(Error::Abort(None));
}
if let Some(ref status) = *sync_status.borrow() {
return status.clone();
}
}
}
Ok(())
}
/// <https://xhr.spec.whatwg.org/#final-charset>
fn final_charset(&self) -> Option<&'static Encoding> {
// 1. Let label be null.
// 2. Let responseMIME be the result of get a response MIME type for xhr.
// 3. If responseMIME’s parameters["charset"] exists, then set label to it.
let response_charset = self
.response_mime_type()
.get_parameter(CHARSET)
.map(ToString::to_string);
// 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.
let override_charset = self
.override_mime_type
.borrow()
.as_ref()
.and_then(|mime| mime.get_parameter(CHARSET))
.map(ToString::to_string);
// 5. If label is null, then return null.
// 6. Let encoding be the result of getting an encoding from label.
// 7. If encoding is failure, then return null.
// 8. Return encoding.
override_charset
.or(response_charset)
.and_then(|charset| Encoding::for_label(charset.as_bytes()))
}
/// <https://xhr.spec.whatwg.org/#response-mime-type>
fn response_mime_type(&self) -> Mime {
// 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s
// header list.
// 2. If mimeType is failure, then set mimeType to text/xml.
// 3. Return mimeType.
extract_mime_type_as_dataurl_mime(&self.response_headers.borrow())
.unwrap_or_else(|| Mime::new(TEXT, XML))
}
/// <https://xhr.spec.whatwg.org/#final-mime-type>
fn final_mime_type(&self) -> Mime {
self.override_mime_type
.borrow()
.as_ref()
.map(MimeExt::clone)
.unwrap_or_else(|| self.response_mime_type())
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub(crate) struct XHRTimeoutCallback {
#[ignore_malloc_size_of = "Because it is non-owning"]
xhr: Trusted<XMLHttpRequest>,
generation_id: GenerationId,
}
impl XHRTimeoutCallback {
pub(crate) fn invoke(self, cx: &mut JSContext) {
let xhr = self.xhr.root();
if xhr.ready_state.get() != XMLHttpRequestState::Done {
xhr.process_partial_response(
cx,
XHRProgress::Errored(self.generation_id, Error::Timeout(None)),
);
}
}
}
fn serialize_document(doc: &Document) -> Fallible<DOMString> {
let mut writer = vec![];
if serialize(
&mut writer,
&HtmlSerialize::new(doc.upcast::<Node>()),
SerializeOpts::default(),
)
.is_err()
{
return Err(Error::InvalidState(Some(
"Could not serialize document".into(),
)));
};
let Ok(string) = String::from_utf8(writer) else {
return Err(Error::InvalidState(Some(
"Could not serialize document".into(),
)));
};
Ok(DOMString::from(string))
}
/// Returns whether `bs` is a `field-value`, as defined by
/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-32).
pub(crate) fn is_field_value(slice: &[u8]) -> bool {
// Classifications of characters necessary for the [CRLF] (SP|HT) rule
#[derive(PartialEq)]
#[expect(clippy::upper_case_acronyms)]
enum PreviousCharacter {
Other,
CR,
LF,
SPHT, // SP or HT
}
let mut prev = PreviousCharacter::Other; // The previous character
slice.iter().all(|&x| {
// http://tools.ietf.org/html/rfc2616#section-2.2
match x {
13 if (prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT) => {
// CR
prev = PreviousCharacter::CR;
true
},
10 if prev == PreviousCharacter::CR => {
// LF
prev = PreviousCharacter::LF;
true
},
10 => false,
32 => {
// SP
if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT {
prev = PreviousCharacter::SPHT;
true
} else if prev == PreviousCharacter::Other {
// Counts as an Other here, since it's not preceded by a CRLF
// SP is not a CTL, so it can be used anywhere
// though if used immediately after a CR the CR is invalid
// We don't change prev since it's already Other
true
} else {
false
}
},
9 if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT => {
// HT
prev = PreviousCharacter::SPHT;
true
},
9 => false,
0..=31 | 127 => false, // CTLs
x if x > 127 => false, // non ASCII
_ if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT => {
prev = PreviousCharacter::Other;
true
},
_ => false, // Previous character was a CR/LF but not part of the [CRLF] (SP|HT) rule
}
})
}