Remove all internal mutability from Request

This commit is contained in:
Anthony Ramine 2017-04-01 00:31:00 +02:00
parent f42a63baea
commit cb2eb81208
11 changed files with 362 additions and 376 deletions

View file

@ -66,7 +66,7 @@ impl CorsCacheEntry {
}
fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool {
cors_cache.origin == *cors_req.origin.borrow() &&
cors_cache.origin == cors_req.origin &&
cors_cache.url == cors_req.current_url() &&
(cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include)
}
@ -97,7 +97,7 @@ impl CorsCache {
pub fn clear(&mut self, request: &Request) {
let CorsCache(buf) = self.clone();
let new_buf: Vec<CorsCacheEntry> =
buf.into_iter().filter(|e| e.origin == *request.origin.borrow() &&
buf.into_iter().filter(|e| e.origin == request.origin &&
request.current_url() == e.url).collect();
*self = CorsCache(new_buf);
}
@ -127,7 +127,7 @@ impl CorsCache {
match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.borrow().clone(), request.current_url(), new_max_age,
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::HeaderData(header_name.to_owned())));
false
@ -149,7 +149,7 @@ impl CorsCache {
match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) {
Some(_) => true,
None => {
self.insert(CorsCacheEntry::new(request.origin.borrow().clone(), request.current_url(), new_max_age,
self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age,
request.credentials_mode == CredentialsMode::Include,
HeaderOrMethod::MethodData(method)));
false

View file

@ -48,31 +48,31 @@ pub struct FetchContext {
pub type DoneChannel = Option<(Sender<Data>, Receiver<Data>)>;
/// [Fetch](https://fetch.spec.whatwg.org#concept-fetch)
pub fn fetch(request: &Request,
pub fn fetch(request: &mut Request,
target: Target,
context: &FetchContext) {
fetch_with_cors_cache(request, &mut CorsCache::new(), target, context);
}
pub fn fetch_with_cors_cache(request: &Request,
pub fn fetch_with_cors_cache(request: &mut Request,
cache: &mut CorsCache,
target: Target,
context: &FetchContext) {
// Step 1
if request.window.get() == Window::Client {
if request.window == Window::Client {
// TODO: Set window to request's client object if client is a Window object
} else {
request.window.set(Window::NoWindow);
request.window = Window::NoWindow;
}
// Step 2
if *request.origin.borrow() == Origin::Client {
if request.origin == Origin::Client {
// TODO: set request's origin to request's client's origin
unimplemented!()
}
// Step 3
if !request.headers.borrow().has::<Accept>() {
if !request.headers.has::<Accept>() {
let value = match request.type_ {
// Substep 2
_ if request.is_navigation_request() =>
@ -101,11 +101,11 @@ pub fn fetch_with_cors_cache(request: &Request,
};
// Substep 4
request.headers.borrow_mut().set(Accept(value));
request.headers.set(Accept(value));
}
// Step 4
set_default_accept_language(&mut request.headers.borrow_mut());
set_default_accept_language(&mut request.headers);
// Step 5
// TODO: Figure out what a Priority object is
@ -120,7 +120,7 @@ pub fn fetch_with_cors_cache(request: &Request,
}
/// [Main fetch](https://fetch.spec.whatwg.org/#concept-main-fetch)
pub fn main_fetch(request: &Request,
pub fn main_fetch(request: &mut Request,
cache: &mut CorsCache,
cors_flag: bool,
recursive_flag: bool,
@ -158,30 +158,30 @@ pub fn main_fetch(request: &Request,
// currently the clients themselves set referrer policy in RequestInit
// Step 7
let referrer_policy = request.referrer_policy.get().unwrap_or(ReferrerPolicy::NoReferrerWhenDowngrade);
request.referrer_policy.set(Some(referrer_policy));
let referrer_policy = request.referrer_policy.unwrap_or(ReferrerPolicy::NoReferrerWhenDowngrade);
request.referrer_policy = Some(referrer_policy);
// Step 8
{
let mut referrer = request.referrer.borrow_mut();
let referrer_url = match mem::replace(&mut *referrer, Referrer::NoReferrer) {
let referrer_url = match mem::replace(&mut request.referrer, Referrer::NoReferrer) {
Referrer::NoReferrer => None,
Referrer::Client => {
// FIXME(#14507): We should never get this value here; it should
// already have been handled in the script thread.
request.headers.borrow_mut().remove::<RefererHeader>();
request.headers.remove::<RefererHeader>();
None
},
Referrer::ReferrerUrl(url) => {
request.headers.borrow_mut().remove::<RefererHeader>();
determine_request_referrer(&mut *request.headers.borrow_mut(),
request.headers.remove::<RefererHeader>();
let current_url = request.current_url().clone();
determine_request_referrer(&mut request.headers,
referrer_policy,
url,
request.current_url().clone())
current_url)
}
};
if let Some(referrer_url) = referrer_url {
*referrer = Referrer::ReferrerUrl(referrer_url);
request.referrer = Referrer::ReferrerUrl(referrer_url);
}
}
@ -192,7 +192,7 @@ pub fn main_fetch(request: &Request,
.read()
.unwrap()
.is_host_secure(request.current_url().domain().unwrap()) {
request.url_list.borrow_mut().last_mut().unwrap().as_mut_url().set_scheme("https").unwrap();
request.url_list.last_mut().unwrap().as_mut_url().set_scheme("https").unwrap();
}
}
@ -204,7 +204,7 @@ pub fn main_fetch(request: &Request,
Some(response) => response,
None => {
let current_url = request.current_url();
let same_origin = if let Origin::Origin(ref origin) = *request.origin.borrow() {
let same_origin = if let Origin::Origin(ref origin) = request.origin {
*origin == current_url.origin()
} else {
false
@ -221,7 +221,7 @@ pub fn main_fetch(request: &Request,
Response::network_error(NetworkError::Internal("Cross-origin response".into()))
} else if request.mode == RequestMode::NoCors {
request.response_tainting.set(ResponseTainting::Opaque);
request.response_tainting = ResponseTainting::Opaque;
basic_fetch(request, cache, target, done_chan, context)
} else if !matches!(current_url.scheme(), "http" | "https") {
@ -229,9 +229,9 @@ pub fn main_fetch(request: &Request,
} else if request.use_cors_preflight ||
(request.unsafe_request &&
(!is_simple_method(&request.method.borrow()) ||
request.headers.borrow().iter().any(|h| !is_simple_header(&h)))) {
request.response_tainting.set(ResponseTainting::CorsTainting);
(!is_simple_method(&request.method) ||
request.headers.iter().any(|h| !is_simple_header(&h)))) {
request.response_tainting = ResponseTainting::CorsTainting;
let response = http_fetch(request, cache, true, true, false,
target, done_chan, context);
if response.is_network_error() {
@ -240,7 +240,7 @@ pub fn main_fetch(request: &Request,
response
} else {
request.response_tainting.set(ResponseTainting::CorsTainting);
request.response_tainting = ResponseTainting::CorsTainting;
http_fetch(request, cache, true, false, false, target, done_chan, context)
}
}
@ -254,7 +254,7 @@ pub fn main_fetch(request: &Request,
// Step 13
// no need to check if response is a network error, since the type would not be `Default`
let response = if response.response_type == ResponseType::Default {
let response_type = match request.response_tainting.get() {
let response_type = match request.response_tainting {
ResponseTainting::Basic => ResponseType::Basic,
ResponseTainting::CorsTainting => ResponseType::Cors,
ResponseTainting::Opaque => ResponseType::Opaque,
@ -276,7 +276,7 @@ pub fn main_fetch(request: &Request,
// Step 15
if internal_response.url_list.borrow().is_empty() {
*internal_response.url_list.borrow_mut() = request.url_list.borrow().clone();
*internal_response.url_list.borrow_mut() = request.url_list.clone();
}
// Step 16
@ -295,7 +295,7 @@ pub fn main_fetch(request: &Request,
// We check `internal_response` since we did not mutate `response` in the previous step.
let not_network_error = !response.is_network_error() && !internal_response.is_network_error();
if not_network_error && (is_null_body_status(&internal_response.status) ||
match *request.method.borrow() {
match request.method {
Method::Head | Method::Connect => true,
_ => false }) {
// when Fetch is used only asynchronously, we will need to make sure
@ -316,13 +316,13 @@ pub fn main_fetch(request: &Request,
// Step 18
let mut response_loaded = false;
let response = if !response.is_network_error() && *request.integrity_metadata.borrow() != "" {
let response = if !response.is_network_error() && request.integrity_metadata != "" {
// Substep 1
wait_for_response(&response, target, done_chan);
response_loaded = true;
// Substep 2
let ref integrity_metadata = *request.integrity_metadata.borrow();
let ref integrity_metadata = &request.integrity_metadata;
if response.termination_reason.is_none() &&
!is_response_integrity_valid(integrity_metadata, &response) {
Response::network_error(NetworkError::Internal("Subresource integrity validation failed".into()))
@ -347,7 +347,7 @@ pub fn main_fetch(request: &Request,
}
// Step 20
if request.body.borrow().is_some() && matches!(request.current_url().scheme(), "http" | "https") {
if request.body.is_some() && matches!(request.current_url().scheme(), "http" | "https") {
// XXXManishearth: We actually should be calling process_request
// in http_network_fetch. However, we can't yet follow the request
// upload progress, so I'm keeping it here for now and pretending
@ -396,7 +396,7 @@ fn wait_for_response(response: &Response, target: Target, done_chan: &mut DoneCh
}
/// [Basic fetch](https://fetch.spec.whatwg.org#basic-fetch)
fn basic_fetch(request: &Request,
fn basic_fetch(request: &mut Request,
cache: &mut CorsCache,
target: Target,
done_chan: &mut DoneChannel,
@ -417,7 +417,7 @@ fn basic_fetch(request: &Request,
},
"data" => {
if *request.method.borrow() == Method::Get {
if request.method == Method::Get {
match decode(&url) {
Ok((mime, bytes)) => {
let mut response = Response::new(url);
@ -433,7 +433,7 @@ fn basic_fetch(request: &Request,
},
"file" => {
if *request.method.borrow() == Method::Get {
if request.method == Method::Get {
match url.to_file_path() {
Ok(file_path) => {
match File::open(file_path.clone()) {
@ -460,7 +460,7 @@ fn basic_fetch(request: &Request,
"blob" => {
println!("Loading blob {}", url.as_str());
// Step 2.
if *request.method.borrow() != Method::Get {
if request.method != Method::Get {
return Response::network_error(NetworkError::Internal("Unexpected method for blob".into()));
}

View file

@ -476,7 +476,7 @@ fn obtain_response(request_factory: &NetworkHttpRequestFactory,
}
/// [HTTP fetch](https://fetch.spec.whatwg.org#http-fetch)
pub fn http_fetch(request: &Request,
pub fn http_fetch(request: &mut Request,
cache: &mut CorsCache,
cors_flag: bool,
cors_preflight_flag: bool,
@ -494,7 +494,7 @@ pub fn http_fetch(request: &Request,
// nothing to do, since actual_response is a function on response
// Step 3
if !request.skip_service_worker.get() && !request.is_service_worker_global_scope {
if !request.skip_service_worker && !request.is_service_worker_global_scope {
// Substep 1
// TODO (handle fetch unimplemented)
@ -506,9 +506,9 @@ pub fn http_fetch(request: &Request,
if (res.response_type == ResponseType::Opaque &&
request.mode != RequestMode::NoCors) ||
(res.response_type == ResponseType::OpaqueRedirect &&
request.redirect_mode.get() != RedirectMode::Manual) ||
request.redirect_mode != RedirectMode::Manual) ||
(res.url_list.borrow().len() > 1 &&
request.redirect_mode.get() != RedirectMode::Follow) ||
request.redirect_mode != RedirectMode::Follow) ||
res.is_network_error() {
return Response::network_error(NetworkError::Internal("Request failed".into()));
}
@ -521,7 +521,7 @@ pub fn http_fetch(request: &Request,
// Step 4
let credentials = match request.credentials_mode {
CredentialsMode::Include => true,
CredentialsMode::CredentialsSameOrigin if request.response_tainting.get() == ResponseTainting::Basic
CredentialsMode::CredentialsSameOrigin if request.response_tainting == ResponseTainting::Basic
=> true,
_ => false
};
@ -531,11 +531,11 @@ pub fn http_fetch(request: &Request,
// Substep 1
if cors_preflight_flag {
let method_cache_match = cache.match_method(&*request,
request.method.borrow().clone());
request.method.clone());
let method_mismatch = !method_cache_match && (!is_simple_method(&request.method.borrow()) ||
let method_mismatch = !method_cache_match && (!is_simple_method(&request.method) ||
request.use_cors_preflight);
let header_mismatch = request.headers.borrow().iter().any(|view|
let header_mismatch = request.headers.iter().any(|view|
!cache.match_header(&*request, view.name()) && !is_simple_header(&view)
);
@ -550,7 +550,7 @@ pub fn http_fetch(request: &Request,
}
// Substep 2
request.skip_service_worker.set(true);
request.skip_service_worker = true;
// Substep 3
let fetch_result = http_network_or_cache_fetch(request, authentication_fetch_flag,
@ -572,7 +572,7 @@ pub fn http_fetch(request: &Request,
match response.actual_response().status {
// Code 301, 302, 303, 307, 308
status if status.map_or(false, is_redirect_status) => {
response = match request.redirect_mode.get() {
response = match request.redirect_mode {
RedirectMode::Error => Response::network_error(NetworkError::Internal("Redirect mode error".into())),
RedirectMode::Manual => {
response.to_filtered(ResponseType::OpaqueRedirect)
@ -648,7 +648,7 @@ pub fn http_fetch(request: &Request,
}
/// [HTTP redirect fetch](https://fetch.spec.whatwg.org#http-redirect-fetch)
fn http_redirect_fetch(request: &Request,
fn http_redirect_fetch(request: &mut Request,
cache: &mut CorsCache,
response: Response,
cors_flag: bool,
@ -683,12 +683,12 @@ fn http_redirect_fetch(request: &Request,
}
// Step 5
if request.redirect_count.get() >= 20 {
if request.redirect_count >= 20 {
return Response::network_error(NetworkError::Internal("Too many redirects".into()));
}
// Step 6
request.redirect_count.set(request.redirect_count.get() + 1);
request.redirect_count += 1;
// Step 7
let same_origin = location_url.origin()== request.current_url().origin();
@ -705,20 +705,20 @@ fn http_redirect_fetch(request: &Request,
// Step 9
if cors_flag && !same_origin {
*request.origin.borrow_mut() = Origin::Origin(ImmutableOrigin::new_opaque());
request.origin = Origin::Origin(ImmutableOrigin::new_opaque());
}
// Step 10
let status_code = response.actual_response().status.unwrap();
if ((status_code == StatusCode::MovedPermanently || status_code == StatusCode::Found) &&
*request.method.borrow() == Method::Post) ||
request.method == Method::Post) ||
status_code == StatusCode::SeeOther {
*request.method.borrow_mut() = Method::Get;
*request.body.borrow_mut() = None;
request.method = Method::Get;
request.body = None;
}
// Step 11
request.url_list.borrow_mut().push(location_url);
request.url_list.push(location_url);
// Step 12
// TODO implement referrer policy
@ -737,7 +737,7 @@ fn try_immutable_origin_to_hyper_origin(url_origin: &ImmutableOrigin) -> Option<
}
/// [HTTP network or cache fetch](https://fetch.spec.whatwg.org#http-network-or-cache-fetch)
fn http_network_or_cache_fetch(request: &Request,
fn http_network_or_cache_fetch(request: &mut Request,
authentication_fetch_flag: bool,
cors_flag: bool,
done_chan: &mut DoneChannel,
@ -747,28 +747,28 @@ fn http_network_or_cache_fetch(request: &Request,
let request_has_no_window = true;
// Step 2
let http_request;
let mut http_request;
let http_request = if request_has_no_window &&
request.redirect_mode.get() == RedirectMode::Error {
request.redirect_mode == RedirectMode::Error {
request
} else {
// Step 3
// TODO Implement body source
http_request = request.clone();
&http_request
&mut http_request
};
// Step 4
let credentials_flag = match http_request.credentials_mode {
CredentialsMode::Include => true,
CredentialsMode::CredentialsSameOrigin if http_request.response_tainting.get() == ResponseTainting::Basic
CredentialsMode::CredentialsSameOrigin if http_request.response_tainting == ResponseTainting::Basic
=> true,
_ => false
};
let content_length_value = match *http_request.body.borrow() {
let content_length_value = match http_request.body {
None =>
match *http_request.method.borrow() {
match http_request.method {
// Step 6
Method::Post | Method::Put =>
Some(0),
@ -781,16 +781,16 @@ fn http_network_or_cache_fetch(request: &Request,
// Step 8
if let Some(content_length_value) = content_length_value {
http_request.headers.borrow_mut().set(ContentLength(content_length_value));
http_request.headers.set(ContentLength(content_length_value));
}
// Step 9 TODO: needs request's client object
// Step 10
match *http_request.referrer.borrow() {
match http_request.referrer {
Referrer::NoReferrer => (),
Referrer::ReferrerUrl(ref http_request_referrer) =>
http_request.headers.borrow_mut().set(Referer(http_request_referrer.to_string())),
http_request.headers.set(Referer(http_request_referrer.to_string())),
Referrer::Client =>
// it should be impossible for referrer to be anything else during fetching
// https://fetch.spec.whatwg.org/#concept-request-referrer
@ -798,45 +798,45 @@ fn http_network_or_cache_fetch(request: &Request,
};
// Step 11
if !http_request.omit_origin_header.get() {
let method = http_request.method.borrow();
if !http_request.omit_origin_header {
let method = &http_request.method;
if cors_flag || (*method != Method::Get && *method != Method::Head) {
debug_assert!(*http_request.origin.borrow() != Origin::Client);
if let Origin::Origin(ref url_origin) = *http_request.origin.borrow() {
debug_assert!(http_request.origin != Origin::Client);
if let Origin::Origin(ref url_origin) = http_request.origin {
if let Some(hyper_origin) = try_immutable_origin_to_hyper_origin(url_origin) {
http_request.headers.borrow_mut().set(hyper_origin)
http_request.headers.set(hyper_origin)
}
}
}
}
// Step 12
if !http_request.headers.borrow().has::<UserAgent>() {
if !http_request.headers.has::<UserAgent>() {
let user_agent = context.user_agent.clone().into_owned();
http_request.headers.borrow_mut().set(UserAgent(user_agent));
http_request.headers.set(UserAgent(user_agent));
}
match http_request.cache_mode.get() {
match http_request.cache_mode {
// Step 13
CacheMode::Default if is_no_store_cache(&http_request.headers.borrow()) => {
http_request.cache_mode.set(CacheMode::NoStore);
CacheMode::Default if is_no_store_cache(&http_request.headers) => {
http_request.cache_mode = CacheMode::NoStore;
},
// Step 14
CacheMode::NoCache if !http_request.headers.borrow().has::<CacheControl>() => {
http_request.headers.borrow_mut().set(CacheControl(vec![CacheDirective::MaxAge(0)]));
CacheMode::NoCache if !http_request.headers.has::<CacheControl>() => {
http_request.headers.set(CacheControl(vec![CacheDirective::MaxAge(0)]));
},
// Step 15
CacheMode::Reload | CacheMode::NoStore => {
// Substep 1
if !http_request.headers.borrow().has::<Pragma>() {
http_request.headers.borrow_mut().set(Pragma::NoCache);
if !http_request.headers.has::<Pragma>() {
http_request.headers.set(Pragma::NoCache);
}
// Substep 2
if !http_request.headers.borrow().has::<CacheControl>() {
http_request.headers.borrow_mut().set(CacheControl(vec![CacheDirective::NoCache]));
if !http_request.headers.has::<CacheControl>() {
http_request.headers.set(CacheControl(vec![CacheDirective::NoCache]));
}
},
@ -845,17 +845,14 @@ fn http_network_or_cache_fetch(request: &Request,
// Step 16
let current_url = http_request.current_url();
{
let headers = &mut *http_request.headers.borrow_mut();
let host = Host {
hostname: current_url.host_str().unwrap().to_owned(),
port: current_url.port()
};
headers.set(host);
// unlike http_loader, we should not set the accept header
// here, according to the fetch spec
set_default_accept_encoding(headers);
}
let host = Host {
hostname: current_url.host_str().unwrap().to_owned(),
port: current_url.port()
};
http_request.headers.set(host);
// unlike http_loader, we should not set the accept header
// here, according to the fetch spec
set_default_accept_encoding(&mut http_request.headers);
// Step 17
// TODO some of this step can't be implemented yet
@ -864,10 +861,10 @@ fn http_network_or_cache_fetch(request: &Request,
// TODO http://mxr.mozilla.org/servo/source/components/net/http_loader.rs#504
// XXXManishearth http_loader has block_cookies: support content blocking here too
set_request_cookies(&current_url,
&mut *http_request.headers.borrow_mut(),
&mut http_request.headers,
&context.state.cookie_jar);
// Substep 2
if !http_request.headers.borrow().has::<Authorization<String>>() {
if !http_request.headers.has::<Authorization<String>>() {
// Substep 3
let mut authorization_value = None;
@ -890,7 +887,7 @@ fn http_network_or_cache_fetch(request: &Request,
// Substep 6
if let Some(basic) = authorization_value {
http_request.headers.borrow_mut().set(Authorization(basic));
http_request.headers.set(Authorization(basic));
}
}
}
@ -907,8 +904,8 @@ fn http_network_or_cache_fetch(request: &Request,
// Step 21
// TODO have a HTTP cache to check for a completed response
let complete_http_response_from_cache: Option<Response> = None;
if http_request.cache_mode.get() != CacheMode::NoStore &&
http_request.cache_mode.get() != CacheMode::Reload &&
if http_request.cache_mode != CacheMode::NoStore &&
http_request.cache_mode != CacheMode::Reload &&
complete_http_response_from_cache.is_some() {
// TODO Substep 1 and 2. Select a response from HTTP cache.
@ -918,8 +915,8 @@ fn http_network_or_cache_fetch(request: &Request,
};
// Substep 4
if http_request.cache_mode.get() == CacheMode::ForceCache ||
http_request.cache_mode.get() == CacheMode::OnlyIfCached {
if http_request.cache_mode == CacheMode::ForceCache ||
http_request.cache_mode == CacheMode::OnlyIfCached {
// TODO pull response from HTTP cache
// response = http_request
}
@ -939,7 +936,7 @@ fn http_network_or_cache_fetch(request: &Request,
// Step 22
if response.is_none() {
// Substep 1
if http_request.cache_mode.get() == CacheMode::OnlyIfCached {
if http_request.cache_mode == CacheMode::OnlyIfCached {
return Response::network_error(
NetworkError::Internal("Couldn't find response in cache".into()))
}
@ -950,7 +947,7 @@ fn http_network_or_cache_fetch(request: &Request,
// Substep 3
Some((200...303, _)) |
Some((305...399, _)) => {
if !http_request.method.borrow().safe() {
if !http_request.method.safe() {
// TODO Invalidate HTTP cache response
}
},
@ -984,7 +981,7 @@ fn http_network_or_cache_fetch(request: &Request,
// TODO: Spec says requires testing on multiple WWW-Authenticate headers
// Substep 2
if http_request.body.borrow().is_some() {
if http_request.body.is_some() {
// TODO Implement body source
}
@ -1065,13 +1062,13 @@ fn http_network_fetch(request: &Request,
// do not. Once we support other kinds of fetches we'll need to be more fine grained here
// since things like image fetches are classified differently by devtools
let is_xhr = request.destination == Destination::None;
let wrapped_response = obtain_response(&factory, &url, &request.method.borrow(),
&request.headers.borrow(),
&request.body.borrow(), &request.method.borrow(),
&request.pipeline_id.get(), request.redirect_count.get() + 1,
let wrapped_response = obtain_response(&factory, &url, &request.method,
&request.headers,
&request.body, &request.method,
&request.pipeline_id, request.redirect_count + 1,
request_id.as_ref().map(Deref::deref), is_xhr);
let pipeline_id = request.pipeline_id.get();
let pipeline_id = request.pipeline_id;
let (res, msg) = match wrapped_response {
Ok(wrapped_response) => wrapped_response,
Err(error) => return Response::network_error(error),
@ -1082,7 +1079,7 @@ fn http_network_fetch(request: &Request,
response.raw_status = Some((res.response.status_raw().0,
res.response.status_raw().1.as_bytes().to_vec()));
response.headers = res.response.headers.clone();
response.referrer = request.referrer.borrow().to_url().cloned();
response.referrer = request.referrer.to_url().cloned();
let res_body = response.body.clone();
@ -1178,7 +1175,7 @@ fn http_network_fetch(request: &Request,
// TODO this step isn't possible yet (CSP)
// Step 12
if response.is_network_error() && request.cache_mode.get() == CacheMode::NoStore {
if response.is_network_error() && request.cache_mode == CacheMode::NoStore {
// TODO update response in the HTTP cache for request
}
@ -1210,32 +1207,33 @@ fn cors_preflight_fetch(request: &Request,
context: &FetchContext)
-> Response {
// Step 1
let mut preflight = Request::new(request.current_url(), Some(request.origin.borrow().clone()),
request.is_service_worker_global_scope, request.pipeline_id.get());
*preflight.method.borrow_mut() = Method::Options;
let mut preflight = Request::new(request.current_url(), Some(request.origin.clone()),
request.is_service_worker_global_scope, request.pipeline_id);
preflight.method = Method::Options;
preflight.initiator = request.initiator.clone();
preflight.type_ = request.type_.clone();
preflight.destination = request.destination.clone();
*preflight.referrer.borrow_mut() = request.referrer.borrow().clone();
preflight.referrer_policy.set(request.referrer_policy.get());
preflight.referrer = request.referrer.clone();
preflight.referrer_policy = request.referrer_policy;
// Step 2
preflight.headers.borrow_mut().set::<AccessControlRequestMethod>(
AccessControlRequestMethod(request.method.borrow().clone()));
preflight.headers.set::<AccessControlRequestMethod>(
AccessControlRequestMethod(request.method.clone()));
// Step 3, 4
let mut value = request.headers.borrow().iter()
.filter(|view| !is_simple_header(view))
.map(|view| UniCase(view.name().to_owned()))
.collect::<Vec<UniCase<String>>>();
let mut value = request.headers
.iter()
.filter(|view| !is_simple_header(view))
.map(|view| UniCase(view.name().to_owned()))
.collect::<Vec<UniCase<String>>>();
value.sort();
// Step 5
preflight.headers.borrow_mut().set::<AccessControlRequestHeaders>(
preflight.headers.set::<AccessControlRequestHeaders>(
AccessControlRequestHeaders(value));
// Step 6
let response = http_network_or_cache_fetch(&preflight, false, false, &mut None, context);
let response = http_network_or_cache_fetch(&mut preflight, false, false, &mut None, context);
// Step 7
if cors_check(&request, &response).is_ok() &&
@ -1264,23 +1262,21 @@ fn cors_preflight_fetch(request: &Request,
// Substep 4
if methods.is_empty() && request.use_cors_preflight {
methods = vec![request.method.borrow().clone()];
methods = vec![request.method.clone()];
}
// Substep 5
debug!("CORS check: Allowed methods: {:?}, current method: {:?}",
methods, request.method.borrow());
if methods.iter().all(|method| *method != *request.method.borrow()) &&
!is_simple_method(&*request.method.borrow()) {
methods, request.method);
if methods.iter().all(|method| *method != request.method) &&
!is_simple_method(&request.method) {
return Response::network_error(NetworkError::Internal("CORS method check failed".into()));
}
// Substep 6
debug!("CORS check: Allowed headers: {:?}, current headers: {:?}",
header_names, request.headers.borrow());
debug!("CORS check: Allowed headers: {:?}, current headers: {:?}", header_names, request.headers);
let set: HashSet<&UniCase<String>> = HashSet::from_iter(header_names.iter());
if request.headers.borrow().iter().any(|ref hv| !set.contains(&UniCase(hv.name().to_owned())) &&
!is_simple_header(hv)) {
if request.headers.iter().any(|ref hv| !set.contains(&UniCase(hv.name().to_owned())) && !is_simple_header(hv)) {
return Response::network_error(NetworkError::Internal("CORS headers check failed".into()));
}
@ -1328,7 +1324,7 @@ fn cors_check(request: &Request, response: &Response) -> Result<(), ()> {
_ => return Err(())
};
match *request.origin.borrow() {
match request.origin {
Origin::Origin(ref o) if o.ascii_serialization() == origin => {},
_ => return Err(())
}

View file

@ -338,7 +338,7 @@ impl CoreResourceManager {
let filemanager = self.filemanager.clone();
thread::Builder::new().name(format!("fetch thread for {}", init.url)).spawn(move || {
let request = Request::from_init(init);
let mut request = Request::from_init(init);
// XXXManishearth: Check origin against pipeline id (also ensure that the mode is allowed)
// todo load context / mimesniff in fetch
// todo referrer policy?
@ -349,7 +349,7 @@ impl CoreResourceManager {
devtools_chan: dc,
filemanager: filemanager,
};
fetch(&request, &mut sender, &context);
fetch(&mut request, &mut sender, &context);
}).expect("Thread spawning failed");
}

View file

@ -7,7 +7,6 @@ use hyper::header::Headers;
use hyper::method::Method;
use msg::constellation_msg::PipelineId;
use servo_url::{ImmutableOrigin, ServoUrl};
use std::cell::{Cell, RefCell};
use std::default::Default;
/// An [initiator](https://fetch.spec.whatwg.org/#concept-request-initiator)
@ -191,42 +190,42 @@ impl Default for RequestInit {
#[derive(Clone, HeapSizeOf)]
pub struct Request {
#[ignore_heap_size_of = "Defined in hyper"]
pub method: RefCell<Method>,
pub method: Method,
pub local_urls_only: bool,
pub sandboxed_storage_area_urls: bool,
#[ignore_heap_size_of = "Defined in hyper"]
pub headers: RefCell<Headers>,
pub headers: Headers,
pub unsafe_request: bool,
pub body: RefCell<Option<Vec<u8>>>,
pub body: Option<Vec<u8>>,
// TODO: client object
pub is_service_worker_global_scope: bool,
pub window: Cell<Window>,
pub window: Window,
// TODO: target browsing context
pub keep_alive: Cell<bool>,
pub skip_service_worker: Cell<bool>,
pub keep_alive: bool,
pub skip_service_worker: bool,
pub initiator: Initiator,
pub type_: Type,
pub destination: Destination,
// TODO: priority object
pub origin: RefCell<Origin>,
pub omit_origin_header: Cell<bool>,
pub origin: Origin,
pub omit_origin_header: bool,
/// https://fetch.spec.whatwg.org/#concept-request-referrer
pub referrer: RefCell<Referrer>,
pub referrer_policy: Cell<Option<ReferrerPolicy>>,
pub pipeline_id: Cell<Option<PipelineId>>,
pub referrer: Referrer,
pub referrer_policy: Option<ReferrerPolicy>,
pub pipeline_id: Option<PipelineId>,
pub synchronous: bool,
pub mode: RequestMode,
pub use_cors_preflight: bool,
pub credentials_mode: CredentialsMode,
pub use_url_credentials: bool,
pub cache_mode: Cell<CacheMode>,
pub redirect_mode: Cell<RedirectMode>,
pub integrity_metadata: RefCell<String>,
pub cache_mode: CacheMode,
pub redirect_mode: RedirectMode,
pub integrity_metadata: String,
// Use the last method on url_list to act as spec current url field, and
// first method to act as spec url field
pub url_list: RefCell<Vec<ServoUrl>>,
pub redirect_count: Cell<u32>,
pub response_tainting: Cell<ResponseTainting>,
pub url_list: Vec<ServoUrl>,
pub redirect_count: u32,
pub response_tainting: ResponseTainting,
}
impl Request {
@ -236,35 +235,35 @@ impl Request {
pipeline_id: Option<PipelineId>)
-> Request {
Request {
method: RefCell::new(Method::Get),
method: Method::Get,
local_urls_only: false,
sandboxed_storage_area_urls: false,
headers: RefCell::new(Headers::new()),
headers: Headers::new(),
unsafe_request: false,
body: RefCell::new(None),
body: None,
is_service_worker_global_scope: is_service_worker_global_scope,
window: Cell::new(Window::Client),
keep_alive: Cell::new(false),
skip_service_worker: Cell::new(false),
window: Window::Client,
keep_alive: false,
skip_service_worker: false,
initiator: Initiator::None,
type_: Type::None,
destination: Destination::None,
origin: RefCell::new(origin.unwrap_or(Origin::Client)),
omit_origin_header: Cell::new(false),
referrer: RefCell::new(Referrer::Client),
referrer_policy: Cell::new(None),
pipeline_id: Cell::new(pipeline_id),
origin: origin.unwrap_or(Origin::Client),
omit_origin_header: false,
referrer: Referrer::Client,
referrer_policy: None,
pipeline_id: pipeline_id,
synchronous: false,
mode: RequestMode::NoCors,
use_cors_preflight: false,
credentials_mode: CredentialsMode::Omit,
use_url_credentials: false,
cache_mode: Cell::new(CacheMode::Default),
redirect_mode: Cell::new(RedirectMode::Follow),
integrity_metadata: RefCell::new(String::new()),
url_list: RefCell::new(vec![url]),
redirect_count: Cell::new(0),
response_tainting: Cell::new(ResponseTainting::Basic),
cache_mode: CacheMode::Default,
redirect_mode: RedirectMode::Follow,
integrity_metadata: String::new(),
url_list: vec![url],
redirect_count: 0,
response_tainting: ResponseTainting::Basic,
}
}
@ -273,10 +272,10 @@ impl Request {
Some(Origin::Origin(init.origin.origin())),
false,
init.pipeline_id);
*req.method.borrow_mut() = init.method;
*req.headers.borrow_mut() = init.headers;
req.method = init.method;
req.headers = init.headers;
req.unsafe_request = init.unsafe_request;
*req.body.borrow_mut() = init.body;
req.body = init.body;
req.type_ = init.type_;
req.destination = init.destination;
req.synchronous = init.synchronous;
@ -284,25 +283,25 @@ impl Request {
req.use_cors_preflight = init.use_cors_preflight;
req.credentials_mode = init.credentials_mode;
req.use_url_credentials = init.use_url_credentials;
req.cache_mode.set(init.cache_mode);
*req.referrer.borrow_mut() = if let Some(url) = init.referrer_url {
req.cache_mode = init.cache_mode;
req.referrer = if let Some(url) = init.referrer_url {
Referrer::ReferrerUrl(url)
} else {
Referrer::NoReferrer
};
req.referrer_policy.set(init.referrer_policy);
req.pipeline_id.set(init.pipeline_id);
req.redirect_mode.set(init.redirect_mode);
*req.integrity_metadata.borrow_mut() = init.integrity_metadata;
req.referrer_policy = init.referrer_policy;
req.pipeline_id = init.pipeline_id;
req.redirect_mode = init.redirect_mode;
req.integrity_metadata = init.integrity_metadata;
req
}
pub fn url(&self) -> ServoUrl {
self.url_list.borrow().first().unwrap().clone()
self.url_list.first().unwrap().clone()
}
pub fn current_url(&self) -> ServoUrl {
self.url_list.borrow().last().unwrap().clone()
self.url_list.last().unwrap().clone()
}
pub fn is_navigation_request(&self) -> bool {

View file

@ -158,9 +158,9 @@ impl Request {
request.method = temporary_request.method;
request.headers = temporary_request.headers.clone();
request.unsafe_request = true;
request.window.set(window);
request.window = window;
// TODO: `entry settings object` is not implemented in Servo yet.
*request.origin.borrow_mut() = Origin::Client;
request.origin = Origin::Client;
request.omit_origin_header = temporary_request.omit_origin_header;
request.referrer = temporary_request.referrer;
request.referrer_policy = temporary_request.referrer_policy;
@ -187,11 +187,11 @@ impl Request {
request.mode = NetTraitsRequestMode::SameOrigin;
}
// Step 13.2
request.omit_origin_header.set(false);
request.omit_origin_header = false;
// Step 13.3
*request.referrer.borrow_mut() = NetTraitsRequestReferrer::Client;
request.referrer = NetTraitsRequestReferrer::Client;
// Step 13.4
request.referrer_policy.set(None);
request.referrer_policy = None;
}
// Step 14
@ -200,7 +200,7 @@ impl Request {
let ref referrer = init_referrer.0;
// Step 14.2
if referrer.is_empty() {
*request.referrer.borrow_mut() = NetTraitsRequestReferrer::NoReferrer;
request.referrer = NetTraitsRequestReferrer::NoReferrer;
} else {
// Step 14.3
let parsed_referrer = base_url.join(referrer);
@ -215,10 +215,10 @@ impl Request {
parsed_referrer.scheme() == "about" &&
parsed_referrer.path() == "client") ||
parsed_referrer.origin() != origin {
*request.referrer.borrow_mut() = NetTraitsRequestReferrer::Client;
request.referrer = NetTraitsRequestReferrer::Client;
} else {
// Step 14.6
*request.referrer.borrow_mut() = NetTraitsRequestReferrer::ReferrerUrl(parsed_referrer);
request.referrer = NetTraitsRequestReferrer::ReferrerUrl(parsed_referrer);
}
}
}
@ -227,7 +227,7 @@ impl Request {
// Step 15
if let Some(init_referrerpolicy) = init.referrerPolicy.as_ref() {
let init_referrer_policy = init_referrerpolicy.clone().into();
request.referrer_policy.set(Some(init_referrer_policy));
request.referrer_policy = Some(init_referrer_policy);
}
// Step 16
@ -254,11 +254,11 @@ impl Request {
// Step 21
if let Some(init_cache) = init.cache.as_ref() {
let cache = init_cache.clone().into();
request.cache_mode.set(cache);
request.cache_mode = cache;
}
// Step 22
if request.cache_mode.get() == NetTraitsRequestCache::OnlyIfCached {
if request.cache_mode == NetTraitsRequestCache::OnlyIfCached {
if request.mode != NetTraitsRequestMode::SameOrigin {
return Err(Error::Type(
"Cache is 'only-if-cached' and mode is not 'same-origin'".to_string()));
@ -268,13 +268,13 @@ impl Request {
// Step 23
if let Some(init_redirect) = init.redirect.as_ref() {
let redirect = init_redirect.clone().into();
request.redirect_mode.set(redirect);
request.redirect_mode = redirect;
}
// Step 24
if let Some(init_integrity) = init.integrity.as_ref() {
let integrity = init_integrity.clone().to_string();
*request.integrity_metadata.borrow_mut() = integrity;
request.integrity_metadata = integrity;
}
// Step 25
@ -292,7 +292,7 @@ impl Request {
None => return Err(Error::Type("Method is not a valid UTF8".to_string())),
};
// Step 25.3
*request.method.borrow_mut() = method;
request.method = method;
}
// Step 26
@ -334,12 +334,12 @@ impl Request {
if r.request.borrow().mode == NetTraitsRequestMode::NoCors {
let borrowed_request = r.request.borrow();
// Step 30.1
if !is_cors_safelisted_method(&borrowed_request.method.borrow()) {
if !is_cors_safelisted_method(&borrowed_request.method) {
return Err(Error::Type(
"The mode is 'no-cors' but the method is not a cors-safelisted method".to_string()));
}
// Step 30.2
if !borrowed_request.integrity_metadata.borrow().is_empty() {
if !borrowed_request.integrity_metadata.is_empty() {
return Err(Error::Type("Integrity metadata is not an empty string".to_string()));
}
// Step 30.3
@ -364,8 +364,7 @@ impl Request {
// Step 32
let mut input_body = if let RequestInfo::Request(ref input_request) = input {
let input_request_request = input_request.request.borrow();
let body = input_request_request.body.borrow();
body.clone()
input_request_request.body.clone()
} else {
None
};
@ -374,11 +373,11 @@ impl Request {
if let Some(init_body_option) = init.body.as_ref() {
if init_body_option.is_some() || input_body.is_some() {
let req = r.request.borrow();
let req_method = req.method.borrow();
match &*req_method {
&HttpMethod::Get => return Err(Error::Type(
let req_method = &req.method;
match *req_method {
HttpMethod::Get => return Err(Error::Type(
"Init's body is non-null, and request method is GET".to_string())),
&HttpMethod::Head => return Err(Error::Type(
HttpMethod::Head => return Err(Error::Type(
"Init's body is non-null, and request method is HEAD".to_string())),
_ => {},
}
@ -402,10 +401,7 @@ impl Request {
}
// Step 35
{
let borrowed_request = r.request.borrow();
*borrowed_request.body.borrow_mut() = input_body;
}
r.request.borrow_mut().body = input_body;
// Step 36
let extracted_mime_type = r.Headers().extract_mime_type();
@ -445,10 +441,10 @@ impl Request {
let mime_type = r.mime_type.borrow().clone();
let headers_guard = r.Headers().get_guard();
let r_clone = Request::new(&r.global(), url, is_service_worker_global_scope);
r_clone.request.borrow_mut().pipeline_id.set(req.pipeline_id.get());
r_clone.request.borrow_mut().pipeline_id = req.pipeline_id;
{
let mut borrowed_r_request = r_clone.request.borrow_mut();
*borrowed_r_request.origin.borrow_mut() = req.origin.borrow().clone();
borrowed_r_request.origin = req.origin.clone();
}
*r_clone.request.borrow_mut() = req.clone();
r_clone.body_used.set(body_used);
@ -540,15 +536,13 @@ impl RequestMethods for Request {
// https://fetch.spec.whatwg.org/#dom-request-method
fn Method(&self) -> ByteString {
let r = self.request.borrow();
let m = r.method.borrow();
ByteString::new(m.as_ref().as_bytes().into())
ByteString::new(r.method.as_ref().as_bytes().into())
}
// https://fetch.spec.whatwg.org/#dom-request-url
fn Url(&self) -> USVString {
let r = self.request.borrow();
let url = r.url_list.borrow();
USVString(url.get(0).map_or("", |u| u.as_str()).into())
USVString(r.url_list.get(0).map_or("", |u| u.as_str()).into())
}
// https://fetch.spec.whatwg.org/#dom-request-headers
@ -569,11 +563,10 @@ impl RequestMethods for Request {
// https://fetch.spec.whatwg.org/#dom-request-referrer
fn Referrer(&self) -> USVString {
let r = self.request.borrow();
let referrer = r.referrer.borrow();
USVString(match &*referrer {
&NetTraitsRequestReferrer::NoReferrer => String::from("no-referrer"),
&NetTraitsRequestReferrer::Client => String::from("about:client"),
&NetTraitsRequestReferrer::ReferrerUrl(ref u) => {
USVString(match r.referrer {
NetTraitsRequestReferrer::NoReferrer => String::from("no-referrer"),
NetTraitsRequestReferrer::Client => String::from("about:client"),
NetTraitsRequestReferrer::ReferrerUrl(ref u) => {
let u_c = u.clone();
u_c.into_string()
}
@ -582,7 +575,7 @@ impl RequestMethods for Request {
// https://fetch.spec.whatwg.org/#dom-request-referrerpolicy
fn ReferrerPolicy(&self) -> ReferrerPolicy {
self.request.borrow().referrer_policy.get().map(|m| m.into()).unwrap_or(ReferrerPolicy::_empty)
self.request.borrow().referrer_policy.map(|m| m.into()).unwrap_or(ReferrerPolicy::_empty)
}
// https://fetch.spec.whatwg.org/#dom-request-mode
@ -599,20 +592,19 @@ impl RequestMethods for Request {
// https://fetch.spec.whatwg.org/#dom-request-cache
fn Cache(&self) -> RequestCache {
let r = self.request.borrow().clone();
r.cache_mode.get().into()
r.cache_mode.into()
}
// https://fetch.spec.whatwg.org/#dom-request-redirect
fn Redirect(&self) -> RequestRedirect {
let r = self.request.borrow().clone();
r.redirect_mode.get().into()
r.redirect_mode.into()
}
// https://fetch.spec.whatwg.org/#dom-request-integrity
fn Integrity(&self) -> DOMString {
let r = self.request.borrow();
let integrity = r.integrity_metadata.borrow();
DOMString::from_string(integrity.clone())
DOMString::from_string(r.integrity_metadata.clone())
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
@ -675,8 +667,8 @@ impl BodyOperations for Request {
}
fn take_body(&self) -> Option<Vec<u8>> {
let request = self.request.borrow_mut();
let body = request.body.borrow_mut().take();
let mut request = self.request.borrow_mut();
let body = request.body.take();
Some(body.unwrap_or(vec![]))
}

View file

@ -37,17 +37,16 @@ struct FetchContext {
}
fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> {
let referrer = request.referrer.borrow();
referrer.to_url().map(|url| url.clone())
request.referrer.to_url().map(|url| url.clone())
}
fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit {
NetTraitsRequestInit {
method: request.method.borrow().clone(),
method: request.method.clone(),
url: request.url(),
headers: request.headers.borrow().clone(),
headers: request.headers.clone(),
unsafe_request: request.unsafe_request,
body: request.body.borrow().clone(),
body: request.body.clone(),
type_: request.type_,
destination: request.destination,
synchronous: request.synchronous,
@ -60,9 +59,9 @@ fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit
// ... NetTraitsRequest.origin: RefCell<Origin>
origin: request.url(),
referrer_url: from_referrer_to_referrer_url(&request),
referrer_policy: request.referrer_policy.get(),
pipeline_id: request.pipeline_id.get(),
redirect_mode: request.redirect_mode.get(),
referrer_policy: request.referrer_policy,
pipeline_id: request.pipeline_id,
redirect_mode: request.redirect_mode,
..NetTraitsRequestInit::default()
}
}