use std::borrow::ToOwned;
use std::cell::Cell;
use std::default::Default;
use std::str::{self, FromStr};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{cmp, slice};
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::header::{self, HeaderMap, HeaderName, HeaderValue};
use http::Method;
use hyper_serde::Serde;
use ipc_channel::ipc;
use js::jsapi::{Heap, JS_ClearPendingException};
use js::jsval::{JSVal, NullValue};
use js::rust::wrappers::JS_ParseJSON;
use js::rust::{HandleObject, MutableHandleValue};
use js::typedarray::{ArrayBuffer, ArrayBufferU8};
use mime::{self, Mime, Name};
use net_traits::http_status::HttpStatus;
use net_traits::request::{
CredentialsMode, Destination, Referrer, RequestBuilder, RequestId, RequestMode,
};
use net_traits::{
trim_http_whitespace, FetchMetadata, FetchResponseListener, FilteredMetadata, NetworkError,
ReferrerPolicy, ResourceFetchTiming, ResourceTimingType,
};
use script_traits::serializable::BlobImpl;
use script_traits::DocumentActivity;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use url::Position;
use crate::body::{BodySource, Extractable, ExtractedBody};
use crate::document_loader::DocumentLoader;
use crate::dom::bindings::buffer_source::HeapBufferSource;
use crate::dom::bindings::cell::DomRefCell;
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::conversions::ToJSValConvertible;
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::{reflect_dom_object_with_proto, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::{is_token, ByteString, DOMString, USVString};
use crate::dom::blob::{normalize_type_string, Blob};
use crate::dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLDocument};
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::headers::{extract_mime_type, is_forbidden_request_header};
use crate::dom::node::Node;
use crate::dom::performanceresourcetiming::InitiatorType;
use crate::dom::progressevent::ProgressEvent;
use crate::dom::readablestream::ReadableStream;
use crate::dom::servoparser::ServoParser;
use crate::dom::window::Window;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget;
use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload;
use crate::fetch::FetchCanceller;
use crate::network_listener::{self, PreInvoke, ResourceTimingListener};
use crate::script_runtime::{CanGc, JSContext};
use crate::task_source::networking::NetworkingTaskSource;
use crate::timers::{OneshotTimerCallback, OneshotTimerHandle};
#[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 struct GenerationId(u32);
struct XHRContext {
xhr: TrustedXHRAddress,
gen_id: GenerationId,
sync_status: DomRefCell<Option<ErrorResult>>,
resource_timing: ResourceFetchTiming,
url: ServoUrl,
}
#[derive(Clone)]
pub enum XHRProgress {
HeadersReceived(GenerationId, Option<HeaderMap>, HttpStatus),
Loading(GenerationId, Vec<u8>),
Done(GenerationId),
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 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>,
response: DomRefCell<Vec<u8>>,
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>,
#[ignore_malloc_size_of = "Defined in hyper"]
#[no_trace]
response_headers: DomRefCell<HeaderMap>,
#[ignore_malloc_size_of = "Defined in hyper"]
#[no_trace]
override_mime_type: DomRefCell<Option<Mime>>,
#[ignore_malloc_size_of = "Defined in hyper"]
#[no_trace]
request_method: DomRefCell<Method>,
#[no_trace]
request_url: DomRefCell<Option<ServoUrl>>,
#[ignore_malloc_size_of = "Defined in hyper"]
#[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) -> 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(&*XMLHttpRequestUpload::new(global)),
response_url: DomRefCell::new(String::new()),
status: DomRefCell::new(HttpStatus::new_error()),
response: DomRefCell::new(vec![]),
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(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> DomRoot<XMLHttpRequest> {
reflect_dom_object_with_proto(
Box::new(XMLHttpRequest::new_inherited(global)),
global,
proto,
can_gc,
)
}
fn sync_in_window(&self) -> bool {
self.sync.get() && self.global().is::<Window>()
}
fn initiate_async_xhr(
context: Arc<Mutex<XHRContext>>,
task_source: NetworkingTaskSource,
global: &GlobalScope,
init: RequestBuilder,
cancellation_chan: ipc::IpcReceiver<()>,
) {
impl FetchResponseListener for XHRContext {
fn process_request_body(&mut self, _: RequestId) {
}
fn process_request_eof(&mut self, _: RequestId) {
}
fn process_response(
&mut self,
_: RequestId,
metadata: Result<FetchMetadata, NetworkError>,
) {
let xhr = self.xhr.root();
let rv = xhr.process_headers_available(self.gen_id, metadata, CanGc::note());
if rv.is_err() {
*self.sync_status.borrow_mut() = Some(rv);
}
}
fn process_response_chunk(&mut self, _: RequestId, chunk: Vec<u8>) {
self.xhr
.root()
.process_data_available(self.gen_id, chunk, CanGc::note());
}
fn process_response_eof(
&mut self,
_: RequestId,
response: Result<ResourceFetchTiming, NetworkError>,
) {
let rv = self.xhr.root().process_response_complete(
self.gen_id,
response.map(|_| ()),
CanGc::note(),
);
*self.sync_status.borrow_mut() = Some(rv);
}
fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
&mut self.resource_timing
}
fn resource_timing(&self) -> &ResourceFetchTiming {
&self.resource_timing
}
fn submit_resource_timing(&mut self) {
network_listener::submit_timing(self, CanGc::note())
}
}
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()
}
}
impl PreInvoke for XHRContext {
fn should_invoke(&self) -> bool {
self.xhr.root().generation_id.get() == self.gen_id
}
}
global.fetch(init, context, task_source, Some(cancellation_chan));
}
}
impl XMLHttpRequestMethods for XMLHttpRequest {
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<XMLHttpRequest>> {
Ok(XMLHttpRequest::new(global, proto, can_gc))
}
event_handler!(
readystatechange,
GetOnreadystatechange,
SetOnreadystatechange
);
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
fn Open(&self, method: ByteString, url: USVString) -> ErrorResult {
self.Open_(method, url, true, None, None)
}
fn Open_(
&self,
method: ByteString,
url: USVString,
asynch: bool,
username: Option<USVString>,
password: Option<USVString>,
) -> ErrorResult {
if let Some(window) = DomRoot::downcast::<Window>(self.global()) {
if !window.Document().is_fully_active() {
return Err(Error::InvalidState);
}
}
let maybe_method = method.as_str().and_then(|s| {
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 {
Some(Method::CONNECT) | Some(Method::TRACE) => Err(Error::Security),
Some(ref t) if t.as_str() == "TRACK" => Err(Error::Security),
Some(parsed_method) => {
if !is_token(&method) {
return Err(Error::Syntax);
}
let base = self.global().api_base_url();
let mut parsed_url = match base.join(&url.0) {
Ok(parsed) => parsed,
Err(_) => return Err(Error::Syntax),
};
if parsed_url.host().is_some() {
if let Some(user_str) = username {
parsed_url.set_username(&user_str.0).unwrap();
}
if let Some(pass_str) = password {
parsed_url.set_password(Some(&pass_str.0)).unwrap();
}
}
if !asynch {
if !self.timeout.get().is_zero() ||
self.response_type.get() != XMLHttpRequestResponseType::_empty
{
return Err(Error::InvalidAccess);
}
}
self.terminate_ongoing_fetch();
*self.request_method.borrow_mut() = parsed_method;
*self.request_url.borrow_mut() = Some(parsed_url);
self.sync.set(!asynch);
*self.request_headers.borrow_mut() = HeaderMap::new();
self.send_flag.set(false);
self.upload_listener.set(false);
*self.status.borrow_mut() = HttpStatus::new_error();
if self.ready_state.get() != XMLHttpRequestState::Opened {
self.change_ready_state(XMLHttpRequestState::Opened, CanGc::note());
}
Ok(())
},
_ => Err(Error::Syntax),
}
}
fn SetRequestHeader(&self, name: ByteString, value: ByteString) -> ErrorResult {
if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
return Err(Error::InvalidState);
}
let value = trim_http_whitespace(&value);
if !is_token(&name) || !is_field_value(value) {
return Err(Error::Syntax);
}
let name_str = name.as_str().ok_or(Error::Syntax)?;
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.borrow_mut();
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(),
};
headers.insert(
HeaderName::from_str(name_str).unwrap(),
HeaderValue::from_bytes(&value).unwrap(),
);
Ok(())
}
fn Timeout(&self) -> u32 {
self.timeout.get().as_millis() as u32
}
fn SetTimeout(&self, timeout: u32) -> ErrorResult {
if self.sync_in_window() {
return Err(Error::InvalidAccess);
}
let timeout = Duration::from_millis(timeout as u64);
self.timeout.set(timeout);
if self.send_flag.get() {
if timeout.is_zero() {
self.cancel_timeout();
return Ok(());
}
let progress = Instant::now() - self.fetch_time.get();
if timeout > progress {
self.set_timeout(timeout - progress);
} else {
self.set_timeout(Duration::ZERO);
}
}
Ok(())
}
fn WithCredentials(&self) -> bool {
self.with_credentials.get()
}
fn SetWithCredentials(&self, with_credentials: bool) -> ErrorResult {
match self.ready_state.get() {
XMLHttpRequestState::HeadersReceived |
XMLHttpRequestState::Loading |
XMLHttpRequestState::Done => Err(Error::InvalidState),
_ if self.send_flag.get() => Err(Error::InvalidState),
_ => {
self.with_credentials.set(with_credentials);
Ok(())
},
}
}
fn Upload(&self) -> DomRoot<XMLHttpRequestUpload> {
DomRoot::from_ref(&*self.upload)
}
fn Send(&self, data: Option<DocumentOrXMLHttpRequestBodyInit>, can_gc: CanGc) -> ErrorResult {
if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
return Err(Error::InvalidState);
}
let data = match *self.request_method.borrow() {
Method::GET | Method::HEAD => None,
_ => data,
};
let mut extracted_or_serialized = match data {
Some(DocumentOrXMLHttpRequestBodyInit::Document(ref doc)) => {
let bytes = Vec::from(serialize_document(doc)?.as_ref());
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(&global, bytes, can_gc);
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(&self.global(), can_gc)
.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(&self.global(), can_gc)
.expect("Couldn't extract body."),
),
Some(DocumentOrXMLHttpRequestBodyInit::String(ref str)) => Some(
str.extract(&self.global(), can_gc)
.expect("Couldn't extract body."),
),
Some(DocumentOrXMLHttpRequestBodyInit::URLSearchParams(ref urlsp)) => Some(
urlsp
.extract(&self.global(), can_gc)
.expect("Couldn't extract body."),
),
Some(DocumentOrXMLHttpRequestBodyInit::ArrayBuffer(ref typedarray)) => {
let bytes = typedarray.to_vec();
let total_bytes = bytes.len();
let global = self.global();
let stream = ReadableStream::new_from_bytes(&global, bytes, can_gc);
Some(ExtractedBody {
stream,
total_bytes: Some(total_bytes),
content_type: None,
source: BodySource::Object,
})
},
Some(DocumentOrXMLHttpRequestBodyInit::ArrayBufferView(ref typedarray)) => {
let bytes = typedarray.to_vec();
let total_bytes = bytes.len();
let global = self.global();
let stream = ReadableStream::new_from_bytes(&global, bytes, can_gc);
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)),
);
let has_handlers = self.upload.upcast::<EventTarget>().has_handlers();
self.upload_listener.set(has_handlers && data.is_some());
self.upload_complete.set(false);
self.upload_complete.set(extracted_or_serialized.is_none());
self.send_flag.set(true);
if !self.sync.get() {
let gen_id = self.generation_id.get();
self.dispatch_response_progress_event(atom!("loadstart"), can_gc);
if self.generation_id.get() != gen_id {
return Ok(());
}
if !self.upload_complete.get() && self.upload_listener.get() {
self.dispatch_upload_progress_event(atom!("loadstart"), Ok(Some(0)), can_gc);
if self.generation_id.get() != gen_id {
return Ok(());
}
}
}
let credentials_mode = if self.with_credentials.get() {
CredentialsMode::Include
} else {
CredentialsMode::CredentialsSameOrigin
};
let use_url_credentials = if let Some(ref url) = *self.request_url.borrow() {
!url.username().is_empty() || url.password().is_some()
} else {
unreachable!()
};
let content_type = match extracted_or_serialized.as_mut() {
Some(body) => body.content_type.take(),
None => None,
};
let mut request = RequestBuilder::new(
self.request_url.borrow().clone().unwrap(),
self.referrer.clone(),
)
.method(self.request_method.borrow().clone())
.headers((*self.request_headers.borrow()).clone())
.unsafe_request(true)
.body(extracted_or_serialized.map(|e| e.into_net_request_body().0))
.destination(Destination::None)
.synchronous(self.sync.get())
.mode(RequestMode::CorsMode)
.use_cors_preflight(self.upload_listener.get())
.credentials_mode(credentials_mode)
.use_url_credentials(use_url_credentials)
.origin(self.global().origin().immutable().clone())
.referrer_policy(self.referrer_policy)
.pipeline_id(Some(self.global().pipeline_id()));
if let Some(content_type) = content_type {
let encoding = match data {
Some(DocumentOrXMLHttpRequestBodyInit::String(_)) |
Some(DocumentOrXMLHttpRequestBodyInit::Document(_)) =>
{
Some("UTF-8")
},
_ => None,
};
let mut content_type_set = false;
if !request.headers.contains_key(header::CONTENT_TYPE) {
request.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_str(&content_type).unwrap(),
);
content_type_set = true;
}
if !content_type_set {
let ct = request.headers.typed_get::<ContentType>();
if let Some(ct) = ct {
if let Some(encoding) = encoding {
let mime: Mime = ct.into();
for param in mime.params() {
if param.0 == mime::CHARSET &&
!param.1.as_ref().eq_ignore_ascii_case(encoding)
{
let new_params: Vec<(Name, Name)> = mime
.params()
.filter(|p| p.0 != mime::CHARSET)
.map(|p| (p.0, p.1))
.collect();
let new_mime = format!(
"{}/{}; charset={}{}{}",
mime.type_().as_ref(),
mime.subtype().as_ref(),
encoding,
if new_params.is_empty() { "" } else { "; " },
new_params
.iter()
.map(|p| format!("{}={}", p.0, p.1))
.collect::<Vec<String>>()
.join("; ")
);
let new_mime: Mime = new_mime.parse().unwrap();
request.headers.typed_insert(ContentType::from(new_mime))
}
}
}
}
}
}
self.fetch_time.set(Instant::now());
let rv = self.fetch(request, &self.global());
if self.sync.get() {
return rv;
}
let timeout = self.timeout.get();
if timeout > Duration::ZERO {
self.set_timeout(timeout);
}
Ok(())
}
fn Abort(&self, can_gc: CanGc) {
self.terminate_ongoing_fetch();
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(XHRProgress::Errored(gen_id, Error::Abort), can_gc);
if self.generation_id.get() != gen_id {
return;
}
}
if self.ready_state.get() == XMLHttpRequestState::Done {
self.change_ready_state(XMLHttpRequestState::Unsent, can_gc);
self.response_status.set(Err(()));
self.response.borrow_mut().clear();
self.response_headers.borrow_mut().clear();
}
}
fn ResponseURL(&self) -> USVString {
USVString(self.response_url.borrow().clone())
}
fn Status(&self) -> u16 {
self.status.borrow().raw_code()
}
fn StatusText(&self) -> ByteString {
ByteString::new(self.status.borrow().message().to_vec())
}
fn GetResponseHeader(&self, name: ByteString) -> Option<ByteString> {
let headers = self.filter_response_headers();
let headers = headers.get_all(HeaderName::from_str(&name.as_str()?.to_lowercase()).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
});
if first {
None
} else {
Some(ByteString::new(s))
}
}
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)
}
fn OverrideMimeType(&self, mime: DOMString) -> ErrorResult {
match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
return Err(Error::InvalidState);
},
_ => {},
}
let override_mime = match mime.parse::<Mime>() {
Ok(mime) => mime,
Err(_) => "application/octet-stream"
.parse::<Mime>()
.map_err(|_| Error::Syntax)?,
};
*self.override_mime_type.borrow_mut() = Some(override_mime);
Ok(())
}
fn ResponseType(&self) -> XMLHttpRequestResponseType {
self.response_type.get()
}
fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult {
if self.global().is::<WorkerGlobalScope>() &&
response_type == XMLHttpRequestResponseType::Document
{
return Ok(());
}
match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => Err(Error::InvalidState),
_ => {
if self.sync_in_window() {
Err(Error::InvalidAccess)
} else {
self.response_type.set(response_type);
Ok(())
}
},
}
}
#[allow(unsafe_code)]
fn Response(&self, cx: JSContext, can_gc: CanGc, mut rval: MutableHandleValue) {
match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => unsafe {
let ready_state = self.ready_state.get();
if ready_state == XMLHttpRequestState::Done ||
ready_state == XMLHttpRequestState::Loading
{
self.text_response().to_jsval(*cx, rval);
} else {
"".to_jsval(*cx, rval);
}
},
_ if self.ready_state.get() != XMLHttpRequestState::Done => {
rval.set(NullValue());
},
XMLHttpRequestResponseType::Document => unsafe {
self.document_response(can_gc).to_jsval(*cx, rval);
},
XMLHttpRequestResponseType::Json => self.json_response(cx, rval),
XMLHttpRequestResponseType::Blob => unsafe {
self.blob_response(can_gc).to_jsval(*cx, rval);
},
XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) {
Some(array_buffer) => unsafe { array_buffer.to_jsval(*cx, rval) },
None => rval.set(NullValue()),
},
}
}
fn GetResponseText(&self) -> Fallible<USVString> {
match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => {
Ok(USVString(match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => {
self.text_response()
},
_ => "".to_owned(),
}))
},
_ => Err(Error::InvalidState),
}
}
fn GetResponseXML(&self, can_gc: CanGc) -> Fallible<Option<DomRoot<Document>>> {
match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Document => {
if let XMLHttpRequestState::Done = self.ready_state.get() {
Ok(self.document_response(can_gc))
} else {
Ok(None)
}
},
_ => Err(Error::InvalidState),
}
}
}
pub type TrustedXHRAddress = Trusted<XMLHttpRequest>;
impl XMLHttpRequest {
fn change_ready_state(&self, rs: XMLHttpRequestState, can_gc: CanGc) {
assert_ne!(self.ready_state.get(), rs);
self.ready_state.set(rs);
if rs != XMLHttpRequestState::Unsent {
let event = Event::new(
&self.global(),
atom!("readystatechange"),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable,
can_gc,
);
event.fire(self.upcast(), can_gc);
}
}
fn process_headers_available(
&self,
gen_id: GenerationId,
metadata: Result<FetchMetadata, NetworkError>,
can_gc: CanGc,
) -> 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),
FilteredMetadata::OpaqueRedirect(_) => return Err(Error::Network),
},
},
Err(_) => {
self.process_partial_response(XHRProgress::Errored(gen_id, Error::Network), can_gc);
return Err(Error::Network);
},
};
metadata.final_url[..Position::AfterQuery].clone_into(&mut self.response_url.borrow_mut());
self.process_partial_response(
XHRProgress::HeadersReceived(
gen_id,
metadata.headers.map(Serde::into_inner),
metadata.status,
),
can_gc,
);
Ok(())
}
fn process_data_available(&self, gen_id: GenerationId, payload: Vec<u8>, can_gc: CanGc) {
self.process_partial_response(XHRProgress::Loading(gen_id, payload), can_gc);
}
fn process_response_complete(
&self,
gen_id: GenerationId,
status: Result<(), NetworkError>,
can_gc: CanGc,
) -> ErrorResult {
match status {
Ok(()) => {
self.process_partial_response(XHRProgress::Done(gen_id), can_gc);
Ok(())
},
Err(_) => {
self.process_partial_response(XHRProgress::Errored(gen_id, Error::Network), can_gc);
Err(Error::Network)
},
}
}
fn process_partial_response(&self, progress: XHRProgress, can_gc: CanGc) {
let msg_id = progress.generation_id();
macro_rules! return_if_fetch_was_terminated(
() => (
if msg_id != self.generation_id.get() {
return
}
);
);
return_if_fetch_was_terminated!();
if self.response_status.get().is_err() {
return;
}
match progress {
XHRProgress::HeadersReceived(_, headers, status) => {
assert!(self.ready_state.get() == XMLHttpRequestState::Opened);
self.upload_complete.set(true);
if !self.sync.get() && self.upload_listener.get() {
self.dispatch_upload_progress_event(atom!("progress"), Ok(None), can_gc);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(atom!("load"), Ok(None), can_gc);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(atom!("loadend"), Ok(None), can_gc);
return_if_fetch_was_terminated!();
}
if !status.is_error() {
*self.status.borrow_mut() = status.clone();
}
if let Some(h) = headers.as_ref() {
*self.response_headers.borrow_mut() = h.clone();
}
{
let len = headers.and_then(|h| h.typed_get::<ContentLength>());
let mut response = self.response.borrow_mut();
response.clear();
if let Some(len) = len {
let size = cmp::min(0b100_0000000000_0000000000, len.0 as usize);
response.reserve(size);
}
}
if !self.sync.get() {
self.change_ready_state(XMLHttpRequestState::HeadersReceived, can_gc);
}
},
XHRProgress::Loading(_, mut partial_response) => {
self.response.borrow_mut().append(&mut partial_response);
if !self.sync.get() {
if self.ready_state.get() == XMLHttpRequestState::HeadersReceived {
self.ready_state.set(XMLHttpRequestState::Loading);
}
let event = Event::new(
&self.global(),
atom!("readystatechange"),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable,
can_gc,
);
event.fire(self.upcast(), can_gc);
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(atom!("progress"), can_gc);
}
},
XHRProgress::Done(_) => {
assert!(
self.ready_state.get() == XMLHttpRequestState::HeadersReceived ||
self.ready_state.get() == XMLHttpRequestState::Loading ||
self.sync.get()
);
self.cancel_timeout();
self.canceller.borrow_mut().ignore();
self.send_flag.set(false);
self.change_ready_state(XMLHttpRequestState::Done, can_gc);
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(atom!("load"), can_gc);
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(atom!("loadend"), can_gc);
},
XHRProgress::Errored(_, e) => {
self.cancel_timeout();
self.canceller.borrow_mut().ignore();
self.discard_subsequent_responses();
self.send_flag.set(false);
self.change_ready_state(XMLHttpRequestState::Done, can_gc);
return_if_fetch_was_terminated!();
let errormsg = match e {
Error::Abort => "abort",
Error::Timeout => "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(Atom::from(errormsg), Err(()), can_gc);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(atom!("loadend"), Err(()), can_gc);
return_if_fetch_was_terminated!();
}
}
self.dispatch_response_progress_event(Atom::from(errormsg), can_gc);
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(atom!("loadend"), can_gc);
},
}
}
fn terminate_ongoing_fetch(&self) {
self.canceller.borrow_mut().cancel();
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,
upload: bool,
type_: Atom,
loaded: u64,
total: Option<u64>,
can_gc: CanGc,
) {
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(
&self.global(),
type_,
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
length_computable,
loaded,
total_length,
can_gc,
);
let target = if upload {
self.upload.upcast()
} else {
self.upcast()
};
progressevent.upcast::<Event>().fire(target, can_gc);
}
fn dispatch_upload_progress_event(
&self,
type_: Atom,
partial_load: Result<Option<u64>, ()>,
can_gc: CanGc,
) {
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(true, type_, loaded, total, can_gc);
}
fn dispatch_response_progress_event(&self, type_: Atom, can_gc: CanGc) {
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(false, type_, len, total, can_gc);
}
fn set_timeout(&self, duration: Duration) {
let callback = OneshotTimerCallback::XhrTimeout(XHRTimeoutCallback {
xhr: Trusted::new(self),
generation_id: self.generation_id.get(),
});
*self.timeout_cancel.borrow_mut() =
Some(self.global().schedule_callback(callback, duration));
}
fn cancel_timeout(&self) {
if let Some(handle) = self.timeout_cancel.borrow_mut().take() {
self.global().unschedule_callback(handle);
}
}
fn text_response(&self) -> String {
let charset = self.final_charset().unwrap_or(UTF_8);
let response = self.response.borrow();
let (text, _, _) = charset.decode(&response);
text.into_owned()
}
fn blob_response(&self, can_gc: CanGc) -> DomRoot<Blob> {
if let Some(response) = self.response_blob.get() {
return response;
}
let mime = self
.final_mime_type()
.as_ref()
.map(|m| normalize_type_string(m.as_ref()))
.unwrap_or("".to_owned());
let bytes = self.response.borrow().to_vec();
let blob = Blob::new(
&self.global(),
BlobImpl::new_from_bytes(bytes, mime),
can_gc,
);
self.response_blob.set(Some(&blob));
blob
}
fn arraybuffer_response(&self, cx: JSContext) -> Option<ArrayBuffer> {
if !self.response_arraybuffer.is_initialized() {
let bytes = self.response.borrow();
self.response_arraybuffer.set_data(cx, &bytes).ok()?;
}
self.response_arraybuffer.get_buffer().ok()
}
fn document_response(&self, can_gc: CanGc) -> Option<DomRoot<Document>> {
let response = self.response_xml.get();
if response.is_some() {
return response;
}
if self.response_status.get().is_err() {
return None;
}
let mime_type = self.final_mime_type();
let charset = self.final_charset().unwrap_or(UTF_8);
let temp_doc: DomRoot<Document>;
match mime_type {
Some(ref mime) if mime.type_() == mime::TEXT && mime.subtype() == mime::HTML => {
if self.response_type.get() == XMLHttpRequestResponseType::_empty {
return None;
} else {
temp_doc = self.document_text_html(can_gc);
}
},
None => {
temp_doc = self.handle_xml(can_gc);
let has_no_child_nodes = temp_doc.upcast::<Node>().children().next().is_none();
if has_no_child_nodes {
return None;
}
},
Some(ref mime)
if (mime.type_() == mime::TEXT && mime.subtype() == mime::XML) ||
(mime.type_() == mime::APPLICATION && mime.subtype() == mime::XML) ||
mime.suffix() == Some(mime::XML) =>
{
temp_doc = self.handle_xml(can_gc);
let has_no_child_nodes = temp_doc.upcast::<Node>().children().next().is_none();
if has_no_child_nodes {
return None;
}
},
_ => {
return None;
},
}
temp_doc.set_encoding(charset);
self.response_xml.set(Some(&temp_doc));
self.response_xml.get()
}
#[allow(unsafe_code)]
fn json_response(&self, cx: JSContext, mut rval: MutableHandleValue) {
let response_json = self.response_json.get();
if !response_json.is_null_or_undefined() {
return rval.set(response_json);
}
let bytes = self.response.borrow();
if bytes.len() == 0 {
return rval.set(NullValue());
}
fn decode_to_utf16_with_bom_removal(bytes: &[u8], encoding: &'static Encoding) -> Vec<u16> {
let mut decoder = encoding.new_decoder_with_bom_removal();
let capacity = decoder
.max_utf16_buffer_length(bytes.len())
.expect("Overflow");
let mut utf16 = Vec::with_capacity(capacity);
let extra = unsafe { slice::from_raw_parts_mut(utf16.as_mut_ptr(), capacity) };
let last = true;
let (_, read, written, _) = decoder.decode_to_utf16(bytes, extra, last);
assert_eq!(read, bytes.len());
unsafe { utf16.set_len(written) }
utf16
}
let json_text = decode_to_utf16_with_bom_removal(&bytes, UTF_8);
unsafe {
if !JS_ParseJSON(*cx, json_text.as_ptr(), json_text.len() as u32, rval) {
JS_ClearPendingException(*cx);
return rval.set(NullValue());
}
}
self.response_json.set(rval.get());
}
fn document_text_html(&self, can_gc: CanGc) -> 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(IsHTMLDocument::HTMLDocument, can_gc);
ServoParser::parse_html_document(
&document,
Some(DOMString::from(decoded)),
wr.get_url(),
can_gc,
);
document
}
fn handle_xml(&self, can_gc: CanGc) -> 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(IsHTMLDocument::NonHTMLDocument, can_gc);
ServoParser::parse_xml_document(
&document,
Some(DOMString::from(decoded)),
wr.get_url(),
can_gc,
);
document
}
fn new_doc(&self, is_html_document: IsHTMLDocument, can_gc: CanGc) -> 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 = match base.join(&self.ResponseURL().0) {
Ok(parsed) => Some(parsed),
Err(_) => None, };
let content_type = self.final_mime_type();
Document::new(
win,
HasBrowsingContext::No,
parsed_url,
doc.origin().clone(),
is_html_document,
content_type,
None,
DocumentActivity::Inactive,
DocumentSource::FromParser,
docloader,
None,
None,
Default::default(),
can_gc,
)
}
fn filter_response_headers(&self) -> HeaderMap {
let mut headers = self.response_headers.borrow().clone();
headers.remove(header::SET_COOKIE);
headers.remove(HeaderName::from_static("set-cookie2"));
headers
}
fn discard_subsequent_responses(&self) {
self.response_status.set(Err(()));
}
fn fetch(&self, init: RequestBuilder, global: &GlobalScope) -> ErrorResult {
let xhr = Trusted::new(self);
let context = Arc::new(Mutex::new(XHRContext {
xhr,
gen_id: self.generation_id.get(),
sync_status: DomRefCell::new(None),
resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
url: init.url.clone(),
}));
let (task_source, script_port) = if self.sync.get() {
let (tx, rx) = global.new_script_pair();
(NetworkingTaskSource(tx, global.pipeline_id()), Some(rx))
} else {
(global.networking_task_source(), None)
};
let cancel_receiver = self.canceller.borrow_mut().initialize();
XMLHttpRequest::initiate_async_xhr(
context.clone(),
task_source,
global,
init,
cancel_receiver,
);
if let Some(script_port) = script_port {
loop {
if !global.process_event(script_port.recv().unwrap()) {
return Err(Error::Abort);
}
let context = context.lock().unwrap();
let sync_status = context.sync_status.borrow();
if let Some(ref status) = *sync_status {
return status.clone();
}
}
}
Ok(())
}
fn final_charset(&self) -> Option<&'static Encoding> {
let response_charset = self
.response_mime_type()
.and_then(|mime| mime.get_param(mime::CHARSET).map(|c| c.to_string()));
let override_charset = self
.override_mime_type
.borrow()
.as_ref()
.and_then(|mime| mime.get_param(mime::CHARSET).map(|c| c.to_string()));
override_charset
.or(response_charset)
.and_then(|charset| Encoding::for_label(charset.as_bytes()))
}
fn response_mime_type(&self) -> Option<Mime> {
return extract_mime_type(&self.response_headers.borrow())
.and_then(|mime_as_bytes| {
String::from_utf8(mime_as_bytes)
.unwrap_or_default()
.parse()
.ok()
})
.or(Some(mime::TEXT_XML));
}
fn final_mime_type(&self) -> Option<Mime> {
if self.override_mime_type.borrow().is_some() {
self.override_mime_type.borrow().clone()
} else {
self.response_mime_type()
}
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct XHRTimeoutCallback {
#[ignore_malloc_size_of = "Because it is non-owning"]
xhr: Trusted<XMLHttpRequest>,
generation_id: GenerationId,
}
impl XHRTimeoutCallback {
pub fn invoke(self, can_gc: CanGc) {
let xhr = self.xhr.root();
if xhr.ready_state.get() != XMLHttpRequestState::Done {
xhr.process_partial_response(
XHRProgress::Errored(self.generation_id, Error::Timeout),
can_gc,
);
}
}
}
fn serialize_document(doc: &Document) -> Fallible<DOMString> {
let mut writer = vec![];
match serialize(&mut writer, &doc.upcast::<Node>(), SerializeOpts::default()) {
Ok(_) => Ok(DOMString::from(String::from_utf8(writer).unwrap())),
Err(_) => Err(Error::InvalidState),
}
}
pub fn is_field_value(slice: &[u8]) -> bool {
#[derive(PartialEq)]
#[allow(clippy::upper_case_acronyms)]
enum PreviousCharacter {
Other,
CR,
LF,
SPHT, }
let mut prev = PreviousCharacter::Other; slice.iter().all(|&x| {
match x {
13 => {
if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT {
prev = PreviousCharacter::CR;
true
} else {
false
}
},
10 => {
if prev == PreviousCharacter::CR {
prev = PreviousCharacter::LF;
true
} else {
false
}
},
32 => {
if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT {
prev = PreviousCharacter::SPHT;
true
} else if prev == PreviousCharacter::Other {
true
} else {
false
}
},
9 => {
if prev == PreviousCharacter::LF || prev == PreviousCharacter::SPHT {
prev = PreviousCharacter::SPHT;
true
} else {
false
}
},
0..=31 | 127 => false, x if x > 127 => false, _ if prev == PreviousCharacter::Other || prev == PreviousCharacter::SPHT => {
prev = PreviousCharacter::Other;
true
},
_ => false, }
})
}