diff --git a/components/net/blob_loader.rs b/components/net/blob_loader.rs index 3af4d531549..c041123bc18 100644 --- a/components/net/blob_loader.rs +++ b/components/net/blob_loader.rs @@ -19,16 +19,16 @@ use servo_url::ServoUrl; /// https://fetch.spec.whatwg.org/#concept-basic-fetch (partial) // TODO: make async. -pub fn load_blob_sync - (url: ServoUrl, - filemanager: FileManager) - -> Result<(HeaderMap, Vec), NetworkError> { +pub fn load_blob_sync( + url: ServoUrl, + filemanager: FileManager, +) -> Result<(HeaderMap, Vec), NetworkError> { let (id, origin) = match parse_blob_url(&url) { Ok((id, origin)) => (id, origin), Err(()) => { let e = format!("Invalid blob URL format {:?}", url); return Err(NetworkError::Internal(e)); - } + }, }; let (sender, receiver) = ipc::channel().unwrap(); @@ -38,11 +38,13 @@ pub fn load_blob_sync let blob_buf = match receiver.recv().unwrap() { Ok(ReadFileProgress::Meta(blob_buf)) => blob_buf, Ok(_) => { - return Err(NetworkError::Internal("Invalid filemanager reply".to_string())); - } + return Err(NetworkError::Internal( + "Invalid filemanager reply".to_string(), + )); + }, Err(e) => { return Err(NetworkError::Internal(format!("{:?}", e))); - } + }, }; let content_type: Mime = blob_buf.type_string.parse().unwrap_or(mime::TEXT_PLAIN); @@ -51,19 +53,31 @@ pub fn load_blob_sync let mut headers = HeaderMap::new(); if let Some(name) = blob_buf.filename { - let charset = charset.map(|c| c.as_ref().into()).unwrap_or("us-ascii".to_owned()); + let charset = charset + .map(|c| c.as_ref().into()) + .unwrap_or("us-ascii".to_owned()); // TODO(eijebong): Replace this once the typed header is there headers.insert( header::CONTENT_DISPOSITION, HeaderValue::from_bytes( - format!("inline; {}", + format!( + "inline; {}", if charset.to_lowercase() == "utf-8" { - format!("filename=\"{}\"", String::from_utf8(name.as_bytes().into()).unwrap()) + format!( + "filename=\"{}\"", + String::from_utf8(name.as_bytes().into()).unwrap() + ) } else { - format!("filename*=\"{}\"''{}", charset, http_percent_encode(name.as_bytes())) + format!( + "filename*=\"{}\"''{}", + charset, + http_percent_encode(name.as_bytes()) + ) } - ).as_bytes() - ).unwrap() + ) + .as_bytes(), + ) + .unwrap(), ); } @@ -77,16 +91,18 @@ pub fn load_blob_sync match receiver.recv().unwrap() { Ok(ReadFileProgress::Partial(ref mut new_bytes)) => { bytes.append(new_bytes); - } + }, Ok(ReadFileProgress::EOF) => { return Ok((headers, bytes)); - } + }, Ok(_) => { - return Err(NetworkError::Internal("Invalid filemanager reply".to_string())); - } + return Err(NetworkError::Internal( + "Invalid filemanager reply".to_string(), + )); + }, Err(e) => { return Err(NetworkError::Internal(format!("{:?}", e))); - } + }, } } } diff --git a/components/net/connector.rs b/components/net/connector.rs index 0311b05b125..c8eb10a1fe2 100644 --- a/components/net/connector.rs +++ b/components/net/connector.rs @@ -20,7 +20,7 @@ use tokio::prelude::future::Executor; pub const BUF_SIZE: usize = 32768; pub struct HttpConnector { - inner: HyperHttpConnector + inner: HyperHttpConnector, } impl HttpConnector { @@ -28,9 +28,7 @@ impl HttpConnector { let mut inner = HyperHttpConnector::new(4); inner.enforce_http(false); inner.set_happy_eyeballs_timeout(None); - HttpConnector { - inner - } + HttpConnector { inner } } } @@ -60,10 +58,7 @@ impl WrappedBody { } pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self { - WrappedBody { - body, - decoder, - } + WrappedBody { body, decoder } } } @@ -90,7 +85,7 @@ impl Stream for WrappedBody { let len = decoder.read(&mut buf).ok()?; buf.truncate(len); Some(buf.into()) - } + }, Decoder::Gzip(None) => { let mut buf = vec![0; BUF_SIZE]; let mut decoder = GzDecoder::new(Cursor::new(chunk.into_bytes())); @@ -98,21 +93,21 @@ impl Stream for WrappedBody { buf.truncate(len); self.decoder = Decoder::Gzip(Some(decoder)); Some(buf.into()) - } + }, Decoder::Deflate(ref mut decoder) => { let mut buf = vec![0; BUF_SIZE]; *decoder.get_mut() = Cursor::new(chunk.into_bytes()); let len = decoder.read(&mut buf).ok()?; buf.truncate(len); Some(buf.into()) - } + }, Decoder::Brotli(ref mut decoder) => { let mut buf = vec![0; BUF_SIZE]; decoder.get_mut().get_mut().extend(&chunk.into_bytes()); let len = decoder.read(&mut buf).ok()?; buf.truncate(len); Some(buf.into()) - } + }, } } else { None @@ -134,33 +129,46 @@ pub fn create_ssl_connector_builder(certs: &str) -> SslConnectorBuilder { let (cert, rest) = certs.split_at(index + token.len()); certs = rest; let cert = x509::X509::from_pem(cert.as_bytes()).unwrap(); - ssl_connector_builder.cert_store_mut().add_cert(cert).or_else(|e| { - let v: Option> = e.errors().iter().nth(0).map(|e| e.reason()); - if v == Some(Some("cert already in hash table")) { - warn!("Cert already in hash table. Ignoring."); - // Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the - // certificate is already in the store. - Ok(()) - } else { - Err(e) - } - }).expect("could not set CA file"); + ssl_connector_builder + .cert_store_mut() + .add_cert(cert) + .or_else(|e| { + let v: Option> = e.errors().iter().nth(0).map(|e| e.reason()); + if v == Some(Some("cert already in hash table")) { + warn!("Cert already in hash table. Ignoring."); + // Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the + // certificate is already in the store. + Ok(()) + } else { + Err(e) + } + }) + .expect("could not set CA file"); } else { break; } } - ssl_connector_builder.set_cipher_list(DEFAULT_CIPHERS).expect("could not set ciphers"); - ssl_connector_builder.set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION); + ssl_connector_builder + .set_cipher_list(DEFAULT_CIPHERS) + .expect("could not set ciphers"); + ssl_connector_builder + .set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION); ssl_connector_builder } -pub fn create_http_client(ssl_connector_builder: SslConnectorBuilder, executor: E) - -> Client - where - E: Executor + Send + 'static>> + Sync + Send + 'static +pub fn create_http_client( + ssl_connector_builder: SslConnectorBuilder, + executor: E, +) -> Client +where + E: Executor + Send + 'static>> + Sync + Send + 'static, { - let connector = HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap(); - Client::builder().http1_title_case_headers(true).executor(executor).build(connector) + let connector = + HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap(); + Client::builder() + .http1_title_case_headers(true) + .executor(executor) + .build(connector) } // The basic logic here is to prefer ciphers with ECDSA certificates, Forward diff --git a/components/net/cookie.rs b/components/net/cookie.rs index fb403628107..dadc78cf14f 100644 --- a/components/net/cookie.rs +++ b/components/net/cookie.rs @@ -19,23 +19,32 @@ use time::{Tm, now, at, Duration}; /// which cookie-rs and hyper's header parsing do not support. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Cookie { - #[serde(deserialize_with = "hyper_serde::deserialize", - serialize_with = "hyper_serde::serialize")] + #[serde( + deserialize_with = "hyper_serde::deserialize", + serialize_with = "hyper_serde::serialize" + )] pub cookie: cookie_rs::Cookie<'static>, pub host_only: bool, pub persistent: bool, - #[serde(deserialize_with = "hyper_serde::deserialize", - serialize_with = "hyper_serde::serialize")] + #[serde( + deserialize_with = "hyper_serde::deserialize", + serialize_with = "hyper_serde::serialize" + )] pub creation_time: Tm, - #[serde(deserialize_with = "hyper_serde::deserialize", - serialize_with = "hyper_serde::serialize")] + #[serde( + deserialize_with = "hyper_serde::deserialize", + serialize_with = "hyper_serde::serialize" + )] pub last_access: Tm, pub expiry_time: Option>, } impl Cookie { - pub fn from_cookie_string(cookie_str: String, request: &ServoUrl, - source: CookieSource) -> Option { + pub fn from_cookie_string( + cookie_str: String, + request: &ServoUrl, + source: CookieSource, + ) -> Option { cookie_rs::Cookie::parse(cookie_str) .ok() .map(|cookie| Cookie::new_wrapped(cookie, request, source)) @@ -43,15 +52,21 @@ impl Cookie { } /// - pub fn new_wrapped(mut cookie: cookie_rs::Cookie<'static>, request: &ServoUrl, source: CookieSource) - -> Option { + pub fn new_wrapped( + mut cookie: cookie_rs::Cookie<'static>, + request: &ServoUrl, + source: CookieSource, + ) -> Option { // Step 3 let (persistent, expiry_time) = match (cookie.max_age(), cookie.expires()) { - (Some(max_age), _) => { - (true, Some(at(now().to_timespec() + Duration::seconds(max_age.num_seconds())))) - } + (Some(max_age), _) => ( + true, + Some(at( + now().to_timespec() + Duration::seconds(max_age.num_seconds()) + )), + ), (_, Some(expires)) => (true, Some(expires)), - _ => (false, None) + _ => (false, None), }; let url_host = request.host_str().unwrap_or("").to_owned(); @@ -64,7 +79,7 @@ impl Cookie { if domain == url_host { domain = "".to_string(); } else { - return None + return None; } } @@ -83,16 +98,18 @@ impl Cookie { // Step 7 let mut has_path_specified = true; - let mut path = cookie.path().unwrap_or_else(|| { - has_path_specified = false; - "" - }).to_owned(); + let mut path = cookie + .path() + .unwrap_or_else(|| { + has_path_specified = false; + "" + }) + .to_owned(); if path.chars().next() != Some('/') { path = Cookie::default_path(&request.path().to_owned()).to_string(); } cookie.set_path(path); - // Step 10 if cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP { return None; @@ -101,14 +118,14 @@ impl Cookie { // https://tools.ietf.org/html/draft-west-cookie-prefixes-04#section-4 // Step 1 of cookie prefixes if (cookie.name().starts_with("__Secure-") || cookie.name().starts_with("__Host-")) && - !(cookie.secure().unwrap_or(false) && request.is_secure_scheme()) + !(cookie.secure().unwrap_or(false) && request.is_secure_scheme()) { return None; } // Step 2 of cookie prefixes if cookie.name().starts_with("__Host-") && - !(host_only && has_path_specified && cookie.path().unwrap() == "/") + !(host_only && has_path_specified && cookie.path().unwrap() == "/") { return None; } @@ -152,16 +169,16 @@ impl Cookie { // The cookie-path and the request-path are identical. request_path == cookie_path || - - (request_path.starts_with(cookie_path) && ( - // The cookie-path is a prefix of the request-path, and the last - // character of the cookie-path is %x2F ("/"). - cookie_path.ends_with("/") || + (request_path.starts_with(cookie_path) && + ( + // The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/"). + cookie_path.ends_with("/") || // The cookie-path is a prefix of the request-path, and the first // character of the request-path that is not included in the cookie- // path is a %x2F ("/") character. request_path[cookie_path.len()..].starts_with("/") - )) + )) } // http://tools.ietf.org/html/rfc6265#section-5.1.3 @@ -170,10 +187,10 @@ impl Cookie { let domain_string = &domain_string.to_lowercase(); string == domain_string || - (string.ends_with(domain_string) && - string.as_bytes()[string.len()-domain_string.len()-1] == b'.' && - string.parse::().is_err() && - string.parse::().is_err()) + (string.ends_with(domain_string) && + string.as_bytes()[string.len() - domain_string.len() - 1] == b'.' && + string.parse::().is_err() && + string.parse::().is_err()) } // http://tools.ietf.org/html/rfc6265#section-5.4 step 1 diff --git a/components/net/cookie_storage.rs b/components/net/cookie_storage.rs index cb066d416fe..af06e876ddf 100644 --- a/components/net/cookie_storage.rs +++ b/components/net/cookie_storage.rs @@ -33,7 +33,12 @@ impl CookieStorage { } // http://tools.ietf.org/html/rfc6265#section-5.3 - pub fn remove(&mut self, cookie: &Cookie, url: &ServoUrl, source: CookieSource) -> Result, ()> { + pub fn remove( + &mut self, + cookie: &Cookie, + url: &ServoUrl, + source: CookieSource, + ) -> Result, ()> { let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&"")); let cookies = self.cookies_map.entry(domain).or_insert(vec![]); @@ -47,10 +52,10 @@ impl CookieStorage { let existing_path = c.cookie.path().as_ref().unwrap().to_owned(); c.cookie.name() == cookie.cookie.name() && - c.cookie.secure().unwrap_or(false) && - (Cookie::domain_match(new_domain, existing_domain) || - Cookie::domain_match(existing_domain, new_domain)) && - Cookie::path_match(new_path, existing_path) + c.cookie.secure().unwrap_or(false) && + (Cookie::domain_match(new_domain, existing_domain) || + Cookie::domain_match(existing_domain, new_domain)) && + Cookie::path_match(new_path, existing_path) }); if any_overlapping { @@ -61,8 +66,8 @@ impl CookieStorage { // Step 11.1 let position = cookies.iter().position(|c| { c.cookie.domain() == cookie.cookie.domain() && - c.cookie.path() == cookie.cookie.path() && - c.cookie.name() == cookie.cookie.name() + c.cookie.path() == cookie.cookie.path() && + c.cookie.name() == cookie.cookie.name() }); if let Some(ind) = position { @@ -111,7 +116,9 @@ impl CookieStorage { let new_len = cookies.len(); // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt - if new_len == old_len && !evict_one_cookie(cookie.cookie.secure().unwrap_or(false), cookies) { + if new_len == old_len && + !evict_one_cookie(cookie.cookie.secure().unwrap_or(false), cookies) + { return; } } @@ -126,7 +133,7 @@ impl CookieStorage { let a_creation_time = a.creation_time.to_timespec(); let b_creation_time = b.creation_time.to_timespec(); a_creation_time.cmp(&b_creation_time) - } + }, // Ensure that longer paths are sorted earlier than shorter paths Ordering::Greater => Ordering::Less, Ordering::Less => Ordering::Greater, @@ -136,13 +143,17 @@ impl CookieStorage { // http://tools.ietf.org/html/rfc6265#section-5.4 pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option { let filterer = |c: &&mut Cookie| -> bool { - info!(" === SENT COOKIE : {} {} {:?} {:?}", - c.cookie.name(), - c.cookie.value(), - c.cookie.domain(), - c.cookie.path()); - info!(" === SENT COOKIE RESULT {}", - c.appropriate_for_url(url, source)); + info!( + " === SENT COOKIE : {} {} {:?} {:?}", + c.cookie.name(), + c.cookie.value(), + c.cookie.domain(), + c.cookie.path() + ); + info!( + " === SENT COOKIE RESULT {}", + c.appropriate_for_url(url, source) + ); // Step 1 c.appropriate_for_url(url, source) }; @@ -161,7 +172,9 @@ impl CookieStorage { (match acc.len() { 0 => acc, _ => acc + "; ", - }) + &c.cookie.name() + "=" + &c.cookie.value() + }) + &c.cookie.name() + + "=" + + &c.cookie.value() }; let result = url_cookies.iter_mut().fold("".to_owned(), reducer); @@ -172,17 +185,21 @@ impl CookieStorage { } } - pub fn cookies_data_for_url<'a>(&'a mut self, - url: &'a ServoUrl, - source: CookieSource) - -> impl Iterator> + 'a { + pub fn cookies_data_for_url<'a>( + &'a mut self, + url: &'a ServoUrl, + source: CookieSource, + ) -> impl Iterator> + 'a { let domain = reg_host(url.host_str().unwrap_or("")); let cookies = self.cookies_map.entry(domain).or_insert(vec![]); - cookies.iter_mut().filter(move |c| c.appropriate_for_url(url, source)).map(|c| { - c.touch(); - c.cookie.clone() - }) + cookies + .iter_mut() + .filter(move |c| c.appropriate_for_url(url, source)) + .map(|c| { + c.touch(); + c.cookie.clone() + }) } } @@ -220,7 +237,10 @@ fn get_oldest_accessed(is_secure_cookie: bool, cookies: &mut Vec) -> Opt let mut oldest_accessed: Option<(usize, Tm)> = None; for (i, c) in cookies.iter().enumerate() { if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) && - oldest_accessed.as_ref().map_or(true, |a| c.last_access < a.1) { + oldest_accessed + .as_ref() + .map_or(true, |a| c.last_access < a.1) + { oldest_accessed = Some((i, c.last_access)); } } diff --git a/components/net/data_loader.rs b/components/net/data_loader.rs index 16ffb75a323..3cd282bb1ed 100644 --- a/components/net/data_loader.rs +++ b/components/net/data_loader.rs @@ -18,7 +18,9 @@ pub type DecodeData = (Mime, Vec); pub fn decode(url: &ServoUrl) -> Result { assert_eq!(url.scheme(), "data"); // Split out content type and data. - let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery].splitn(2, ',').collect(); + let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery] + .splitn(2, ',') + .collect(); if parts.len() != 2 { return Err(DecodeError::InvalidDataUri); } @@ -36,15 +38,18 @@ pub fn decode(url: &ServoUrl) -> Result { ct_str.to_owned() }; - let content_type = ct_str.parse().unwrap_or_else(|_| { - "text/plain; charset=US-ASCII".parse().unwrap() - }); + let content_type = ct_str + .parse() + .unwrap_or_else(|_| "text/plain; charset=US-ASCII".parse().unwrap()); let mut bytes = percent_decode(parts[1].as_bytes()).collect::>(); if is_base64 { // FIXME(#2909): It’s unclear what to do with non-alphabet characters, // but Acid 3 apparently depends on spaces being ignored. - bytes = bytes.into_iter().filter(|&b| b != b' ').collect::>(); + bytes = bytes + .into_iter() + .filter(|&b| b != b' ') + .collect::>(); match base64::decode(&bytes) { Err(..) => return Err(DecodeError::NonBase64DataUri), Ok(data) => bytes = data, diff --git a/components/net/fetch/cors_cache.rs b/components/net/fetch/cors_cache.rs index 95e070cfc8e..f23af159455 100644 --- a/components/net/fetch/cors_cache.rs +++ b/components/net/fetch/cors_cache.rs @@ -21,21 +21,21 @@ use time::{self, Timespec}; #[derive(Clone, Debug)] pub enum HeaderOrMethod { HeaderData(HeaderName), - MethodData(Method) + MethodData(Method), } impl HeaderOrMethod { fn match_header(&self, header_name: &HeaderName) -> bool { match *self { HeaderOrMethod::HeaderData(ref n) => n == header_name, - _ => false + _ => false, } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, - _ => false + _ => false, } } } @@ -48,19 +48,24 @@ pub struct CorsCacheEntry { pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, - created: Timespec + created: Timespec, } impl CorsCacheEntry { - fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool, - header_or_method: HeaderOrMethod) -> CorsCacheEntry { + fn new( + origin: Origin, + url: ServoUrl, + max_age: u32, + credentials: bool, + header_or_method: HeaderOrMethod, + ) -> CorsCacheEntry { CorsCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, - created: time::now().to_timespec() + created: time::now().to_timespec(), } } } @@ -80,25 +85,36 @@ impl CorsCache { CorsCache(vec![]) } - fn find_entry_by_header<'a>(&'a mut self, request: &Request, - header_name: &HeaderName) -> Option<&'a mut CorsCacheEntry> { + fn find_entry_by_header<'a>( + &'a mut self, + request: &Request, + header_name: &HeaderName, + ) -> Option<&'a mut CorsCacheEntry> { self.cleanup(); - self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) + self.0 + .iter_mut() + .find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) } - fn find_entry_by_method<'a>(&'a mut self, request: &Request, - method: Method) -> Option<&'a mut CorsCacheEntry> { + fn find_entry_by_method<'a>( + &'a mut self, + request: &Request, + method: Method, + ) -> Option<&'a mut CorsCacheEntry> { // we can take the method from CorSRequest itself self.cleanup(); - self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) + self.0 + .iter_mut() + .find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) } /// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear) pub fn clear(&mut self, request: &Request) { let CorsCache(buf) = self.clone(); - let new_buf: Vec = - buf.into_iter().filter(|e| e.origin == request.origin && - request.current_url() == e.url).collect(); + let new_buf: Vec = buf + .into_iter() + .filter(|e| e.origin == request.origin && request.current_url() == e.url) + .collect(); *self = CorsCache(new_buf); } @@ -106,9 +122,10 @@ impl CorsCache { pub fn cleanup(&mut self) { let CorsCache(buf) = self.clone(); let now = time::now().to_timespec(); - let new_buf: Vec = buf.into_iter() - .filter(|e| now.sec < e.created.sec + e.max_age as i64) - .collect(); + let new_buf: Vec = buf + .into_iter() + .filter(|e| now.sec < e.created.sec + e.max_age as i64) + .collect(); *self = CorsCache(new_buf); } @@ -122,16 +139,27 @@ impl CorsCache { /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found. /// /// If not, it will insert an equivalent entry - pub fn match_header_and_update(&mut self, request: &Request, - header_name: &HeaderName, new_max_age: u32) -> bool { - match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) { + pub fn match_header_and_update( + &mut self, + request: &Request, + header_name: &HeaderName, + new_max_age: u32, + ) -> bool { + 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.clone(), request.current_url(), new_max_age, - request.credentials_mode == CredentialsMode::Include, - HeaderOrMethod::HeaderData(header_name.clone()))); + self.insert(CorsCacheEntry::new( + request.origin.clone(), + request.current_url(), + new_max_age, + request.credentials_mode == CredentialsMode::Include, + HeaderOrMethod::HeaderData(header_name.clone()), + )); false - } + }, } } @@ -145,15 +173,27 @@ impl CorsCache { /// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found. /// /// If not, it will insert an equivalent entry - pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool { - match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) { + pub fn match_method_and_update( + &mut self, + request: &Request, + method: Method, + new_max_age: u32, + ) -> bool { + 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.clone(), request.current_url(), new_max_age, - request.credentials_mode == CredentialsMode::Include, - HeaderOrMethod::MethodData(method))); + self.insert(CorsCacheEntry::new( + request.origin.clone(), + request.current_url(), + new_max_age, + request.credentials_mode == CredentialsMode::Include, + HeaderOrMethod::MethodData(method), + )); false - } + }, } } diff --git a/components/net/fetch/methods.rs b/components/net/fetch/methods.rs index edc6e3be45a..d9fdebf895f 100644 --- a/components/net/fetch/methods.rs +++ b/components/net/fetch/methods.rs @@ -35,7 +35,8 @@ use std::thread; use subresource_integrity::is_response_integrity_valid; lazy_static! { - static ref X_CONTENT_TYPE_OPTIONS: HeaderName = HeaderName::from_static("x-content-type-options"); + static ref X_CONTENT_TYPE_OPTIONS: HeaderName = + HeaderName::from_static("x-content-type-options"); } const FILE_CHUNK_SIZE: usize = 32768; //32 KB @@ -87,16 +88,16 @@ impl CancellationListener { pub type DoneChannel = Option<(Sender, Receiver)>; /// [Fetch](https://fetch.spec.whatwg.org#concept-fetch) -pub fn fetch(request: &mut Request, - target: Target, - context: &FetchContext) { +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: &mut Request, - cache: &mut CorsCache, - target: Target, - context: &FetchContext) { +pub fn fetch_with_cors_cache( + request: &mut Request, + cache: &mut CorsCache, + target: Target, + context: &FetchContext, +) { // Step 1. if request.window == Window::Client { // TODO: Set window to request's client object if client is a Window object @@ -132,21 +133,27 @@ pub fn fetch_with_cors_cache(request: &mut Request, } /// [Main fetch](https://fetch.spec.whatwg.org/#concept-main-fetch) -pub fn main_fetch(request: &mut Request, - cache: &mut CorsCache, - cors_flag: bool, - recursive_flag: bool, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext) - -> Response { +pub fn main_fetch( + request: &mut Request, + cache: &mut CorsCache, + cors_flag: bool, + recursive_flag: bool, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext, +) -> Response { // Step 1. let mut response = None; // Step 2. if request.local_urls_only { - if !matches!(request.current_url().scheme(), "about" | "blob" | "data" | "filesystem") { - response = Some(Response::network_error(NetworkError::Internal("Non-local scheme".into()))); + if !matches!( + request.current_url().scheme(), + "about" | "blob" | "data" | "filesystem" + ) { + response = Some(Response::network_error(NetworkError::Internal( + "Non-local scheme".into(), + ))); } } @@ -158,7 +165,9 @@ pub fn main_fetch(request: &mut Request, // Step 5. if should_be_blocked_due_to_bad_port(&request.current_url()) { - response = Some(Response::network_error(NetworkError::Internal("Request attempted on bad port".into()))); + response = Some(Response::network_error(NetworkError::Internal( + "Request attempted on bad port".into(), + ))); } // TODO: handle blocking as mixed content. // TODO: handle blocking by content security policy. @@ -167,7 +176,9 @@ pub fn main_fetch(request: &mut Request, // TODO: handle request's client's referrer policy. // Step 7. - request.referrer_policy = request.referrer_policy.or(Some(ReferrerPolicy::NoReferrerWhenDowngrade)); + request.referrer_policy = request + .referrer_policy + .or(Some(ReferrerPolicy::NoReferrerWhenDowngrade)); // Step 8. { @@ -182,11 +193,13 @@ pub fn main_fetch(request: &mut Request, Referrer::ReferrerUrl(url) => { request.headers.remove(header::REFERER); let current_url = request.current_url().clone(); - determine_request_referrer(&mut request.headers, - request.referrer_policy.unwrap(), - url, - current_url) - } + determine_request_referrer( + &mut request.headers, + request.referrer_policy.unwrap(), + url, + current_url, + ) + }, }; if let Some(referrer_url) = referrer_url { request.referrer = Referrer::ReferrerUrl(referrer_url); @@ -197,8 +210,12 @@ pub fn main_fetch(request: &mut Request, // TODO: handle FTP URLs. // Step 10. - context.state.hsts_list.read().unwrap().switch_known_hsts_host_domain_url_to_https( - request.current_url_mut()); + context + .state + .hsts_list + .read() + .unwrap() + .switch_known_hsts_host_domain_url_to_https(request.current_url_mut()); // Step 11. // Not applicable: see fetch_async. @@ -218,47 +235,48 @@ pub fn main_fetch(request: &mut Request, // and about: schemes, but CSS tests will break on loading Ahem // since we load them through a file: URL. current_url.scheme() == "about" || - request.mode == RequestMode::Navigate { + request.mode == RequestMode::Navigate + { // Substep 1. request.response_tainting = ResponseTainting::Basic; // Substep 2. scheme_fetch(request, cache, target, done_chan, context) - } else if request.mode == RequestMode::SameOrigin { Response::network_error(NetworkError::Internal("Cross-origin response".into())) - } else if request.mode == RequestMode::NoCors { // Substep 1. request.response_tainting = ResponseTainting::Opaque; // Substep 2. scheme_fetch(request, cache, target, done_chan, context) - } else if !matches!(current_url.scheme(), "http" | "https") { Response::network_error(NetworkError::Internal("Non-http scheme".into())) - } else if request.use_cors_preflight || (request.unsafe_request && (!is_cors_safelisted_method(&request.method) || - request.headers.iter().any(|(name, value)| !is_cors_safelisted_request_header(&name, &value)))) { + request.headers.iter().any(|(name, value)| { + !is_cors_safelisted_request_header(&name, &value) + }))) { // Substep 1. request.response_tainting = ResponseTainting::CorsTainting; // Substep 2. - let response = http_fetch(request, cache, true, true, false, - target, done_chan, context); + let response = http_fetch( + request, cache, true, true, false, target, done_chan, context, + ); // Substep 3. if response.is_network_error() { // TODO clear cache entries using request } // Substep 4. response - } else { // Substep 1. request.response_tainting = ResponseTainting::CorsTainting; // Substep 2. - http_fetch(request, cache, true, false, false, target, done_chan, context) + http_fetch( + request, cache, true, false, false, target, done_chan, context, + ) } }); @@ -272,19 +290,25 @@ pub fn main_fetch(request: &mut Request, // Substep 1. if request.response_tainting == ResponseTainting::CorsTainting { // Subsubstep 1. - let header_names: Option> = response.headers.typed_get::() + let header_names: Option> = response + .headers + .typed_get::() .map(|v| v.iter().collect()); match header_names { // Subsubstep 2. Some(ref list) if request.credentials_mode != CredentialsMode::Include => { if list.len() == 1 && list[0] == "*" { - response.cors_exposed_header_name_list = - response.headers.iter().map(|(name, _)| name.as_str().to_owned()).collect(); + response.cors_exposed_header_name_list = response + .headers + .iter() + .map(|(name, _)| name.as_str().to_owned()) + .collect(); } }, // Subsubstep 3. Some(list) => { - response.cors_exposed_header_name_list = list.iter().map(|h| h.as_str().to_owned()).collect(); + response.cors_exposed_header_name_list = + list.iter().map(|h| h.as_str().to_owned()).collect(); }, _ => (), } @@ -304,13 +328,16 @@ pub fn main_fetch(request: &mut Request, let internal_error = { // Tests for steps 17 and 18, before step 15 for borrowing concerns. let response_is_network_error = response.is_network_error(); - let should_replace_with_nosniff_error = - !response_is_network_error && should_be_blocked_due_to_nosniff(request.destination, &response.headers); - let should_replace_with_mime_type_error = - !response_is_network_error && should_be_blocked_due_to_mime_type(request.destination, &response.headers); + let should_replace_with_nosniff_error = !response_is_network_error && + should_be_blocked_due_to_nosniff(request.destination, &response.headers); + let should_replace_with_mime_type_error = !response_is_network_error && + should_be_blocked_due_to_mime_type(request.destination, &response.headers); // Step 15. - let mut network_error_response = response.get_network_error().cloned().map(Response::network_error); + let mut network_error_response = response + .get_network_error() + .cloned() + .map(Response::network_error); let internal_response = if let Some(error_response) = network_error_response.as_mut() { error_response } else { @@ -326,27 +353,30 @@ pub fn main_fetch(request: &mut Request, // TODO: handle blocking as mixed content. // TODO: handle blocking by content security policy. let blocked_error_response; - let internal_response = - if should_replace_with_nosniff_error { - // Defer rebinding result - blocked_error_response = Response::network_error(NetworkError::Internal("Blocked by nosniff".into())); - &blocked_error_response - } else if should_replace_with_mime_type_error { - // Defer rebinding result - blocked_error_response = Response::network_error(NetworkError::Internal("Blocked by mime type".into())); - &blocked_error_response - } else { - internal_response - }; + let internal_response = if should_replace_with_nosniff_error { + // Defer rebinding result + blocked_error_response = + Response::network_error(NetworkError::Internal("Blocked by nosniff".into())); + &blocked_error_response + } else if should_replace_with_mime_type_error { + // Defer rebinding result + blocked_error_response = + Response::network_error(NetworkError::Internal("Blocked by mime type".into())); + &blocked_error_response + } else { + internal_response + }; // Step 18. // 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 { - Method::HEAD | Method::CONNECT => true, - _ => false }) { + if not_network_error && + (is_null_body_status(&internal_response.status) || + match request.method { + Method::HEAD | Method::CONNECT => true, + _ => false, + }) { // when Fetch is used only asynchronously, we will need to make sure // that nothing tries to write to the body at this point let mut body = internal_response.body.lock().unwrap(); @@ -373,8 +403,11 @@ pub fn main_fetch(request: &mut Request, // Step 19.2. 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())) + !is_response_integrity_valid(integrity_metadata, &response) + { + Response::network_error(NetworkError::Internal( + "Subresource integrity validation failed".into(), + )) } else { response } @@ -410,7 +443,7 @@ pub fn main_fetch(request: &mut Request, // Step 23. if !response_loaded { - wait_for_response(&mut response, target, done_chan); + wait_for_response(&mut response, target, done_chan); } // Step 24. @@ -430,8 +463,11 @@ pub fn main_fetch(request: &mut Request, fn wait_for_response(response: &mut Response, target: Target, done_chan: &mut DoneChannel) { if let Some(ref ch) = *done_chan { loop { - match ch.1.recv() - .expect("fetch worker should always send Done before terminating") { + match ch + .1 + .recv() + .expect("fetch worker should always send Done before terminating") + { Data::Payload(vec) => { target.process_response_chunk(vec); }, @@ -439,7 +475,7 @@ fn wait_for_response(response: &mut Response, target: Target, done_chan: &mut Do Data::Cancelled => { response.aborted.store(true, Ordering::Relaxed); break; - } + }, } } } else { @@ -456,139 +492,156 @@ fn wait_for_response(response: &mut Response, target: Target, done_chan: &mut Do } /// [Scheme fetch](https://fetch.spec.whatwg.org#scheme-fetch) -fn scheme_fetch(request: &mut Request, - cache: &mut CorsCache, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext) - -> Response { +fn scheme_fetch( + request: &mut Request, + cache: &mut CorsCache, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext, +) -> Response { let url = request.current_url(); match url.scheme() { "about" if url.path() == "blank" => { let mut response = Response::new(url); - response.headers.typed_insert(ContentType::from(mime::TEXT_HTML_UTF_8)); + response + .headers + .typed_insert(ContentType::from(mime::TEXT_HTML_UTF_8)); *response.body.lock().unwrap() = ResponseBody::Done(vec![]); response }, - "http" | "https" => { - http_fetch(request, cache, false, false, false, target, done_chan, context) - }, + "http" | "https" => http_fetch( + request, cache, false, false, false, target, done_chan, context, + ), - "data" => { - match decode(&url) { - Ok((mime, bytes)) => { - let mut response = Response::new(url); - *response.body.lock().unwrap() = ResponseBody::Done(bytes); - response.headers.typed_insert(ContentType::from(mime)); - response - }, - Err(_) => Response::network_error(NetworkError::Internal("Decoding data URL failed".into())) - } + "data" => match decode(&url) { + Ok((mime, bytes)) => { + let mut response = Response::new(url); + *response.body.lock().unwrap() = ResponseBody::Done(bytes); + response.headers.typed_insert(ContentType::from(mime)); + response + }, + Err(_) => { + Response::network_error(NetworkError::Internal("Decoding data URL failed".into())) + }, }, "file" => { - if request.method == Method::GET { - match url.to_file_path() { - Ok(file_path) => { - match File::open(file_path.clone()) { - Ok(mut file) => { - let mime = guess_mime_type(file_path); + if request.method != Method::GET { + return Response::network_error(NetworkError::Internal( + "Unexpected method for file".into(), + )); + } + if let Ok(file_path) = url.to_file_path() { + if let Ok(file) = File::open(file_path.clone()) { + let mime = guess_mime_type(file_path); - let mut response = Response::new(url); - response.headers.typed_insert(ContentType::from(mime)); + let mut response = Response::new(url); + response.headers.typed_insert(ContentType::from(mime)); - let (done_sender, done_receiver) = channel(); - *done_chan = Some((done_sender.clone(), done_receiver)); - *response.body.lock().unwrap() = ResponseBody::Receiving(vec![]); + let (done_sender, done_receiver) = channel(); + *done_chan = Some((done_sender.clone(), done_receiver)); + *response.body.lock().unwrap() = ResponseBody::Receiving(vec![]); - let mut res_body = response.body.clone(); + let mut res_body = response.body.clone(); - let cancellation_listener = context.cancellation_listener.clone(); + let cancellation_listener = context.cancellation_listener.clone(); - let (start, end) = if let Some(ref range) = request.headers.typed_get::() { - match range.iter().collect::, Bound)>>().first() { - Some(&(Bound::Included(start), Bound::Unbounded)) => (start, None), - Some(&(Bound::Included(start), Bound::Included(end))) => { - // `end` should be less or equal to `start`. - (start, Some(u64::max(start, end))) - }, - Some(&(Bound::Unbounded, Bound::Included(offset))) => { - if let Ok(metadata) = file.metadata() { - // `offset` cannot be bigger than the file size. - (metadata.len() - u64::min(metadata.len(), offset), None) - } else { - (0, None) - } - }, - _ => (0, None) - } + let (start, end) = if let Some(ref range) = request.headers.typed_get::() + { + match range + .iter() + .collect::, Bound)>>() + .first() + { + Some(&(Bound::Included(start), Bound::Unbounded)) => (start, None), + Some(&(Bound::Included(start), Bound::Included(end))) => { + // `end` should be less or equal to `start`. + (start, Some(u64::max(start, end))) + }, + Some(&(Bound::Unbounded, Bound::Included(offset))) => { + if let Ok(metadata) = file.metadata() { + // `offset` cannot be bigger than the file size. + (metadata.len() - u64::min(metadata.len(), offset), None) } else { (0, None) - }; + } + }, + _ => (0, None), + } + } else { + (0, None) + }; - thread::Builder::new().name("fetch file worker thread".to_string()).spawn(move || { - let mut reader = BufReader::with_capacity(FILE_CHUNK_SIZE, file); - if reader.seek(SeekFrom::Start(start)).is_err() { - warn!("Fetch - could not seek to {:?}", start); - } + thread::Builder::new() + .name("fetch file worker thread".to_string()) + .spawn(move || { + let mut reader = BufReader::with_capacity(FILE_CHUNK_SIZE, file); + if reader.seek(SeekFrom::Start(start)).is_err() { + warn!("Fetch - could not seek to {:?}", start); + } - loop { - if cancellation_listener.lock().unwrap().cancelled() { - *res_body.lock().unwrap() = ResponseBody::Done(vec![]); - let _ = done_sender.send(Data::Cancelled); - return; - } - let length = { - let mut buffer = reader.fill_buf().unwrap().to_vec(); - let mut buffer_len = buffer.len(); - if let ResponseBody::Receiving(ref mut body) = *res_body.lock().unwrap() { - let offset = usize::min({ - if let Some(end) = end { - let remaining_bytes = - end as usize - start as usize - body.len(); - if remaining_bytes <= FILE_CHUNK_SIZE { - // This is the last chunk so we set buffer len to 0 to break - // the reading loop. - buffer_len = 0; - remaining_bytes - } else { - FILE_CHUNK_SIZE - } + loop { + if cancellation_listener.lock().unwrap().cancelled() { + *res_body.lock().unwrap() = ResponseBody::Done(vec![]); + let _ = done_sender.send(Data::Cancelled); + return; + } + let length = { + let mut buffer = reader.fill_buf().unwrap().to_vec(); + let mut buffer_len = buffer.len(); + if let ResponseBody::Receiving(ref mut body) = + *res_body.lock().unwrap() + { + let offset = usize::min( + { + if let Some(end) = end { + let remaining_bytes = + end as usize - start as usize - body.len(); + if remaining_bytes <= FILE_CHUNK_SIZE { + // This is the last chunk so we set buffer + // len to 0 to break the reading loop. + buffer_len = 0; + remaining_bytes } else { FILE_CHUNK_SIZE } - }, buffer.len()); - body.extend_from_slice(&buffer[0..offset]); - let _ = done_sender.send(Data::Payload(buffer)); - } - buffer_len - }; - if length == 0 { - let mut body = res_body.lock().unwrap(); - let completed_body = match *body { - ResponseBody::Receiving(ref mut body) => { - mem::replace(body, vec![]) - }, - _ => vec![], - }; - *body = ResponseBody::Done(completed_body); - let _ = done_sender.send(Data::Done); - break; - } - reader.consume(length); + } else { + FILE_CHUNK_SIZE + } + }, + buffer.len(), + ); + body.extend_from_slice(&buffer[0..offset]); + let _ = done_sender.send(Data::Payload(buffer)); } - }).expect("Failed to create fetch file worker thread"); - response - }, - _ => Response::network_error(NetworkError::Internal("Opening file failed".into())), - } - }, - _ => Response::network_error(NetworkError::Internal("Constructing file path failed".into())) + buffer_len + }; + if length == 0 { + let mut body = res_body.lock().unwrap(); + let completed_body = match *body { + ResponseBody::Receiving(ref mut body) => { + mem::replace(body, vec![]) + }, + _ => vec![], + }; + *body = ResponseBody::Done(completed_body); + let _ = done_sender.send(Data::Done); + break; + } + reader.consume(length); + } + }) + .expect("Failed to create fetch file worker thread"); + response + } else { + Response::network_error(NetworkError::Internal("Opening file failed".into())) } } else { - Response::network_error(NetworkError::Internal("Unexpected method for file".into())) + Response::network_error(NetworkError::Internal( + "Constructing file path failed".into(), + )) } }, @@ -596,7 +649,9 @@ fn scheme_fetch(request: &mut Request, println!("Loading blob {}", url.as_str()); // Step 2. if request.method != Method::GET { - return Response::network_error(NetworkError::Internal("Unexpected method for blob".into())); + return Response::network_error(NetworkError::Internal( + "Unexpected method for blob".into(), + )); } match load_blob_sync(url.clone(), context.filemanager.clone()) { @@ -618,7 +673,7 @@ fn scheme_fetch(request: &mut Request, Response::network_error(NetworkError::Internal("Unexpected scheme".into())) }, - _ => Response::network_error(NetworkError::Internal("Unexpected scheme".into())) + _ => Response::network_error(NetworkError::Internal("Unexpected scheme".into())), } } @@ -627,13 +682,15 @@ pub fn is_cors_safelisted_request_header(name: &HeaderName, value: &HeaderValue) if name == header::CONTENT_TYPE { if let Some(m) = value.to_str().ok().and_then(|s| s.parse::().ok()) { m.type_() == mime::TEXT && m.subtype() == mime::PLAIN || - m.type_() == mime::APPLICATION && m.subtype() == mime::WWW_FORM_URLENCODED || - m.type_() == mime::MULTIPART && m.subtype() == mime::FORM_DATA + m.type_() == mime::APPLICATION && m.subtype() == mime::WWW_FORM_URLENCODED || + m.type_() == mime::MULTIPART && m.subtype() == mime::FORM_DATA } else { false } } else { - name == header::ACCEPT || name == header::ACCEPT_LANGUAGE || name == header::CONTENT_LANGUAGE + name == header::ACCEPT || + name == header::ACCEPT_LANGUAGE || + name == header::CONTENT_LANGUAGE } } @@ -641,28 +698,35 @@ pub fn is_cors_safelisted_request_header(name: &HeaderName, value: &HeaderValue) pub fn is_cors_safelisted_method(m: &Method) -> bool { match *m { Method::GET | Method::HEAD | Method::POST => true, - _ => false + _ => false, } } fn is_null_body_status(status: &Option<(StatusCode, String)>) -> bool { match *status { Some((status, _)) => match status { - StatusCode::SWITCHING_PROTOCOLS | StatusCode::NO_CONTENT | - StatusCode::RESET_CONTENT | StatusCode::NOT_MODIFIED => true, - _ => false + StatusCode::SWITCHING_PROTOCOLS | + StatusCode::NO_CONTENT | + StatusCode::RESET_CONTENT | + StatusCode::NOT_MODIFIED => true, + _ => false, }, - _ => false + _ => false, } } /// -pub fn should_be_blocked_due_to_nosniff(destination: Destination, response_headers: &HeaderMap) -> bool { +pub fn should_be_blocked_due_to_nosniff( + destination: Destination, + response_headers: &HeaderMap, +) -> bool { // Steps 1-3. // TODO(eijebong): Replace this once typed headers allow custom ones... - if response_headers.get("x-content-type-options") - .map_or(true, |val| val.to_str().unwrap_or("").to_lowercase() != "nosniff") - { + if response_headers + .get("x-content-type-options") + .map_or(true, |val| { + val.to_str().unwrap_or("").to_lowercase() != "nosniff" + }) { return false; } @@ -692,30 +756,34 @@ pub fn should_be_blocked_due_to_nosniff(destination: Destination, response_heade "text/x-javascript".parse().unwrap(), ]; - javascript_mime_types.iter() + javascript_mime_types + .iter() .any(|mime| mime.type_() == mime_type.type_() && mime.subtype() == mime_type.subtype()) } match content_type_header { // Step 6 - Some(ref ct) if destination.is_script_like() - => !is_javascript_mime_type(&ct.clone().into()), + Some(ref ct) if destination.is_script_like() => { + !is_javascript_mime_type(&ct.clone().into()) + }, // Step 7 - Some(ref ct) if destination == Destination::Style - => { - let m: mime::Mime = ct.clone().into(); - m.type_() != mime::TEXT && m.subtype() != mime::CSS - }, + Some(ref ct) if destination == Destination::Style => { + let m: mime::Mime = ct.clone().into(); + m.type_() != mime::TEXT && m.subtype() != mime::CSS + }, None if destination == Destination::Style || destination.is_script_like() => true, // Step 8 - _ => false + _ => false, } } /// -fn should_be_blocked_due_to_mime_type(destination: Destination, response_headers: &HeaderMap) -> bool { +fn should_be_blocked_due_to_mime_type( + destination: Destination, + response_headers: &HeaderMap, +) -> bool { // Step 1 let mime_type: mime::Mime = match response_headers.typed_get::() { Some(header) => header.into(), @@ -725,12 +793,10 @@ fn should_be_blocked_due_to_mime_type(destination: Destination, response_headers // Step 2-3 destination.is_script_like() && match mime_type.type_() { - mime::AUDIO | - mime::VIDEO | - mime::IMAGE => true, + mime::AUDIO | mime::VIDEO | mime::IMAGE => true, mime::TEXT if mime_type.subtype() == mime::CSV => true, // Step 4 - _ => false + _ => false, } } @@ -745,14 +811,17 @@ pub fn should_be_blocked_due_to_bad_port(url: &ServoUrl) -> bool { // If there is no explicit port, this means the default one is used for // the given scheme, and thus this means the request should not be blocked // due to a bad port. - let port = if let Some(port) = url.port() { port } else { return false }; + let port = if let Some(port) = url.port() { + port + } else { + return false; + }; // Step 4. if scheme == "ftp" && (port == 20 || port == 21) { return false; } - // Step 5. if is_network_scheme(scheme) && is_bad_port(port) { return true; @@ -770,12 +839,10 @@ fn is_network_scheme(scheme: &str) -> bool { /// fn is_bad_port(port: u16) -> bool { static BAD_PORTS: [u16; 64] = [ - 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, - 43, 53, 77, 79, 87, 95, 101, 102, 103, 104, 109, 110, 111, - 113, 115, 117, 119, 123, 135, 139, 143, 179, 389, 465, 512, - 513, 514, 515, 526, 530, 531, 532, 540, 556, 563, 587, 601, - 636, 993, 995, 2049, 3659, 4045, 6000, 6665, 6666, 6667, - 6668, 6669 + 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 77, 79, 87, 95, 101, 102, + 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 139, 143, 179, 389, 465, 512, 513, + 514, 515, 526, 530, 531, 532, 540, 556, 563, 587, 601, 636, 993, 995, 2049, 3659, 4045, + 6000, 6665, 6666, 6667, 6668, 6669, ]; BAD_PORTS.binary_search(&port).is_ok() diff --git a/components/net/filemanager_thread.rs b/components/net/filemanager_thread.rs index 3dda46a979d..f1e3b3e61df 100644 --- a/components/net/filemanager_thread.rs +++ b/components/net/filemanager_thread.rs @@ -34,7 +34,7 @@ struct FileStoreEntry { /// UUIDs only become valid blob URIs when explicitly requested /// by the user with createObjectURL. Validity can be revoked as well. /// (The UUID is the one that maps to this entry in `FileManagerStore`) - is_valid_url: AtomicBool + is_valid_url: AtomicBool, } #[derive(Clone)] @@ -71,29 +71,38 @@ impl FileManager { } } - pub fn read_file(&self, - sender: IpcSender>, - id: Uuid, - check_url_validity: bool, - origin: FileOrigin) { + pub fn read_file( + &self, + sender: IpcSender>, + id: Uuid, + check_url_validity: bool, + origin: FileOrigin, + ) { let store = self.store.clone(); - thread::Builder::new().name("read file".to_owned()).spawn(move || { - if let Err(e) = store.try_read_file(&sender, id, check_url_validity, - origin) { - let _ = sender.send(Err(FileManagerThreadError::BlobURLStoreError(e))); - } - }).expect("Thread spawning failed"); + thread::Builder::new() + .name("read file".to_owned()) + .spawn(move || { + if let Err(e) = store.try_read_file(&sender, id, check_url_validity, origin) { + let _ = sender.send(Err(FileManagerThreadError::BlobURLStoreError(e))); + } + }) + .expect("Thread spawning failed"); } - pub fn promote_memory(&self, - blob_buf: BlobBuf, - set_valid: bool, - sender: IpcSender>, - origin: FileOrigin) { + pub fn promote_memory( + &self, + blob_buf: BlobBuf, + set_valid: bool, + sender: IpcSender>, + origin: FileOrigin, + ) { let store = self.store.clone(); - thread::Builder::new().name("transfer memory".to_owned()).spawn(move || { - store.promote_memory(blob_buf, set_valid, sender, origin); - }).expect("Thread spawning failed"); + thread::Builder::new() + .name("transfer memory".to_owned()) + .spawn(move || { + store.promote_memory(blob_buf, set_valid, sender, origin); + }) + .expect("Thread spawning failed"); } /// Message handler @@ -102,35 +111,41 @@ impl FileManager { FileManagerThreadMsg::SelectFile(filter, sender, origin, opt_test_path) => { let store = self.store.clone(); let embedder = self.embedder_proxy.clone(); - thread::Builder::new().name("select file".to_owned()).spawn(move || { - store.select_file(filter, sender, origin, opt_test_path, embedder); - }).expect("Thread spawning failed"); - } + thread::Builder::new() + .name("select file".to_owned()) + .spawn(move || { + store.select_file(filter, sender, origin, opt_test_path, embedder); + }) + .expect("Thread spawning failed"); + }, FileManagerThreadMsg::SelectFiles(filter, sender, origin, opt_test_paths) => { let store = self.store.clone(); let embedder = self.embedder_proxy.clone(); - thread::Builder::new().name("select files".to_owned()).spawn(move || { - store.select_files(filter, sender, origin, opt_test_paths, embedder); - }).expect("Thread spawning failed"); - } + thread::Builder::new() + .name("select files".to_owned()) + .spawn(move || { + store.select_files(filter, sender, origin, opt_test_paths, embedder); + }) + .expect("Thread spawning failed"); + }, FileManagerThreadMsg::ReadFile(sender, id, check_url_validity, origin) => { self.read_file(sender, id, check_url_validity, origin); - } + }, FileManagerThreadMsg::PromoteMemory(blob_buf, set_valid, sender, origin) => { self.promote_memory(blob_buf, set_valid, sender, origin); - } - FileManagerThreadMsg::AddSlicedURLEntry(id, rel_pos, sender, origin) =>{ + }, + FileManagerThreadMsg::AddSlicedURLEntry(id, rel_pos, sender, origin) => { self.store.add_sliced_url_entry(id, rel_pos, sender, origin); - } + }, FileManagerThreadMsg::DecRef(id, origin, sender) => { let _ = sender.send(self.store.dec_ref(&id, &origin)); - } + }, FileManagerThreadMsg::RevokeBlobURL(id, origin, sender) => { let _ = sender.send(self.store.set_blob_url_validity(false, &id, &origin)); - } + }, FileManagerThreadMsg::ActivateBlobURL(id, sender, origin) => { let _ = sender.send(self.store.set_blob_url_validity(true, &id, &origin)); - } + }, } } } @@ -150,8 +165,12 @@ impl FileManagerStore { } /// Copy out the file backend implementation content - fn get_impl(&self, id: &Uuid, origin_in: &FileOrigin, - check_url_validity: bool) -> Result { + fn get_impl( + &self, + id: &Uuid, + origin_in: &FileOrigin, + check_url_validity: bool, + ) -> Result { match self.entries.read().unwrap().get(id) { Some(ref entry) => { if *origin_in != *entry.origin { @@ -164,7 +183,7 @@ impl FileManagerStore { Ok(entry.file_impl.clone()) } } - } + }, None => Err(BlobURLStoreError::InvalidFileID), } } @@ -177,7 +196,7 @@ impl FileManagerStore { self.entries.write().unwrap().remove(id); } - fn inc_ref(&self, id: &Uuid, origin_in: &FileOrigin) -> Result<(), BlobURLStoreError>{ + fn inc_ref(&self, id: &Uuid, origin_in: &FileOrigin) -> Result<(), BlobURLStoreError> { match self.entries.read().unwrap().get(id) { Some(entry) => { if entry.origin == *origin_in { @@ -186,41 +205,53 @@ impl FileManagerStore { } else { Err(BlobURLStoreError::InvalidOrigin) } - } + }, None => Err(BlobURLStoreError::InvalidFileID), } } - fn add_sliced_url_entry(&self, parent_id: Uuid, rel_pos: RelativePos, - sender: IpcSender>, - origin_in: FileOrigin) { + fn add_sliced_url_entry( + &self, + parent_id: Uuid, + rel_pos: RelativePos, + sender: IpcSender>, + origin_in: FileOrigin, + ) { match self.inc_ref(&parent_id, &origin_in) { Ok(_) => { let new_id = Uuid::new_v4(); - self.insert(new_id, FileStoreEntry { - origin: origin_in, - file_impl: FileImpl::Sliced(parent_id, rel_pos), - refs: AtomicUsize::new(1), - // Valid here since AddSlicedURLEntry implies URL creation - // from a BlobImpl::Sliced - is_valid_url: AtomicBool::new(true), - }); + self.insert( + new_id, + FileStoreEntry { + origin: origin_in, + file_impl: FileImpl::Sliced(parent_id, rel_pos), + refs: AtomicUsize::new(1), + // Valid here since AddSlicedURLEntry implies URL creation + // from a BlobImpl::Sliced + is_valid_url: AtomicBool::new(true), + }, + ); // We assume that the returned id will be held by BlobImpl::File let _ = sender.send(Ok(new_id)); - } + }, Err(e) => { let _ = sender.send(Err(e)); - } + }, } } - fn query_files_from_embedder(&self, - patterns: Vec, - multiple_files: bool, - embedder_proxy: EmbedderProxy) -> Option> { + fn query_files_from_embedder( + &self, + patterns: Vec, + multiple_files: bool, + embedder_proxy: EmbedderProxy, + ) -> Option> { let (ipc_sender, ipc_receiver) = ipc::channel().expect("Failed to create IPC channel!"); - let msg = (None, EmbedderMsg::SelectFiles(patterns, multiple_files, ipc_sender)); + let msg = ( + None, + EmbedderMsg::SelectFiles(patterns, multiple_files, ipc_sender), + ); embedder_proxy.send(msg); match ipc_receiver.recv() { @@ -228,23 +259,26 @@ impl FileManagerStore { Err(e) => { warn!("Failed to receive files from embedder ({}).", e); None - } + }, } } - fn select_file(&self, - patterns: Vec, - sender: IpcSender>, - origin: FileOrigin, - opt_test_path: Option, - embedder_proxy: EmbedderProxy) { + fn select_file( + &self, + patterns: Vec, + sender: IpcSender>, + origin: FileOrigin, + opt_test_path: Option, + embedder_proxy: EmbedderProxy, + ) { // Check if the select_files preference is enabled // to ensure process-level security against compromised script; // Then try applying opt_test_path directly for testing convenience let opt_s = if select_files_pref_enabled() { opt_test_path } else { - self.query_files_from_embedder(patterns, false, embedder_proxy).and_then(|mut x| x.pop()) + self.query_files_from_embedder(patterns, false, embedder_proxy) + .and_then(|mut x| x.pop()) }; match opt_s { @@ -252,20 +286,22 @@ impl FileManagerStore { let selected_path = Path::new(&s); let result = self.create_entry(selected_path, &origin); let _ = sender.send(result); - } + }, None => { let _ = sender.send(Err(FileManagerThreadError::UserCancelled)); return; - } + }, } } - fn select_files(&self, - patterns: Vec, - sender: IpcSender>>, - origin: FileOrigin, - opt_test_paths: Option>, - embedder_proxy: EmbedderProxy) { + fn select_files( + &self, + patterns: Vec, + sender: IpcSender>>, + origin: FileOrigin, + opt_test_paths: Option>, + embedder_proxy: EmbedderProxy, + ) { // Check if the select_files preference is enabled // to ensure process-level security against compromised script; // Then try applying opt_test_paths directly for testing convenience @@ -291,30 +327,42 @@ impl FileManagerStore { Err(e) => { let _ = sender.send(Err(e)); return; - } + }, }; } let _ = sender.send(Ok(replies)); - } + }, None => { let _ = sender.send(Err(FileManagerThreadError::UserCancelled)); return; - } + }, } } - fn create_entry(&self, file_path: &Path, origin: &str) -> Result { + fn create_entry( + &self, + file_path: &Path, + origin: &str, + ) -> Result { use net_traits::filemanager_thread::FileManagerThreadError::FileSystemError; let file = File::open(file_path).map_err(|e| FileSystemError(e.to_string()))?; - let metadata = file.metadata().map_err(|e| FileSystemError(e.to_string()))?; - let modified = metadata.modified().map_err(|e| FileSystemError(e.to_string()))?; - let elapsed = modified.elapsed().map_err(|e| FileSystemError(e.to_string()))?; + let metadata = file + .metadata() + .map_err(|e| FileSystemError(e.to_string()))?; + let modified = metadata + .modified() + .map_err(|e| FileSystemError(e.to_string()))?; + let elapsed = modified + .elapsed() + .map_err(|e| FileSystemError(e.to_string()))?; // Unix Epoch: https://doc.servo.org/std/time/constant.UNIX_EPOCH.html let modified_epoch = elapsed.as_secs() * 1000 + elapsed.subsec_nanos() as u64 / 1000000; let file_size = metadata.len(); - let file_name = file_path.file_name().ok_or(FileSystemError("Invalid filepath".to_string()))?; + let file_name = file_path + .file_name() + .ok_or(FileSystemError("Invalid filepath".to_string()))?; let file_impl = FileImpl::MetaDataOnly(FileMetaData { path: file_path.to_path_buf(), @@ -324,18 +372,21 @@ impl FileManagerStore { let id = Uuid::new_v4(); - self.insert(id, FileStoreEntry { - origin: origin.to_string(), - file_impl: file_impl, - refs: AtomicUsize::new(1), - // Invalid here since create_entry is called by file selection - is_valid_url: AtomicBool::new(false), - }); + self.insert( + id, + FileStoreEntry { + origin: origin.to_string(), + file_impl: file_impl, + refs: AtomicUsize::new(1), + // Invalid here since create_entry is called by file selection + is_valid_url: AtomicBool::new(false), + }, + ); let filename_path = Path::new(file_name); let type_string = match guess_mime_type_opt(filename_path) { Some(x) => format!("{}", x), - None => "".to_string(), + None => "".to_string(), }; Ok(SelectedFile { @@ -347,9 +398,14 @@ impl FileManagerStore { }) } - fn get_blob_buf(&self, sender: &IpcSender>, - id: &Uuid, origin_in: &FileOrigin, rel_pos: RelativePos, - check_url_validity: bool) -> Result<(), BlobURLStoreError> { + fn get_blob_buf( + &self, + sender: &IpcSender>, + id: &Uuid, + origin_in: &FileOrigin, + rel_pos: RelativePos, + check_url_validity: bool, + ) -> Result<(), BlobURLStoreError> { let file_impl = self.get_impl(id, origin_in, check_url_validity)?; match file_impl { FileImpl::Memory(buf) => { @@ -365,7 +421,7 @@ impl FileManagerStore { let _ = sender.send(Ok(ReadFileProgress::EOF)); Ok(()) - } + }, FileImpl::MetaDataOnly(metadata) => { /* XXX: Snapshot state check (optional) https://w3c.github.io/FileAPI/#snapshot-state. Concretely, here we create another file, and this file might not @@ -373,45 +429,62 @@ impl FileManagerStore { create_entry is called. */ - let opt_filename = metadata.path.file_name() - .and_then(|osstr| osstr.to_str()) - .map(|s| s.to_string()); + let opt_filename = metadata + .path + .file_name() + .and_then(|osstr| osstr.to_str()) + .map(|s| s.to_string()); let mime = guess_mime_type_opt(metadata.path.clone()); let range = rel_pos.to_abs_range(metadata.size as usize); let mut file = File::open(&metadata.path) - .map_err(|e| BlobURLStoreError::External(e.to_string()))?; - let seeked_start = file.seek(SeekFrom::Start(range.start as u64)) - .map_err(|e| BlobURLStoreError::External(e.to_string()))?; + .map_err(|e| BlobURLStoreError::External(e.to_string()))?; + let seeked_start = file + .seek(SeekFrom::Start(range.start as u64)) + .map_err(|e| BlobURLStoreError::External(e.to_string()))?; if seeked_start == (range.start as u64) { let type_string = match mime { Some(x) => format!("{}", x), - None => "".to_string(), + None => "".to_string(), }; - chunked_read(sender, &mut file, range.len(), opt_filename, - type_string); + chunked_read(sender, &mut file, range.len(), opt_filename, type_string); Ok(()) } else { Err(BlobURLStoreError::InvalidEntry) } - } + }, FileImpl::Sliced(parent_id, inner_rel_pos) => { // Next time we don't need to check validity since // we have already done that for requesting URL if necessary - self.get_blob_buf(sender, &parent_id, origin_in, - rel_pos.slice_inner(&inner_rel_pos), false) - } + self.get_blob_buf( + sender, + &parent_id, + origin_in, + rel_pos.slice_inner(&inner_rel_pos), + false, + ) + }, } } // Convenient wrapper over get_blob_buf - fn try_read_file(&self, sender: &IpcSender>, - id: Uuid, check_url_validity: bool, origin_in: FileOrigin) - -> Result<(), BlobURLStoreError> { - self.get_blob_buf(sender, &id, &origin_in, RelativePos::full_range(), check_url_validity) + fn try_read_file( + &self, + sender: &IpcSender>, + id: Uuid, + check_url_validity: bool, + origin_in: FileOrigin, + ) -> Result<(), BlobURLStoreError> { + self.get_blob_buf( + sender, + &id, + &origin_in, + RelativePos::full_range(), + check_url_validity, + ) } fn dec_ref(&self, id: &Uuid, origin_in: &FileOrigin) -> Result<(), BlobURLStoreError> { @@ -436,7 +509,7 @@ impl FileManagerStore { } else { return Err(BlobURLStoreError::InvalidOrigin); } - } + }, None => return Err(BlobURLStoreError::InvalidFileID), }; @@ -454,28 +527,41 @@ impl FileManagerStore { Ok(()) } - fn promote_memory(&self, blob_buf: BlobBuf, set_valid: bool, - sender: IpcSender>, origin: FileOrigin) { - match Url::parse(&origin) { // parse to check sanity + fn promote_memory( + &self, + blob_buf: BlobBuf, + set_valid: bool, + sender: IpcSender>, + origin: FileOrigin, + ) { + match Url::parse(&origin) { + // parse to check sanity Ok(_) => { let id = Uuid::new_v4(); - self.insert(id, FileStoreEntry { - origin: origin.clone(), - file_impl: FileImpl::Memory(blob_buf), - refs: AtomicUsize::new(1), - is_valid_url: AtomicBool::new(set_valid), - }); + self.insert( + id, + FileStoreEntry { + origin: origin.clone(), + file_impl: FileImpl::Memory(blob_buf), + refs: AtomicUsize::new(1), + is_valid_url: AtomicBool::new(set_valid), + }, + ); let _ = sender.send(Ok(id)); - } + }, Err(_) => { let _ = sender.send(Err(BlobURLStoreError::InvalidOrigin)); - } + }, } } - fn set_blob_url_validity(&self, validity: bool, id: &Uuid, - origin_in: &FileOrigin) -> Result<(), BlobURLStoreError> { + fn set_blob_url_validity( + &self, + validity: bool, + id: &Uuid, + origin_in: &FileOrigin, + ) -> Result<(), BlobURLStoreError> { let (do_remove, opt_parent_id, res) = match self.entries.read().unwrap().get(id) { Some(entry) => { if *entry.origin == *origin_in { @@ -485,7 +571,7 @@ impl FileManagerStore { // Check if it is the last possible reference // since refs only accounts for blob id holders // and store entry id holders - let zero_refs = entry.refs.load(Ordering::Acquire) == 0; + let zero_refs = entry.refs.load(Ordering::Acquire) == 0; if let FileImpl::Sliced(ref parent_id, _) = entry.file_impl { (zero_refs, Some(parent_id.clone()), Ok(())) @@ -498,8 +584,8 @@ impl FileManagerStore { } else { (false, None, Err(BlobURLStoreError::InvalidOrigin)) } - } - None => (false, None, Err(BlobURLStoreError::InvalidFileID)) + }, + None => (false, None, Err(BlobURLStoreError::InvalidFileID)), }; if do_remove { @@ -515,15 +601,21 @@ impl FileManagerStore { } fn select_files_pref_enabled() -> bool { - PREFS.get("dom.testing.htmlinputelement.select_files.enabled") - .as_boolean().unwrap_or(false) + PREFS + .get("dom.testing.htmlinputelement.select_files.enabled") + .as_boolean() + .unwrap_or(false) } const CHUNK_SIZE: usize = 8192; -fn chunked_read(sender: &IpcSender>, - file: &mut File, size: usize, opt_filename: Option, - type_string: String) { +fn chunked_read( + sender: &IpcSender>, + file: &mut File, + size: usize, + opt_filename: Option, + type_string: String, +) { // First chunk let mut buf = vec![0; CHUNK_SIZE]; match file.read(&mut buf) { @@ -536,11 +628,11 @@ fn chunked_read(sender: &IpcSender>, bytes: buf, }; let _ = sender.send(Ok(ReadFileProgress::Meta(blob_buf))); - } + }, Err(e) => { let _ = sender.send(Err(FileManagerThreadError::FileSystemError(e.to_string()))); return; - } + }, } // Send the remaining chunks @@ -550,15 +642,15 @@ fn chunked_read(sender: &IpcSender>, Ok(0) => { let _ = sender.send(Ok(ReadFileProgress::EOF)); return; - } + }, Ok(n) => { buf.truncate(n); let _ = sender.send(Ok(ReadFileProgress::Partial(buf))); - } + }, Err(e) => { let _ = sender.send(Err(FileManagerThreadError::FileSystemError(e.to_string()))); return; - } + }, } } } diff --git a/components/net/hosts.rs b/components/net/hosts.rs index 4cc688a474b..52fd5fe671e 100644 --- a/components/net/hosts.rs +++ b/components/net/hosts.rs @@ -31,21 +31,32 @@ pub fn replace_host_table(table: HashMap) { } pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap { - hostsfile_content.lines().filter_map(|line| { - let mut iter = line.split('#').next().unwrap().split_whitespace(); - Some((iter.next()?.parse().ok()?, iter)) - }).flat_map(|(ip, hosts)| { - hosts.filter(|host| { - let invalid = ['\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']']; - host.parse::().is_err() && !host.contains(&invalid[..]) - }).map(move |host| { - (host.to_owned(), ip) + hostsfile_content + .lines() + .filter_map(|line| { + let mut iter = line.split('#').next().unwrap().split_whitespace(); + Some((iter.next()?.parse().ok()?, iter)) }) - }).collect() + .flat_map(|(ip, hosts)| { + hosts + .filter(|host| { + let invalid = [ + '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']', + ]; + host.parse::().is_err() && !host.contains(&invalid[..]) + }) + .map(move |host| (host.to_owned(), ip)) + }) + .collect() } pub fn replace_host(host: &str) -> Cow { - HOST_TABLE.lock().unwrap().as_ref() + HOST_TABLE + .lock() + .unwrap() + .as_ref() .and_then(|table| table.get(host)) - .map_or(host.into(), |replaced_host| replaced_host.to_string().into()) + .map_or(host.into(), |replaced_host| { + replaced_host.to_string().into() + }) } diff --git a/components/net/hsts.rs b/components/net/hsts.rs index d1268a958ad..bcf6ee02747 100644 --- a/components/net/hsts.rs +++ b/components/net/hsts.rs @@ -16,11 +16,15 @@ pub struct HstsEntry { pub host: String, pub include_subdomains: bool, pub max_age: Option, - pub timestamp: Option + pub timestamp: Option, } impl HstsEntry { - pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option) -> Option { + pub fn new( + host: String, + subdomains: IncludeSubdomains, + max_age: Option, + ) -> Option { if host.parse::().is_ok() || host.parse::().is_ok() { None } else { @@ -28,7 +32,7 @@ impl HstsEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, - timestamp: Some(time::get_time().sec as u64) + timestamp: Some(time::get_time().sec as u64), }) } } @@ -37,9 +41,9 @@ impl HstsEntry { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age - } + }, - _ => false + _ => false, } } @@ -59,7 +63,9 @@ pub struct HstsList { impl HstsList { pub fn new() -> HstsList { - HstsList { entries_map: HashMap::new() } + HstsList { + entries_map: HashMap::new(), + } } /// Create an `HstsList` from the bytes of a JSON preload file. @@ -107,9 +113,9 @@ impl HstsList { } fn has_subdomain(&self, host: &str, base_domain: &str) -> bool { - self.entries_map.get(base_domain).map_or(false, |entries| { - entries.iter().any(|e| e.matches_subdomain(host)) - }) + self.entries_map.get(base_domain).map_or(false, |entries| { + entries.iter().any(|e| e.matches_subdomain(host)) + }) } pub fn push(&mut self, entry: HstsEntry) { @@ -118,7 +124,10 @@ impl HstsList { let have_domain = self.has_domain(&entry.host, base_domain); let have_subdomain = self.has_subdomain(&entry.host, base_domain); - let entries = self.entries_map.entry(base_domain.to_owned()).or_insert(vec![]); + let entries = self + .entries_map + .entry(base_domain.to_owned()) + .or_insert(vec![]); if !have_domain && !have_subdomain { entries.push(entry); } else if !have_subdomain { @@ -136,7 +145,10 @@ impl HstsList { if url.scheme() != "http" { return; } - if url.domain().map_or(false, |domain| self.is_host_secure(domain)) { + if url + .domain() + .map_or(false, |domain| self.is_host_secure(domain)) + { url.as_mut_url().set_scheme("https").unwrap(); } } diff --git a/components/net/http_cache.rs b/components/net/http_cache.rs index dbb777eb103..f9466523852 100644 --- a/components/net/http_cache.rs +++ b/components/net/http_cache.rs @@ -30,23 +30,22 @@ use std::time::SystemTime; use time; use time::{Duration, Timespec, Tm}; - /// The key used to differentiate requests in the cache. -#[derive(Clone, Eq, Hash, MallocSizeOf, PartialEq )] +#[derive(Clone, Eq, Hash, MallocSizeOf, PartialEq)] pub struct CacheKey { - url: ServoUrl + url: ServoUrl, } impl CacheKey { fn new(request: Request) -> CacheKey { CacheKey { - url: request.current_url().clone() + url: request.current_url().clone(), } } fn from_servo_url(servo_url: &ServoUrl) -> CacheKey { CacheKey { - url: servo_url.clone() + url: servo_url.clone(), } } @@ -63,7 +62,7 @@ struct CachedResource { body: Arc>, aborted: Arc, awaiting_body: Arc>>>, - data: Measurable + data: Measurable, } #[derive(Clone, MallocSizeOf)] @@ -82,9 +81,9 @@ impl MallocSizeOf for CachedResource { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { // TODO: self.request_headers.unconditional_size_of(ops) + self.body.unconditional_size_of(ops) + - self.aborted.unconditional_size_of(ops) + - self.awaiting_body.unconditional_size_of(ops) + - self.data.size_of(ops) + self.aborted.unconditional_size_of(ops) + + self.awaiting_body.unconditional_size_of(ops) + + self.data.size_of(ops) } } @@ -94,7 +93,7 @@ struct CachedMetadata { /// Headers pub headers: Arc>, /// Fields that implement MallocSizeOf - pub data: Measurable + pub data: Measurable, } #[derive(Clone, MallocSizeOf)] @@ -106,7 +105,7 @@ struct MeasurableCachedMetadata { /// Character set. pub charset: Option, /// HTTP Status - pub status: Option<(u16, Vec)> + pub status: Option<(u16, Vec)>, } impl MallocSizeOf for CachedMetadata { @@ -122,7 +121,7 @@ pub struct CachedResponse { /// The response constructed from the cached resource pub response: Response, /// The revalidation flag for the stored response - pub needs_validation: bool + pub needs_validation: bool, } /// A memory cache. @@ -132,7 +131,6 @@ pub struct HttpCache { entries: HashMap>, } - /// Determine if a given response is cacheable based on the initial metadata received. /// Based on fn response_is_cacheable(metadata: &Metadata) -> bool { @@ -143,15 +141,18 @@ fn response_is_cacheable(metadata: &Metadata) -> bool { let headers = metadata.headers.as_ref().unwrap(); if headers.contains_key(header::EXPIRES) || headers.contains_key(header::LAST_MODIFIED) || - headers.contains_key(header::ETAG) { + headers.contains_key(header::ETAG) + { is_cacheable = true; } if let Some(ref directive) = headers.typed_get::() { if directive.no_store() { - return false + return false; } - if directive.public() || directive.s_max_age().is_some() || - directive.max_age().is_some() || directive.no_cache() + if directive.public() || + directive.s_max_age().is_some() || + directive.max_age().is_some() || + directive.no_cache() { is_cacheable = true; } @@ -245,12 +246,11 @@ fn get_response_expiry(response: &Response) -> Duration { match *code { 200 | 203 | 204 | 206 | 300 | 301 | 404 | 405 | 410 | 414 | 501 => { // Status codes that are cacheable by default - return heuristic_freshness + return heuristic_freshness; }, _ => { // Other status codes can only use heuristic freshness if the public cache directive is present. - if let Some(ref directives) = response.headers.typed_get::() - { + if let Some(ref directives) = response.headers.typed_get::() { if directives.public() { return heuristic_freshness; } @@ -288,25 +288,30 @@ fn get_expiry_adjustment_from_request_headers(request: &Request, expires: Durati return expires - min_fresh; } if directive.no_cache() || directive.no_store() { - return Duration::min_value() + return Duration::min_value(); } expires } /// Create a CachedResponse from a request and a CachedResource. -fn create_cached_response(request: &Request, +fn create_cached_response( + request: &Request, cached_resource: &CachedResource, cached_headers: &HeaderMap, - done_chan: &mut DoneChannel) - -> CachedResponse { + done_chan: &mut DoneChannel, +) -> CachedResponse { let mut response = Response::new(cached_resource.data.metadata.data.final_url.clone()); response.headers = cached_headers.clone(); response.body = cached_resource.body.clone(); if let ResponseBody::Receiving(_) = *cached_resource.body.lock().unwrap() { let (done_sender, done_receiver) = channel(); *done_chan = Some((done_sender.clone(), done_receiver)); - cached_resource.awaiting_body.lock().unwrap().push(done_sender); + cached_resource + .awaiting_body + .lock() + .unwrap() + .push(done_sender); } response.location_url = cached_resource.data.location_url.clone(); response.status = cached_resource.data.status.clone(); @@ -324,15 +329,20 @@ fn create_cached_response(request: &Request, // TODO: take must-revalidate into account // TODO: if this cache is to be considered shared, take proxy-revalidate into account // - let has_expired = (adjusted_expires < time_since_validated) || - (adjusted_expires == time_since_validated); - CachedResponse { response: response, needs_validation: has_expired } + let has_expired = + (adjusted_expires < time_since_validated) || (adjusted_expires == time_since_validated); + CachedResponse { + response: response, + needs_validation: has_expired, + } } /// Create a new resource, based on the bytes requested, and an existing resource, /// with a status-code of 206. -fn create_resource_with_bytes_from_resource(bytes: &[u8], resource: &CachedResource) - -> CachedResource { +fn create_resource_with_bytes_from_resource( + bytes: &[u8], + resource: &CachedResource, +) -> CachedResource { CachedResource { request_headers: resource.request_headers.clone(), body: Arc::new(Mutex::new(ResponseBody::Done(bytes.to_owned()))), @@ -347,29 +357,35 @@ fn create_resource_with_bytes_from_resource(bytes: &[u8], resource: &CachedResou url_list: resource.data.url_list.clone(), expires: resource.data.expires.clone(), last_validated: resource.data.last_validated.clone(), - }) + }), } } /// Support for range requests . -fn handle_range_request(request: &Request, +fn handle_range_request( + request: &Request, candidates: Vec<&CachedResource>, range_spec: Vec<(Bound, Bound)>, - done_chan: &mut DoneChannel) - -> Option { - let mut complete_cached_resources = candidates.iter().filter(|resource| { - match resource.data.raw_status { - Some((ref code, _)) => *code == 200, - None => false - } - }); - let partial_cached_resources = candidates.iter().filter(|resource| { - match resource.data.raw_status { - Some((ref code, _)) => *code == 206, - None => false - } - }); - match (range_spec.first().unwrap(), complete_cached_resources.next()) { + done_chan: &mut DoneChannel, +) -> Option { + let mut complete_cached_resources = + candidates + .iter() + .filter(|resource| match resource.data.raw_status { + Some((ref code, _)) => *code == 200, + None => false, + }); + let partial_cached_resources = + candidates + .iter() + .filter(|resource| match resource.data.raw_status { + Some((ref code, _)) => *code == 206, + None => false, + }); + match ( + range_spec.first().unwrap(), + complete_cached_resources.next(), + ) { // TODO: take the full range spec into account. // If we have a complete resource, take the request range from the body. // When there isn't a complete resource available, we loop over cached partials, @@ -384,9 +400,11 @@ fn handle_range_request(request: &Request, let e = end as usize + 1; let requested = body.get(b..e); if let Some(bytes) = requested { - let new_resource = create_resource_with_bytes_from_resource(bytes, complete_resource); + let new_resource = + create_resource_with_bytes_from_resource(bytes, complete_resource); let cached_headers = new_resource.data.metadata.headers.lock().unwrap(); - let cached_response = create_cached_response(request, &new_resource, &*cached_headers, done_chan); + let cached_response = + create_cached_response(request, &new_resource, &*cached_headers, done_chan); return Some(cached_response); } } @@ -400,9 +418,9 @@ fn handle_range_request(request: &Request, if let Some(bytes_range) = range.bytes_range() { bytes_range } else { - continue + continue; } - } + }, _ => continue, }; if res_beginning - 1 < beginning && res_end + 1 > end { @@ -416,8 +434,10 @@ fn handle_range_request(request: &Request, _ => continue, }; if let Some(bytes) = requested { - let new_resource = create_resource_with_bytes_from_resource(&bytes, partial_resource); - let cached_response = create_cached_response(request, &new_resource, &*headers, done_chan); + let new_resource = + create_resource_with_bytes_from_resource(&bytes, partial_resource); + let cached_response = + create_cached_response(request, &new_resource, &*headers, done_chan); return Some(cached_response); } } @@ -428,9 +448,11 @@ fn handle_range_request(request: &Request, let b = beginning as usize; let requested = body.get(b..); if let Some(bytes) = requested { - let new_resource = create_resource_with_bytes_from_resource(bytes, complete_resource); + let new_resource = + create_resource_with_bytes_from_resource(bytes, complete_resource); let cached_headers = new_resource.data.metadata.headers.lock().unwrap(); - let cached_response = create_cached_response(request, &new_resource, &*cached_headers, done_chan); + let cached_response = + create_cached_response(request, &new_resource, &*cached_headers, done_chan); return Some(cached_response); } } @@ -457,8 +479,10 @@ fn handle_range_request(request: &Request, _ => continue, }; if let Some(bytes) = requested { - let new_resource = create_resource_with_bytes_from_resource(&bytes, partial_resource); - let cached_response = create_cached_response(request, &new_resource, &*headers, done_chan); + let new_resource = + create_resource_with_bytes_from_resource(&bytes, partial_resource); + let cached_response = + create_cached_response(request, &new_resource, &*headers, done_chan); return Some(cached_response); } } @@ -469,9 +493,11 @@ fn handle_range_request(request: &Request, let from_byte = body.len() - offset as usize; let requested = body.get(from_byte..); if let Some(bytes) = requested { - let new_resource = create_resource_with_bytes_from_resource(bytes, complete_resource); + let new_resource = + create_resource_with_bytes_from_resource(bytes, complete_resource); let cached_headers = new_resource.data.metadata.headers.lock().unwrap(); - let cached_response = create_cached_response(request, &new_resource, &*cached_headers, done_chan); + let cached_response = + create_cached_response(request, &new_resource, &*cached_headers, done_chan); return Some(cached_response); } } @@ -488,7 +514,7 @@ fn handle_range_request(request: &Request, } else { continue; }; - if (total - res_beginning) > (offset - 1 ) && (total - res_end) < offset + 1 { + if (total - res_beginning) > (offset - 1) && (total - res_end) < offset + 1 { let resource_body = &*partial_resource.body.lock().unwrap(); let requested = match resource_body { &ResponseBody::Done(ref body) => { @@ -498,38 +524,47 @@ fn handle_range_request(request: &Request, _ => continue, }; if let Some(bytes) = requested { - let new_resource = create_resource_with_bytes_from_resource(&bytes, partial_resource); - let cached_response = create_cached_response(request, &new_resource, &*headers, done_chan); + let new_resource = + create_resource_with_bytes_from_resource(&bytes, partial_resource); + let cached_response = + create_cached_response(request, &new_resource, &*headers, done_chan); return Some(cached_response); } } } }, // All the cases with Bound::Excluded should be unreachable anyway - _ => return None + _ => return None, } None } - impl HttpCache { /// Create a new memory cache instance. pub fn new() -> HttpCache { HttpCache { - entries: HashMap::new() + entries: HashMap::new(), } } /// Constructing Responses from Caches. /// - pub fn construct_response(&self, request: &Request, done_chan: &mut DoneChannel) -> Option { + pub fn construct_response( + &self, + request: &Request, + done_chan: &mut DoneChannel, + ) -> Option { // TODO: generate warning headers as appropriate if request.method != Method::GET { // Only Get requests are cached, avoid a url based match for others. return None; } let entry_key = CacheKey::new(request.clone()); - let resources = self.entries.get(&entry_key)?.into_iter().filter(|r| { !r.aborted.load(Ordering::Relaxed) }); + let resources = self + .entries + .get(&entry_key)? + .into_iter() + .filter(|r| !r.aborted.load(Ordering::Relaxed)); let mut candidates = vec![]; for cached_resource in resources { let mut can_be_constructed = true; @@ -545,7 +580,9 @@ impl HttpCache { match request.headers.get(vary_val) { Some(header_data) => { // If the header is present in the request. - if let Some(original_header_data) = original_request_headers.get(vary_val) { + if let Some(original_header_data) = + original_request_headers.get(vary_val) + { // Check that the value of the nominated header field, // in the original request, matches the value in the current request. if original_header_data != header_data { @@ -558,7 +595,8 @@ impl HttpCache { // If a header field is absent from a request, // it can only match a stored response if those headers, // were also absent in the original request. - can_be_constructed = original_request_headers.get(vary_val).is_none(); + can_be_constructed = + original_request_headers.get(vary_val).is_none(); }, } if !can_be_constructed { @@ -573,7 +611,12 @@ impl HttpCache { } // Support for range requests if let Some(range_spec) = request.headers.typed_get::() { - return handle_range_request(request, candidates, range_spec.iter().collect(), done_chan); + return handle_range_request( + request, + candidates, + range_spec.iter().collect(), + done_chan, + ); } else { // Not a Range request. if let Some(ref cached_resource) = candidates.first() { @@ -581,7 +624,8 @@ impl HttpCache { // TODO: select the most appropriate one, using a known mechanism from a selecting header field, // or using the Date header to return the most recent one. let cached_headers = cached_resource.data.metadata.headers.lock().unwrap(); - let cached_response = create_cached_response(request, cached_resource, &*cached_headers, done_chan); + let cached_response = + create_cached_response(request, cached_resource, &*cached_headers, done_chan); return Some(cached_response); } } @@ -602,7 +646,7 @@ impl HttpCache { let _ = done_sender.send(Data::Payload(completed_body.clone())); let _ = done_sender.send(Data::Done); } - }; + } } } } @@ -610,7 +654,12 @@ impl HttpCache { /// Freshening Stored Responses upon Validation. /// - pub fn refresh(&mut self, request: &Request, response: Response, done_chan: &mut DoneChannel) -> Option { + pub fn refresh( + &mut self, + request: &Request, + response: Response, + done_chan: &mut DoneChannel, + ) -> Option { assert_eq!(response.status.map(|s| s.0), Some(StatusCode::NOT_MODIFIED)); let entry_key = CacheKey::new(request.clone()); if let Some(cached_resources) = self.entries.get_mut(&entry_key) { @@ -620,22 +669,25 @@ impl HttpCache { // Otherwise, create a new dedicated channel to update the consumer. // The response constructed here will replace the 304 one from the network. let in_progress_channel = match *cached_resource.body.lock().unwrap() { - ResponseBody::Receiving(..) => { - Some(channel()) - }, - ResponseBody::Empty | ResponseBody::Done(..) => None + ResponseBody::Receiving(..) => Some(channel()), + ResponseBody::Empty | ResponseBody::Done(..) => None, }; match in_progress_channel { Some((done_sender, done_receiver)) => { *done_chan = Some((done_sender.clone(), done_receiver)); - cached_resource.awaiting_body.lock().unwrap().push(done_sender); + cached_resource + .awaiting_body + .lock() + .unwrap() + .push(done_sender); }, - None => *done_chan = None + None => *done_chan = None, } // Received a response with 304 status code, in response to a request that matches a cached resource. // 1. update the headers of the cached resource. // 2. return a response, constructed from the cached resource. - let mut constructed_response = Response::new(cached_resource.data.metadata.data.final_url.clone()); + let mut constructed_response = + Response::new(cached_resource.data.metadata.data.final_url.clone()); constructed_response.body = cached_resource.body.clone(); constructed_response.status = cached_resource.data.status.clone(); constructed_response.https_state = cached_resource.data.https_state.clone(); @@ -666,12 +718,19 @@ impl HttpCache { /// pub fn invalidate(&mut self, request: &Request, response: &Response) { // TODO(eijebong): Once headers support typed_get, update this to use them - if let Some(Ok(location)) = response.headers.get(header::LOCATION).map(HeaderValue::to_str) { + if let Some(Ok(location)) = response + .headers + .get(header::LOCATION) + .map(HeaderValue::to_str) + { if let Ok(url) = request.current_url().join(location) { self.invalidate_for_url(&url); } } - if let Some(Ok(ref content_location)) = response.headers.get(header::CONTENT_LOCATION).map(HeaderValue::to_str) + if let Some(Ok(ref content_location)) = response + .headers + .get(header::CONTENT_LOCATION) + .map(HeaderValue::to_str) { if let Ok(url) = request.current_url().join(&content_location) { self.invalidate_for_url(&url); @@ -683,18 +742,23 @@ impl HttpCache { /// Storing Responses in Caches. /// pub fn store(&mut self, request: &Request, response: &Response) { - if PREFS.get("network.http-cache.disabled").as_boolean().unwrap_or(false) { - return + if PREFS + .get("network.http-cache.disabled") + .as_boolean() + .unwrap_or(false) + { + return; } if request.method != Method::GET { // Only Get requests are cached. - return + return; } let entry_key = CacheKey::new(request.clone()); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { - filtered: _, - unsafe_: metadata }) | + filtered: _, + unsafe_: metadata, + }) | Ok(FetchMetadata::Unfiltered(metadata)) => metadata, _ => return, }; @@ -708,8 +772,8 @@ impl HttpCache { final_url: metadata.final_url, content_type: metadata.content_type.map(|v| v.0.to_string()), charset: metadata.charset, - status: metadata.status - }) + status: metadata.status, + }), }; let entry_resource = CachedResource { request_headers: Arc::new(Mutex::new(request.headers.clone())), @@ -724,11 +788,10 @@ impl HttpCache { raw_status: response.raw_status.clone(), url_list: response.url_list.clone(), expires: expiry, - last_validated: time::now() - }) + last_validated: time::now(), + }), }; let entry = self.entries.entry(entry_key).or_insert(vec![]); entry.push(entry_resource); } - } diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index 20aaaffc237..e7077f7df0e 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -55,9 +55,7 @@ use tokio::runtime::Runtime; use uuid; lazy_static! { - pub static ref HANDLE: Mutex = { - Mutex::new(Runtime::new().unwrap()) - }; + pub static ref HANDLE: Mutex = { Mutex::new(Runtime::new().unwrap()) }; } pub struct HttpState { @@ -93,34 +91,29 @@ pub fn set_default_accept(destination: Destination, headers: &mut HeaderMap) { } let value = match destination { // Step 3.2. - Destination::Document => { - vec![ - QualityItem::new(mime::TEXT_HTML, Quality::from_u16(1000)), - QualityItem::new("application/xhtml+xml".parse().unwrap(), Quality::from_u16(1000)), - QualityItem::new("application/xml".parse().unwrap(), Quality::from_u16(900)), - QualityItem::new(mime::STAR_STAR, Quality::from_u16(800)) - ] - }, + Destination::Document => vec![ + QualityItem::new(mime::TEXT_HTML, Quality::from_u16(1000)), + QualityItem::new( + "application/xhtml+xml".parse().unwrap(), + Quality::from_u16(1000), + ), + QualityItem::new("application/xml".parse().unwrap(), Quality::from_u16(900)), + QualityItem::new(mime::STAR_STAR, Quality::from_u16(800)), + ], // Step 3.3. - Destination::Image => { - vec![ - QualityItem::new(mime::IMAGE_PNG, Quality::from_u16(1000)), - QualityItem::new(mime::IMAGE_SVG, Quality::from_u16(1000)), - QualityItem::new(mime::IMAGE_STAR, Quality::from_u16(800)), - QualityItem::new(mime::STAR_STAR, Quality::from_u16(500)) - ] - }, + Destination::Image => vec![ + QualityItem::new(mime::IMAGE_PNG, Quality::from_u16(1000)), + QualityItem::new(mime::IMAGE_SVG, Quality::from_u16(1000)), + QualityItem::new(mime::IMAGE_STAR, Quality::from_u16(800)), + QualityItem::new(mime::STAR_STAR, Quality::from_u16(500)), + ], // Step 3.3. - Destination::Style => { - vec![ - QualityItem::new(mime::TEXT_CSS, Quality::from_u16(1000)), - QualityItem::new(mime::STAR_STAR, Quality::from_u16(100)) - ] - }, + Destination::Style => vec![ + QualityItem::new(mime::TEXT_CSS, Quality::from_u16(1000)), + QualityItem::new(mime::STAR_STAR, Quality::from_u16(100)), + ], // Step 3.1. - _ => { - vec![QualityItem::new(mime::STAR_STAR, Quality::from_u16(1000))] - }, + _ => vec![QualityItem::new(mime::STAR_STAR, Quality::from_u16(1000))], }; // Step 3.4. @@ -130,11 +123,14 @@ pub fn set_default_accept(destination: Destination, headers: &mut HeaderMap) { fn set_default_accept_encoding(headers: &mut HeaderMap) { if headers.contains_key(header::ACCEPT_ENCODING) { - return + return; } // TODO(eijebong): Change this once typed headers are done - headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("gzip, deflate, br")); + headers.insert( + header::ACCEPT_ENCODING, + HeaderValue::from_static("gzip, deflate, br"), + ); } pub fn set_default_accept_language(headers: &mut HeaderMap) { @@ -143,7 +139,10 @@ pub fn set_default_accept_language(headers: &mut HeaderMap) { } // TODO(eijebong): Change this once typed headers are done - headers.insert(header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US, en; q=0.5")); + headers.insert( + header::ACCEPT_LANGUAGE, + HeaderValue::from_static("en-US, en; q=0.5"), + ); } /// @@ -191,11 +190,12 @@ fn strip_url(mut referrer_url: ServoUrl, origin_only: bool) -> Option /// /// Steps 4-6. -pub fn determine_request_referrer(headers: &mut HeaderMap, - referrer_policy: ReferrerPolicy, - referrer_source: ServoUrl, - current_url: ServoUrl) - -> Option { +pub fn determine_request_referrer( + headers: &mut HeaderMap, + referrer_policy: ReferrerPolicy, + referrer_source: ServoUrl, + current_url: ServoUrl, +) -> Option { assert!(!headers.contains_key(header::REFERER)); // FIXME(#14505): this does not seem to be the correct way of checking for // same-origin requests. @@ -205,25 +205,40 @@ pub fn determine_request_referrer(headers: &mut HeaderMap, match referrer_policy { ReferrerPolicy::NoReferrer => None, ReferrerPolicy::Origin => strip_url(referrer_source, true), - ReferrerPolicy::SameOrigin => if cross_origin { None } else { strip_url(referrer_source, false) }, + ReferrerPolicy::SameOrigin => { + if cross_origin { + None + } else { + strip_url(referrer_source, false) + } + }, ReferrerPolicy::UnsafeUrl => strip_url(referrer_source, false), ReferrerPolicy::OriginWhenCrossOrigin => strip_url(referrer_source, cross_origin), ReferrerPolicy::StrictOrigin => strict_origin(referrer_source, current_url), - ReferrerPolicy::StrictOriginWhenCrossOrigin => strict_origin_when_cross_origin(referrer_source, current_url), - ReferrerPolicy::NoReferrerWhenDowngrade => no_referrer_when_downgrade_header(referrer_source, current_url), + ReferrerPolicy::StrictOriginWhenCrossOrigin => { + strict_origin_when_cross_origin(referrer_source, current_url) + }, + ReferrerPolicy::NoReferrerWhenDowngrade => { + no_referrer_when_downgrade_header(referrer_source, current_url) + }, } } -pub fn set_request_cookies(url: &ServoUrl, headers: &mut HeaderMap, cookie_jar: &RwLock) { +pub fn set_request_cookies( + url: &ServoUrl, + headers: &mut HeaderMap, + cookie_jar: &RwLock, +) { let mut cookie_jar = cookie_jar.write().unwrap(); if let Some(cookie_list) = cookie_jar.cookies_for_url(url, CookieSource::HTTP) { - headers.insert(header::COOKIE, HeaderValue::from_bytes(cookie_list.as_bytes()).unwrap()); + headers.insert( + header::COOKIE, + HeaderValue::from_bytes(cookie_list.as_bytes()).unwrap(), + ); } } -fn set_cookie_for_url(cookie_jar: &RwLock, - request: &ServoUrl, - cookie_val: &str) { +fn set_cookie_for_url(cookie_jar: &RwLock, request: &ServoUrl, cookie_val: &str) { let mut cookie_jar = cookie_jar.write().unwrap(); let source = CookieSource::HTTP; @@ -232,12 +247,14 @@ fn set_cookie_for_url(cookie_jar: &RwLock, } } -fn set_cookies_from_headers(url: &ServoUrl, headers: &HeaderMap, cookie_jar: &RwLock) { +fn set_cookies_from_headers( + url: &ServoUrl, + headers: &HeaderMap, + cookie_jar: &RwLock, +) { for cookie in headers.get_all(header::SET_COOKIE) { if let Ok(cookie_str) = cookie.to_str() { - set_cookie_for_url(&cookie_jar, - &url, - &cookie_str); + set_cookie_for_url(&cookie_jar, &url, &cookie_str); } } } @@ -247,11 +264,9 @@ impl Decoder { if let Some(encoding) = response.headers().typed_get::() { if encoding.contains("gzip") { Decoder::Gzip(None) - } - else if encoding.contains("deflate") { + } else if encoding.contains("deflate") { Decoder::Deflate(DeflateDecoder::new(Cursor::new(Bytes::new()))) - } - else if encoding.contains("br") { + } else if encoding.contains("br") { Decoder::Brotli(Decompressor::new(Cursor::new(Bytes::new()), BUF_SIZE)) } else { Decoder::Plain @@ -269,16 +284,18 @@ pub enum Decoder { Plain, } -fn prepare_devtools_request(request_id: String, - url: ServoUrl, - method: Method, - headers: HeaderMap, - body: Option>, - pipeline_id: PipelineId, - now: Tm, - connect_time: u64, - send_time: u64, - is_xhr: bool) -> ChromeToDevtoolsControlMsg { +fn prepare_devtools_request( + request_id: String, + url: ServoUrl, + method: Method, + headers: HeaderMap, + body: Option>, + pipeline_id: PipelineId, + now: Tm, + connect_time: u64, + send_time: u64, + is_xhr: bool, +) -> ChromeToDevtoolsControlMsg { let request = DevtoolsHttpRequest { url: url, method: method, @@ -296,45 +313,72 @@ fn prepare_devtools_request(request_id: String, ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event) } -fn send_request_to_devtools(msg: ChromeToDevtoolsControlMsg, - devtools_chan: &Sender) { - devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)).unwrap(); +fn send_request_to_devtools( + msg: ChromeToDevtoolsControlMsg, + devtools_chan: &Sender, +) { + devtools_chan + .send(DevtoolsControlMsg::FromChrome(msg)) + .unwrap(); } -fn send_response_to_devtools(devtools_chan: &Sender, - request_id: String, - headers: Option, - status: Option<(u16, Vec)>, - pipeline_id: PipelineId) { - let response = DevtoolsHttpResponse { headers: headers, status: status, body: None, pipeline_id: pipeline_id }; +fn send_response_to_devtools( + devtools_chan: &Sender, + request_id: String, + headers: Option, + status: Option<(u16, Vec)>, + pipeline_id: PipelineId, +) { + let response = DevtoolsHttpResponse { + headers: headers, + status: status, + body: None, + pipeline_id: pipeline_id, + }; let net_event_response = NetworkEvent::HttpResponse(response); let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event_response); let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)); } -fn auth_from_cache(auth_cache: &RwLock, origin: &ImmutableOrigin) -> Option> { - if let Some(ref auth_entry) = auth_cache.read().unwrap().entries.get(&origin.ascii_serialization()) { +fn auth_from_cache( + auth_cache: &RwLock, + origin: &ImmutableOrigin, +) -> Option> { + if let Some(ref auth_entry) = auth_cache + .read() + .unwrap() + .entries + .get(&origin.ascii_serialization()) + { let user_name = &auth_entry.user_name; - let password = &auth_entry.password; + let password = &auth_entry.password; Some(Authorization::basic(user_name, password)) } else { None } } -fn obtain_response(client: &Client, - url: &ServoUrl, - method: &Method, - request_headers: &HeaderMap, - data: &Option>, - load_data_method: &Method, - pipeline_id: &Option, - iters: u32, - request_id: Option<&str>, - is_xhr: bool) - -> Box, Option), - Error = NetworkError>> { +fn obtain_response( + client: &Client, + url: &ServoUrl, + method: &Method, + request_headers: &HeaderMap, + data: &Option>, + load_data_method: &Method, + pipeline_id: &Option, + iters: u32, + request_id: Option<&str>, + is_xhr: bool, +) -> Box< + Future< + Item = ( + HyperResponse, + Option, + ), + Error = NetworkError, + >, +> { let mut headers = request_headers.clone(); // Avoid automatically sending request body if a redirect has occurred. @@ -349,13 +393,13 @@ fn obtain_response(client: &Client, &Some(ref d) if !is_redirected_request => { headers.typed_insert(ContentLength(d.len() as u64)); request_body = d.clone(); - } + }, _ => { if *load_data_method != Method::GET && *load_data_method != Method::HEAD { headers.typed_insert(ContentLength(0)) } request_body = vec![]; - } + }, } if log_enabled!(log::Level::Info) { @@ -370,7 +414,14 @@ fn obtain_response(client: &Client, // https://url.spec.whatwg.org/#percent-encoded-bytes let request = HyperRequest::builder() .method(method) - .uri(url.clone().into_url().as_ref().replace("|", "%7C").replace("{", "%7B").replace("}", "%7D")) + .uri( + url.clone() + .into_url() + .as_ref() + .replace("|", "%7C") + .replace("{", "%7B") + .replace("}", "%7D"), + ) .body(WrappedBody::new(request_body.clone().into())); let mut request = match request { @@ -386,43 +437,59 @@ fn obtain_response(client: &Client, let method = method.clone(); let send_start = precise_time_ms(); - Box::new(client.request(request).and_then(move |res| { - let send_end = precise_time_ms(); + Box::new( + client + .request(request) + .and_then(move |res| { + let send_end = precise_time_ms(); - let msg = if let Some(request_id) = request_id { - if let Some(pipeline_id) = pipeline_id { - Some(prepare_devtools_request( - request_id, - closure_url, method.clone(), headers, - Some(request_body.clone()), pipeline_id, time::now(), - connect_end - connect_start, send_end - send_start, is_xhr)) + let msg = if let Some(request_id) = request_id { + if let Some(pipeline_id) = pipeline_id { + Some(prepare_devtools_request( + request_id, + closure_url, + method.clone(), + headers, + Some(request_body.clone()), + pipeline_id, + time::now(), + connect_end - connect_start, + send_end - send_start, + is_xhr, + )) // TODO: ^This is not right, connect_start is taken before contructing the // request and connect_end at the end of it. send_start is takend before the // connection too. I'm not sure it's currently possible to get the time at the // point between the connection and the start of a request. - } else { - debug!("Not notifying devtools (no pipeline_id)"); - None - } - } else { - debug!("Not notifying devtools (no request_id)"); - None - }; - let decoder = Decoder::from_http_response(&res); - Ok((res.map(move |r| WrappedBody::new_with_decoder(r, decoder)), msg)) - }).map_err(move |e| NetworkError::from_hyper_error(&e))) + } else { + debug!("Not notifying devtools (no pipeline_id)"); + None + } + } else { + debug!("Not notifying devtools (no request_id)"); + None + }; + let decoder = Decoder::from_http_response(&res); + Ok(( + res.map(move |r| WrappedBody::new_with_decoder(r, decoder)), + msg, + )) + }) + .map_err(move |e| NetworkError::from_hyper_error(&e)), + ) } /// [HTTP fetch](https://fetch.spec.whatwg.org#http-fetch) -pub fn http_fetch(request: &mut Request, - cache: &mut CorsCache, - cors_flag: bool, - cors_preflight_flag: bool, - authentication_fetch_flag: bool, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext) - -> Response { +pub fn http_fetch( + request: &mut Request, + cache: &mut CorsCache, + cors_flag: bool, + cors_preflight_flag: bool, + authentication_fetch_flag: bool, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext, +) -> Response { // This is a new async fetch, reset the channel we are waiting on *done_chan = None; // Step 1 @@ -439,10 +506,12 @@ pub fn http_fetch(request: &mut Request, } // Substep 2 - if response.is_none() && request.is_subresource_request() && match request.origin { - Origin::Origin(ref origin) => *origin == request.url().origin(), - _ => false, - } { + if response.is_none() && + request.is_subresource_request() && + match request.origin { + Origin::Origin(ref origin) => *origin == request.url().origin(), + _ => false, + } { // TODO (handle foreign fetch unimplemented) } @@ -455,12 +524,12 @@ pub fn http_fetch(request: &mut Request, // nothing to do, since actual_response is a function on response // Subsubstep 3 - if (res.response_type == ResponseType::Opaque && - request.mode != RequestMode::NoCors) || - (res.response_type == ResponseType::OpaqueRedirect && - request.redirect_mode != RedirectMode::Manual) || - (res.url_list.len() > 1 && request.redirect_mode != RedirectMode::Follow) || - res.is_network_error() { + if (res.response_type == ResponseType::Opaque && request.mode != RequestMode::NoCors) || + (res.response_type == ResponseType::OpaqueRedirect && + request.redirect_mode != RedirectMode::Manual) || + (res.url_list.len() > 1 && request.redirect_mode != RedirectMode::Follow) || + res.is_network_error() + { return Response::network_error(NetworkError::Internal("Request failed".into())); } @@ -473,14 +542,14 @@ pub fn http_fetch(request: &mut Request, if response.is_none() { // Substep 1 if cors_preflight_flag { - let method_cache_match = cache.match_method(&*request, - request.method.clone()); + let method_cache_match = cache.match_method(&*request, request.method.clone()); - let method_mismatch = !method_cache_match && (!is_cors_safelisted_method(&request.method) || - request.use_cors_preflight); - let header_mismatch = request.headers.iter().any(|(name, value)| - !cache.match_header(&*request, &name) && !is_cors_safelisted_request_header(&name, &value) - ); + let method_mismatch = !method_cache_match && + (!is_cors_safelisted_method(&request.method) || request.use_cors_preflight); + let header_mismatch = request.headers.iter().any(|(name, value)| { + !cache.match_header(&*request, &name) && + !is_cors_safelisted_request_header(&name, &value) + }); // Sub-substep 1 if method_mismatch || header_mismatch { @@ -499,7 +568,12 @@ pub fn http_fetch(request: &mut Request, // Substep 3 let mut fetch_result = http_network_or_cache_fetch( - request, authentication_fetch_flag, cors_flag, done_chan, context); + request, + authentication_fetch_flag, + cors_flag, + done_chan, + context, + ); // Substep 4 if cors_flag && cors_check(&request, &fetch_result).is_err() { @@ -514,35 +588,52 @@ pub fn http_fetch(request: &mut Request, let mut response = response.unwrap(); // Step 5 - if response.actual_response().status.as_ref().map_or(false, is_redirect_status) { + if response + .actual_response() + .status + .as_ref() + .map_or(false, is_redirect_status) + { // Substep 1. - if response.actual_response().status.as_ref().map_or(true, |s| s.0 != StatusCode::SEE_OTHER) { + if response + .actual_response() + .status + .as_ref() + .map_or(true, |s| s.0 != StatusCode::SEE_OTHER) + { // TODO: send RST_STREAM frame } // Substep 2-3. - let location = response.actual_response().headers.get(header::LOCATION) - .and_then(|v| HeaderValue::to_str(v).map(|l| { - ServoUrl::parse_with_base(response.actual_response().url(), &l) - .map_err(|err| err.description().into()) - }).ok() - ); + let location = response + .actual_response() + .headers + .get(header::LOCATION) + .and_then(|v| { + HeaderValue::to_str(v) + .map(|l| { + ServoUrl::parse_with_base(response.actual_response().url(), &l) + .map_err(|err| err.description().into()) + }) + .ok() + }); // Substep 4. response.actual_response_mut().location_url = location; // Substep 5. response = match request.redirect_mode { - RedirectMode::Error => Response::network_error(NetworkError::Internal("Redirect mode error".into())), - RedirectMode::Manual => { - response.to_filtered(ResponseType::OpaqueRedirect) + RedirectMode::Error => { + Response::network_error(NetworkError::Internal("Redirect mode error".into())) }, + RedirectMode::Manual => response.to_filtered(ResponseType::OpaqueRedirect), RedirectMode::Follow => { // set back to default response.return_internal = true; - http_redirect_fetch(request, cache, response, - cors_flag, target, done_chan, context) - } + http_redirect_fetch( + request, cache, response, cors_flag, target, done_chan, context, + ) + }, }; } // set back to default @@ -552,14 +643,15 @@ pub fn http_fetch(request: &mut Request, } /// [HTTP redirect fetch](https://fetch.spec.whatwg.org#http-redirect-fetch) -pub fn http_redirect_fetch(request: &mut Request, - cache: &mut CorsCache, - response: Response, - cors_flag: bool, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext) - -> Response { +pub fn http_redirect_fetch( + request: &mut Request, + cache: &mut CorsCache, + response: Response, + cors_flag: bool, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext, +) -> Response { // Step 1 assert!(response.return_internal); @@ -568,12 +660,17 @@ pub fn http_redirect_fetch(request: &mut Request, // Step 2 None => return response, // Step 3 - Some(Err(err)) => - return Response::network_error( - NetworkError::Internal("Location URL parse failure: ".to_owned() + &err)), + Some(Err(err)) => { + return Response::network_error(NetworkError::Internal( + "Location URL parse failure: ".to_owned() + &err, + )) + }, // Step 4 - Some(Ok(ref url)) if !matches!(url.scheme(), "http" | "https") => - return Response::network_error(NetworkError::Internal("Location URL not an HTTP(S) scheme".into())), + Some(Ok(ref url)) if !matches!(url.scheme(), "http" | "https") => { + return Response::network_error(NetworkError::Internal( + "Location URL not an HTTP(S) scheme".into(), + )) + }, Some(Ok(url)) => url, }; @@ -588,12 +685,17 @@ pub fn http_redirect_fetch(request: &mut Request, // Step 7 let same_origin = match request.origin { Origin::Origin(ref origin) => *origin == location_url.origin(), - Origin::Client => panic!("Request origin should not be client for {}", request.current_url()), + Origin::Client => panic!( + "Request origin should not be client for {}", + request.current_url() + ), }; let has_credentials = has_credentials(&location_url); if request.mode == RequestMode::CorsMode && !same_origin && has_credentials { - return Response::network_error(NetworkError::Internal("Cross-origin credentials check failed".into())); + return Response::network_error(NetworkError::Internal( + "Cross-origin credentials check failed".into(), + )); } // Step 8 @@ -602,8 +704,13 @@ pub fn http_redirect_fetch(request: &mut Request, } // Step 9 - if response.actual_response().status.as_ref().map_or(true, |s| s.0 != StatusCode::SEE_OTHER) && - request.body.as_ref().map_or(false, |b| b.is_empty()) { + if response + .actual_response() + .status + .as_ref() + .map_or(true, |s| s.0 != StatusCode::SEE_OTHER) && + request.body.as_ref().map_or(false, |b| b.is_empty()) + { return Response::network_error(NetworkError::Internal("Request body is not done".into())); } @@ -613,9 +720,15 @@ pub fn http_redirect_fetch(request: &mut Request, } // Step 11 - if response.actual_response().status.as_ref().map_or(false, |(code, _)| - ((*code == StatusCode::MOVED_PERMANENTLY || *code == StatusCode::FOUND) && request.method == Method::POST) || - (*code == StatusCode::SEE_OTHER && request.method != Method::HEAD)) { + if response + .actual_response() + .status + .as_ref() + .map_or(false, |(code, _)| { + ((*code == StatusCode::MOVED_PERMANENTLY || *code == StatusCode::FOUND) && + request.method == Method::POST) || + (*code == StatusCode::SEE_OTHER && request.method != Method::HEAD) + }) { request.method = Method::GET; request.body = None; } @@ -634,31 +747,40 @@ pub fn http_redirect_fetch(request: &mut Request, // Step 15 let recursive_flag = request.redirect_mode != RedirectMode::Manual; - main_fetch(request, cache, cors_flag, recursive_flag, target, done_chan, context) + main_fetch( + request, + cache, + cors_flag, + recursive_flag, + target, + done_chan, + context, + ) } fn try_immutable_origin_to_hyper_origin(url_origin: &ImmutableOrigin) -> Option { match *url_origin { ImmutableOrigin::Opaque(_) => Some(HyperOrigin::NULL), - ImmutableOrigin::Tuple(ref scheme, ref host, ref port) => + ImmutableOrigin::Tuple(ref scheme, ref host, ref port) => { HyperOrigin::try_from_parts(&scheme, &host.to_string(), Some(port.clone())).ok() + }, } } /// [HTTP network or cache fetch](https://fetch.spec.whatwg.org#http-network-or-cache-fetch) -fn http_network_or_cache_fetch(request: &mut Request, - authentication_fetch_flag: bool, - cors_flag: bool, - done_chan: &mut DoneChannel, - context: &FetchContext) - -> Response { +fn http_network_or_cache_fetch( + request: &mut Request, + authentication_fetch_flag: bool, + cors_flag: bool, + done_chan: &mut DoneChannel, + context: &FetchContext, +) -> Response { // TODO: Implement Window enum for Request let request_has_no_window = true; // Step 2 let mut http_request; - let http_request = if request_has_no_window && - request.redirect_mode == RedirectMode::Error { + let http_request = if request_has_no_window && request.redirect_mode == RedirectMode::Error { request } else { // Step 3 @@ -670,42 +792,47 @@ fn http_network_or_cache_fetch(request: &mut Request, // Step 4 let credentials_flag = match http_request.credentials_mode { CredentialsMode::Include => true, - CredentialsMode::CredentialsSameOrigin if http_request.response_tainting == ResponseTainting::Basic - => true, - _ => false + CredentialsMode::CredentialsSameOrigin + if http_request.response_tainting == ResponseTainting::Basic => + { + true + }, + _ => false, }; let content_length_value = match http_request.body { - None => - match http_request.method { - // Step 6 - Method::POST | Method::PUT => - Some(0), - // Step 5 - _ => None - }, + None => match http_request.method { + // Step 6 + Method::POST | Method::PUT => Some(0), + // Step 5 + _ => None, + }, // Step 7 - Some(ref http_request_body) => Some(http_request_body.len() as u64) + Some(ref http_request_body) => Some(http_request_body.len() as u64), }; // Step 8 if let Some(content_length_value) = content_length_value { - http_request.headers.typed_insert(ContentLength(content_length_value)); + http_request + .headers + .typed_insert(ContentLength(content_length_value)); if http_request.keep_alive { // Step 9 TODO: needs request's client object } } - // Step 10 match http_request.referrer { Referrer::NoReferrer => (), - Referrer::ReferrerUrl(ref http_request_referrer) => - http_request.headers.typed_insert::(http_request_referrer.to_string().parse().unwrap()), + Referrer::ReferrerUrl(ref http_request_referrer) => http_request + .headers + .typed_insert::(http_request_referrer.to_string().parse().unwrap()), Referrer::Client => - // it should be impossible for referrer to be anything else during fetching - // https://fetch.spec.whatwg.org/#concept-request-referrer + // it should be impossible for referrer to be anything else during fetching + // https://fetch.spec.whatwg.org/#concept-request-referrer + { unreachable!() + }, }; // Step 11 @@ -721,7 +848,9 @@ fn http_network_or_cache_fetch(request: &mut Request, // Step 12 if !http_request.headers.contains_key(header::USER_AGENT) { let user_agent = context.user_agent.clone().into_owned(); - http_request.headers.typed_insert::(user_agent.parse().unwrap()); + http_request + .headers + .typed_insert::(user_agent.parse().unwrap()); } match http_request.cache_mode { @@ -732,7 +861,9 @@ fn http_network_or_cache_fetch(request: &mut Request, // Step 14 CacheMode::NoCache if !http_request.headers.contains_key(header::CACHE_CONTROL) => { - http_request.headers.typed_insert(CacheControl::new().with_max_age(Duration::from_secs(0))); + http_request + .headers + .typed_insert(CacheControl::new().with_max_age(Duration::from_secs(0))); }, // Step 15 @@ -744,19 +875,28 @@ fn http_network_or_cache_fetch(request: &mut Request, // Substep 2 if !http_request.headers.contains_key(header::CACHE_CONTROL) { - http_request.headers.typed_insert(CacheControl::new().with_no_cache()); + http_request + .headers + .typed_insert(CacheControl::new().with_no_cache()); } }, - _ => {} + _ => {}, } // Step 16 let current_url = http_request.current_url(); let host = Host::from( - format!("{}{}", current_url.host_str().unwrap(), - current_url.port().map(|v| format!(":{}", v)).unwrap_or("".into()) - ).parse::().unwrap() + format!( + "{}{}", + current_url.host_str().unwrap(), + current_url + .port() + .map(|v| format!(":{}", v)) + .unwrap_or("".into()) + ) + .parse::() + .unwrap(), ); http_request.headers.typed_insert(host); @@ -770,9 +910,11 @@ fn http_network_or_cache_fetch(request: &mut Request, // Substep 1 // 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(¤t_url, - &mut http_request.headers, - &context.state.cookie_jar); + set_request_cookies( + ¤t_url, + &mut http_request.headers, + &context.state.cookie_jar, + ); // Substep 2 if !http_request.headers.contains_key(header::AUTHORIZATION) { // Substep 3 @@ -790,7 +932,7 @@ fn http_network_or_cache_fetch(request: &mut Request, if has_credentials(¤t_url) { authorization_value = Some(Authorization::basic( current_url.username(), - current_url.password().unwrap_or("") + current_url.password().unwrap_or(""), )); } } @@ -816,21 +958,33 @@ fn http_network_or_cache_fetch(request: &mut Request, if let Some(response_from_cache) = http_cache.construct_response(&http_request, done_chan) { let response_headers = response_from_cache.response.headers.clone(); // Substep 1, 2, 3, 4 - let (cached_response, needs_revalidation) = match (http_request.cache_mode, &http_request.mode) { - (CacheMode::ForceCache, _) => (Some(response_from_cache.response), false), - (CacheMode::OnlyIfCached, &RequestMode::SameOrigin) => (Some(response_from_cache.response), false), - (CacheMode::OnlyIfCached, _) | (CacheMode::NoStore, _) | (CacheMode::Reload, _) => (None, false), - (_, _) => (Some(response_from_cache.response), response_from_cache.needs_validation) - }; + let (cached_response, needs_revalidation) = + match (http_request.cache_mode, &http_request.mode) { + (CacheMode::ForceCache, _) => (Some(response_from_cache.response), false), + (CacheMode::OnlyIfCached, &RequestMode::SameOrigin) => { + (Some(response_from_cache.response), false) + }, + (CacheMode::OnlyIfCached, _) | + (CacheMode::NoStore, _) | + (CacheMode::Reload, _) => (None, false), + (_, _) => ( + Some(response_from_cache.response), + response_from_cache.needs_validation, + ), + }; if needs_revalidation { revalidating_flag = true; // Substep 5 if let Some(http_date) = response_headers.typed_get::() { let http_date: SystemTime = http_date.into(); - http_request.headers.typed_insert(IfModifiedSince::from(http_date)); + http_request + .headers + .typed_insert(IfModifiedSince::from(http_date)); } if let Some(entity_tag) = response_headers.get(header::ETAG) { - http_request.headers.insert(header::IF_NONE_MATCH, entity_tag.clone()); + http_request + .headers + .insert(header::IF_NONE_MATCH, entity_tag.clone()); } } else { // Substep 6 @@ -845,8 +999,11 @@ fn http_network_or_cache_fetch(request: &mut Request, // We wait for the response in the cache to "finish", // with a body of either Done or Cancelled. loop { - match ch.1.recv() - .expect("HTTP cache should always send Done or Cancelled") { + match ch + .1 + .recv() + .expect("HTTP cache should always send Done or Cancelled") + { Data::Payload(_) => {}, Data::Done => break, // Return the full response as if it was initially cached as such. Data::Cancelled => { @@ -854,7 +1011,7 @@ fn http_network_or_cache_fetch(request: &mut Request, // Set response to None, which will trigger a network fetch below. *response = None; break; - } + }, } } } @@ -868,15 +1025,16 @@ fn http_network_or_cache_fetch(request: &mut Request, if response.is_none() { // Substep 1 if http_request.cache_mode == CacheMode::OnlyIfCached { - return Response::network_error( - NetworkError::Internal("Couldn't find response in cache".into())) + return Response::network_error(NetworkError::Internal( + "Couldn't find response in cache".into(), + )); } } // More Step 22 if response.is_none() { // Substep 2 - let forward_response = http_network_fetch(http_request, credentials_flag, - done_chan, context); + let forward_response = + http_network_fetch(http_request, credentials_flag, done_chan, context); // Substep 3 if let Some((200...399, _)) = forward_response.raw_status { if !http_request.method.is_safe() { @@ -886,7 +1044,12 @@ fn http_network_or_cache_fetch(request: &mut Request, } } // Substep 4 - if revalidating_flag && forward_response.status.as_ref().map_or(false, |s| s.0 == StatusCode::NOT_MODIFIED) { + if revalidating_flag && + forward_response + .status + .as_ref() + .map_or(false, |s| s.0 == StatusCode::NOT_MODIFIED) + { if let Ok(mut http_cache) = context.state.http_cache.write() { response = http_cache.refresh(&http_request, forward_response.clone(), done_chan); wait_for_cached_response(done_chan, &mut response); @@ -932,16 +1095,22 @@ fn http_network_or_cache_fetch(request: &mut Request, } // Substep 4 - response = http_network_or_cache_fetch(http_request, - true /* authentication flag */, - cors_flag, done_chan, context); + response = http_network_or_cache_fetch( + http_request, + true, /* authentication flag */ + cors_flag, + done_chan, + context, + ); } // Step 24 if let Some((StatusCode::PROXY_AUTHENTICATION_REQUIRED, _)) = response.status.as_ref() { // Step 1 if request_has_no_window { - return Response::network_error(NetworkError::Internal("Can't find Window object".into())); + return Response::network_error(NetworkError::Internal( + "Can't find Window object".into(), + )); } // Step 2 @@ -970,11 +1139,12 @@ fn http_network_or_cache_fetch(request: &mut Request, } /// [HTTP network fetch](https://fetch.spec.whatwg.org/#http-network-fetch) -fn http_network_fetch(request: &Request, - credentials_flag: bool, - done_chan: &mut DoneChannel, - context: &FetchContext) - -> Response { +fn http_network_fetch( + request: &Request, + credentials_flag: bool, + done_chan: &mut DoneChannel, + context: &FetchContext, +) -> Response { // Step 1 // nothing to do here, since credentials_flag is already a boolean @@ -990,21 +1160,27 @@ fn http_network_fetch(request: &Request, // Step 5 let url = request.current_url(); - let request_id = context.devtools_chan.as_ref().map(|_| { - uuid::Uuid::new_v4().simple().to_string() - }); + let request_id = context + .devtools_chan + .as_ref() + .map(|_| uuid::Uuid::new_v4().simple().to_string()); // XHR uses the default destination; other kinds of fetches (which haven't been implemented yet) // 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 response_future = obtain_response(&context.state.client, - &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 response_future = obtain_response( + &context.state.client, + &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; // This will only get the headers, the body is read later @@ -1021,8 +1197,14 @@ fn http_network_fetch(request: &Request, } let mut response = Response::new(url.clone()); - response.status = Some((res.status(), res.status().canonical_reason().unwrap_or("").into())); - response.raw_status = Some((res.status().as_u16(), res.status().canonical_reason().unwrap_or("").into())); + response.status = Some(( + res.status(), + res.status().canonical_reason().unwrap_or("").into(), + )); + response.raw_status = Some(( + res.status().as_u16(), + res.status().canonical_reason().unwrap_or("").into(), + )); response.headers = res.headers().clone(); response.referrer = request.referrer.to_url().cloned(); response.referrer_policy = request.referrer_policy.clone(); @@ -1032,16 +1214,19 @@ fn http_network_fetch(request: &Request, // We're about to spawn a future to be waited on here let (done_sender, done_receiver) = channel(); *done_chan = Some((done_sender.clone(), done_receiver)); - let meta = match response.metadata().expect("Response metadata should exist at this stage") { + let meta = match response + .metadata() + .expect("Response metadata should exist at this stage") + { FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_ + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, }; let devtools_sender = context.devtools_chan.clone(); let meta_status = meta.status.clone(); let meta_headers = meta.headers.clone(); let cancellation_listener = context.cancellation_listener.clone(); if cancellation_listener.lock().unwrap().cancelled() { - return Response::network_error(NetworkError::Internal("Fetch aborted".into())) + return Response::network_error(NetworkError::Internal("Fetch aborted".into())); } *res_body.lock().unwrap() = ResponseBody::Receiving(vec![]); @@ -1055,39 +1240,45 @@ fn http_network_fetch(request: &Request, // Send an HttpResponse message to devtools with the corresponding request_id if let Some(pipeline_id) = pipeline_id { send_response_to_devtools( - &sender, request_id.unwrap(), + &sender, + request_id.unwrap(), meta_headers.map(Serde::into_inner), meta_status, - pipeline_id); + pipeline_id, + ); } } let done_sender = done_sender.clone(); let done_sender2 = done_sender.clone(); - HANDLE.lock().unwrap().spawn(res.into_body().map_err(|_|()).fold(res_body, move |res_body, chunk| { - if cancellation_listener.lock().unwrap().cancelled() { - *res_body.lock().unwrap() = ResponseBody::Done(vec![]); - let _ = done_sender.send(Data::Cancelled); - return future::failed(()); - } - if let ResponseBody::Receiving(ref mut body) = *res_body.lock().unwrap() { - let bytes = chunk.into_bytes(); - body.extend_from_slice(&*bytes); - let _ = done_sender.send(Data::Payload(bytes.to_vec())); - } - future::ok(res_body) - }).and_then(move |res_body| { - let mut body = res_body.lock().unwrap(); - let completed_body = match *body { - ResponseBody::Receiving(ref mut body) => { - mem::replace(body, vec![]) - }, - _ => vec![], - }; - *body = ResponseBody::Done(completed_body); - let _ = done_sender2.send(Data::Done); - future::ok(()) - }).map_err(|_| ())); + HANDLE.lock().unwrap().spawn( + res.into_body() + .map_err(|_| ()) + .fold(res_body, move |res_body, chunk| { + if cancellation_listener.lock().unwrap().cancelled() { + *res_body.lock().unwrap() = ResponseBody::Done(vec![]); + let _ = done_sender.send(Data::Cancelled); + return future::failed(()); + } + if let ResponseBody::Receiving(ref mut body) = *res_body.lock().unwrap() { + let bytes = chunk.into_bytes(); + body.extend_from_slice(&*bytes); + let _ = done_sender.send(Data::Payload(bytes.to_vec())); + } + future::ok(res_body) + }) + .and_then(move |res_body| { + let mut body = res_body.lock().unwrap(); + let completed_body = match *body { + ResponseBody::Receiving(ref mut body) => mem::replace(body, vec![]), + _ => vec![], + }; + *body = ResponseBody::Done(completed_body); + let _ = done_sender2.send(Data::Done); + future::ok(()) + }) + .map_err(|_| ()), + ); // TODO these substeps aren't possible yet // Substep 1 @@ -1109,9 +1300,7 @@ fn http_network_fetch(request: &Request, // TODO this step if let Some(encoding) = response.headers.typed_get::() { if encoding.contains("gzip") { - } - - else if encoding.contains("compress") { + } else if encoding.contains("compress") { } }; @@ -1133,25 +1322,30 @@ fn http_network_fetch(request: &Request, // TODO these steps // Step 16 - // Substep 1 - // Substep 2 - // Sub-substep 1 - // Sub-substep 2 - // Sub-substep 3 - // Sub-substep 4 - // Substep 3 + // Substep 1 + // Substep 2 + // Sub-substep 1 + // Sub-substep 2 + // Sub-substep 3 + // Sub-substep 4 + // Substep 3 // Step 16 response } /// [CORS preflight fetch](https://fetch.spec.whatwg.org#cors-preflight-fetch) -fn cors_preflight_fetch(request: &Request, - cache: &mut CorsCache, - context: &FetchContext) - -> Response { +fn cors_preflight_fetch( + request: &Request, + cache: &mut CorsCache, + context: &FetchContext, +) -> Response { // Step 1 - let mut preflight = Request::new(request.current_url(), Some(request.origin.clone()), request.pipeline_id); + let mut preflight = Request::new( + request.current_url(), + Some(request.origin.clone()), + request.pipeline_id, + ); preflight.method = Method::OPTIONS; preflight.initiator = request.initiator.clone(); preflight.destination = request.destination.clone(); @@ -1160,11 +1354,15 @@ fn cors_preflight_fetch(request: &Request, preflight.referrer_policy = request.referrer_policy; // Step 2 - preflight.headers.typed_insert::( - AccessControlRequestMethod::from(request.method.clone())); + preflight + .headers + .typed_insert::(AccessControlRequestMethod::from( + request.method.clone(), + )); // Step 3 - let mut headers = request.headers + let mut headers = request + .headers .iter() .filter(|(name, value)| !is_cors_safelisted_request_header(&name, &value)) .map(|(name, _)| name.as_str()) @@ -1177,7 +1375,9 @@ fn cors_preflight_fetch(request: &Request, // Step 4 if !headers.is_empty() { - preflight.headers.typed_insert(AccessControlRequestHeaders::from_iter(headers)); + preflight + .headers + .typed_insert(AccessControlRequestHeaders::from_iter(headers)); } // Step 5 @@ -1185,24 +1385,42 @@ fn cors_preflight_fetch(request: &Request, // Step 6 if cors_check(&request, &response).is_ok() && - response.status.as_ref().map_or(false, |(status, _)| status.is_success()) { + response + .status + .as_ref() + .map_or(false, |(status, _)| status.is_success()) + { // Substep 1, 2 - let mut methods = if response.headers.contains_key(header::ACCESS_CONTROL_ALLOW_METHODS) { + let mut methods = if response + .headers + .contains_key(header::ACCESS_CONTROL_ALLOW_METHODS) + { match response.headers.typed_get::() { Some(methods) => methods.iter().collect(), // Substep 4 - None => return Response::network_error(NetworkError::Internal("CORS ACAM check failed".into())) + None => { + return Response::network_error(NetworkError::Internal( + "CORS ACAM check failed".into(), + )) + }, } } else { vec![] }; // Substep 3 - let header_names = if response.headers.contains_key(header::ACCESS_CONTROL_ALLOW_HEADERS) { + let header_names = if response + .headers + .contains_key(header::ACCESS_CONTROL_ALLOW_HEADERS) + { match response.headers.typed_get::() { Some(names) => names.iter().collect(), // Substep 4 - None => return Response::network_error(NetworkError::Internal("CORS ACAH check failed".into())) + None => { + return Response::network_error(NetworkError::Internal( + "CORS ACAH check failed".into(), + )) + }, } } else { vec![] @@ -1211,9 +1429,11 @@ fn cors_preflight_fetch(request: &Request, // Substep 5 if (methods.iter().any(|m| m.as_ref() == "*") || header_names.iter().any(|hn| hn.as_str() == "*")) && - request.credentials_mode == CredentialsMode::Include { - return Response::network_error( - NetworkError::Internal("CORS ACAH/ACAM and request credentials mode mismatch".into())); + request.credentials_mode == CredentialsMode::Include + { + return Response::network_error(NetworkError::Internal( + "CORS ACAH/ACAM and request credentials mode mismatch".into(), + )); } // Substep 6 @@ -1222,31 +1442,46 @@ fn cors_preflight_fetch(request: &Request, } // Substep 7 - debug!("CORS check: Allowed methods: {:?}, current method: {:?}", - methods, request.method); + debug!( + "CORS check: Allowed methods: {:?}, current method: {:?}", + methods, request.method + ); if methods.iter().all(|method| *method != request.method) && !is_cors_safelisted_method(&request.method) && - methods.iter().all(|m| m.as_ref() != "*") { - return Response::network_error(NetworkError::Internal("CORS method check failed".into())); + methods.iter().all(|m| m.as_ref() != "*") + { + return Response::network_error(NetworkError::Internal( + "CORS method check failed".into(), + )); } // Substep 8 - if request.headers.iter().any( - |(name, _)| name == header::AUTHORIZATION && - header_names.iter().all(|hn| hn != name)) { - return Response::network_error(NetworkError::Internal("CORS authorization check failed".into())); + if request.headers.iter().any(|(name, _)| { + name == header::AUTHORIZATION && header_names.iter().all(|hn| hn != name) + }) { + return Response::network_error(NetworkError::Internal( + "CORS authorization check failed".into(), + )); } // Substep 9 - debug!("CORS check: Allowed headers: {:?}, current headers: {:?}", header_names, request.headers); + debug!( + "CORS check: Allowed headers: {:?}, current headers: {:?}", + header_names, request.headers + ); let set: HashSet<&HeaderName> = HashSet::from_iter(header_names.iter()); - if request.headers.iter().any( - |(name, value)| !set.contains(name) && !is_cors_safelisted_request_header(&name, &value)) { - return Response::network_error(NetworkError::Internal("CORS headers check failed".into())); + if request.headers.iter().any(|(name, value)| { + !set.contains(name) && !is_cors_safelisted_request_header(&name, &value) + }) { + return Response::network_error(NetworkError::Internal( + "CORS headers check failed".into(), + )); } // Substep 10, 11 - let max_age: Duration = response.headers.typed_get::() + let max_age: Duration = response + .headers + .typed_get::() .map(|acma| acma.into()) .unwrap_or(Duration::from_secs(0)); let max_age = max_age.as_secs() as u32; @@ -1283,7 +1518,8 @@ fn cors_check(request: &Request, response: &Response) -> Result<(), ()> { // Step 3 if request.credentials_mode != CredentialsMode::Include && - origin == AccessControlAllowOrigin::ANY { + origin == AccessControlAllowOrigin::ANY + { return Ok(()); } @@ -1291,12 +1527,12 @@ fn cors_check(request: &Request, response: &Response) -> Result<(), ()> { let origin = match origin.origin() { Some(origin) => origin, // if it's Any or Null at this point, there's nothing to do but return Err(()) - None => return Err(()) + None => return Err(()), }; match request.origin { Origin::Origin(ref o) if o.ascii_serialization() == origin.to_string().trim() => {}, - _ => return Err(()) + _ => return Err(()), } // Step 5 @@ -1305,7 +1541,9 @@ fn cors_check(request: &Request, response: &Response) -> Result<(), ()> { } // Step 6 - let credentials = response.headers.typed_get::(); + let credentials = response + .headers + .typed_get::(); // Step 7 if credentials.is_some() { @@ -1321,9 +1559,11 @@ fn has_credentials(url: &ServoUrl) -> bool { } fn is_no_store_cache(headers: &HeaderMap) -> bool { - headers.contains_key(header::IF_MODIFIED_SINCE) | headers.contains_key(header::IF_NONE_MATCH) | - headers.contains_key(header::IF_UNMODIFIED_SINCE) | headers.contains_key(header::IF_MATCH) | - headers.contains_key(header::IF_RANGE) + headers.contains_key(header::IF_MODIFIED_SINCE) | + headers.contains_key(header::IF_NONE_MATCH) | + headers.contains_key(header::IF_UNMODIFIED_SINCE) | + headers.contains_key(header::IF_MATCH) | + headers.contains_key(header::IF_RANGE) } /// diff --git a/components/net/image_cache.rs b/components/net/image_cache.rs index ba0d679b0e3..4272bdcb6a3 100644 --- a/components/net/image_cache.rs +++ b/components/net/image_cache.rs @@ -37,39 +37,39 @@ fn decode_bytes_sync(key: LoadKey, bytes: &[u8]) -> DecoderMsg { let image = load_from_memory(bytes); DecoderMsg { key: key, - image: image + image: image, } } -fn get_placeholder_image(webrender_api: &webrender_api::RenderApi, data: &[u8]) -> io::Result> { +fn get_placeholder_image( + webrender_api: &webrender_api::RenderApi, + data: &[u8], +) -> io::Result> { let mut image = load_from_memory(&data).unwrap(); set_webrender_image_key(webrender_api, &mut image); Ok(Arc::new(image)) } fn set_webrender_image_key(webrender_api: &webrender_api::RenderApi, image: &mut Image) { - if image.id.is_some() { return; } + if image.id.is_some() { + return; + } let mut bytes = Vec::new(); let is_opaque = match image.format { PixelFormat::BGRA8 => { bytes.extend_from_slice(&*image.bytes); pixels::premultiply_inplace(bytes.as_mut_slice()) - } + }, PixelFormat::RGB8 => { for bgr in image.bytes.chunks(3) { - bytes.extend_from_slice(&[ - bgr[2], - bgr[1], - bgr[0], - 0xff - ]); + bytes.extend_from_slice(&[bgr[2], bgr[1], bgr[0], 0xff]); } true - } + }, PixelFormat::K8 | PixelFormat::KA8 => { panic!("Not support by webrender yet"); - } + }, }; let descriptor = webrender_api::ImageDescriptor { size: webrender_api::DeviceUintSize::new(image.width, image.height), @@ -121,20 +121,22 @@ impl AllPendingLoads { } fn remove(&mut self, key: &LoadKey) -> Option { - self.loads.remove(key). - and_then(|pending_load| { - self.url_to_load_key.remove(&pending_load.url).unwrap(); - Some(pending_load) - }) + self.loads.remove(key).and_then(|pending_load| { + self.url_to_load_key.remove(&pending_load.url).unwrap(); + Some(pending_load) + }) } - fn get_cached<'a>(&'a mut self, url: ServoUrl, can_request: CanRequestImages) - -> CacheResult<'a> { + fn get_cached<'a>( + &'a mut self, + url: ServoUrl, + can_request: CanRequestImages, + ) -> CacheResult<'a> { match self.url_to_load_key.entry(url.clone()) { Occupied(url_entry) => { let load_key = url_entry.get(); CacheResult::Hit(*load_key, self.loads.get_mut(load_key).unwrap()) - } + }, Vacant(url_entry) => { if can_request == CanRequestImages::No { return CacheResult::Miss(None); @@ -149,9 +151,9 @@ impl AllPendingLoads { Vacant(load_entry) => { let mut_load = load_entry.insert(pending_load); CacheResult::Miss(Some((load_key, mut_load))) - } + }, } - } + }, } } } @@ -226,14 +228,12 @@ impl ImageBytes { type LoadKey = PendingImageId; struct LoadKeyGenerator { - counter: u64 + counter: u64, } impl LoadKeyGenerator { fn new() -> LoadKeyGenerator { - LoadKeyGenerator { - counter: 0 - } + LoadKeyGenerator { counter: 0 } } fn next(&mut self) -> PendingImageId { self.counter += 1; @@ -244,7 +244,7 @@ impl LoadKeyGenerator { enum LoadResult { Loaded(Image), PlaceholderLoaded(Arc), - None + None, } /// Represents an image that is either being loaded @@ -271,10 +271,10 @@ struct PendingLoad { impl PendingLoad { fn new(url: ServoUrl) -> PendingLoad { PendingLoad { - bytes: ImageBytes::InProgress(vec!()), + bytes: ImageBytes::InProgress(vec![]), metadata: None, result: None, - listeners: vec!(), + listeners: vec![], url: url, final_url: None, } @@ -314,20 +314,24 @@ impl ImageCacheStore { }; match load_result { - LoadResult::Loaded(ref mut image) => set_webrender_image_key(&self.webrender_api, image), - LoadResult::PlaceholderLoaded(..) | LoadResult::None => {} + LoadResult::Loaded(ref mut image) => { + set_webrender_image_key(&self.webrender_api, image) + }, + LoadResult::PlaceholderLoaded(..) | LoadResult::None => {}, } let url = pending_load.final_url.clone(); let image_response = match load_result { LoadResult::Loaded(image) => ImageResponse::Loaded(Arc::new(image), url.unwrap()), - LoadResult::PlaceholderLoaded(image) => - ImageResponse::PlaceholderLoaded(image, self.placeholder_url.clone()), + LoadResult::PlaceholderLoaded(image) => { + ImageResponse::PlaceholderLoaded(image, self.placeholder_url.clone()) + }, LoadResult::None => ImageResponse::None, }; let completed_load = CompletedLoad::new(image_response.clone(), key); - self.completed_loads.insert(pending_load.url.into(), completed_load); + self.completed_loads + .insert(pending_load.url.into(), completed_load); for listener in pending_load.listeners { listener.respond(image_response.clone()); @@ -336,21 +340,20 @@ impl ImageCacheStore { /// Return a completed image if it exists, or None if there is no complete load /// or the complete load is not fully decoded or is unavailable. - fn get_completed_image_if_available(&self, - url: &ServoUrl, - placeholder: UsePlaceholder) - -> Option> { + fn get_completed_image_if_available( + &self, + url: &ServoUrl, + placeholder: UsePlaceholder, + ) -> Option> { self.completed_loads.get(url).map(|completed_load| { match (&completed_load.image_response, placeholder) { (&ImageResponse::Loaded(ref image, ref url), _) | - (&ImageResponse::PlaceholderLoaded(ref image, ref url), UsePlaceholder::Yes) => { - Ok(ImageOrMetadataAvailable::ImageAvailable(image.clone(), url.clone())) - } + (&ImageResponse::PlaceholderLoaded(ref image, ref url), UsePlaceholder::Yes) => Ok( + ImageOrMetadataAvailable::ImageAvailable(image.clone(), url.clone()), + ), (&ImageResponse::PlaceholderLoaded(_, _), UsePlaceholder::No) | (&ImageResponse::None, _) | - (&ImageResponse::MetadataLoaded(_), _) => { - Err(ImageState::LoadError) - } + (&ImageResponse::MetadataLoaded(_), _) => Err(ImageState::LoadError), } }) } @@ -383,18 +386,19 @@ impl ImageCache for ImageCacheImpl { placeholder_image: get_placeholder_image(&webrender_api, &rippy_data).ok(), placeholder_url: ServoUrl::parse("chrome://resources/rippy.png").unwrap(), webrender_api: webrender_api, - })) + })), } } /// Return any available metadata or image for the given URL, /// or an indication that the image is not yet available if it is in progress, /// or else reserve a slot in the cache for the URL if the consumer can request images. - fn find_image_or_metadata(&self, - url: ServoUrl, - use_placeholder: UsePlaceholder, - can_request: CanRequestImages) - -> Result { + fn find_image_or_metadata( + &self, + url: ServoUrl, + use_placeholder: UsePlaceholder, + can_request: CanRequestImages, + ) -> Result { debug!("Find image or metadata for {}", url); let mut store = self.store.lock().unwrap(); if let Some(result) = store.get_completed_image_if_available(&url, use_placeholder) { @@ -409,24 +413,24 @@ impl ImageCache for ImageCacheImpl { (&Some(Ok(_)), _) => { debug!("Sync decoding {} ({:?})", url, key); decode_bytes_sync(key, &pl.bytes.as_slice()) - } + }, (&None, &Some(ref meta)) => { debug!("Metadata available for {} ({:?})", url, key); - return Ok(ImageOrMetadataAvailable::MetadataAvailable(meta.clone())) - } + return Ok(ImageOrMetadataAvailable::MetadataAvailable(meta.clone())); + }, (&Some(Err(_)), _) | (&None, &None) => { debug!("{} ({:?}) is still pending", url, key); return Err(ImageState::Pending(key)); - } + }, }, CacheResult::Miss(Some((key, _pl))) => { debug!("Should be requesting {} ({:?})", url, key); return Err(ImageState::NotRequested(key)); - } + }, CacheResult::Miss(None) => { debug!("Couldn't find an entry for {}", url); return Err(ImageState::LoadError); - } + }, } }; @@ -468,17 +472,15 @@ impl ImageCache for ImageCacheImpl { let mut store = self.store.lock().unwrap(); let pending_load = store.pending_loads.get_by_key_mut(&id).unwrap(); let metadata = match response { - Ok(meta) => { - Some(match meta { - FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_, - }) - }, + Ok(meta) => Some(match meta { + FetchMetadata::Unfiltered(m) => m, + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, + }), Err(_) => None, }; let final_url = metadata.as_ref().map(|m| m.final_url.clone()); pending_load.final_url = final_url; - } + }, (FetchResponseMsg::ProcessResponseChunk(data), _) => { debug!("Got some data for {:?}", id); let mut store = self.store.lock().unwrap(); @@ -488,16 +490,17 @@ impl ImageCache for ImageCacheImpl { if let None = pending_load.metadata { if let Ok(metadata) = load_from_buf(&pending_load.bytes.as_slice()) { let dimensions = metadata.dimensions(); - let img_metadata = ImageMetadata { width: dimensions.width, - height: dimensions.height }; + let img_metadata = ImageMetadata { + width: dimensions.width, + height: dimensions.height, + }; for listener in &pending_load.listeners { - listener.respond( - ImageResponse::MetadataLoaded(img_metadata.clone())); + listener.respond(ImageResponse::MetadataLoaded(img_metadata.clone())); } pending_load.metadata = Some(img_metadata); } } - } + }, (FetchResponseMsg::ProcessResponseEOF(result), key) => { debug!("Received EOF for {:?}", key); match result { @@ -516,20 +519,20 @@ impl ImageCache for ImageCacheImpl { debug!("Image decoded"); local_store.lock().unwrap().handle_decoder(msg); }); - } + }, Err(_) => { debug!("Processing error for {:?}", key); let mut store = self.store.lock().unwrap(); match store.placeholder_image.clone() { - Some(placeholder_image) => { - store.complete_load( - id, LoadResult::PlaceholderLoaded(placeholder_image)) - } + Some(placeholder_image) => store.complete_load( + id, + LoadResult::PlaceholderLoaded(placeholder_image), + ), None => store.complete_load(id, LoadResult::None), } - } + }, } - } + }, } } diff --git a/components/net/lib.rs b/components/net/lib.rs index cebeb447aef..7f9714df07e 100644 --- a/components/net/lib.rs +++ b/components/net/lib.rs @@ -21,10 +21,14 @@ extern crate immeta; extern crate ipc_channel; #[macro_use] extern crate lazy_static; -#[macro_use] extern crate log; +#[macro_use] +extern crate log; extern crate malloc_size_of; -#[macro_use] extern crate malloc_size_of_derive; -#[macro_use] #[no_link] extern crate matches; +#[macro_use] +extern crate malloc_size_of_derive; +#[macro_use] +#[no_link] +extern crate matches; extern crate mime; extern crate mime_guess; extern crate msg; @@ -33,7 +37,8 @@ extern crate openssl; extern crate pixels; #[macro_use] extern crate profile_traits; -#[macro_use] extern crate serde; +#[macro_use] +extern crate serde; extern crate serde_json; extern crate servo_allocator; extern crate servo_arc; diff --git a/components/net/mime_classifier.rs b/components/net/mime_classifier.rs index 801f5bce9b3..7dd5b61bc97 100644 --- a/components/net/mime_classifier.rs +++ b/components/net/mime_classifier.rs @@ -25,16 +25,17 @@ pub enum MediaType { pub enum ApacheBugFlag { On, - Off + Off, } impl ApacheBugFlag { /// pub fn from_content_type(last_raw_content_type: &[u8]) -> ApacheBugFlag { - if last_raw_content_type == b"text/plain" - || last_raw_content_type == b"text/plain; charset=ISO-8859-1" - || last_raw_content_type == b"text/plain; charset=iso-8859-1" - || last_raw_content_type == b"text/plain; charset=UTF-8" { + if last_raw_content_type == b"text/plain" || + last_raw_content_type == b"text/plain; charset=ISO-8859-1" || + last_raw_content_type == b"text/plain; charset=iso-8859-1" || + last_raw_content_type == b"text/plain; charset=UTF-8" + { ApacheBugFlag::On } else { ApacheBugFlag::Off @@ -45,19 +46,22 @@ impl ApacheBugFlag { #[derive(PartialEq)] pub enum NoSniffFlag { On, - Off + Off, } - impl MimeClassifier { //Performs MIME Type Sniffing Algorithm (sections 7 and 8) - pub fn classify<'a>(&'a self, - context: LoadContext, - no_sniff_flag: NoSniffFlag, - apache_bug_flag: ApacheBugFlag, - supplied_type: &Option, - data: &'a [u8]) -> Mime { - let supplied_type_or_octet_stream = supplied_type.clone().unwrap_or(mime::APPLICATION_OCTET_STREAM); + pub fn classify<'a>( + &'a self, + context: LoadContext, + no_sniff_flag: NoSniffFlag, + apache_bug_flag: ApacheBugFlag, + supplied_type: &Option, + data: &'a [u8], + ) -> Mime { + let supplied_type_or_octet_stream = supplied_type + .clone() + .unwrap_or(mime::APPLICATION_OCTET_STREAM); match context { LoadContext::Browsing => match *supplied_type { None => self.sniff_unknown_type(no_sniff_flag, data), @@ -69,30 +73,41 @@ impl MimeClassifier { NoSniffFlag::On => supplied_type.clone(), NoSniffFlag::Off => match apache_bug_flag { ApacheBugFlag::On => self.sniff_text_or_data(data), - ApacheBugFlag::Off => match MimeClassifier::get_media_type(supplied_type) { - Some(MediaType::Html) => self.feeds_classifier.classify(data), - Some(MediaType::Image) => self.image_classifier.classify(data), - Some(MediaType::AudioVideo) => self.audio_video_classifier.classify(data), - Some(MediaType::Xml) | None => None, - }.unwrap_or(supplied_type.clone()) - } + ApacheBugFlag::Off => { + match MimeClassifier::get_media_type(supplied_type) { + Some(MediaType::Html) => { + self.feeds_classifier.classify(data) + }, + Some(MediaType::Image) => { + self.image_classifier.classify(data) + }, + Some(MediaType::AudioVideo) => { + self.audio_video_classifier.classify(data) + }, + Some(MediaType::Xml) | None => None, + } + .unwrap_or(supplied_type.clone()) + }, + }, } } - } + }, }, LoadContext::Image => { // Section 8.2 Sniffing an image context match MimeClassifier::maybe_get_media_type(supplied_type) { Some(MediaType::Xml) => None, _ => self.image_classifier.classify(data), - }.unwrap_or(supplied_type_or_octet_stream) + } + .unwrap_or(supplied_type_or_octet_stream) }, LoadContext::AudioVideo => { // Section 8.3 Sniffing an image context match MimeClassifier::maybe_get_media_type(supplied_type) { Some(MediaType::Xml) => None, _ => self.audio_video_classifier.classify(data), - }.unwrap_or(supplied_type_or_octet_stream) + } + .unwrap_or(supplied_type_or_octet_stream) }, LoadContext::Plugin => { // 8.4 Sniffing in a plugin context @@ -129,7 +144,8 @@ impl MimeClassifier { match MimeClassifier::maybe_get_media_type(supplied_type) { Some(MediaType::Xml) => None, _ => self.font_classifier.classify(data), - }.unwrap_or(supplied_type_or_octet_stream) + } + .unwrap_or(supplied_type_or_octet_stream) }, LoadContext::TextTrack => { // 8.8 Sniffing in a text track context @@ -149,16 +165,16 @@ impl MimeClassifier { } pub fn new() -> MimeClassifier { - MimeClassifier { - image_classifier: GroupedClassifier::image_classifer(), - audio_video_classifier: GroupedClassifier::audio_video_classifier(), - scriptable_classifier: GroupedClassifier::scriptable_classifier(), - plaintext_classifier: GroupedClassifier::plaintext_classifier(), - archive_classifier: GroupedClassifier::archive_classifier(), - binary_or_plaintext: BinaryOrPlaintextClassifier, - feeds_classifier: FeedsClassifier, - font_classifier: GroupedClassifier::font_classifier() - } + MimeClassifier { + image_classifier: GroupedClassifier::image_classifer(), + audio_video_classifier: GroupedClassifier::audio_video_classifier(), + scriptable_classifier: GroupedClassifier::scriptable_classifier(), + plaintext_classifier: GroupedClassifier::plaintext_classifier(), + archive_classifier: GroupedClassifier::archive_classifier(), + binary_or_plaintext: BinaryOrPlaintextClassifier, + feeds_classifier: FeedsClassifier, + font_classifier: GroupedClassifier::font_classifier(), + } } pub fn validate(&self) -> Result<(), String> { @@ -182,7 +198,8 @@ impl MimeClassifier { None }; - sniffed.or_else(|| self.plaintext_classifier.classify(data)) + sniffed + .or_else(|| self.plaintext_classifier.classify(data)) .or_else(|| self.image_classifier.classify(data)) .or_else(|| self.audio_video_classifier.classify(data)) .or_else(|| self.archive_classifier.classify(data)) @@ -191,13 +208,15 @@ impl MimeClassifier { } fn sniff_text_or_data<'a>(&'a self, data: &'a [u8]) -> Mime { - self.binary_or_plaintext.classify(data).expect("BinaryOrPlaintextClassifier always succeeds") + self.binary_or_plaintext + .classify(data) + .expect("BinaryOrPlaintextClassifier always succeeds") } fn is_xml(mt: &Mime) -> bool { mt.suffix() == Some(mime::XML) || - (mt.type_() == mime::APPLICATION && mt.subtype() == mime::XML) || - (mt.type_() == mime::TEXT && mt.subtype() == mime::XML) + (mt.type_() == mime::APPLICATION && mt.subtype() == mime::XML) || + (mt.type_() == mime::TEXT && mt.subtype() == mime::XML) } fn is_html(mt: &Mime) -> bool { @@ -210,21 +229,21 @@ impl MimeClassifier { fn is_audio_video(mt: &Mime) -> bool { mt.type_() == mime::AUDIO || - mt.type_() == mime::VIDEO || - mt.type_() == mime::APPLICATION && mt.subtype() == mime::OGG + mt.type_() == mime::VIDEO || + mt.type_() == mime::APPLICATION && mt.subtype() == mime::OGG } fn is_explicit_unknown(mt: &Mime) -> bool { mt.type_().as_str() == "unknown" && mt.subtype().as_str() == "unknown" || - mt.type_() == mime::APPLICATION && mt.subtype().as_str() == "unknown" || - mt.type_() == mime::STAR && mt.subtype() == mime::STAR + mt.type_() == mime::APPLICATION && mt.subtype().as_str() == "unknown" || + mt.type_() == mime::STAR && mt.subtype() == mime::STAR } fn get_media_type(mime: &Mime) -> Option { if MimeClassifier::is_xml(&mime) { Some(MediaType::Xml) } else if MimeClassifier::is_html(&mime) { - Some(MediaType::Html) + Some(MediaType::Html) } else if MimeClassifier::is_image(&mime) { Some(MediaType::Image) } else if MimeClassifier::is_audio_video(&mime) { @@ -235,9 +254,9 @@ impl MimeClassifier { } fn maybe_get_media_type(supplied_type: &Option) -> Option { - supplied_type.as_ref().and_then(|ref mime| { - MimeClassifier::get_media_type(mime) - }) + supplied_type + .as_ref() + .and_then(|ref mime| MimeClassifier::get_media_type(mime)) } } @@ -252,7 +271,7 @@ trait Matches { fn matches(&mut self, matches: &[u8]) -> bool; } -impl <'a, T: Iterator + Clone> Matches for T { +impl<'a, T: Iterator + Clone> Matches for T { // Matching function that works on an iterator. // see if the next matches.len() bytes in data_iterator equal matches // move iterator and return true or just return false @@ -270,7 +289,7 @@ impl <'a, T: Iterator + Clone> Matches for T { fn matches(&mut self, matches: &[u8]) -> bool { if self.clone().nth(matches.len()).is_none() { // there are less than matches.len() elements in self - return false + return false; } let result = self.clone().zip(matches).all(|(s, m)| *s == *m); if result { @@ -294,64 +313,68 @@ impl ByteMatcher { } else if data == self.pattern { Some(self.pattern.len()) } else { - data[..data.len() - self.pattern.len() + 1].iter() + data[..data.len() - self.pattern.len() + 1] + .iter() .position(|x| !self.leading_ignore.contains(x)) - .and_then(|start| - if data[start..].iter() - .zip(self.pattern.iter()).zip(self.mask.iter()) - .all(|((&data, &pattern), &mask)| (data & mask) == pattern) { + .and_then(|start| { + if data[start..] + .iter() + .zip(self.pattern.iter()) + .zip(self.mask.iter()) + .all(|((&data, &pattern), &mask)| (data & mask) == pattern) + { Some(start + self.pattern.len()) } else { None - }) + } + }) } } } impl MIMEChecker for ByteMatcher { fn classify(&self, data: &[u8]) -> Option { - self.matches(data).map(|_| { - self.content_type.clone() - }) + self.matches(data).map(|_| self.content_type.clone()) } fn validate(&self) -> Result<(), String> { if self.pattern.len() == 0 { - return Err(format!( - "Zero length pattern for {:?}", - self.content_type - )) + return Err(format!("Zero length pattern for {:?}", self.content_type)); } if self.pattern.len() != self.mask.len() { return Err(format!( "Unequal pattern and mask length for {:?}", self.content_type - )) + )); } - if self.pattern.iter().zip(self.mask.iter()).any( - |(&pattern, &mask)| pattern & mask != pattern - ) { + if self + .pattern + .iter() + .zip(self.mask.iter()) + .any(|(&pattern, &mask)| pattern & mask != pattern) + { return Err(format!( "Pattern not pre-masked for {:?}", self.content_type - )) + )); } Ok(()) } } struct TagTerminatedByteMatcher { - matcher: ByteMatcher + matcher: ByteMatcher, } impl MIMEChecker for TagTerminatedByteMatcher { fn classify(&self, data: &[u8]) -> Option { - self.matcher.matches(data).and_then(|j| + self.matcher.matches(data).and_then(|j| { if j < data.len() && (data[j] == b' ' || data[j] == b'>') { Some(self.matcher.content_type.clone()) } else { None - }) + } + }) } fn validate(&self) -> Result<(), String> { @@ -367,8 +390,10 @@ impl Mp4Matcher { return false; } - let box_size = ((data[0] as u32) << 24 | (data[1] as u32) << 16 | - (data[2] as u32) << 8 | (data[3] as u32)) as usize; + let box_size = ((data[0] as u32) << 24 | + (data[1] as u32) << 16 | + (data[2] as u32) << 8 | + (data[3] as u32)) as usize; if (data.len() < box_size) || (box_size % 4 != 0) { return false; } @@ -380,9 +405,10 @@ impl Mp4Matcher { let mp4 = [0x6D, 0x70, 0x34]; data[8..].starts_with(&mp4) || - data[16..box_size].chunks(4).any(|chunk| chunk.starts_with(&mp4)) + data[16..box_size] + .chunks(4) + .any(|chunk| chunk.starts_with(&mp4)) } - } impl MIMEChecker for Mp4Matcher { fn classify(&self, data: &[u8]) -> Option { @@ -403,14 +429,16 @@ struct BinaryOrPlaintextClassifier; impl BinaryOrPlaintextClassifier { fn classify_impl(&self, data: &[u8]) -> Mime { if data.starts_with(&[0xFFu8, 0xFEu8]) || - data.starts_with(&[0xFEu8, 0xFFu8]) || - data.starts_with(&[0xEFu8, 0xBBu8, 0xBFu8]) + data.starts_with(&[0xFEu8, 0xFFu8]) || + data.starts_with(&[0xEFu8, 0xBBu8, 0xBFu8]) { mime::TEXT_PLAIN - } else if data.iter().any(|&x| x <= 0x08u8 || - x == 0x0Bu8 || - (x >= 0x0Eu8 && x <= 0x1Au8) || - (x >= 0x1Cu8 && x <= 0x1Fu8)) { + } else if data.iter().any(|&x| { + x <= 0x08u8 || + x == 0x0Bu8 || + (x >= 0x0Eu8 && x <= 0x1Au8) || + (x >= 0x1Cu8 && x <= 0x1Fu8) + }) { mime::APPLICATION_OCTET_STREAM } else { mime::TEXT_PLAIN @@ -425,7 +453,6 @@ impl MIMEChecker for BinaryOrPlaintextClassifier { fn validate(&self) -> Result<(), String> { Ok(()) } - } struct GroupedClassifier { byte_matchers: Vec>, @@ -442,7 +469,7 @@ impl GroupedClassifier { Box::new(ByteMatcher::image_webp()), Box::new(ByteMatcher::image_png()), Box::new(ByteMatcher::image_jpeg()), - ] + ], } } fn audio_video_classifier() -> GroupedClassifier { @@ -456,8 +483,8 @@ impl GroupedClassifier { Box::new(ByteMatcher::audio_midi()), Box::new(ByteMatcher::video_avi()), Box::new(ByteMatcher::audio_wave()), - Box::new(Mp4Matcher) - ] + Box::new(Mp4Matcher), + ], } } fn scriptable_classifier() -> GroupedClassifier { @@ -481,8 +508,8 @@ impl GroupedClassifier { Box::new(ByteMatcher::text_html_p()), Box::new(ByteMatcher::text_html_comment()), Box::new(ByteMatcher::text_xml()), - Box::new(ByteMatcher::application_pdf()) - ] + Box::new(ByteMatcher::application_pdf()), + ], } } fn plaintext_classifier() -> GroupedClassifier { @@ -491,8 +518,8 @@ impl GroupedClassifier { Box::new(ByteMatcher::text_plain_utf_8_bom()), Box::new(ByteMatcher::text_plain_utf_16le_bom()), Box::new(ByteMatcher::text_plain_utf_16be_bom()), - Box::new(ByteMatcher::application_postscript()) - ] + Box::new(ByteMatcher::application_postscript()), + ], } } fn archive_classifier() -> GroupedClassifier { @@ -500,8 +527,8 @@ impl GroupedClassifier { byte_matchers: vec![ Box::new(ByteMatcher::application_x_gzip()), Box::new(ByteMatcher::application_zip()), - Box::new(ByteMatcher::application_x_rar_compressed()) - ] + Box::new(ByteMatcher::application_x_rar_compressed()), + ], } } @@ -513,7 +540,7 @@ impl GroupedClassifier { Box::new(ByteMatcher::open_type()), Box::new(ByteMatcher::true_type()), Box::new(ByteMatcher::application_vnd_ms_font_object()), - ] + ], } } } @@ -536,7 +563,7 @@ impl MIMEChecker for GroupedClassifier { enum Match { Start, DidNotMatch, - StartAndEnd + StartAndEnd, } impl Match { @@ -549,7 +576,9 @@ impl Match { } fn eats_until<'a, T>(matcher: &mut T, start: &[u8], end: &[u8]) -> Match -where T: Iterator + Clone { +where + T: Iterator + Clone, +{ if !matcher.matches(start) { Match::DidNotMatch } else if end.len() == 1 { @@ -593,11 +622,12 @@ impl FeedsClassifier { // Steps 5.2.1 to 5.2.4 match eats_until(&mut matcher, b"?", b"?>") - .chain(|| eats_until(&mut matcher, b"!--", b"-->")) - .chain(|| eats_until(&mut matcher, b"!", b">")) { + .chain(|| eats_until(&mut matcher, b"!--", b"-->")) + .chain(|| eats_until(&mut matcher, b"!", b">")) + { Match::StartAndEnd => continue, Match::DidNotMatch => {}, - Match::Start => return None + Match::Start => return None, } // Step 5.2.5 @@ -611,15 +641,21 @@ impl FeedsClassifier { // Step 5.2.7 if matcher.matches(b"rdf:RDF") { while matcher.next().is_some() { - match eats_until(&mut matcher, - b"http://purl.org/rss/1.0/", - b"http://www.w3.org/1999/02/22-rdf-syntax-ns#") - .chain(|| eats_until(&mut matcher, - b"http://www.w3.org/1999/02/22-rdf-syntax-ns#", - b"http://purl.org/rss/1.0/")) { + match eats_until( + &mut matcher, + b"http://purl.org/rss/1.0/", + b"http://www.w3.org/1999/02/22-rdf-syntax-ns#", + ) + .chain(|| { + eats_until( + &mut matcher, + b"http://www.w3.org/1999/02/22-rdf-syntax-ns#", + b"http://purl.org/rss/1.0/", + ) + }) { Match::StartAndEnd => return Some("application/rss+xml".parse().unwrap()), Match::DidNotMatch => {}, - Match::Start => return None + Match::Start => return None, } } return None; @@ -630,7 +666,7 @@ impl FeedsClassifier { impl MIMEChecker for FeedsClassifier { fn classify(&self, data: &[u8]) -> Option { - self.classify_impl(data) + self.classify_impl(data) } fn validate(&self) -> Result<(), String> { @@ -647,7 +683,7 @@ impl ByteMatcher { pattern: b"\x00\x00\x01\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: "image/x-icon".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //A Windows Cursor signature. @@ -656,7 +692,7 @@ impl ByteMatcher { pattern: b"\x00\x00\x02\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: "image/x-icon".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string "BM", a BMP signature. @@ -665,7 +701,7 @@ impl ByteMatcher { pattern: b"BM", mask: b"\xFF\xFF", content_type: mime::IMAGE_BMP, - leading_ignore: &[] + leading_ignore: &[], } } //The string "GIF89a", a GIF signature. @@ -674,7 +710,7 @@ impl ByteMatcher { pattern: b"GIF89a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", content_type: mime::IMAGE_GIF, - leading_ignore: &[] + leading_ignore: &[], } } //The string "GIF87a", a GIF signature. @@ -683,7 +719,7 @@ impl ByteMatcher { pattern: b"GIF87a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", content_type: mime::IMAGE_GIF, - leading_ignore: &[] + leading_ignore: &[], } } //The string "RIFF" followed by four bytes followed by the string "WEBPVP". @@ -692,7 +728,7 @@ impl ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WEBPVP", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF", content_type: "image/webp".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //An error-checking byte followed by the string "PNG" followed by CR LF SUB LF, the PNG @@ -702,7 +738,7 @@ impl ByteMatcher { pattern: b"\x89PNG\r\n\x1A\n", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: mime::IMAGE_PNG, - leading_ignore: &[] + leading_ignore: &[], } } // The JPEG Start of Image marker followed by the indicator byte of another marker. @@ -711,7 +747,7 @@ impl ByteMatcher { pattern: b"\xFF\xD8\xFF", mask: b"\xFF\xFF\xFF", content_type: mime::IMAGE_JPEG, - leading_ignore: &[] + leading_ignore: &[], } } //The WebM signature. [TODO: Use more bytes?] @@ -720,7 +756,7 @@ impl ByteMatcher { pattern: b"\x1A\x45\xDF\xA3", mask: b"\xFF\xFF\xFF\xFF", content_type: "video/webm".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string ".snd", the basic audio signature. @@ -729,16 +765,16 @@ impl ByteMatcher { pattern: b".snd", mask: b"\xFF\xFF\xFF\xFF", content_type: "audio/basic".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string "FORM" followed by four bytes followed by the string "AIFF", the AIFF signature. fn audio_aiff() -> ByteMatcher { ByteMatcher { - pattern: b"FORM\x00\x00\x00\x00AIFF", - mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", + pattern: b"FORM\x00\x00\x00\x00AIFF", + mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: "audio/aiff".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string "ID3", the ID3v2-tagged MP3 signature. @@ -747,7 +783,7 @@ impl ByteMatcher { pattern: b"ID3", mask: b"\xFF\xFF\xFF", content_type: "audio/mpeg".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string "OggS" followed by NUL, the Ogg container signature. @@ -756,7 +792,7 @@ impl ByteMatcher { pattern: b"OggS\x00", mask: b"\xFF\xFF\xFF\xFF\xFF", content_type: "application/ogg".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string "MThd" followed by four bytes representing the number 6 in 32 bits (big-endian), @@ -766,7 +802,7 @@ impl ByteMatcher { pattern: b"MThd\x00\x00\x00\x06", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: "audio/midi".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } //The string "RIFF" followed by four bytes followed by the string "AVI ", the AVI signature. @@ -775,7 +811,7 @@ impl ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00AVI ", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: "video/avi".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } // The string "RIFF" followed by four bytes followed by the string "WAVE", the WAVE signature. @@ -784,7 +820,7 @@ impl ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WAVE", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: "audio/wave".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } // doctype terminated with Tag terminating (TT) Byte @@ -794,8 +830,8 @@ impl ByteMatcher { pattern: b" TagTerminatedByteMatcher { - TagTerminatedByteMatcher { + TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b" TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { - pattern: b" ByteMatcher { ByteMatcher { pattern: b"%!PS-Adobe-", - mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: "application/postscript".parse().unwrap(), - leading_ignore: &[] + leading_ignore: &[], } } // UTF-16BE BOM @@ -1100,7 +1136,7 @@ impl ByteMatcher { pattern: b"\xFE\xFF\x00\x00", mask: b"\xFF\xFF\x00\x00", content_type: mime::TEXT_PLAIN, - leading_ignore: &[] + leading_ignore: &[], } } //UTF-16LE BOM @@ -1109,7 +1145,7 @@ impl ByteMatcher { pattern: b"\xFF\xFE\x00\x00", mask: b"\xFF\xFF\x00\x00", content_type: mime::TEXT_PLAIN, - leading_ignore: &[] + leading_ignore: &[], } } //UTF-8 BOM @@ -1118,7 +1154,7 @@ impl ByteMatcher { pattern: b"\xEF\xBB\xBF\x00", mask: b"\xFF\xFF\xFF\x00", content_type: mime::TEXT_PLAIN, - leading_ignore: &[] + leading_ignore: &[], } } } diff --git a/components/net/resource_thread.rs b/components/net/resource_thread.rs index 74a18760cb0..8c0a1652778 100644 --- a/components/net/resource_thread.rs +++ b/components/net/resource_thread.rs @@ -48,59 +48,65 @@ use storage_thread::StorageThreadFactory; use websocket_loader; /// Returns a tuple of (public, private) senders to the new threads. -pub fn new_resource_threads(user_agent: Cow<'static, str>, - devtools_chan: Option>, - time_profiler_chan: ProfilerChan, - mem_profiler_chan: MemProfilerChan, - embedder_proxy: EmbedderProxy, - config_dir: Option) - -> (ResourceThreads, ResourceThreads) { +pub fn new_resource_threads( + user_agent: Cow<'static, str>, + devtools_chan: Option>, + time_profiler_chan: ProfilerChan, + mem_profiler_chan: MemProfilerChan, + embedder_proxy: EmbedderProxy, + config_dir: Option, +) -> (ResourceThreads, ResourceThreads) { let (public_core, private_core) = new_core_resource_thread( user_agent, devtools_chan, time_profiler_chan, mem_profiler_chan, embedder_proxy, - config_dir.clone()); + config_dir.clone(), + ); let storage: IpcSender = StorageThreadFactory::new(config_dir); - (ResourceThreads::new(public_core, storage.clone()), - ResourceThreads::new(private_core, storage)) + ( + ResourceThreads::new(public_core, storage.clone()), + ResourceThreads::new(private_core, storage), + ) } - /// Create a CoreResourceThread -pub fn new_core_resource_thread(user_agent: Cow<'static, str>, - devtools_chan: Option>, - time_profiler_chan: ProfilerChan, - mem_profiler_chan: MemProfilerChan, - embedder_proxy: EmbedderProxy, - config_dir: Option) - -> (CoreResourceThread, CoreResourceThread) { +pub fn new_core_resource_thread( + user_agent: Cow<'static, str>, + devtools_chan: Option>, + time_profiler_chan: ProfilerChan, + mem_profiler_chan: MemProfilerChan, + embedder_proxy: EmbedderProxy, + config_dir: Option, +) -> (CoreResourceThread, CoreResourceThread) { let (public_setup_chan, public_setup_port) = ipc::channel().unwrap(); let (private_setup_chan, private_setup_port) = ipc::channel().unwrap(); let (report_chan, report_port) = ipc::channel().unwrap(); - thread::Builder::new().name("ResourceManager".to_owned()).spawn(move || { - let resource_manager = CoreResourceManager::new( - user_agent, devtools_chan, time_profiler_chan, embedder_proxy - ); + thread::Builder::new() + .name("ResourceManager".to_owned()) + .spawn(move || { + let resource_manager = CoreResourceManager::new( + user_agent, + devtools_chan, + time_profiler_chan, + embedder_proxy, + ); - let mut channel_manager = ResourceChannelManager { - resource_manager: resource_manager, - config_dir: config_dir, - }; + let mut channel_manager = ResourceChannelManager { + resource_manager: resource_manager, + config_dir: config_dir, + }; - mem_profiler_chan.run_with_memory_reporting(|| ( - channel_manager.start( - public_setup_port, - private_setup_port, - report_port) - ), - String::from("network-cache-reporter"), - report_chan, - |report_chan| report_chan); - - }).expect("Thread spawning failed"); + mem_profiler_chan.run_with_memory_reporting( + || (channel_manager.start(public_setup_port, private_setup_port, report_port)), + String::from("network-cache-reporter"), + report_chan, + |report_chan| report_chan, + ); + }) + .expect("Thread spawning failed"); (public_setup_chan, private_setup_chan) } @@ -121,12 +127,8 @@ fn create_http_states(config_dir: Option<&Path>) -> (Arc, Arc { - fs::read_to_string(path).expect("Couldn't not find certificate file") - } - None => { - resources::read_string(Resource::SSLCertificates) - }, + Some(ref path) => fs::read_to_string(path).expect("Couldn't not find certificate file"), + None => resources::read_string(Resource::SSLCertificates), }; let ssl_connector_builder = create_ssl_connector_builder(&certs); @@ -147,10 +149,12 @@ fn create_http_states(config_dir: Option<&Path>) -> (Arc, Arc, - private_receiver: IpcReceiver, - memory_reporter: IpcReceiver) { + fn start( + &mut self, + public_receiver: IpcReceiver, + private_receiver: IpcReceiver, + memory_reporter: IpcReceiver, + ) { let (public_http_state, private_http_state) = create_http_states(self.config_dir.as_ref().map(Deref::deref)); @@ -164,7 +168,7 @@ impl ResourceChannelManager { // Handles case where profiler thread shuts down before resource thread. match receiver { ipc::IpcSelectionResult::ChannelClosed(..) => continue, - _ => {} + _ => {}, } let (id, data) = receiver.unwrap(); // If message is memory report, get the size_of of public and private http caches @@ -190,10 +194,12 @@ impl ResourceChannelManager { } } - fn process_report(&mut self, - msg: ReportsChan, - public_http_state: &Arc, - private_http_state: &Arc) { + fn process_report( + &mut self, + msg: ReportsChan, + public_http_state: &Arc, + private_http_state: &Arc, + ) { let mut ops = MallocSizeOfOps::new(servo_allocator::usable_size, None, None); let public_cache = public_http_state.http_cache.read().unwrap(); let private_cache = private_http_state.http_cache.read().unwrap(); @@ -201,74 +207,95 @@ impl ResourceChannelManager { let public_report = Report { path: path!["memory-cache", "public"], kind: ReportKind::ExplicitJemallocHeapSize, - size: public_cache.size_of(&mut ops) + size: public_cache.size_of(&mut ops), }; let private_report = Report { path: path!["memory-cache", "private"], kind: ReportKind::ExplicitJemallocHeapSize, - size: private_cache.size_of(&mut ops) + size: private_cache.size_of(&mut ops), }; - msg.send(vec!(public_report, private_report)); + msg.send(vec![public_report, private_report]); } /// Returns false if the thread should exit. - fn process_msg(&mut self, - msg: CoreResourceMsg, - http_state: &Arc) -> bool { + fn process_msg(&mut self, msg: CoreResourceMsg, http_state: &Arc) -> bool { match msg { - CoreResourceMsg::Fetch(req_init, channels) => { - match channels { - FetchChannels::ResponseMsg(sender, cancel_chan) => - self.resource_manager.fetch(req_init, None, sender, http_state, cancel_chan), - FetchChannels::WebSocket { event_sender, action_receiver } => - self.resource_manager.websocket_connect(req_init, event_sender, action_receiver, http_state), - } - } - CoreResourceMsg::FetchRedirect(req_init, res_init, sender, cancel_chan) => - self.resource_manager.fetch(req_init, Some(res_init), sender, http_state, cancel_chan), - CoreResourceMsg::SetCookieForUrl(request, cookie, source) => - self.resource_manager.set_cookie_for_url(&request, cookie.into_inner(), source, http_state), + CoreResourceMsg::Fetch(req_init, channels) => match channels { + FetchChannels::ResponseMsg(sender, cancel_chan) => { + self.resource_manager + .fetch(req_init, None, sender, http_state, cancel_chan) + }, + FetchChannels::WebSocket { + event_sender, + action_receiver, + } => self.resource_manager.websocket_connect( + req_init, + event_sender, + action_receiver, + http_state, + ), + }, + CoreResourceMsg::FetchRedirect(req_init, res_init, sender, cancel_chan) => self + .resource_manager + .fetch(req_init, Some(res_init), sender, http_state, cancel_chan), + CoreResourceMsg::SetCookieForUrl(request, cookie, source) => self + .resource_manager + .set_cookie_for_url(&request, cookie.into_inner(), source, http_state), CoreResourceMsg::SetCookiesForUrl(request, cookies, source) => { for cookie in cookies { - self.resource_manager.set_cookie_for_url(&request, cookie.into_inner(), source, http_state); + self.resource_manager.set_cookie_for_url( + &request, + cookie.into_inner(), + source, + http_state, + ); } - } + }, CoreResourceMsg::GetCookiesForUrl(url, consumer, source) => { let mut cookie_jar = http_state.cookie_jar.write().unwrap(); - consumer.send(cookie_jar.cookies_for_url(&url, source)).unwrap(); - } + consumer + .send(cookie_jar.cookies_for_url(&url, source)) + .unwrap(); + }, CoreResourceMsg::NetworkMediator(mediator_chan) => { self.resource_manager.swmanager_chan = Some(mediator_chan) - } + }, CoreResourceMsg::GetCookiesDataForUrl(url, consumer, source) => { let mut cookie_jar = http_state.cookie_jar.write().unwrap(); - let cookies = cookie_jar.cookies_data_for_url(&url, source).map(Serde).collect(); + let cookies = cookie_jar + .cookies_data_for_url(&url, source) + .map(Serde) + .collect(); consumer.send(cookies).unwrap(); - } + }, CoreResourceMsg::GetHistoryState(history_state_id, consumer) => { let history_states = http_state.history_states.read().unwrap(); - consumer.send(history_states.get(&history_state_id).cloned()).unwrap(); - } + consumer + .send(history_states.get(&history_state_id).cloned()) + .unwrap(); + }, CoreResourceMsg::SetHistoryState(history_state_id, history_state) => { let mut history_states = http_state.history_states.write().unwrap(); history_states.insert(history_state_id, history_state); - } + }, CoreResourceMsg::RemoveHistoryStates(states_to_remove) => { let mut history_states = http_state.history_states.write().unwrap(); for history_state in states_to_remove { history_states.remove(&history_state); } - } + }, CoreResourceMsg::Synchronize(sender) => { let _ = sender.send(()); - } + }, CoreResourceMsg::ToFileManager(msg) => self.resource_manager.filemanager.handle(msg), CoreResourceMsg::Exit(sender) => { if let Some(ref config_dir) = self.config_dir { match http_state.auth_cache.read() { - Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"), + Ok(auth_cache) => { + write_json_to_file(&*auth_cache, config_dir, "auth_cache.json") + }, Err(_) => warn!("Error writing auth cache to disk"), } match http_state.cookie_jar.read() { @@ -282,14 +309,15 @@ impl ResourceChannelManager { } let _ = sender.send(()); return false; - } + }, } true } } pub fn read_json_from_file(data: &mut T, config_dir: &Path, filename: &str) - where T: for<'de> Deserialize<'de> +where + T: for<'de> Deserialize<'de>, { let path = config_dir.join(filename); let display = path.display(); @@ -304,10 +332,11 @@ pub fn read_json_from_file(data: &mut T, config_dir: &Path, filename: &str) let mut string_buffer: String = String::new(); match file.read_to_string(&mut string_buffer) { - Err(why) => { - panic!("couldn't read from {}: {}", display, - Error::description(&why)) - }, + Err(why) => panic!( + "couldn't read from {}: {}", + display, + Error::description(&why) + ), Ok(_) => println!("successfully read from {}", display), } @@ -318,7 +347,8 @@ pub fn read_json_from_file(data: &mut T, config_dir: &Path, filename: &str) } pub fn write_json_to_file(data: &T, config_dir: &Path, filename: &str) - where T: Serialize +where + T: Serialize, { let json_encoded: String; match serde_json::to_string_pretty(&data) { @@ -329,17 +359,16 @@ pub fn write_json_to_file(data: &T, config_dir: &Path, filename: &str) let display = path.display(); let mut file = match File::create(&path) { - Err(why) => panic!("couldn't create {}: {}", - display, - Error::description(&why)), + Err(why) => panic!("couldn't create {}: {}", display, Error::description(&why)), Ok(file) => file, }; match file.write_all(json_encoded.as_bytes()) { - Err(why) => { - panic!("couldn't write to {}: {}", display, - Error::description(&why)) - }, + Err(why) => panic!( + "couldn't write to {}: {}", + display, + Error::description(&why) + ), Ok(_) => println!("successfully wrote to {}", display), } } @@ -354,7 +383,7 @@ impl AuthCache { pub fn new() -> AuthCache { AuthCache { version: 1, - entries: HashMap::new() + entries: HashMap::new(), } } } @@ -373,10 +402,12 @@ pub struct CoreResourceManager { } impl CoreResourceManager { - pub fn new(user_agent: Cow<'static, str>, - devtools_channel: Option>, - _profiler_chan: ProfilerChan, - embedder_proxy: EmbedderProxy) -> CoreResourceManager { + pub fn new( + user_agent: Cow<'static, str>, + devtools_channel: Option>, + _profiler_chan: ProfilerChan, + embedder_proxy: EmbedderProxy, + ) -> CoreResourceManager { CoreResourceManager { user_agent: user_agent, devtools_chan: devtools_channel, @@ -385,55 +416,67 @@ impl CoreResourceManager { } } - fn set_cookie_for_url(&mut self, request: &ServoUrl, - cookie: cookie_rs::Cookie<'static>, - source: CookieSource, - http_state: &Arc) { + fn set_cookie_for_url( + &mut self, + request: &ServoUrl, + cookie: cookie_rs::Cookie<'static>, + source: CookieSource, + http_state: &Arc, + ) { if let Some(cookie) = cookie::Cookie::new_wrapped(cookie, request, source) { let mut cookie_jar = http_state.cookie_jar.write().unwrap(); cookie_jar.push(cookie, request, source) } } - fn fetch(&self, - req_init: RequestInit, - res_init_: Option, - mut sender: IpcSender, - http_state: &Arc, - cancel_chan: Option>) { + fn fetch( + &self, + req_init: RequestInit, + res_init_: Option, + mut sender: IpcSender, + http_state: &Arc, + cancel_chan: Option>, + ) { let http_state = http_state.clone(); let ua = self.user_agent.clone(); let dc = self.devtools_chan.clone(); let filemanager = self.filemanager.clone(); - thread::Builder::new().name(format!("fetch thread for {}", req_init.url)).spawn(move || { - let mut request = Request::from_init(req_init); - // XXXManishearth: Check origin against pipeline id (also ensure that the mode is allowed) - // todo load context / mimesniff in fetch - // todo referrer policy? - // todo service worker stuff - let context = FetchContext { - state: http_state, - user_agent: ua, - devtools_chan: dc, - filemanager: filemanager, - cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(cancel_chan))), - }; + thread::Builder::new() + .name(format!("fetch thread for {}", req_init.url)) + .spawn(move || { + let mut request = Request::from_init(req_init); + // XXXManishearth: Check origin against pipeline id (also ensure that the mode is allowed) + // todo load context / mimesniff in fetch + // todo referrer policy? + // todo service worker stuff + let context = FetchContext { + state: http_state, + user_agent: ua, + devtools_chan: dc, + filemanager: filemanager, + cancellation_listener: Arc::new(Mutex::new(CancellationListener::new( + cancel_chan, + ))), + }; - match res_init_ { - Some(res_init) => { - let response = Response::from_init(res_init); - http_redirect_fetch(&mut request, - &mut CorsCache::new(), - response, - true, - &mut sender, - &mut None, - &context); - }, - None => fetch(&mut request, &mut sender, &context), - }; - }).expect("Thread spawning failed"); + match res_init_ { + Some(res_init) => { + let response = Response::from_init(res_init); + http_redirect_fetch( + &mut request, + &mut CorsCache::new(), + response, + true, + &mut sender, + &mut None, + &context, + ); + }, + None => fetch(&mut request, &mut sender, &context), + }; + }) + .expect("Thread spawning failed"); } fn websocket_connect( @@ -441,7 +484,7 @@ impl CoreResourceManager { request: RequestInit, event_sender: IpcSender, action_receiver: IpcReceiver, - http_state: &Arc + http_state: &Arc, ) { websocket_loader::init(request, event_sender, action_receiver, http_state.clone()); } diff --git a/components/net/storage_thread.rs b/components/net/storage_thread.rs index 5a336d2ea7a..ec5503046ad 100644 --- a/components/net/storage_thread.rs +++ b/components/net/storage_thread.rs @@ -22,9 +22,12 @@ impl StorageThreadFactory for IpcSender { /// Create a storage thread fn new(config_dir: Option) -> IpcSender { let (chan, port) = ipc::channel().unwrap(); - thread::Builder::new().name("StorageManager".to_owned()).spawn(move || { - StorageManager::new(port, config_dir).start(); - }).expect("Thread spawning failed"); + thread::Builder::new() + .name("StorageManager".to_owned()) + .spawn(move || { + StorageManager::new(port, config_dir).start(); + }) + .expect("Thread spawning failed"); chan } } @@ -37,9 +40,7 @@ struct StorageManager { } impl StorageManager { - fn new(port: IpcReceiver, - config_dir: Option) - -> StorageManager { + fn new(port: IpcReceiver, config_dir: Option) -> StorageManager { let mut local_data = HashMap::new(); if let Some(ref config_dir) = config_dir { resource_thread::read_json_from_file(&mut local_data, config_dir, "local_data.json"); @@ -59,33 +60,33 @@ impl StorageManager { match self.port.recv().unwrap() { StorageThreadMsg::Length(sender, url, storage_type) => { self.length(sender, url, storage_type) - } + }, StorageThreadMsg::Key(sender, url, storage_type, index) => { self.key(sender, url, storage_type, index) - } + }, StorageThreadMsg::Keys(sender, url, storage_type) => { self.keys(sender, url, storage_type) - } + }, StorageThreadMsg::SetItem(sender, url, storage_type, name, value) => { self.set_item(sender, url, storage_type, name, value); self.save_state() - } + }, StorageThreadMsg::GetItem(sender, url, storage_type, name) => { self.request_item(sender, url, storage_type, name) - } + }, StorageThreadMsg::RemoveItem(sender, url, storage_type, name) => { self.remove_item(sender, url, storage_type, name); self.save_state() - } + }, StorageThreadMsg::Clear(sender, url, storage_type) => { self.clear(sender, url, storage_type); self.save_state() - } + }, StorageThreadMsg::Exit(sender) => { // Nothing to do since we save localstorage set eagerly. let _ = sender.send(()); - break - } + break; + }, } } } @@ -96,49 +97,56 @@ impl StorageManager { } } - fn select_data(&self, storage_type: StorageType) - -> &HashMap)> { + fn select_data( + &self, + storage_type: StorageType, + ) -> &HashMap)> { match storage_type { StorageType::Session => &self.session_data, - StorageType::Local => &self.local_data + StorageType::Local => &self.local_data, } } - fn select_data_mut(&mut self, storage_type: StorageType) - -> &mut HashMap)> { + fn select_data_mut( + &mut self, + storage_type: StorageType, + ) -> &mut HashMap)> { match storage_type { StorageType::Session => &mut self.session_data, - StorageType::Local => &mut self.local_data + StorageType::Local => &mut self.local_data, } } fn length(&self, sender: IpcSender, url: ServoUrl, storage_type: StorageType) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - sender.send(data.get(&origin).map_or(0, |&(_, ref entry)| entry.len())).unwrap(); + sender + .send(data.get(&origin).map_or(0, |&(_, ref entry)| entry.len())) + .unwrap(); } - fn key(&self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType, - index: u32) { + fn key( + &self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType, + index: u32, + ) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - let key = data.get(&origin) - .and_then(|&(_, ref entry)| entry.keys().nth(index as usize)) - .cloned(); + let key = data + .get(&origin) + .and_then(|&(_, ref entry)| entry.keys().nth(index as usize)) + .cloned(); sender.send(key).unwrap(); } - fn keys(&self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType) { + fn keys(&self, sender: IpcSender>, url: ServoUrl, storage_type: StorageType) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - let keys = data.get(&origin) - .map_or(vec![], |&(_, ref entry)| entry.keys().cloned().collect()); + let keys = data + .get(&origin) + .map_or(vec![], |&(_, ref entry)| entry.keys().cloned().collect()); sender.send(keys).unwrap(); } @@ -147,12 +155,14 @@ impl StorageManager { /// value with the same key name but with different value name /// otherwise sends Err(()) to indicate that the operation would result in /// exceeding the quota limit - fn set_item(&mut self, - sender: IpcSender), ()>>, - url: ServoUrl, - storage_type: StorageType, - name: String, - value: String) { + fn set_item( + &mut self, + sender: IpcSender), ()>>, + url: ServoUrl, + storage_type: StorageType, + name: String, + value: String, + ) { let origin = self.origin_as_string(url); let (this_storage_size, other_storage_size) = { @@ -171,64 +181,82 @@ impl StorageManager { data.insert(origin.clone(), (0, BTreeMap::new())); } - let message = data.get_mut(&origin).map(|&mut (ref mut total, ref mut entry)| { - let mut new_total_size = this_storage_size + value.as_bytes().len(); - if let Some(old_value) = entry.get(&name) { - new_total_size -= old_value.as_bytes().len(); - } else { - new_total_size += name.as_bytes().len(); - } - - if (new_total_size + other_storage_size) > QUOTA_SIZE_LIMIT { - return Err(()); - } - - let message = entry.insert(name.clone(), value.clone()).map_or( - Ok((true, None)), - |old| if old == value { - Ok((false, None)) + let message = data + .get_mut(&origin) + .map(|&mut (ref mut total, ref mut entry)| { + let mut new_total_size = this_storage_size + value.as_bytes().len(); + if let Some(old_value) = entry.get(&name) { + new_total_size -= old_value.as_bytes().len(); } else { - Ok((true, Some(old))) - }); - *total = new_total_size; - message - }).unwrap(); + new_total_size += name.as_bytes().len(); + } + + if (new_total_size + other_storage_size) > QUOTA_SIZE_LIMIT { + return Err(()); + } + + let message = + entry + .insert(name.clone(), value.clone()) + .map_or(Ok((true, None)), |old| { + if old == value { + Ok((false, None)) + } else { + Ok((true, Some(old))) + } + }); + *total = new_total_size; + message + }) + .unwrap(); sender.send(message).unwrap(); } - fn request_item(&self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType, - name: String) { + fn request_item( + &self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType, + name: String, + ) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - sender.send(data.get(&origin) + sender + .send( + data.get(&origin) .and_then(|&(_, ref entry)| entry.get(&name)) - .map(String::clone)).unwrap(); + .map(String::clone), + ) + .unwrap(); } /// Sends Some(old_value) in case there was a previous value with the key name, otherwise sends None - fn remove_item(&mut self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType, - name: String) { + fn remove_item( + &mut self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType, + name: String, + ) { let origin = self.origin_as_string(url); let data = self.select_data_mut(storage_type); - let old_value = data.get_mut(&origin).and_then(|&mut (ref mut total, ref mut entry)| { - entry.remove(&name).and_then(|old| { - *total -= name.as_bytes().len() + old.as_bytes().len(); - Some(old) - }) - }); + let old_value = data + .get_mut(&origin) + .and_then(|&mut (ref mut total, ref mut entry)| { + entry.remove(&name).and_then(|old| { + *total -= name.as_bytes().len() + old.as_bytes().len(); + Some(old) + }) + }); sender.send(old_value).unwrap(); } fn clear(&mut self, sender: IpcSender, url: ServoUrl, storage_type: StorageType) { let origin = self.origin_as_string(url); let data = self.select_data_mut(storage_type); - sender.send(data.get_mut(&origin) + sender + .send( + data.get_mut(&origin) .map_or(false, |&mut (ref mut total, ref mut entry)| { if !entry.is_empty() { entry.clear(); @@ -236,7 +264,10 @@ impl StorageManager { true } else { false - }})).unwrap(); + } + }), + ) + .unwrap(); } fn origin_as_string(&self, url: ServoUrl) -> String { diff --git a/components/net/subresource_integrity.rs b/components/net/subresource_integrity.rs index e0a7168de97..6abeb39149c 100644 --- a/components/net/subresource_integrity.rs +++ b/components/net/subresource_integrity.rs @@ -9,22 +9,13 @@ use std::iter::Filter; use std::str::Split; use std::sync::MutexGuard; -const SUPPORTED_ALGORITHM: &'static [&'static str] = &[ - "sha256", - "sha384", - "sha512", -]; +const SUPPORTED_ALGORITHM: &'static [&'static str] = &["sha256", "sha384", "sha512"]; pub type StaticCharVec = &'static [char]; /// A "space character" according to: /// /// -pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ - '\u{0020}', - '\u{0009}', - '\u{000a}', - '\u{000c}', - '\u{000d}', -]; +pub static HTML_SPACE_CHARACTERS: StaticCharVec = + &['\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}']; #[derive(Clone)] pub struct SriEntry { pub alg: String, @@ -79,9 +70,18 @@ pub fn parsed_metadata(integrity_metadata: &str) -> Vec { } /// -pub fn get_prioritized_hash_function(hash_func_left: &str, hash_func_right: &str) -> Option { - let left_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_left).unwrap(); - let right_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_right).unwrap(); +pub fn get_prioritized_hash_function( + hash_func_left: &str, + hash_func_right: &str, +) -> Option { + let left_priority = SUPPORTED_ALGORITHM + .iter() + .position(|s| s.to_owned() == hash_func_left) + .unwrap(); + let right_priority = SUPPORTED_ALGORITHM + .iter() + .position(|s| s.to_owned() == hash_func_right) + .unwrap(); if left_priority == right_priority { return None; @@ -91,7 +91,6 @@ pub fn get_prioritized_hash_function(hash_func_left: &str, hash_func_right: &str } else { Some(hash_func_right.to_owned()) } - } /// @@ -100,8 +99,8 @@ pub fn get_strongest_metadata(integrity_metadata_list: Vec) -> Vec) -> Vec -fn apply_algorithm_to_response(body: MutexGuard, - message_digest: MessageDigest) - -> String { +fn apply_algorithm_to_response( + body: MutexGuard, + message_digest: MessageDigest, +) -> String { if let ResponseBody::Done(ref vec) = *body { let response_digest = hash(message_digest, vec).unwrap(); //Now hash base64::encode(&response_digest) @@ -171,8 +171,12 @@ pub fn is_response_integrity_valid(integrity_metadata: &str, response: &Response false } -pub fn split_html_space_chars<'a>(s: &'a str) -> - Filter, fn(&&str) -> bool> { - fn not_empty(&split: &&str) -> bool { !split.is_empty() } - s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) +pub fn split_html_space_chars<'a>( + s: &'a str, +) -> Filter, fn(&&str) -> bool> { + fn not_empty(&split: &&str) -> bool { + !split.is_empty() + } + s.split(HTML_SPACE_CHARACTERS) + .filter(not_empty as fn(&&str) -> bool) } diff --git a/components/net/tests/cookie.rs b/components/net/tests/cookie.rs index 3702f93fee2..219b2979aa9 100644 --- a/components/net/tests/cookie.rs +++ b/components/net/tests/cookie.rs @@ -118,11 +118,13 @@ fn test_cookie_secure_prefix() { assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("http://example.com").unwrap(); - let cookie = cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); + let cookie = + cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("https://example.com").unwrap(); - let cookie = cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); + let cookie = + cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_some()); } @@ -157,7 +159,8 @@ fn test_cookie_host_prefix() { assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("https://example.com").unwrap(); - let cookie = cookie_rs::Cookie::parse("__Host-SID=12345; Secure; Domain=example.com; Path=/").unwrap(); + let cookie = + cookie_rs::Cookie::parse("__Host-SID=12345; Secure; Domain=example.com; Path=/").unwrap(); assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("https://example.com").unwrap(); @@ -193,13 +196,18 @@ fn test_sort_order() { assert!(b.cookie.path().as_ref().unwrap().len() > a.cookie.path().as_ref().unwrap().len()); assert_eq!(CookieStorage::cookie_comparator(&a, &b), Ordering::Greater); assert_eq!(CookieStorage::cookie_comparator(&b, &a), Ordering::Less); - assert_eq!(CookieStorage::cookie_comparator(&a, &a_prime), Ordering::Less); - assert_eq!(CookieStorage::cookie_comparator(&a_prime, &a), Ordering::Greater); + assert_eq!( + CookieStorage::cookie_comparator(&a, &a_prime), + Ordering::Less + ); + assert_eq!( + CookieStorage::cookie_comparator(&a_prime, &a), + Ordering::Greater + ); assert_eq!(CookieStorage::cookie_comparator(&a, &a), Ordering::Equal); } -fn add_cookie_to_storage(storage: &mut CookieStorage, url: &ServoUrl, cookie_str: &str) -{ +fn add_cookie_to_storage(storage: &mut CookieStorage, url: &ServoUrl, cookie_str: &str) { let source = CookieSource::HTTP; let cookie = cookie_rs::Cookie::parse(cookie_str.to_owned()).unwrap(); let cookie = Cookie::new_wrapped(cookie, url, source).unwrap(); @@ -225,21 +233,40 @@ fn test_insecure_cookies_cannot_evict_secure_cookie() { let insecure_url = ServoUrl::parse("http://home.example.org:8888/cookie-parser?0001").unwrap(); - add_cookie_to_storage(&mut storage, &insecure_url, "foo=value; Domain=home.example.org"); - add_cookie_to_storage(&mut storage, &insecure_url, "foo2=value; Domain=.example.org"); + add_cookie_to_storage( + &mut storage, + &insecure_url, + "foo=value; Domain=home.example.org", + ); + add_cookie_to_storage( + &mut storage, + &insecure_url, + "foo2=value; Domain=.example.org", + ); add_cookie_to_storage(&mut storage, &insecure_url, "foo3=value; Path=/foo/bar"); add_cookie_to_storage(&mut storage, &insecure_url, "foo4=value; Path=/foo"); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&secure_url, source).unwrap(), "foo=bar; foo2=bar"); + assert_eq!( + storage.cookies_for_url(&secure_url, source).unwrap(), + "foo=bar; foo2=bar" + ); - let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); + let url = + ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo=bar; foo2=bar"); + assert_eq!( + storage.cookies_for_url(&url, source).unwrap(), + "foo3=bar; foo4=value; foo=bar; foo2=bar" + ); - let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); + let url = + ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo4=bar; foo3=bar; foo4=value; foo=bar; foo2=bar"); + assert_eq!( + storage.cookies_for_url(&url, source).unwrap(), + "foo4=bar; foo3=bar; foo4=value; foo=bar; foo2=bar" + ); } #[test] @@ -267,14 +294,21 @@ fn test_secure_cookies_eviction() { let source = CookieSource::HTTP; assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo2=value"); - let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); + let url = + ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo2=value"); + assert_eq!( + storage.cookies_for_url(&url, source).unwrap(), + "foo3=bar; foo4=value; foo2=value" + ); - let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); + let url = + ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&url, source).unwrap(), - "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value"); + assert_eq!( + storage.cookies_for_url(&url, source).unwrap(), + "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value" + ); } #[test] @@ -302,21 +336,28 @@ fn test_secure_cookies_eviction_non_http_source() { let source = CookieSource::HTTP; assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo2=value"); - let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); + let url = + ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo2=value"); + assert_eq!( + storage.cookies_for_url(&url, source).unwrap(), + "foo3=bar; foo4=value; foo2=value" + ); - let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); + let url = + ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!(storage.cookies_for_url(&url, source).unwrap(), - "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value"); + assert_eq!( + storage.cookies_for_url(&url, source).unwrap(), + "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value" + ); } - -fn add_retrieve_cookies(set_location: &str, - set_cookies: &[String], - final_location: &str) - -> String { +fn add_retrieve_cookies( + set_location: &str, + set_cookies: &[String], + final_location: &str, +) -> String { let mut storage = CookieStorage::new(5); let url = ServoUrl::parse(set_location).unwrap(); let source = CookieSource::HTTP; @@ -329,56 +370,75 @@ fn add_retrieve_cookies(set_location: &str, // Get cookies for the test location let url = ServoUrl::parse(final_location).unwrap(); - storage.cookies_for_url(&url, source).unwrap_or("".to_string()) + storage + .cookies_for_url(&url, source) + .unwrap_or("".to_string()) } - #[test] fn test_cookie_eviction_expired() { let mut vec = Vec::new(); for i in 1..6 { - let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2000 21:06:29 GMT", - i); + let st = format!( + "extra{}=bar; Secure; expires=Sun, 18-Apr-2000 21:06:29 GMT", + i + ); vec.push(st); } vec.push("foo=bar; Secure; expires=Sun, 18-Apr-2027 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", - &vec, "https://home.example.org:8888/cookie-parser-result?0001"); + let r = add_retrieve_cookies( + "https://home.example.org:8888/cookie-parser?0001", + &vec, + "https://home.example.org:8888/cookie-parser-result?0001", + ); assert_eq!(&r, "foo=bar"); } - #[test] fn test_cookie_eviction_all_secure_one_nonsecure() { let mut vec = Vec::new(); for i in 1..5 { - let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", - i); + let st = format!( + "extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", + i + ); vec.push(st); } vec.push("foo=bar; expires=Sun, 18-Apr-2026 21:06:29 GMT".to_owned()); vec.push("foo2=bar; Secure; expires=Sun, 18-Apr-2028 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", - &vec, "https://home.example.org:8888/cookie-parser-result?0001"); - assert_eq!(&r, "extra1=bar; extra2=bar; extra3=bar; extra4=bar; foo2=bar"); + let r = add_retrieve_cookies( + "https://home.example.org:8888/cookie-parser?0001", + &vec, + "https://home.example.org:8888/cookie-parser-result?0001", + ); + assert_eq!( + &r, + "extra1=bar; extra2=bar; extra3=bar; extra4=bar; foo2=bar" + ); } - #[test] fn test_cookie_eviction_all_secure_new_nonsecure() { let mut vec = Vec::new(); for i in 1..6 { - let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", - i); + let st = format!( + "extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", + i + ); vec.push(st); } vec.push("foo=bar; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", - &vec, "https://home.example.org:8888/cookie-parser-result?0001"); - assert_eq!(&r, "extra1=bar; extra2=bar; extra3=bar; extra4=bar; extra5=bar"); + let r = add_retrieve_cookies( + "https://home.example.org:8888/cookie-parser?0001", + &vec, + "https://home.example.org:8888/cookie-parser-result?0001", + ); + assert_eq!( + &r, + "extra1=bar; extra2=bar; extra3=bar; extra4=bar; extra5=bar" + ); } - #[test] fn test_cookie_eviction_all_nonsecure_new_secure() { let mut vec = Vec::new(); @@ -387,12 +447,17 @@ fn test_cookie_eviction_all_nonsecure_new_secure() { vec.push(st); } vec.push("foo=bar; Secure; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", - &vec, "https://home.example.org:8888/cookie-parser-result?0001"); - assert_eq!(&r, "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar"); + let r = add_retrieve_cookies( + "https://home.example.org:8888/cookie-parser?0001", + &vec, + "https://home.example.org:8888/cookie-parser-result?0001", + ); + assert_eq!( + &r, + "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar" + ); } - #[test] fn test_cookie_eviction_all_nonsecure_new_nonsecure() { let mut vec = Vec::new(); @@ -401,7 +466,13 @@ fn test_cookie_eviction_all_nonsecure_new_nonsecure() { vec.push(st); } vec.push("foo=bar; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", - &vec, "https://home.example.org:8888/cookie-parser-result?0001"); - assert_eq!(&r, "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar"); + let r = add_retrieve_cookies( + "https://home.example.org:8888/cookie-parser?0001", + &vec, + "https://home.example.org:8888/cookie-parser-result?0001", + ); + assert_eq!( + &r, + "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar" + ); } diff --git a/components/net/tests/cookie_http_state.rs b/components/net/tests/cookie_http_state.rs index ab310f6a35e..ef929277fcb 100644 --- a/components/net/tests/cookie_http_state.rs +++ b/components/net/tests/cookie_http_state.rs @@ -14,14 +14,17 @@ fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String // Add all cookies to the store for str_cookie in set_cookies { - if let Some(cookie) = Cookie::from_cookie_string(str_cookie.to_owned().into(), &url, source) { + if let Some(cookie) = Cookie::from_cookie_string(str_cookie.to_owned().into(), &url, source) + { storage.push(cookie, &url, source); } } // Get cookies for the test location let url = ServoUrl::parse(final_location).unwrap(); - storage.cookies_for_url(&url, source).unwrap_or("".to_string()) + storage + .cookies_for_url(&url, source) + .unwrap_or("".to_string()) } // Following are all tests extracted from https://github.com/abarth/http-state.git @@ -30,1890 +33,2392 @@ fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String #[test] fn test_0001() { - let r = run("http://home.example.org:8888/cookie-parser?0001", - &["foo=bar"], - "http://home.example.org:8888/cookie-parser-result?0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?0001", + &["foo=bar"], + "http://home.example.org:8888/cookie-parser-result?0001", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_0002() { - let r = run("http://home.example.org:8888/cookie-parser?0002", - &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], - "http://home.example.org:8888/cookie-parser-result?0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?0002", + &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], + "http://home.example.org:8888/cookie-parser-result?0002", + ); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_0003() { - let r = run("http://home.example.org:8888/cookie-parser?0003", - &["foo=bar; Expires=Fri, 07 Aug 2007 08:04:19 GMT", - "foo2=bar2; Expires=Fri, 07 Aug 2017 08:04:19 GMT"], - "http://home.example.org:8888/cookie-parser-result?0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?0003", + &[ + "foo=bar; Expires=Fri, 07 Aug 2007 08:04:19 GMT", + "foo2=bar2; Expires=Fri, 07 Aug 2017 08:04:19 GMT", + ], + "http://home.example.org:8888/cookie-parser-result?0003", + ); assert_eq!(&r, "foo2=bar2"); } #[test] fn test_0004() { - let r = run("http://home.example.org:8888/cookie-parser?0004", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?0004", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0004", + ); assert_eq!(&r, ""); } #[test] fn test_0005() { - let r = run("http://home.example.org:8888/cookie-parser?0005", - &["foo=bar; max-age=10000;"], - "http://home.example.org:8888/cookie-parser-result?0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?0005", + &["foo=bar; max-age=10000;"], + "http://home.example.org:8888/cookie-parser-result?0005", + ); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_0006() { - let r = run("http://home.example.org:8888/cookie-parser?0006", - &["foo=bar; max-age=0;"], - "http://home.example.org:8888/cookie-parser-result?0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?0006", + &["foo=bar; max-age=0;"], + "http://home.example.org:8888/cookie-parser-result?0006", + ); assert_eq!(&r, ""); } #[test] fn test_0007() { - let r = run("http://home.example.org:8888/cookie-parser?0007", - &["foo=bar; version=1;"], - "http://home.example.org:8888/cookie-parser-result?0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?0007", + &["foo=bar; version=1;"], + "http://home.example.org:8888/cookie-parser-result?0007", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_0008() { - let r = run("http://home.example.org:8888/cookie-parser?0008", - &["foo=bar; version=1000;"], - "http://home.example.org:8888/cookie-parser-result?0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?0008", + &["foo=bar; version=1000;"], + "http://home.example.org:8888/cookie-parser-result?0008", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_0009() { - let r = run("http://home.example.org:8888/cookie-parser?0009", - &["foo=bar; customvalue=1000;"], - "http://home.example.org:8888/cookie-parser-result?0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?0009", + &["foo=bar; customvalue=1000;"], + "http://home.example.org:8888/cookie-parser-result?0009", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_0010() { - let r = run("http://home.example.org:8888/cookie-parser?0010", - &["foo=bar; secure;"], - "http://home.example.org:8888/cookie-parser-result?0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?0010", + &["foo=bar; secure;"], + "http://home.example.org:8888/cookie-parser-result?0010", + ); assert_eq!(&r, ""); } #[test] fn test_0011() { - let r = run("http://home.example.org:8888/cookie-parser?0011", - &["foo=bar; customvalue=\"1000 or more\";"], - "http://home.example.org:8888/cookie-parser-result?0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?0011", + &["foo=bar; customvalue=\"1000 or more\";"], + "http://home.example.org:8888/cookie-parser-result?0011", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_0012() { - let r = run("http://home.example.org:8888/cookie-parser?0012", - &["foo=bar; customvalue=\"no trailing semicolon\""], - "http://home.example.org:8888/cookie-parser-result?0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?0012", + &["foo=bar; customvalue=\"no trailing semicolon\""], + "http://home.example.org:8888/cookie-parser-result?0012", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_0013() { - let r = run("http://home.example.org:8888/cookie-parser?0013", - &["foo=bar", "foo=qux"], - "http://home.example.org:8888/cookie-parser-result?0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?0013", + &["foo=bar", "foo=qux"], + "http://home.example.org:8888/cookie-parser-result?0013", + ); assert_eq!(&r, "foo=qux"); } #[test] fn test_0014() { - let r = run("http://home.example.org:8888/cookie-parser?0014", - &["foo1=bar", "foo2=qux"], - "http://home.example.org:8888/cookie-parser-result?0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?0014", + &["foo1=bar", "foo2=qux"], + "http://home.example.org:8888/cookie-parser-result?0014", + ); assert_eq!(&r, "foo1=bar; foo2=qux"); } #[test] fn test_0015() { - let r = run("http://home.example.org:8888/cookie-parser?0015", - &["a=b", "z=y"], - "http://home.example.org:8888/cookie-parser-result?0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?0015", + &["a=b", "z=y"], + "http://home.example.org:8888/cookie-parser-result?0015", + ); assert_eq!(&r, "a=b; z=y"); } #[test] fn test_0016() { - let r = run("http://home.example.org:8888/cookie-parser?0016", - &["z=y", "a=b"], - "http://home.example.org:8888/cookie-parser-result?0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?0016", + &["z=y", "a=b"], + "http://home.example.org:8888/cookie-parser-result?0016", + ); assert_eq!(&r, "z=y; a=b"); } #[test] fn test_0017() { - let r = run("http://home.example.org:8888/cookie-parser?0017", - &["z=y, a=b"], - "http://home.example.org:8888/cookie-parser-result?0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?0017", + &["z=y, a=b"], + "http://home.example.org:8888/cookie-parser-result?0017", + ); assert_eq!(&r, "z=y, a=b"); } #[test] fn test_0018() { - let r = run("http://home.example.org:8888/cookie-parser?0018", - &["z=y; foo=bar, a=b"], - "http://home.example.org:8888/cookie-parser-result?0018"); + let r = run( + "http://home.example.org:8888/cookie-parser?0018", + &["z=y; foo=bar, a=b"], + "http://home.example.org:8888/cookie-parser-result?0018", + ); assert_eq!(&r, "z=y"); } #[test] fn test_0019() { - let r = run("http://home.example.org:8888/cookie-parser?0019", - &["foo=b;max-age=3600, c=d;path=/"], - "http://home.example.org:8888/cookie-parser-result?0019"); + let r = run( + "http://home.example.org:8888/cookie-parser?0019", + &["foo=b;max-age=3600, c=d;path=/"], + "http://home.example.org:8888/cookie-parser-result?0019", + ); assert_eq!(&r, "foo=b"); } #[test] fn test_0020() { - let r = run("http://home.example.org:8888/cookie-parser?0020", - &["a=b", "=", "c=d"], - "http://home.example.org:8888/cookie-parser-result?0020"); + let r = run( + "http://home.example.org:8888/cookie-parser?0020", + &["a=b", "=", "c=d"], + "http://home.example.org:8888/cookie-parser-result?0020", + ); assert_eq!(&r, "a=b; c=d"); } #[test] fn test_0021() { - let r = run("http://home.example.org:8888/cookie-parser?0021", - &["a=b", "=x", "c=d"], - "http://home.example.org:8888/cookie-parser-result?0021"); + let r = run( + "http://home.example.org:8888/cookie-parser?0021", + &["a=b", "=x", "c=d"], + "http://home.example.org:8888/cookie-parser-result?0021", + ); assert_eq!(&r, "a=b; c=d"); } #[test] fn test_0022() { - let r = run("http://home.example.org:8888/cookie-parser?0022", - &["a=b", "x=", "c=d"], - "http://home.example.org:8888/cookie-parser-result?0022"); + let r = run( + "http://home.example.org:8888/cookie-parser?0022", + &["a=b", "x=", "c=d"], + "http://home.example.org:8888/cookie-parser-result?0022", + ); assert_eq!(&r, "a=b; x=; c=d"); } #[test] fn test_0023() { - let r = run("http://home.example.org:8888/cookie-parser?0023", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0023"); + let r = run( + "http://home.example.org:8888/cookie-parser?0023", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0023", + ); assert_eq!(&r, ""); } #[test] fn test_0024() { - let r = run("http://home.example.org:8888/cookie-parser?0024", - &["foo", "="], - "http://home.example.org:8888/cookie-parser-result?0024"); + let r = run( + "http://home.example.org:8888/cookie-parser?0024", + &["foo", "="], + "http://home.example.org:8888/cookie-parser-result?0024", + ); assert_eq!(&r, ""); } #[test] fn test_0025() { - let r = run("http://home.example.org:8888/cookie-parser?0025", - &["foo", "; bar"], - "http://home.example.org:8888/cookie-parser-result?0025"); + let r = run( + "http://home.example.org:8888/cookie-parser?0025", + &["foo", "; bar"], + "http://home.example.org:8888/cookie-parser-result?0025", + ); assert_eq!(&r, ""); } #[test] fn test_0026() { - let r = run("http://home.example.org:8888/cookie-parser?0026", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0026"); + let r = run( + "http://home.example.org:8888/cookie-parser?0026", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0026", + ); assert_eq!(&r, ""); } #[test] fn test_0027() { - let r = run("http://home.example.org:8888/cookie-parser?0027", - &["foo", "bar"], - "http://home.example.org:8888/cookie-parser-result?0027"); + let r = run( + "http://home.example.org:8888/cookie-parser?0027", + &["foo", "bar"], + "http://home.example.org:8888/cookie-parser-result?0027", + ); assert_eq!(&r, ""); } #[test] fn test_0028() { - let r = run("http://home.example.org:8888/cookie-parser?0028", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0028"); + let r = run( + "http://home.example.org:8888/cookie-parser?0028", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0028", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0001() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0001", - &["foo=bar; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0001", + &["foo=bar; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0001", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0002() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0002", - &["foo=bar; seCURe"], - "http://home.example.org:8888/cookie-parser-result?attribute0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0002", + &["foo=bar; seCURe"], + "http://home.example.org:8888/cookie-parser-result?attribute0002", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0003() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0003", - &["foo=bar; \"Secure\""], - "http://home.example.org:8888/cookie-parser-result?attribute0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0003", + &["foo=bar; \"Secure\""], + "http://home.example.org:8888/cookie-parser-result?attribute0003", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0004() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0004", - &["foo=bar; Secure="], - "http://home.example.org:8888/cookie-parser-result?attribute0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0004", + &["foo=bar; Secure="], + "http://home.example.org:8888/cookie-parser-result?attribute0004", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0005() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0005", - &["foo=bar; Secure=aaaa"], - "http://home.example.org:8888/cookie-parser-result?attribute0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0005", + &["foo=bar; Secure=aaaa"], + "http://home.example.org:8888/cookie-parser-result?attribute0005", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0006() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0006", - &["foo=bar; Secure qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0006", + &["foo=bar; Secure qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0006", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0007() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0007", - &["foo=bar; Secure =aaaaa"], - "http://home.example.org:8888/cookie-parser-result?attribute0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0007", + &["foo=bar; Secure =aaaaa"], + "http://home.example.org:8888/cookie-parser-result?attribute0007", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0008() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0008", - &["foo=bar; Secure= aaaaa"], - "http://home.example.org:8888/cookie-parser-result?attribute0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0008", + &["foo=bar; Secure= aaaaa"], + "http://home.example.org:8888/cookie-parser-result?attribute0008", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0009() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0009", - &["foo=bar; Secure; qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0009", + &["foo=bar; Secure; qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0009", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0010() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0010", - &["foo=bar; Secure;qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0010", + &["foo=bar; Secure;qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0010", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0011() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0011", - &["foo=bar; Secure ; qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0011", + &["foo=bar; Secure ; qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0011", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0012() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0012", - &["foo=bar; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0012", + &["foo=bar; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0012", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0013() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0013", - &["foo=bar; Secure ;"], - "http://home.example.org:8888/cookie-parser-result?attribute0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0013", + &["foo=bar; Secure ;"], + "http://home.example.org:8888/cookie-parser-result?attribute0013", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0014() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0014", - &["foo=bar; Path"], - "http://home.example.org:8888/cookie-parser-result?attribute0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0014", + &["foo=bar; Path"], + "http://home.example.org:8888/cookie-parser-result?attribute0014", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0015() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0015", - &["foo=bar; Path="], - "http://home.example.org:8888/cookie-parser-result?attribute0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0015", + &["foo=bar; Path="], + "http://home.example.org:8888/cookie-parser-result?attribute0015", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0016() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0016", - &["foo=bar; Path=/"], - "http://home.example.org:8888/cookie-parser-result?attribute0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0016", + &["foo=bar; Path=/"], + "http://home.example.org:8888/cookie-parser-result?attribute0016", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0017() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0017", - &["foo=bar; Path=/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0017", + &["foo=bar; Path=/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0017", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0018() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0018", - &["foo=bar; Path =/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0018"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0018", + &["foo=bar; Path =/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0018", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0019() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0019", - &["foo=bar; Path= /qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0019"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0019", + &["foo=bar; Path= /qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0019", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0020() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0020", - &["foo=bar; Path=/qux ; taz"], - "http://home.example.org:8888/cookie-parser-result?attribute0020"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0020", + &["foo=bar; Path=/qux ; taz"], + "http://home.example.org:8888/cookie-parser-result?attribute0020", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0021() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0021", - &["foo=bar; Path=/qux; Path=/"], - "http://home.example.org:8888/cookie-parser-result?attribute0021"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0021", + &["foo=bar; Path=/qux; Path=/"], + "http://home.example.org:8888/cookie-parser-result?attribute0021", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0022() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0022", - &["foo=bar; Path=/; Path=/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0022"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0022", + &["foo=bar; Path=/; Path=/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0022", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0023() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0023", - &["foo=bar; Path=/qux; Path=/cookie-parser-result"], - "http://home.example.org:8888/cookie-parser-result?attribute0023"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0023", + &["foo=bar; Path=/qux; Path=/cookie-parser-result"], + "http://home.example.org:8888/cookie-parser-result?attribute0023", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0024() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0024", - &["foo=bar; Path=/cookie-parser-result; Path=/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0024"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0024", + &["foo=bar; Path=/cookie-parser-result; Path=/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0024", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0025() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0025", - &["foo=bar; qux; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0025"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0025", + &["foo=bar; qux; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0025", + ); assert_eq!(&r, ""); } #[test] fn test_attribute0026() { - let r = run("http://home.example.org:8888/cookie-parser?attribute0026", - &["foo=bar; qux=\"aaa;bbb\"; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0026"); + let r = run( + "http://home.example.org:8888/cookie-parser?attribute0026", + &["foo=bar; qux=\"aaa;bbb\"; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0026", + ); assert_eq!(&r, ""); } #[test] fn test_charset0001() { - let r = run("http://home.example.org:8888/cookie-parser?charset0001", - &["foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ -\u{5168}\u{624b}\u{518c}"], - "http://home.example.org:8888/cookie-parser-result?charset0001"); - assert_eq!(&r, "foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ -\u{5168}\u{624b}\u{518c}"); + let r = run( + "http://home.example.org:8888/cookie-parser?charset0001", + &[ + "foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ + \u{5168}\u{624b}\u{518c}", + ], + "http://home.example.org:8888/cookie-parser-result?charset0001", + ); + assert_eq!( + &r, + "foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ + \u{5168}\u{624b}\u{518c}" + ); } #[test] fn test_charset0002() { - let r = run("http://home.example.org:8888/cookie-parser?charset0002", - &["\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ -\u{5168}\u{624b}\u{518c}"], - "http://home.example.org:8888/cookie-parser-result?charset0002"); - assert_eq!(&r, "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ -\u{5168}\u{624b}\u{518c}"); + let r = run( + "http://home.example.org:8888/cookie-parser?charset0002", + &[ + "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ + \u{5168}\u{624b}\u{518c}", + ], + "http://home.example.org:8888/cookie-parser-result?charset0002", + ); + assert_eq!( + &r, + "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ + \u{5168}\u{624b}\u{518c}" + ); } #[test] fn test_charset0003() { - let r = run("http://home.example.org:8888/cookie-parser?charset0003", - &["\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}; \u{5b8c}\ -\u{5168}\u{624b}\u{518c}"], - "http://home.example.org:8888/cookie-parser-result?charset0003"); - assert_eq!(&r, "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}"); + let r = run( + "http://home.example.org:8888/cookie-parser?charset0003", + &[ + "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}; \u{5b8c}\ + \u{5168}\u{624b}\u{518c}", + ], + "http://home.example.org:8888/cookie-parser-result?charset0003", + ); + assert_eq!( + &r, + "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}" + ); } #[test] fn test_charset0004() { - let r = run("http://home.example.org:8888/cookie-parser?charset0004", - &["foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ -\u{5168}\u{624b}\u{518c}\""], - "http://home.example.org:8888/cookie-parser-result?charset0004"); - assert_eq!(&r, "foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ -\u{5168}\u{624b}\u{518c}\""); + let r = run( + "http://home.example.org:8888/cookie-parser?charset0004", + &[ + "foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ + \u{5168}\u{624b}\u{518c}\"", + ], + "http://home.example.org:8888/cookie-parser-result?charset0004", + ); + assert_eq!( + &r, + "foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ + \u{5168}\u{624b}\u{518c}\"" + ); } #[test] fn test_chromium0001() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0001", - &["a=b"], - "http://home.example.org:8888/cookie-parser-result?chromium0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0001", + &["a=b"], + "http://home.example.org:8888/cookie-parser-result?chromium0001", + ); assert_eq!(&r, "a=b"); } #[test] fn test_chromium0002() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0002", - &["aBc=\"zzz \" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0002", + &["aBc=\"zzz \" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0002", + ); assert_eq!(&r, "aBc=\"zzz \""); } #[test] fn test_chromium0003() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0003", - &["aBc=\"zzz \" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0003", + &["aBc=\"zzz \" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0003", + ); assert_eq!(&r, "aBc=\"zzz \""); } #[test] fn test_chromium0004() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0004", - &["aBc=\"zz;pp\" ; ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0004", + &["aBc=\"zz;pp\" ; ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0004", + ); assert_eq!(&r, "aBc=\"zz"); } #[test] fn test_chromium0005() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0005", - &["aBc=\"zz ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0005", + &["aBc=\"zz ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0005", + ); assert_eq!(&r, "aBc=\"zz"); } #[test] fn test_chromium0006() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0006", - &["aBc=\"zzz \" \"ppp\" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0006", + &["aBc=\"zzz \" \"ppp\" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0006", + ); assert_eq!(&r, "aBc=\"zzz \" \"ppp\""); } #[test] fn test_chromium0007() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0007", - &["aBc=\"zzz \" \"ppp\" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0007", + &["aBc=\"zzz \" \"ppp\" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0007", + ); assert_eq!(&r, "aBc=\"zzz \" \"ppp\""); } #[test] fn test_chromium0008() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0008", - &["aBc=A\"B ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0008", + &["aBc=A\"B ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0008", + ); assert_eq!(&r, "aBc=A\"B"); } #[test] fn test_chromium0009() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0009", - &["BLAHHH; path=/;"], - "http://home.example.org:8888/cookie-parser-result?chromium0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0009", + &["BLAHHH; path=/;"], + "http://home.example.org:8888/cookie-parser-result?chromium0009", + ); assert_eq!(&r, ""); } #[test] fn test_chromium0010() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0010", - &["\"BLA\\\"HHH\"; path=/;"], - "http://home.example.org:8888/cookie-parser-result?chromium0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0010", + &["\"BLA\\\"HHH\"; path=/;"], + "http://home.example.org:8888/cookie-parser-result?chromium0010", + ); assert_eq!(&r, ""); } #[test] fn test_chromium0011() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0011", - &["a=\"B"], - "http://home.example.org:8888/cookie-parser-result?chromium0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0011", + &["a=\"B"], + "http://home.example.org:8888/cookie-parser-result?chromium0011", + ); assert_eq!(&r, "a=\"B"); } #[test] fn test_chromium0012() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0012", - &["=ABC"], - "http://home.example.org:8888/cookie-parser-result?chromium0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0012", + &["=ABC"], + "http://home.example.org:8888/cookie-parser-result?chromium0012", + ); assert_eq!(&r, ""); } #[test] fn test_chromium0013() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0013", - &["ABC=; path = /"], - "http://home.example.org:8888/cookie-parser-result?chromium0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0013", + &["ABC=; path = /"], + "http://home.example.org:8888/cookie-parser-result?chromium0013", + ); assert_eq!(&r, "ABC="); } #[test] fn test_chromium0014() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0014", - &[" A = BC ;foo;;; bar"], - "http://home.example.org:8888/cookie-parser-result?chromium0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0014", + &[" A = BC ;foo;;; bar"], + "http://home.example.org:8888/cookie-parser-result?chromium0014", + ); assert_eq!(&r, "A=BC"); } #[test] fn test_chromium0015() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0015", - &[" A=== BC ;foo;;; bar"], - "http://home.example.org:8888/cookie-parser-result?chromium0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0015", + &[" A=== BC ;foo;;; bar"], + "http://home.example.org:8888/cookie-parser-result?chromium0015", + ); assert_eq!(&r, "A=== BC"); } #[test] fn test_chromium0016() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0016", - &["foo=\"zohNumRKgI0oxyhSsV3Z7D\" ; expires=Sun, 18-Apr-2027 21:06:29 GMT\ - ; path=/ ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0016", + &[ + "foo=\"zohNumRKgI0oxyhSsV3Z7D\" ; expires=Sun, 18-Apr-2027 21:06:29 GMT\ + ; path=/ ;", + ], + "http://home.example.org:8888/cookie-parser-result?chromium0016", + ); assert_eq!(&r, "foo=\"zohNumRKgI0oxyhSsV3Z7D\""); } #[test] fn test_chromium0017() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0017", - &["foo=zohNumRKgI0oxyhSsV3Z7D ; expires=Sun, 18-Apr-2027 21:06:29 GMT ; p\ -ath=/ ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0017", + &[ + "foo=zohNumRKgI0oxyhSsV3Z7D ; expires=Sun, 18-Apr-2027 21:06:29 GMT ; p\ + ath=/ ;", + ], + "http://home.example.org:8888/cookie-parser-result?chromium0017", + ); assert_eq!(&r, "foo=zohNumRKgI0oxyhSsV3Z7D"); } #[test] fn test_chromium0018() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0018", - &[], - "http://home.example.org:8888/cookie-parser-result?chromium0018"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0018", + &[], + "http://home.example.org:8888/cookie-parser-result?chromium0018", + ); assert_eq!(&r, ""); } #[test] fn test_chromium0019() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0019", - &["a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], - "http://home.example.org:8888/cookie-parser-result?chromium0019"); - assert_eq!(&r, "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0019", + &[ + "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + ], + "http://home.example.org:8888/cookie-parser-result?chromium0019", + ); + assert_eq!( + &r, + "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ); } #[test] fn test_chromium0021() { - let r = run("http://home.example.org:8888/cookie-parser?chromium0021", - &[], - "http://home.example.org:8888/cookie-parser-result?chromium0021"); + let r = run( + "http://home.example.org:8888/cookie-parser?chromium0021", + &[], + "http://home.example.org:8888/cookie-parser-result?chromium0021", + ); assert_eq!(&r, ""); } #[test] fn test_comma0001() { - let r = run("http://home.example.org:8888/cookie-parser?comma0001", - &["foo=bar, baz=qux"], - "http://home.example.org:8888/cookie-parser-result?comma0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0001", + &["foo=bar, baz=qux"], + "http://home.example.org:8888/cookie-parser-result?comma0001", + ); assert_eq!(&r, "foo=bar, baz=qux"); } #[test] fn test_comma0002() { - let r = run("http://home.example.org:8888/cookie-parser?comma0002", - &["foo=\"bar, baz=qux\""], - "http://home.example.org:8888/cookie-parser-result?comma0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0002", + &["foo=\"bar, baz=qux\""], + "http://home.example.org:8888/cookie-parser-result?comma0002", + ); assert_eq!(&r, "foo=\"bar, baz=qux\""); } #[test] fn test_comma0003() { - let r = run("http://home.example.org:8888/cookie-parser?comma0003", - &["foo=bar; b,az=qux"], - "http://home.example.org:8888/cookie-parser-result?comma0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0003", + &["foo=bar; b,az=qux"], + "http://home.example.org:8888/cookie-parser-result?comma0003", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0004() { - let r = run("http://home.example.org:8888/cookie-parser?comma0004", - &["foo=bar; baz=q,ux"], - "http://home.example.org:8888/cookie-parser-result?comma0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0004", + &["foo=bar; baz=q,ux"], + "http://home.example.org:8888/cookie-parser-result?comma0004", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0005() { - let r = run("http://home.example.org:8888/cookie-parser?comma0005", - &["foo=bar; Max-Age=50,399"], - "http://home.example.org:8888/cookie-parser-result?comma0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0005", + &["foo=bar; Max-Age=50,399"], + "http://home.example.org:8888/cookie-parser-result?comma0005", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0006() { - let r = run("http://home.example.org:8888/cookie-parser?comma0006", - &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], - "http://home.example.org:8888/cookie-parser-result?comma0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0006", + &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], + "http://home.example.org:8888/cookie-parser-result?comma0006", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0007() { - let r = run("http://home.example.org:8888/cookie-parser?comma0007", - &["foo=bar; Expires=Fri 07 Aug 2019 08:04:19 GMT, baz=qux"], - "http://home.example.org:8888/cookie-parser-result?comma0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?comma0007", + &["foo=bar; Expires=Fri 07 Aug 2019 08:04:19 GMT, baz=qux"], + "http://home.example.org:8888/cookie-parser-result?comma0007", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0001() { - let r = run("http://home.example.org:8888/cookie-parser?domain0001", - &["foo=bar; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0001", + &["foo=bar; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0001", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0002() { - let r = run("http://home.example.org:8888/cookie-parser?domain0002", - &["foo=bar; domain=home.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0002", + &["foo=bar; domain=home.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0002", + ); assert_eq!(&r, ""); } #[test] fn test_domain0003() { - let r = run("http://home.example.org:8888/cookie-parser?domain0003", - &["foo=bar; domain=.home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0003", + &["foo=bar; domain=.home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0003", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0004() { - let r = run("http://home.example.org:8888/cookie-parser?domain0004", - &["foo=bar; domain=home.example.org"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0004", + &["foo=bar; domain=home.example.org"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0004", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0005() { - let r = run("http://home.example.org:8888/cookie-parser?domain0005", - &["foo=bar; domain=.home.example.org"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0005", + &["foo=bar; domain=.home.example.org"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0005", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0006() { - let r = run("http://home.example.org:8888/cookie-parser?domain0006", - &["foo=bar; domain=.home.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0006", + &["foo=bar; domain=.home.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0006", + ); assert_eq!(&r, ""); } #[test] fn test_domain0007() { - let r = run("http://home.example.org:8888/cookie-parser?domain0007", - &["foo=bar; domain=sibling.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0007", + &["foo=bar; domain=sibling.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0007", + ); assert_eq!(&r, ""); } #[test] fn test_domain0008() { - let r = run("http://home.example.org:8888/cookie-parser?domain0008", - &["foo=bar; domain=.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0008", + &["foo=bar; domain=.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0008", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0009() { - let r = run("http://home.example.org:8888/cookie-parser?domain0009", - &["foo=bar; domain=example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0009", + &["foo=bar; domain=example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0009", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0010() { - let r = run("http://home.example.org:8888/cookie-parser?domain0010", - &["foo=bar; domain=..home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0010", + &["foo=bar; domain=..home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0010", + ); assert_eq!(&r, ""); } #[test] fn test_domain0011() { - let r = run("http://home.example.org:8888/cookie-parser?domain0011", - &["foo=bar; domain=home..example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0011", + &["foo=bar; domain=home..example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0011", + ); assert_eq!(&r, ""); } #[test] fn test_domain0012() { - let r = run("http://home.example.org:8888/cookie-parser?domain0012", - &["foo=bar; domain= .home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0012", + &["foo=bar; domain= .home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0012", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0013() { - let r = run("http://home.example.org:8888/cookie-parser?domain0013", - &["foo=bar; domain= . home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0013", + &["foo=bar; domain= . home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0013", + ); assert_eq!(&r, ""); } #[test] fn test_domain0014() { - let r = run("http://home.example.org:8888/cookie-parser?domain0014", - &["foo=bar; domain=home.example.org."], - "http://home.example.org:8888/cookie-parser-result?domain0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0014", + &["foo=bar; domain=home.example.org."], + "http://home.example.org:8888/cookie-parser-result?domain0014", + ); assert_eq!(&r, ""); } #[test] fn test_domain0015() { - let r = run("http://home.example.org:8888/cookie-parser?domain0015", - &["foo=bar; domain=home.example.org.."], - "http://home.example.org:8888/cookie-parser-result?domain0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0015", + &["foo=bar; domain=home.example.org.."], + "http://home.example.org:8888/cookie-parser-result?domain0015", + ); assert_eq!(&r, ""); } #[test] fn test_domain0016() { - let r = run("http://home.example.org:8888/cookie-parser?domain0016", - &["foo=bar; domain=home.example.org ."], - "http://home.example.org:8888/cookie-parser-result?domain0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0016", + &["foo=bar; domain=home.example.org ."], + "http://home.example.org:8888/cookie-parser-result?domain0016", + ); assert_eq!(&r, ""); } #[test] fn test_domain0017() { - let r = run("http://home.example.org:8888/cookie-parser?domain0017", - &["foo=bar; domain=.org"], - "http://home.example.org:8888/cookie-parser-result?domain0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0017", + &["foo=bar; domain=.org"], + "http://home.example.org:8888/cookie-parser-result?domain0017", + ); assert_eq!(&r, ""); } #[test] fn test_domain0018() { - let r = run("http://home.example.org:8888/cookie-parser?domain0018", - &["foo=bar; domain=.org."], - "http://home.example.org:8888/cookie-parser-result?domain0018"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0018", + &["foo=bar; domain=.org."], + "http://home.example.org:8888/cookie-parser-result?domain0018", + ); assert_eq!(&r, ""); } #[test] fn test_domain0019() { - let r = run("http://home.example.org:8888/cookie-parser?domain0019", - &["foo=bar; domain=home.example.org", "foo2=bar2; domain=.home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0019"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0019", + &[ + "foo=bar; domain=home.example.org", + "foo2=bar2; domain=.home.example.org", + ], + "http://home.example.org:8888/cookie-parser-result?domain0019", + ); assert_eq!(&r, "foo=bar; foo2=bar2"); } #[test] fn test_domain0020() { - let r = run("http://home.example.org:8888/cookie-parser?domain0020", - &["foo2=bar2; domain=.home.example.org", "foo=bar; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0020"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0020", + &[ + "foo2=bar2; domain=.home.example.org", + "foo=bar; domain=home.example.org", + ], + "http://home.example.org:8888/cookie-parser-result?domain0020", + ); assert_eq!(&r, "foo2=bar2; foo=bar"); } #[test] fn test_domain0021() { - let r = run("http://home.example.org:8888/cookie-parser?domain0021", - &["foo=bar; domain=\"home.example.org\""], - "http://home.example.org:8888/cookie-parser-result?domain0021"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0021", + &["foo=bar; domain=\"home.example.org\""], + "http://home.example.org:8888/cookie-parser-result?domain0021", + ); assert_eq!(&r, ""); } #[test] fn test_domain0022() { - let r = run("http://home.example.org:8888/cookie-parser?domain0022", - &["foo=bar; domain=home.example.org", "foo2=bar2; domain=.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0022"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0022", + &[ + "foo=bar; domain=home.example.org", + "foo2=bar2; domain=.example.org", + ], + "http://home.example.org:8888/cookie-parser-result?domain0022", + ); assert_eq!(&r, "foo=bar; foo2=bar2"); } #[test] fn test_domain0023() { - let r = run("http://home.example.org:8888/cookie-parser?domain0023", - &["foo2=bar2; domain=.example.org", "foo=bar; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0023"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0023", + &[ + "foo2=bar2; domain=.example.org", + "foo=bar; domain=home.example.org", + ], + "http://home.example.org:8888/cookie-parser-result?domain0023", + ); assert_eq!(&r, "foo2=bar2; foo=bar"); } #[test] fn test_domain0024() { - let r = run("http://home.example.org:8888/cookie-parser?domain0024", - &["foo=bar; domain=.example.org; domain=home.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0024"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0024", + &["foo=bar; domain=.example.org; domain=home.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0024", + ); assert_eq!(&r, ""); } #[test] fn test_domain0025() { - let r = run("http://home.example.org:8888/cookie-parser?domain0025", - &["foo=bar; domain=home.example.org; domain=.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0025"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0025", + &["foo=bar; domain=home.example.org; domain=.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0025", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0026() { - let r = run("http://home.example.org:8888/cookie-parser?domain0026", - &["foo=bar; domain=home.eXaMpLe.org"], - "http://home.example.org:8888/cookie-parser-result?domain0026"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0026", + &["foo=bar; domain=home.eXaMpLe.org"], + "http://home.example.org:8888/cookie-parser-result?domain0026", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0027() { - let r = run("http://home.example.org:8888/cookie-parser?domain0027", - &["foo=bar; domain=home.example.org:8888"], - "http://home.example.org:8888/cookie-parser-result?domain0027"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0027", + &["foo=bar; domain=home.example.org:8888"], + "http://home.example.org:8888/cookie-parser-result?domain0027", + ); assert_eq!(&r, ""); } #[test] fn test_domain0028() { - let r = run("http://home.example.org:8888/cookie-parser?domain0028", - &["foo=bar; domain=subdomain.home.example.org"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0028"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0028", + &["foo=bar; domain=subdomain.home.example.org"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0028", + ); assert_eq!(&r, ""); } #[test] fn test_domain0029() { - let r = run("http://home.example.org:8888/cookie-parser?domain0029", - &["foo=bar"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0029"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0029", + &["foo=bar"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0029", + ); assert_eq!(&r, ""); } #[test] fn test_domain0031() { - let r = run("http://home.example.org:8888/cookie-parser?domain0031", - &["foo=bar; domain=home.example.org; domain=.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0031"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0031", + &["foo=bar; domain=home.example.org; domain=.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0031", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0033() { - let r = run("http://home.example.org:8888/cookie-parser?domain0033", - &["foo=bar; domain=home.example.org"], - "http://hoMe.eXaMplE.org:8888/cookie-parser-result?domain0033"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0033", + &["foo=bar; domain=home.example.org"], + "http://hoMe.eXaMplE.org:8888/cookie-parser-result?domain0033", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0034() { - let r = run("http://home.example.org:8888/cookie-parser?domain0034", - &["foo=bar; domain=home.example.org; domain=home.example.com"], - "http://home.example.org:8888/cookie-parser-result?domain0034"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0034", + &["foo=bar; domain=home.example.org; domain=home.example.com"], + "http://home.example.org:8888/cookie-parser-result?domain0034", + ); assert_eq!(&r, ""); } #[test] fn test_domain0035() { - let r = run("http://home.example.org:8888/cookie-parser?domain0035", - &["foo=bar; domain=home.example.com; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0035"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0035", + &["foo=bar; domain=home.example.com; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0035", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0036() { - let r = run("http://home.example.org:8888/cookie-parser?domain0036", - &["foo=bar; domain=home.example.org; domain=home.example.com; domain=home.\ -example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0036"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0036", + &[ + "foo=bar; domain=home.example.org; domain=home.example.com; domain=home.\ + example.org", + ], + "http://home.example.org:8888/cookie-parser-result?domain0036", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0037() { - let r = run("http://home.example.org:8888/cookie-parser?domain0037", - &["foo=bar; domain=home.example.com; domain=home.example.org; domain=home.\ -example.com"], - "http://home.example.org:8888/cookie-parser-result?domain0037"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0037", + &[ + "foo=bar; domain=home.example.com; domain=home.example.org; domain=home.\ + example.com", + ], + "http://home.example.org:8888/cookie-parser-result?domain0037", + ); assert_eq!(&r, ""); } #[test] fn test_domain0038() { - let r = run("http://home.example.org:8888/cookie-parser?domain0038", - &["foo=bar; domain=home.example.org; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0038"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0038", + &["foo=bar; domain=home.example.org; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0038", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0039() { - let r = run("http://home.example.org:8888/cookie-parser?domain0039", - &["foo=bar; domain=home.example.org; domain=example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0039"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0039", + &["foo=bar; domain=home.example.org; domain=example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0039", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0040() { - let r = run("http://home.example.org:8888/cookie-parser?domain0040", - &["foo=bar; domain=example.org; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0040"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0040", + &["foo=bar; domain=example.org; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0040", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0041() { - let r = run("http://home.example.org:8888/cookie-parser?domain0041", - &["foo=bar; domain=.sibling.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0041"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0041", + &["foo=bar; domain=.sibling.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0041", + ); assert_eq!(&r, ""); } #[test] fn test_domain0042() { - let r = run("http://home.example.org:8888/cookie-parser?domain0042", - &["foo=bar; domain=.sibling.home.example.org"], - "http://sibling.home.example.org:8888/cookie-parser-result?domain0042"); + let r = run( + "http://home.example.org:8888/cookie-parser?domain0042", + &["foo=bar; domain=.sibling.home.example.org"], + "http://sibling.home.example.org:8888/cookie-parser-result?domain0042", + ); assert_eq!(&r, ""); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0001() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0001", - &["foo=bar; max-age=-1"], - "http://home.example.org:8888/cookie-parser-result?mozilla0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0001", + &["foo=bar; max-age=-1"], + "http://home.example.org:8888/cookie-parser-result?mozilla0001", + ); assert_eq!(&r, ""); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0002() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0002", - &["foo=bar; max-age=0"], - "http://home.example.org:8888/cookie-parser-result?mozilla0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0002", + &["foo=bar; max-age=0"], + "http://home.example.org:8888/cookie-parser-result?mozilla0002", + ); assert_eq!(&r, ""); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0003() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0003", - &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], - "http://home.example.org:8888/cookie-parser-result?mozilla0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0003", + &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], + "http://home.example.org:8888/cookie-parser-result?mozilla0003", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0004() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0004", - &["foo=bar; max-age=60"], - "http://home.example.org:8888/cookie-parser-result?mozilla0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0004", + &["foo=bar; max-age=60"], + "http://home.example.org:8888/cookie-parser-result?mozilla0004", + ); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0005() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0005", - &["foo=bar; max-age=-20"], - "http://home.example.org:8888/cookie-parser-result?mozilla0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0005", + &["foo=bar; max-age=-20"], + "http://home.example.org:8888/cookie-parser-result?mozilla0005", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0006() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0006", - &["foo=bar; max-age=60"], - "http://home.example.org:8888/cookie-parser-result?mozilla0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0006", + &["foo=bar; max-age=60"], + "http://home.example.org:8888/cookie-parser-result?mozilla0006", + ); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0007() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0007", - &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], - "http://home.example.org:8888/cookie-parser-result?mozilla0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0007", + &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], + "http://home.example.org:8888/cookie-parser-result?mozilla0007", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0008() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0008", - &["foo=bar; max-age=60", "foo1=bar; max-age=60"], - "http://home.example.org:8888/cookie-parser-result?mozilla0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0008", + &["foo=bar; max-age=60", "foo1=bar; max-age=60"], + "http://home.example.org:8888/cookie-parser-result?mozilla0008", + ); assert_eq!(&r, "foo=bar; foo1=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0009() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0009", - &["foo=bar; max-age=60", "foo1=bar; max-age=60", "foo=differentvalue; max-age=0"], - "http://home.example.org:8888/cookie-parser-result?mozilla0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0009", + &[ + "foo=bar; max-age=60", + "foo1=bar; max-age=60", + "foo=differentvalue; max-age=0", + ], + "http://home.example.org:8888/cookie-parser-result?mozilla0009", + ); assert_eq!(&r, "foo1=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0010() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0010", - &["foo=bar; max-age=60", - "foo1=bar; max-age=60", - "foo=differentvalue; max-age=0", - "foo2=evendifferentvalue; max-age=0"], - "http://home.example.org:8888/cookie-parser-result?mozilla0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0010", + &[ + "foo=bar; max-age=60", + "foo1=bar; max-age=60", + "foo=differentvalue; max-age=0", + "foo2=evendifferentvalue; max-age=0", + ], + "http://home.example.org:8888/cookie-parser-result?mozilla0010", + ); assert_eq!(&r, "foo1=bar"); } #[test] fn test_mozilla0011() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0011", - &["test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! ma\ -x-age=20;=;;"], - "http://home.example.org:8888/cookie-parser-result?mozilla0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0011", + &[ + "test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! ma\ + x-age=20;=;;", + ], + "http://home.example.org:8888/cookie-parser-result?mozilla0011", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0012() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0012", - &["test=\"fubar! = foo;bar\\\";\" parser; max-age=6", "five; max-age=2.63,"], - "http://home.example.org:8888/cookie-parser-result?mozilla0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0012", + &[ + "test=\"fubar! = foo;bar\\\";\" parser; max-age=6", + "five; max-age=2.63,", + ], + "http://home.example.org:8888/cookie-parser-result?mozilla0012", + ); assert_eq!(&r, "test=\"fubar! = foo"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0013() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0013", - &["test=kill; max-age=0", "five; max-age=0"], - "http://home.example.org:8888/cookie-parser-result?mozilla0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0013", + &["test=kill; max-age=0", "five; max-age=0"], + "http://home.example.org:8888/cookie-parser-result?mozilla0013", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0014() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0014", - &["six"], - "http://home.example.org:8888/cookie-parser-result?mozilla0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0014", + &["six"], + "http://home.example.org:8888/cookie-parser-result?mozilla0014", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0015() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0015", - &["six", "seven"], - "http://home.example.org:8888/cookie-parser-result?mozilla0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0015", + &["six", "seven"], + "http://home.example.org:8888/cookie-parser-result?mozilla0015", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0016() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0016", - &["six", "seven", " =eight"], - "http://home.example.org:8888/cookie-parser-result?mozilla0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0016", + &["six", "seven", " =eight"], + "http://home.example.org:8888/cookie-parser-result?mozilla0016", + ); assert_eq!(&r, ""); } #[test] fn test_mozilla0017() { - let r = run("http://home.example.org:8888/cookie-parser?mozilla0017", - &["six", "seven", " =eight", "test=six"], - "http://home.example.org:8888/cookie-parser-result?mozilla0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?mozilla0017", + &["six", "seven", " =eight", "test=six"], + "http://home.example.org:8888/cookie-parser-result?mozilla0017", + ); assert_eq!(&r, "test=six"); } #[test] fn test_name0001() { - let r = run("http://home.example.org:8888/cookie-parser?name0001", - &["a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0001", + &["a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0001", + ); assert_eq!(&r, "a=bar"); } #[test] fn test_name0002() { - let r = run("http://home.example.org:8888/cookie-parser?name0002", - &["1=bar"], - "http://home.example.org:8888/cookie-parser-result?name0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0002", + &["1=bar"], + "http://home.example.org:8888/cookie-parser-result?name0002", + ); assert_eq!(&r, "1=bar"); } #[test] fn test_name0003() { - let r = run("http://home.example.org:8888/cookie-parser?name0003", - &["$=bar"], - "http://home.example.org:8888/cookie-parser-result?name0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0003", + &["$=bar"], + "http://home.example.org:8888/cookie-parser-result?name0003", + ); assert_eq!(&r, "$=bar"); } #[test] fn test_name0004() { - let r = run("http://home.example.org:8888/cookie-parser?name0004", - &["!a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0004", + &["!a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0004", + ); assert_eq!(&r, "!a=bar"); } #[test] fn test_name0005() { - let r = run("http://home.example.org:8888/cookie-parser?name0005", - &["@a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0005", + &["@a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0005", + ); assert_eq!(&r, "@a=bar"); } #[test] fn test_name0006() { - let r = run("http://home.example.org:8888/cookie-parser?name0006", - &["#a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0006", + &["#a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0006", + ); assert_eq!(&r, "#a=bar"); } #[test] fn test_name0007() { - let r = run("http://home.example.org:8888/cookie-parser?name0007", - &["$a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0007", + &["$a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0007", + ); assert_eq!(&r, "$a=bar"); } #[test] fn test_name0008() { - let r = run("http://home.example.org:8888/cookie-parser?name0008", - &["%a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0008", + &["%a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0008", + ); assert_eq!(&r, "%a=bar"); } #[test] fn test_name0009() { - let r = run("http://home.example.org:8888/cookie-parser?name0009", - &["^a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0009", + &["^a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0009", + ); assert_eq!(&r, "^a=bar"); } #[test] fn test_name0010() { - let r = run("http://home.example.org:8888/cookie-parser?name0010", - &["&a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0010", + &["&a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0010", + ); assert_eq!(&r, "&a=bar"); } #[test] fn test_name0011() { - let r = run("http://home.example.org:8888/cookie-parser?name0011", - &["*a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0011", + &["*a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0011", + ); assert_eq!(&r, "*a=bar"); } #[test] fn test_name0012() { - let r = run("http://home.example.org:8888/cookie-parser?name0012", - &["(a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0012", + &["(a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0012", + ); assert_eq!(&r, "(a=bar"); } #[test] fn test_name0013() { - let r = run("http://home.example.org:8888/cookie-parser?name0013", - &[")a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0013", + &[")a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0013", + ); assert_eq!(&r, ")a=bar"); } #[test] fn test_name0014() { - let r = run("http://home.example.org:8888/cookie-parser?name0014", - &["-a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0014", + &["-a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0014", + ); assert_eq!(&r, "-a=bar"); } #[test] fn test_name0015() { - let r = run("http://home.example.org:8888/cookie-parser?name0015", - &["_a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0015", + &["_a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0015", + ); assert_eq!(&r, "_a=bar"); } #[test] fn test_name0016() { - let r = run("http://home.example.org:8888/cookie-parser?name0016", - &["+=bar"], - "http://home.example.org:8888/cookie-parser-result?name0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0016", + &["+=bar"], + "http://home.example.org:8888/cookie-parser-result?name0016", + ); assert_eq!(&r, "+=bar"); } #[test] fn test_name0017() { - let r = run("http://home.example.org:8888/cookie-parser?name0017", - &["=a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0017", + &["=a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0017", + ); assert_eq!(&r, ""); } #[test] fn test_name0018() { - let r = run("http://home.example.org:8888/cookie-parser?name0018", - &["a =bar"], - "http://home.example.org:8888/cookie-parser-result?name0018"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0018", + &["a =bar"], + "http://home.example.org:8888/cookie-parser-result?name0018", + ); assert_eq!(&r, "a=bar"); } #[test] fn test_name0019() { - let r = run("http://home.example.org:8888/cookie-parser?name0019", - &["\"a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0019"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0019", + &["\"a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0019", + ); assert_eq!(&r, "\"a=bar"); } #[test] fn test_name0020() { - let r = run("http://home.example.org:8888/cookie-parser?name0020", - &["\"a=b\"=bar"], - "http://home.example.org:8888/cookie-parser-result?name0020"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0020", + &["\"a=b\"=bar"], + "http://home.example.org:8888/cookie-parser-result?name0020", + ); assert_eq!(&r, "\"a=b\"=bar"); } #[test] fn test_name0021() { - let r = run("http://home.example.org:8888/cookie-parser?name0021", - &["\"a=b\"=bar", "\"a=qux"], - "http://home.example.org:8888/cookie-parser-result?name0021"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0021", + &["\"a=b\"=bar", "\"a=qux"], + "http://home.example.org:8888/cookie-parser-result?name0021", + ); assert_eq!(&r, "\"a=qux"); } #[test] fn test_name0022() { - let r = run("http://home.example.org:8888/cookie-parser?name0022", - &[" foo=bar"], - "http://home.example.org:8888/cookie-parser-result?name0022"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0022", + &[" foo=bar"], + "http://home.example.org:8888/cookie-parser-result?name0022", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_name0023() { - let r = run("http://home.example.org:8888/cookie-parser?name0023", - &["foo;bar=baz"], - "http://home.example.org:8888/cookie-parser-result?name0023"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0023", + &["foo;bar=baz"], + "http://home.example.org:8888/cookie-parser-result?name0023", + ); assert_eq!(&r, ""); } #[test] fn test_name0024() { - let r = run("http://home.example.org:8888/cookie-parser?name0024", - &["$Version=1; foo=bar"], - "http://home.example.org:8888/cookie-parser-result?name0024"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0024", + &["$Version=1; foo=bar"], + "http://home.example.org:8888/cookie-parser-result?name0024", + ); assert_eq!(&r, "$Version=1"); } #[test] fn test_name0025() { - let r = run("http://home.example.org:8888/cookie-parser?name0025", - &["===a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0025"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0025", + &["===a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0025", + ); assert_eq!(&r, ""); } #[test] fn test_name0026() { - let r = run("http://home.example.org:8888/cookie-parser?name0026", - &["foo=bar"], - "http://home.example.org:8888/cookie-parser-result?name0026"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0026", + &["foo=bar"], + "http://home.example.org:8888/cookie-parser-result?name0026", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_name0027() { - let r = run("http://home.example.org:8888/cookie-parser?name0027", - &["foo=bar ;"], - "http://home.example.org:8888/cookie-parser-result?name0027"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0027", + &["foo=bar ;"], + "http://home.example.org:8888/cookie-parser-result?name0027", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_name0028() { - let r = run("http://home.example.org:8888/cookie-parser?name0028", - &["=a"], - "http://home.example.org:8888/cookie-parser-result?name0028"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0028", + &["=a"], + "http://home.example.org:8888/cookie-parser-result?name0028", + ); assert_eq!(&r, ""); } #[test] fn test_name0029() { - let r = run("http://home.example.org:8888/cookie-parser?name0029", - &["="], - "http://home.example.org:8888/cookie-parser-result?name0029"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0029", + &["="], + "http://home.example.org:8888/cookie-parser-result?name0029", + ); assert_eq!(&r, ""); } #[test] fn test_name0030() { - let r = run("http://home.example.org:8888/cookie-parser?name0030", - &["foo bar=baz"], - "http://home.example.org:8888/cookie-parser-result?name0030"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0030", + &["foo bar=baz"], + "http://home.example.org:8888/cookie-parser-result?name0030", + ); assert_eq!(&r, "foo bar=baz"); } #[test] fn test_name0031() { - let r = run("http://home.example.org:8888/cookie-parser?name0031", - &["\"foo;bar\"=baz"], - "http://home.example.org:8888/cookie-parser-result?name0031"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0031", + &["\"foo;bar\"=baz"], + "http://home.example.org:8888/cookie-parser-result?name0031", + ); assert_eq!(&r, ""); } #[test] fn test_name0032() { - let r = run("http://home.example.org:8888/cookie-parser?name0032", - &["\"foo\\\"bar;baz\"=qux"], - "http://home.example.org:8888/cookie-parser-result?name0032"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0032", + &["\"foo\\\"bar;baz\"=qux"], + "http://home.example.org:8888/cookie-parser-result?name0032", + ); assert_eq!(&r, ""); } #[test] fn test_name0033() { - let r = run("http://home.example.org:8888/cookie-parser?name0033", - &["=foo=bar", "aaa"], - "http://home.example.org:8888/cookie-parser-result?name0033"); + let r = run( + "http://home.example.org:8888/cookie-parser?name0033", + &["=foo=bar", "aaa"], + "http://home.example.org:8888/cookie-parser-result?name0033", + ); assert_eq!(&r, ""); } #[test] fn test_optional_domain0030() { - let r = run("http://home.example.org:8888/cookie-parser?optional-domain0030", - &["foo=bar; domain="], - "http://home.example.org:8888/cookie-parser-result?optional-domain0030"); + let r = run( + "http://home.example.org:8888/cookie-parser?optional-domain0030", + &["foo=bar; domain="], + "http://home.example.org:8888/cookie-parser-result?optional-domain0030", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_optional_domain0041() { - let r = run("http://home.example.org:8888/cookie-parser?optional-domain0041", - &["foo=bar; domain=example.org; domain="], - "http://home.example.org:8888/cookie-parser-result?optional-domain0041"); + let r = run( + "http://home.example.org:8888/cookie-parser?optional-domain0041", + &["foo=bar; domain=example.org; domain="], + "http://home.example.org:8888/cookie-parser-result?optional-domain0041", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_optional_domain0042() { - let r = run("http://home.example.org:8888/cookie-parser?optional-domain0042", - &["foo=bar; domain=foo.example.org; domain="], - "http://home.example.org:8888/cookie-parser-result?optional-domain0042"); + let r = run( + "http://home.example.org:8888/cookie-parser?optional-domain0042", + &["foo=bar; domain=foo.example.org; domain="], + "http://home.example.org:8888/cookie-parser-result?optional-domain0042", + ); assert_eq!(&r, ""); } #[test] fn test_optional_domain0043() { - let r = run("http://home.example.org:8888/cookie-parser?optional-domain0043", - &["foo=bar; domain=foo.example.org; domain="], - "http://subdomain.home.example.org:8888/cookie-parser-result?optional-do\ -main0043"); + let r = run( + "http://home.example.org:8888/cookie-parser?optional-domain0043", + &["foo=bar; domain=foo.example.org; domain="], + "http://subdomain.home.example.org:8888/cookie-parser-result?optional-do\ + main0043", + ); assert_eq!(&r, ""); } #[test] fn test_ordering0001() { - let r = run("http://home.example.org:8888/cookie-parser?ordering0001", - &["key=val0;", - "key=val1; path=/cookie-parser-result", - "key=val2; path=/", - "key=val3; path=/bar", - "key=val4; domain=.example.org", - "key=val5; domain=.example.org; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result/foo/baz?ordering0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?ordering0001", + &[ + "key=val0;", + "key=val1; path=/cookie-parser-result", + "key=val2; path=/", + "key=val3; path=/bar", + "key=val4; domain=.example.org", + "key=val5; domain=.example.org; path=/cookie-parser-result/foo", + ], + "http://home.example.org:8888/cookie-parser-result/foo/baz?ordering0001", + ); assert_eq!(&r, "key=val5; key=val1; key=val2; key=val4"); } #[test] fn test_path0001() { - let r = run("http://home.example.org:8888/cookie-parser?path0001", - &["a=b; path=/", "x=y; path=/cookie-parser-result"], - "http://home.example.org:8888/cookie-parser-result?path0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0001", + &["a=b; path=/", "x=y; path=/cookie-parser-result"], + "http://home.example.org:8888/cookie-parser-result?path0001", + ); assert_eq!(&r, "x=y; a=b"); } #[test] fn test_path0002() { - let r = run("http://home.example.org:8888/cookie-parser?path0002", - &["a=b; path=/cookie-parser-result", "x=y; path=/"], - "http://home.example.org:8888/cookie-parser-result?path0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0002", + &["a=b; path=/cookie-parser-result", "x=y; path=/"], + "http://home.example.org:8888/cookie-parser-result?path0002", + ); assert_eq!(&r, "a=b; x=y"); } #[test] fn test_path0003() { - let r = run("http://home.example.org:8888/cookie-parser?path0003", - &["x=y; path=/", "a=b; path=/cookie-parser-result"], - "http://home.example.org:8888/cookie-parser-result?path0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0003", + &["x=y; path=/", "a=b; path=/cookie-parser-result"], + "http://home.example.org:8888/cookie-parser-result?path0003", + ); assert_eq!(&r, "a=b; x=y"); } #[test] fn test_path0004() { - let r = run("http://home.example.org:8888/cookie-parser?path0004", - &["x=y; path=/cookie-parser-result", "a=b; path=/"], - "http://home.example.org:8888/cookie-parser-result?path0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0004", + &["x=y; path=/cookie-parser-result", "a=b; path=/"], + "http://home.example.org:8888/cookie-parser-result?path0004", + ); assert_eq!(&r, "x=y; a=b"); } #[test] fn test_path0005() { - let r = run("http://home.example.org:8888/cookie-parser?path0005", - &["foo=bar; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result?path0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0005", + &["foo=bar; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result?path0005", + ); assert_eq!(&r, ""); } #[test] fn test_path0006() { - let r = run("http://home.example.org:8888/cookie-parser?path0006", - &["foo=bar", "foo=qux; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result?path0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0006", + &["foo=bar", "foo=qux; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result?path0006", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0007() { - let r = run("http://home.example.org:8888/cookie-parser?path0007", - &["foo=bar; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result/foo?path0007"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0007", + &["foo=bar; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result/foo?path0007", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0008() { - let r = run("http://home.example.org:8888/cookie-parser?path0008", - &["foo=bar; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result/bar?path0008"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0008", + &["foo=bar; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result/bar?path0008", + ); assert_eq!(&r, ""); } #[test] fn test_path0009() { - let r = run("http://home.example.org:8888/cookie-parser?path0009", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/foo?path0009"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0009", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/foo?path0009", + ); assert_eq!(&r, ""); } #[test] fn test_path0010() { - let r = run("http://home.example.org:8888/cookie-parser?path0010", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0010"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0010", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0010", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0011() { - let r = run("http://home.example.org:8888/cookie-parser?path0011", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/bar/qux?path0011"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0011", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/bar/qux?path0011", + ); assert_eq!(&r, ""); } #[test] fn test_path0012() { - let r = run("http://home.example.org:8888/cookie-parser?path0012", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/foo/baz?path0012"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0012", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/foo/baz?path0012", + ); assert_eq!(&r, ""); } #[test] fn test_path0013() { - let r = run("http://home.example.org:8888/cookie-parser?path0013", - &["foo=bar; path=/cookie-parser-result/foo/qux/"], - "http://home.example.org:8888/cookie-parser-result/foo/baz?path0013"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0013", + &["foo=bar; path=/cookie-parser-result/foo/qux/"], + "http://home.example.org:8888/cookie-parser-result/foo/baz?path0013", + ); assert_eq!(&r, ""); } #[test] fn test_path0014() { - let r = run("http://home.example.org:8888/cookie-parser?path0014", - &["foo=bar; path=/cookie-parser-result/foo/qux/"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0014"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0014", + &["foo=bar; path=/cookie-parser-result/foo/qux/"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0014", + ); assert_eq!(&r, ""); } #[test] fn test_path0015() { - let r = run("http://home.example.org:8888/cookie-parser?path0015", - &["foo=bar; path=/cookie-parser-result/foo/qux/"], - "http://home.example.org:8888/cookie-parser-result/foo/qux/?path0015"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0015", + &["foo=bar; path=/cookie-parser-result/foo/qux/"], + "http://home.example.org:8888/cookie-parser-result/foo/qux/?path0015", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0016() { - let r = run("http://home.example.org:8888/cookie-parser?path0016", - &["foo=bar; path=/cookie-parser-result/foo/"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0016"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0016", + &["foo=bar; path=/cookie-parser-result/foo/"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0016", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0017() { - let r = run("http://home.example.org:8888/cookie-parser?path0017", - &["foo=bar; path=/cookie-parser-result/foo/"], - "http://home.example.org:8888/cookie-parser-result/foo//qux?path0017"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0017", + &["foo=bar; path=/cookie-parser-result/foo/"], + "http://home.example.org:8888/cookie-parser-result/foo//qux?path0017", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0018() { - let r = run("http://home.example.org:8888/cookie-parser?path0018", - &["foo=bar; path=/cookie-parser-result/foo/"], - "http://home.example.org:8888/cookie-parser-result/fooqux?path0018"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0018", + &["foo=bar; path=/cookie-parser-result/foo/"], + "http://home.example.org:8888/cookie-parser-result/fooqux?path0018", + ); assert_eq!(&r, ""); } #[test] fn test_path0019() { - let r = run("http://home.example.org:8888/cookie-parser?path0019", - &["foo=bar; path"], - "http://home.example.org:8888/cookie-parser-result?path0019"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0019", + &["foo=bar; path"], + "http://home.example.org:8888/cookie-parser-result?path0019", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0020() { - let r = run("http://home.example.org:8888/cookie-parser?path0020", - &["foo=bar; path="], - "http://home.example.org:8888/cookie-parser-result?path0020"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0020", + &["foo=bar; path="], + "http://home.example.org:8888/cookie-parser-result?path0020", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0021() { - let r = run("http://home.example.org:8888/cookie-parser?path0021", - &["foo=bar; path=/"], - "http://home.example.org:8888/cookie-parser-result?path0021"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0021", + &["foo=bar; path=/"], + "http://home.example.org:8888/cookie-parser-result?path0021", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0022() { - let r = run("http://home.example.org:8888/cookie-parser?path0022", - &["foo=bar; path= /"], - "http://home.example.org:8888/cookie-parser-result?path0022"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0022", + &["foo=bar; path= /"], + "http://home.example.org:8888/cookie-parser-result?path0022", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0023() { - let r = run("http://home.example.org:8888/cookie-parser?path0023", - &["foo=bar; Path=/cookie-PARSER-result"], - "http://home.example.org:8888/cookie-parser-result?path0023"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0023", + &["foo=bar; Path=/cookie-PARSER-result"], + "http://home.example.org:8888/cookie-parser-result?path0023", + ); assert_eq!(&r, ""); } #[test] fn test_path0024() { - let r = run("http://home.example.org:8888/cookie-parser?path0024", - &["foo=bar; path=/cookie-parser-result/foo/qux?"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0024"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0024", + &["foo=bar; path=/cookie-parser-result/foo/qux?"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0024", + ); assert_eq!(&r, ""); } #[test] fn test_path0025() { - let r = run("http://home.example.org:8888/cookie-parser?path0025", - &["foo=bar; path=/cookie-parser-result/foo/qux#"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0025"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0025", + &["foo=bar; path=/cookie-parser-result/foo/qux#"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0025", + ); assert_eq!(&r, ""); } #[test] fn test_path0026() { - let r = run("http://home.example.org:8888/cookie-parser?path0026", - &["foo=bar; path=/cookie-parser-result/foo/qux;"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0026"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0026", + &["foo=bar; path=/cookie-parser-result/foo/qux;"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0026", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0027() { - let r = run("http://home.example.org:8888/cookie-parser?path0027", - &["foo=bar; path=\"/cookie-parser-result/foo/qux;\""], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0027"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0027", + &["foo=bar; path=\"/cookie-parser-result/foo/qux;\""], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0027", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0028() { - let r = run("http://home.example.org:8888/cookie-parser?path0028", - &["foo=bar; path=/cookie-parser-result/f%6Fo/bar"], - "http://home.example.org:8888/cookie-parser-result/foo/bar?path0028"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0028", + &["foo=bar; path=/cookie-parser-result/f%6Fo/bar"], + "http://home.example.org:8888/cookie-parser-result/foo/bar?path0028", + ); assert_eq!(&r, ""); } #[test] fn test_path0029() { - let r = run("http://home.example.org:8888/cookie-parser?path0029", - &["a=b; \tpath\t=\t/cookie-parser-result", "x=y; \tpath\t=\t/book"], - "http://home.example.org:8888/cookie-parser-result?path0029"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0029", + &[ + "a=b; \tpath\t=\t/cookie-parser-result", + "x=y; \tpath\t=\t/book", + ], + "http://home.example.org:8888/cookie-parser-result?path0029", + ); assert_eq!(&r, "a=b"); } #[test] fn test_path0030() { - let r = run("http://home.example.org:8888/cookie-parser?path0030", - &["foo=bar; path=/dog; path="], - "http://home.example.org:8888/cookie-parser-result?path0030"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0030", + &["foo=bar; path=/dog; path="], + "http://home.example.org:8888/cookie-parser-result?path0030", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0031() { - let r = run("http://home.example.org:8888/cookie-parser?path0031", - &["foo=bar; path=; path=/dog"], - "http://home.example.org:8888/cookie-parser-result?path0031"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0031", + &["foo=bar; path=; path=/dog"], + "http://home.example.org:8888/cookie-parser-result?path0031", + ); assert_eq!(&r, ""); } #[test] fn test_path0032() { - let r = run("http://home.example.org:8888/cookie-parser?path0032", - &["foo=bar; path=/cookie-parser-result", "foo=qux; path=/cookie-parser-result/"], - "http://home.example.org:8888/cookie-parser-result/dog?path0032"); + let r = run( + "http://home.example.org:8888/cookie-parser?path0032", + &[ + "foo=bar; path=/cookie-parser-result", + "foo=qux; path=/cookie-parser-result/", + ], + "http://home.example.org:8888/cookie-parser-result/dog?path0032", + ); assert_eq!(&r, "foo=qux; foo=bar"); } #[test] fn test_value0001() { - let r = run("http://home.example.org:8888/cookie-parser?value0001", - &["foo= bar"], - "http://home.example.org:8888/cookie-parser-result?value0001"); + let r = run( + "http://home.example.org:8888/cookie-parser?value0001", + &["foo= bar"], + "http://home.example.org:8888/cookie-parser-result?value0001", + ); assert_eq!(&r, "foo=bar"); } #[test] fn test_value0002() { - let r = run("http://home.example.org:8888/cookie-parser?value0002", - &["foo=\"bar\""], - "http://home.example.org:8888/cookie-parser-result?value0002"); + let r = run( + "http://home.example.org:8888/cookie-parser?value0002", + &["foo=\"bar\""], + "http://home.example.org:8888/cookie-parser-result?value0002", + ); assert_eq!(&r, "foo=\"bar\""); } #[test] fn test_value0003() { - let r = run("http://home.example.org:8888/cookie-parser?value0003", - &["foo=\" bar \""], - "http://home.example.org:8888/cookie-parser-result?value0003"); + let r = run( + "http://home.example.org:8888/cookie-parser?value0003", + &["foo=\" bar \""], + "http://home.example.org:8888/cookie-parser-result?value0003", + ); assert_eq!(&r, "foo=\" bar \""); } #[test] fn test_value0004() { - let r = run("http://home.example.org:8888/cookie-parser?value0004", - &["foo=\"bar;baz\""], - "http://home.example.org:8888/cookie-parser-result?value0004"); + let r = run( + "http://home.example.org:8888/cookie-parser?value0004", + &["foo=\"bar;baz\""], + "http://home.example.org:8888/cookie-parser-result?value0004", + ); assert_eq!(&r, "foo=\"bar"); } #[test] fn test_value0005() { - let r = run("http://home.example.org:8888/cookie-parser?value0005", - &["foo=\"bar=baz\""], - "http://home.example.org:8888/cookie-parser-result?value0005"); + let r = run( + "http://home.example.org:8888/cookie-parser?value0005", + &["foo=\"bar=baz\""], + "http://home.example.org:8888/cookie-parser-result?value0005", + ); assert_eq!(&r, "foo=\"bar=baz\""); } #[test] fn test_value0006() { - let r = run("http://home.example.org:8888/cookie-parser?value0006", - &["\tfoo\t=\tbar\t \t;\tttt"], - "http://home.example.org:8888/cookie-parser-result?value0006"); + let r = run( + "http://home.example.org:8888/cookie-parser?value0006", + &["\tfoo\t=\tbar\t \t;\tttt"], + "http://home.example.org:8888/cookie-parser-result?value0006", + ); assert_eq!(&r, "foo=bar"); } diff --git a/components/net/tests/data_loader.rs b/components/net/tests/data_loader.rs index 56b70af9e99..cc8bfd69b38 100644 --- a/components/net/tests/data_loader.rs +++ b/components/net/tests/data_loader.rs @@ -14,10 +14,12 @@ use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] -fn assert_parse(url: &'static str, - content_type: Option, - charset: Option<&str>, - data: Option<&[u8]>) { +fn assert_parse( + url: &'static str, + content_type: Option, + charset: Option<&str>, + data: Option<&[u8]>, +) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -33,7 +35,10 @@ fn assert_parse(url: &'static str, assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { - Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, + Ok(FetchMetadata::Filtered { + filtered: FilteredMetadata::Basic(m), + .. + }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); @@ -49,7 +54,12 @@ fn assert_parse(url: &'static str, }, None => { assert!(response.is_network_error()); - assert_eq!(response.metadata().err(), Some(NetworkError::Internal("Decoding data URL failed".to_owned()))); + assert_eq!( + response.metadata().err(), + Some(NetworkError::Internal( + "Decoding data URL failed".to_owned() + )) + ); }, } } @@ -63,9 +73,12 @@ fn empty_invalid() { fn plain() { assert_parse( "data:,hello%20world", - Some(ContentType::from("text/plain; charset=US-ASCII".parse::().unwrap())), + Some(ContentType::from( + "text/plain; charset=US-ASCII".parse::().unwrap(), + )), Some("us-ascii"), - Some(b"hello world")); + Some(b"hello world"), + ); } #[test] @@ -74,7 +87,8 @@ fn plain_ct() { "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, - Some(b"hello")); + Some(b"hello"), + ); } #[test] @@ -83,16 +97,20 @@ fn plain_html() { "data:text/html,

Servo

", Some(ContentType::from(mime::TEXT_HTML)), None, - Some(b"

Servo

")); + Some(b"

Servo

"), + ); } #[test] fn plain_charset() { assert_parse( "data:text/plain;charset=latin1,hello", - Some(ContentType::from("text/plain; charset=latin1".parse::().unwrap())), + Some(ContentType::from( + "text/plain; charset=latin1".parse::().unwrap(), + )), Some("latin1"), - Some(b"hello")); + Some(b"hello"), + ); } #[test] @@ -101,16 +119,20 @@ fn plain_only_charset() { "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), - Some(b"hello")); + Some(b"hello"), + ); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", - Some(ContentType::from("text/plain; charset=US-ASCII".parse::().unwrap())), + Some(ContentType::from( + "text/plain; charset=US-ASCII".parse::().unwrap(), + )), Some("us-ascii"), - Some(&[0x0B, 0xAD, 0xBE, 0xEF])); + Some(&[0x0B, 0xAD, 0xBE, 0xEF]), + ); } #[test] @@ -119,14 +141,20 @@ fn base64_ct() { "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, - Some(&[0x0B, 0xAD, 0xBE, 0xEF])); + Some(&[0x0B, 0xAD, 0xBE, 0xEF]), + ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", - Some(ContentType::from("text/plain; charset=koi8-r".parse::().unwrap())), + Some(ContentType::from( + "text/plain; charset=koi8-r".parse::().unwrap(), + )), Some("koi8-r"), - Some(&[0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4])); + Some(&[ + 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, + ]), + ); } diff --git a/components/net/tests/fetch.rs b/components/net/tests/fetch.rs index d0d472614f9..f89ed8170ba 100644 --- a/components/net/tests/fetch.rs +++ b/components/net/tests/fetch.rs @@ -70,7 +70,10 @@ fn test_fetch_on_bad_port_is_network_error() { let fetch_response = fetch(&mut request, None); assert!(fetch_response.is_network_error()); let fetch_error = fetch_response.get_network_error().unwrap(); - assert_eq!(fetch_error, &NetworkError::Internal("Request attempted on bad port".into())) + assert_eq!( + fetch_error, + &NetworkError::Internal("Request attempted on bad port".into()) + ) } #[test] @@ -94,7 +97,7 @@ fn test_fetch_response_body_matches_const_message() { ResponseBody::Done(ref body) => { assert_eq!(&**body, MESSAGE); }, - _ => panic!() + _ => panic!(), }; } @@ -106,7 +109,10 @@ fn test_fetch_aboutblank() { request.referrer = Referrer::NoReferrer; let fetch_response = fetch(&mut request, None); assert!(!fetch_response.is_network_error()); - assert_eq!(*fetch_response.body.lock().unwrap(), ResponseBody::Done(vec![])); + assert_eq!( + *fetch_response.body.lock().unwrap(), + ResponseBody::Done(vec![]) + ); } #[test] @@ -127,11 +133,12 @@ fn test_fetch_blob() { let origin = ServoUrl::parse("http://www.example.org/").unwrap(); let (sender, receiver) = ipc::channel().unwrap(); - context.filemanager.promote_memory(blob_buf, true, sender, "http://www.example.org".into()); + context + .filemanager + .promote_memory(blob_buf, true, sender, "http://www.example.org".into()); let id = receiver.recv().unwrap().unwrap(); let url = ServoUrl::parse(&format!("blob:{}{}", origin.as_str(), id.simple())).unwrap(); - let mut request = Request::new(url, Some(Origin::Origin(origin.origin())), None); let fetch_response = fetch_with_context(&mut request, &context); @@ -139,19 +146,27 @@ fn test_fetch_blob() { assert_eq!(fetch_response.headers.len(), 2); - let content_type: Mime = fetch_response.headers.typed_get::().unwrap().into(); + let content_type: Mime = fetch_response + .headers + .typed_get::() + .unwrap() + .into(); assert_eq!(content_type, mime::TEXT_PLAIN); let content_length: ContentLength = fetch_response.headers.typed_get().unwrap(); assert_eq!(content_length.0, bytes.len() as u64); - assert_eq!(*fetch_response.body.lock().unwrap(), - ResponseBody::Done(bytes.to_vec())); + assert_eq!( + *fetch_response.body.lock().unwrap(), + ResponseBody::Done(bytes.to_vec()) + ); } #[test] fn test_fetch_file() { - let path = Path::new("../../resources/servo.css").canonicalize().unwrap(); + let path = Path::new("../../resources/servo.css") + .canonicalize() + .unwrap(); let url = ServoUrl::from_file_path(path.clone()).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -159,7 +174,11 @@ fn test_fetch_file() { let fetch_response = fetch(&mut request, None); assert!(!fetch_response.is_network_error()); assert_eq!(fetch_response.headers.len(), 1); - let content_type: Mime = fetch_response.headers.typed_get::().unwrap().into(); + let content_type: Mime = fetch_response + .headers + .typed_get::() + .unwrap() + .into(); assert_eq!(content_type, mime::TEXT_CSS); let resp_body = fetch_response.body.lock().unwrap(); @@ -171,7 +190,7 @@ fn test_fetch_file() { ResponseBody::Done(ref val) => { assert_eq!(val, &bytes); }, - _ => panic!() + _ => panic!(), } } @@ -200,15 +219,34 @@ fn test_cors_preflight_fetch() { static ACK: &'static [u8] = b"ACK"; let state = Arc::new(AtomicUsize::new(0)); let handler = move |request: HyperRequest, response: &mut HyperResponse| { - if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 { - assert!(request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)); - assert!(!request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)); - assert!(!request.headers().get(header::REFERER).unwrap().to_str().unwrap().contains("a.html")); - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); - response.headers_mut().typed_insert(AccessControlAllowCredentials); - response.headers_mut().typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); + if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 + { + assert!(request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)); + assert!(!request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)); + assert!(!request + .headers() + .get(header::REFERER) + .unwrap() + .to_str() + .unwrap() + .contains("a.html")); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowCredentials); + response + .headers_mut() + .typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); } else { - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); *response.body_mut() = ACK.to_vec().into(); } }; @@ -228,7 +266,7 @@ fn test_cors_preflight_fetch() { assert!(!fetch_response.is_network_error()); match *fetch_response.body.lock().unwrap() { ResponseBody::Done(ref body) => assert_eq!(&**body, ACK), - _ => panic!() + _ => panic!(), }; } @@ -239,15 +277,30 @@ fn test_cors_preflight_cache_fetch() { let counter = state.clone(); let mut cache = CorsCache::new(); let handler = move |request: HyperRequest, response: &mut HyperResponse| { - if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 { - assert!(request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)); - assert!(!request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)); - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); - response.headers_mut().typed_insert(AccessControlAllowCredentials); - response.headers_mut().typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); - response.headers_mut().typed_insert(AccessControlMaxAge::from(Duration::new(6000, 0))); + if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 + { + assert!(request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)); + assert!(!request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowCredentials); + response + .headers_mut() + .typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); + response + .headers_mut() + .typed_insert(AccessControlMaxAge::from(Duration::new(6000, 0))); } else { - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); *response.body_mut() = ACK.to_vec().into(); } }; @@ -276,11 +329,11 @@ fn test_cors_preflight_cache_fetch() { match *fetch_response0.body.lock().unwrap() { ResponseBody::Done(ref body) => assert_eq!(&**body, ACK), - _ => panic!() + _ => panic!(), }; match *fetch_response1.body.lock().unwrap() { ResponseBody::Done(ref body) => assert_eq!(&**body, ACK), - _ => panic!() + _ => panic!(), }; } @@ -289,14 +342,27 @@ fn test_cors_preflight_fetch_network_error() { static ACK: &'static [u8] = b"ACK"; let state = Arc::new(AtomicUsize::new(0)); let handler = move |request: HyperRequest, response: &mut HyperResponse| { - if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 { - assert!(request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)); - assert!(!request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)); - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); - response.headers_mut().typed_insert(AccessControlAllowCredentials); - response.headers_mut().typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); + if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 + { + assert!(request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD)); + assert!(!request + .headers() + .contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS)); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowCredentials); + response + .headers_mut() + .typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); } else { - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); *response.body_mut() = ACK.to_vec().into(); } }; @@ -318,11 +384,13 @@ fn test_cors_preflight_fetch_network_error() { fn test_fetch_response_is_basic_filtered() { static MESSAGE: &'static [u8] = b""; let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static("")); + response + .headers_mut() + .insert(header::SET_COOKIE, HeaderValue::from_static("")); // this header is obsoleted, so hyper doesn't implement it, but it's still covered by the spec response.headers_mut().insert( HeaderName::from_static("set-cookie2"), - HeaderValue::from_bytes(&vec![]).unwrap() + HeaderValue::from_bytes(&vec![]).unwrap(), ); *response.body_mut() = MESSAGE.to_vec().into(); @@ -340,7 +408,9 @@ fn test_fetch_response_is_basic_filtered() { let headers = fetch_response.headers; assert!(!headers.contains_key(header::SET_COOKIE)); - assert!(headers.get(HeaderName::from_static("set-cookie2")).is_none()); + assert!(headers + .get(HeaderName::from_static("set-cookie2")) + .is_none()); } #[test] @@ -349,28 +419,41 @@ fn test_fetch_response_is_cors_filtered() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { // this is mandatory for the Cors Check to pass // TODO test using different url encodings with this value ie. punycode - response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); + response + .headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); // these are the headers that should be kept after filtering response.headers_mut().typed_insert(CacheControl::new()); - response.headers_mut().insert(header::CONTENT_LANGUAGE, HeaderValue::from_bytes(&vec![]).unwrap()); - response.headers_mut().typed_insert(ContentType::from(mime::TEXT_HTML)); - response.headers_mut().typed_insert(Expires::from(SystemTime::now() + Duration::new(86400, 0))); - response.headers_mut().typed_insert(LastModified::from(SystemTime::now())); + response.headers_mut().insert( + header::CONTENT_LANGUAGE, + HeaderValue::from_bytes(&vec![]).unwrap(), + ); + response + .headers_mut() + .typed_insert(ContentType::from(mime::TEXT_HTML)); + response + .headers_mut() + .typed_insert(Expires::from(SystemTime::now() + Duration::new(86400, 0))); + response + .headers_mut() + .typed_insert(LastModified::from(SystemTime::now())); response.headers_mut().typed_insert(Pragma::no_cache()); // these headers should not be kept after filtering, even though they are given a pass - response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static("")); + response + .headers_mut() + .insert(header::SET_COOKIE, HeaderValue::from_static("")); response.headers_mut().insert( HeaderName::from_static("set-cookie2"), - HeaderValue::from_bytes(&vec![]).unwrap() + HeaderValue::from_bytes(&vec![]).unwrap(), ); - response.headers_mut().typed_insert( - AccessControlAllowHeaders::from_iter(vec![ + response + .headers_mut() + .typed_insert(AccessControlAllowHeaders::from_iter(vec![ HeaderName::from_static("set-cookie"), - HeaderName::from_static("set-cookie2") - ]) - ); + HeaderName::from_static("set-cookie2"), + ])); *response.body_mut() = MESSAGE.to_vec().into(); }; @@ -397,7 +480,9 @@ fn test_fetch_response_is_cors_filtered() { assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); assert!(!headers.contains_key(header::SET_COOKIE)); - assert!(headers.get(HeaderName::from_static("set-cookie2")).is_none()); + assert!(headers + .get(HeaderName::from_static("set-cookie2")) + .is_none()); } #[test] @@ -424,12 +509,12 @@ fn test_fetch_response_is_opaque_filtered() { assert!(fetch_response.status.is_none()); assert_eq!(fetch_response.headers, HeaderMap::new()); match *fetch_response.body.lock().unwrap() { - ResponseBody::Empty => { }, - _ => panic!() + ResponseBody::Empty => {}, + _ => panic!(), } match fetch_response.cache_state { - CacheState::None => { }, - _ => panic!() + CacheState::None => {}, + _ => panic!(), } } @@ -437,13 +522,21 @@ fn test_fetch_response_is_opaque_filtered() { fn test_fetch_response_is_opaque_redirect_filtered() { static MESSAGE: &'static [u8] = b""; let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request.uri().path().split("/").collect::().parse::().unwrap_or(0); + let redirects = request + .uri() + .path() + .split("/") + .collect::() + .parse::() + .unwrap_or(0); if redirects == 1 { *response.body_mut() = MESSAGE.to_vec().into(); } else { *response.status_mut() = StatusCode::FOUND; - response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1")); + response + .headers_mut() + .insert(header::LOCATION, HeaderValue::from_static("1")); } }; @@ -463,12 +556,12 @@ fn test_fetch_response_is_opaque_redirect_filtered() { assert!(fetch_response.status.is_none()); assert_eq!(fetch_response.headers, HeaderMap::new()); match *fetch_response.body.lock().unwrap() { - ResponseBody::Empty => { }, - _ => panic!() + ResponseBody::Empty => {}, + _ => panic!(), } match fetch_response.cache_state { - CacheState::None => { }, - _ => panic!() + CacheState::None => {}, + _ => panic!(), } } @@ -516,12 +609,19 @@ fn test_fetch_with_hsts() { *response.body_mut() = MESSAGE.to_vec().into(); }; - let cert_path = Path::new("../../resources/self_signed_certificate_for_testing.crt").canonicalize().unwrap(); - let key_path = Path::new("../../resources/privatekey_for_testing.key").canonicalize().unwrap(); + let cert_path = Path::new("../../resources/self_signed_certificate_for_testing.crt") + .canonicalize() + .unwrap(); + let key_path = Path::new("../../resources/privatekey_for_testing.key") + .canonicalize() + .unwrap(); let (server, url) = make_ssl_server(handler, cert_path.clone(), key_path.clone()); let mut ca_content = String::new(); - File::open(cert_path).unwrap().read_to_string(&mut ca_content).unwrap(); + File::open(cert_path) + .unwrap() + .read_to_string(&mut ca_content) + .unwrap(); let ssl_client = create_ssl_connector_builder(&ca_content); let context = FetchContext { @@ -534,8 +634,9 @@ fn test_fetch_with_hsts() { { let mut list = context.state.hsts_list.write().unwrap(); - list.push(HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None) - .unwrap()); + list.push( + HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None).unwrap(), + ); } let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -544,8 +645,10 @@ fn test_fetch_with_hsts() { request.local_urls_only = false; let response = fetch_with_context(&mut request, &context); server.close(); - assert_eq!(response.internal_response.unwrap().url().unwrap().scheme(), - "https"); + assert_eq!( + response.internal_response.unwrap().url().unwrap().scheme(), + "https" + ); } #[test] @@ -562,7 +665,7 @@ fn test_fetch_with_sri_network_error() { // To calulate hash use : // echo -n "alert('Hello, Network Error');" | openssl dgst -sha384 -binary | openssl base64 -A request.integrity_metadata = - "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); + "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); // Set the flag. request.local_urls_only = false; @@ -586,7 +689,7 @@ fn test_fetch_with_sri_sucess() { // To calulate hash use : // echo -n "alert('Hello, Network Error');" | openssl dgst -sha384 -binary | openssl base64 -A request.integrity_metadata = - "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); + "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); // Set the flag. request.local_urls_only = false; @@ -600,9 +703,7 @@ fn test_fetch_with_sri_sucess() { #[test] fn test_fetch_blocked_nosniff() { #[inline] - fn test_nosniff_request(destination: Destination, - mime: Mime, - should_error: bool) { + fn test_nosniff_request(destination: Destination, mime: Mime, should_error: bool) { const MESSAGE: &'static [u8] = b""; const HEADER: &'static str = "x-content-type-options"; const VALUE: &'static [u8] = b"nosniff"; @@ -612,7 +713,10 @@ fn test_fetch_blocked_nosniff() { response.headers_mut().typed_insert(mime_header); assert!(response.headers().contains_key(header::CONTENT_TYPE)); // Add the nosniff header - response.headers_mut().insert(HeaderName::from_static(HEADER), HeaderValue::from_bytes(VALUE).unwrap()); + response.headers_mut().insert( + HeaderName::from_static(HEADER), + HeaderValue::from_bytes(VALUE).unwrap(), + ); *response.body_mut() = MESSAGE.to_vec().into(); }; @@ -631,7 +735,7 @@ fn test_fetch_blocked_nosniff() { let tests = vec![ (Destination::Script, mime::TEXT_JAVASCRIPT, false), (Destination::Script, mime::TEXT_CSS, true), - (Destination::Style, mime::TEXT_CSS, false), + (Destination::Style, mime::TEXT_CSS, false), ]; for test in tests { @@ -642,14 +746,22 @@ fn test_fetch_blocked_nosniff() { fn setup_server_and_fetch(message: &'static [u8], redirect_cap: u32) -> Response { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request.uri().path().split("/").collect::().parse::().unwrap_or(0); + let redirects = request + .uri() + .path() + .split("/") + .collect::() + .parse::() + .unwrap_or(0); if redirects >= redirect_cap { *response.body_mut() = message.to_vec().into(); } else { *response.status_mut() = StatusCode::FOUND; let url = format!("{redirects}", redirects = redirects + 1); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&url).unwrap()); + response + .headers_mut() + .insert(header::LOCATION, HeaderValue::from_str(&url).unwrap()); } }; @@ -678,7 +790,7 @@ fn test_fetch_redirect_count_ceiling() { ResponseBody::Done(ref body) => { assert_eq!(&**body, MESSAGE); }, - _ => panic!() + _ => panic!(), }; } @@ -694,31 +806,43 @@ fn test_fetch_redirect_count_failure() { match *fetch_response.body.lock().unwrap() { ResponseBody::Done(_) | ResponseBody::Receiving(_) => panic!(), - _ => { } + _ => {}, }; } -fn test_fetch_redirect_updates_method_runner(tx: Sender, status_code: StatusCode, method: Method) { +fn test_fetch_redirect_updates_method_runner( + tx: Sender, + status_code: StatusCode, + method: Method, +) { let handler_method = method.clone(); let handler_tx = Arc::new(Mutex::new(tx)); let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request.uri().path().split("/").collect::().parse::().unwrap_or(0); + let redirects = request + .uri() + .path() + .split("/") + .collect::() + .parse::() + .unwrap_or(0); let mut test_pass = true; if redirects == 0 { *response.status_mut() = StatusCode::TEMPORARY_REDIRECT; - response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1")); - + response + .headers_mut() + .insert(header::LOCATION, HeaderValue::from_static("1")); } else if redirects == 1 { // this makes sure that the request method does't change from the wrong status code if handler_method != Method::GET && request.method() == Method::GET { test_pass = false; } *response.status_mut() = status_code; - response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("2")); - + response + .headers_mut() + .insert(header::LOCATION, HeaderValue::from_static("2")); } else if request.method() != Method::GET { test_pass = false; } @@ -727,7 +851,6 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender, status_code: Stat if redirects > 0 { handler_tx.lock().unwrap().send(test_pass).unwrap(); } - }; let (server, url) = make_server(handler); @@ -745,7 +868,11 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender, status_code: Stat fn test_fetch_redirect_updates_method() { let (tx, rx) = channel(); - test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MOVED_PERMANENTLY, Method::POST); + test_fetch_redirect_updates_method_runner( + tx.clone(), + StatusCode::MOVED_PERMANENTLY, + Method::POST, + ); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.recv().unwrap(), true); // make sure the test doesn't send more data than expected @@ -763,7 +890,11 @@ fn test_fetch_redirect_updates_method() { let extension = Method::from_bytes(b"FOO").unwrap(); - test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MOVED_PERMANENTLY, extension.clone()); + test_fetch_redirect_updates_method_runner( + tx.clone(), + StatusCode::MOVED_PERMANENTLY, + extension.clone(), + ); assert_eq!(rx.recv().unwrap(), true); // for MovedPermanently and Found, Method should only be changed if it was Post assert_eq!(rx.recv().unwrap(), false); @@ -785,9 +916,9 @@ fn response_is_done(response: &Response) -> bool { let response_complete = match response.response_type { ResponseType::Default | ResponseType::Basic | ResponseType::Cors => { (*response.body.lock().unwrap()).is_done() - } + }, // if the internal response cannot have a body, it shouldn't block the "done" state - ResponseType::Opaque | ResponseType::OpaqueRedirect | ResponseType::Error(..) => true + ResponseType::Opaque | ResponseType::OpaqueRedirect | ResponseType::Error(..) => true, }; let internal_complete = if let Some(ref res) = response.internal_response { @@ -842,13 +973,21 @@ fn test_opaque_filtered_fetch_async_returns_complete_response() { fn test_opaque_redirect_filtered_fetch_async_returns_complete_response() { static MESSAGE: &'static [u8] = b""; let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request.uri().path().split("/").collect::().parse::().unwrap_or(0); + let redirects = request + .uri() + .path() + .split("/") + .collect::() + .parse::() + .unwrap_or(0); if redirects == 1 { *response.body_mut() = MESSAGE.to_vec().into(); } else { *response.status_mut() = StatusCode::FOUND; - response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1")); + response + .headers_mut() + .insert(header::LOCATION, HeaderValue::from_static("1")); } }; @@ -892,13 +1031,22 @@ fn test_fetch_with_devtools() { //Creating default headers for request let mut headers = HeaderMap::new(); - headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("gzip, deflate, br")); - headers.typed_insert( - Host::from(format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()).parse::().unwrap())); + headers.insert( + header::ACCEPT_ENCODING, + HeaderValue::from_static("gzip, deflate, br"), + ); + headers.typed_insert(Host::from( + format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()) + .parse::() + .unwrap(), + )); headers.insert(header::ACCEPT, HeaderValue::from_static("*/*")); - headers.insert(header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US, en; q=0.5")); + headers.insert( + header::ACCEPT_LANGUAGE, + HeaderValue::from_static("en-US, en; q=0.5"), + ); headers.typed_insert::(DEFAULT_USER_AGENT.parse().unwrap()); @@ -918,7 +1066,11 @@ fn test_fetch_with_devtools() { let content = "Yay!"; let mut response_headers = HeaderMap::new(); response_headers.typed_insert(ContentLength(content.len() as u64)); - devhttpresponse.headers.as_mut().unwrap().remove(header::DATE); + devhttpresponse + .headers + .as_mut() + .unwrap() + .remove(header::DATE); let httpresponse = DevtoolsHttpResponse { headers: Some(response_headers), diff --git a/components/net/tests/filemanager_thread.rs b/components/net/tests/filemanager_thread.rs index 8612bdae672..2320fa41a2f 100644 --- a/components/net/tests/filemanager_thread.rs +++ b/components/net/tests/filemanager_thread.rs @@ -16,14 +16,18 @@ use std::path::PathBuf; #[test] fn test_filemanager() { let filemanager = FileManager::new(create_embedder_proxy()); - PREFS.set("dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true)); + PREFS.set( + "dom.testing.htmlinputelement.select_files.enabled", + PrefValue::Boolean(true), + ); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; - handler.read_to_end(&mut test_file_content) - .expect("Read components/net/tests/test.jpeg error"); + handler + .read_to_end(&mut test_file_content) + .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); @@ -31,10 +35,16 @@ fn test_filemanager() { { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::SelectFile(patterns.clone(), tx, origin.clone(), - Some("tests/test.jpeg".to_string()))); - let selected = rx.recv().expect("Broken channel") - .expect("The file manager failed to find test.jpeg"); + filemanager.handle(FileManagerThreadMsg::SelectFile( + patterns.clone(), + tx, + origin.clone(), + Some("tests/test.jpeg".to_string()), + )); + let selected = rx + .recv() + .expect("Broken channel") + .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); @@ -43,24 +53,35 @@ fn test_filemanager() { // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::ReadFile(tx2, selected.id.clone(), false, origin.clone())); + filemanager.handle(FileManagerThreadMsg::ReadFile( + tx2, + selected.id.clone(), + false, + origin.clone(), + )); let msg = rx2.recv().expect("Broken channel"); - if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { + if let ReadFileProgress::Meta(blob_buf) = + msg.expect("File manager reading failure is unexpected") + { let mut bytes = blob_buf.bytes; loop { - match rx2.recv().expect("Broken channel").expect("File manager reading failure is unexpected") { + match rx2 + .recv() + .expect("Broken channel") + .expect("File manager reading failure is unexpected") + { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); - } + }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); - } + }, ReadFileProgress::EOF => { break; - } + }, } } @@ -73,7 +94,11 @@ fn test_filemanager() { // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::DecRef(selected.id.clone(), origin.clone(), tx2)); + filemanager.handle(FileManagerThreadMsg::DecRef( + selected.id.clone(), + origin.clone(), + tx2, + )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); @@ -82,15 +107,26 @@ fn test_filemanager() { // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::ReadFile(tx2, selected.id.clone(), false, origin.clone())); + filemanager.handle(FileManagerThreadMsg::ReadFile( + tx2, + selected.id.clone(), + false, + origin.clone(), + )); let msg = rx2.recv().expect("Broken channel"); match msg { - Err(FileManagerThreadError::BlobURLStoreError(BlobURLStoreError::InvalidFileID)) => {}, + Err(FileManagerThreadError::BlobURLStoreError( + BlobURLStoreError::InvalidFileID, + )) => {}, other => { - assert!(false, "Get unexpected response after deleting the id: {:?}", other); - } + assert!( + false, + "Get unexpected response after deleting the id: {:?}", + other + ); + }, } } } diff --git a/components/net/tests/hsts.rs b/components/net/tests/hsts.rs index 3c857edc5e1..a16c104f061 100644 --- a/components/net/tests/hsts.rs +++ b/components/net/tests/hsts.rs @@ -13,7 +13,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_timestamp() { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: Some(20), - timestamp: None + timestamp: None, }; assert!(!entry.is_expired()); @@ -25,7 +25,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_max_age() { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: None, - timestamp: Some(time::get_time().sec as u64) + timestamp: Some(time::get_time().sec as u64), }; assert!(!entry.is_expired()); @@ -37,7 +37,7 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: Some(10), - timestamp: Some(time::get_time().sec as u64 - 20u64) + timestamp: Some(time::get_time().sec as u64 - 20u64), }; assert!(entry.is_expired()); @@ -46,7 +46,9 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() { #[test] fn test_hsts_entry_cant_be_created_with_ipv6_address_as_host() { let entry = HstsEntry::new( - "2001:0db8:0000:0000:0000:ff00:0042:8329".to_owned(), IncludeSubdomains::NotIncluded, None + "2001:0db8:0000:0000:0000:ff00:0042:8329".to_owned(), + IncludeSubdomains::NotIncluded, + None, ); assert!(entry.is_none(), "able to create HstsEntry with IPv6 host"); @@ -54,9 +56,7 @@ fn test_hsts_entry_cant_be_created_with_ipv6_address_as_host() { #[test] fn test_hsts_entry_cant_be_created_with_ipv4_address_as_host() { - let entry = HstsEntry::new( - "4.4.4.4".to_owned(), IncludeSubdomains::NotIncluded, None - ); + let entry = HstsEntry::new("4.4.4.4".to_owned(), IncludeSubdomains::NotIncluded, None); assert!(entry.is_none(), "able to create HstsEntry with IPv4 host"); } @@ -66,15 +66,33 @@ fn test_base_domain_in_entries_map() { let entries_map = HashMap::new(); let mut list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; - list.push(HstsEntry::new("servo.mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()); - list.push(HstsEntry::new("firefox.mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()); - list.push(HstsEntry::new("bugzilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()); + list.push( + HstsEntry::new( + "servo.mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap(), + ); + list.push( + HstsEntry::new( + "firefox.mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap(), + ); + list.push( + HstsEntry::new( + "bugzilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap(), + ); assert_eq!(list.entries_map.len(), 2); assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 2); @@ -83,14 +101,27 @@ fn test_base_domain_in_entries_map() { #[test] fn test_push_entry_with_0_max_age_evicts_entry_from_list() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, Some(500000u64)).unwrap())); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + Some(500000u64), + ) + .unwrap()], + ); let mut list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; - list.push(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, Some(0)).unwrap()); + list.push( + HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + Some(0), + ) + .unwrap(), + ); assert_eq!(list.is_host_secure("mozilla.org"), false) } @@ -98,14 +129,22 @@ fn test_push_entry_with_0_max_age_evicts_entry_from_list() { #[test] fn test_push_entry_to_hsts_list_should_not_add_subdomains_whose_superdomain_is_already_matched() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap())); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], + ); let mut list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; - list.push(HstsEntry::new("servo.mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()); + list.push( + HstsEntry::new( + "servo.mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap(), + ); assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 1) } @@ -113,16 +152,24 @@ fn test_push_entry_to_hsts_list_should_not_add_subdomains_whose_superdomain_is_a #[test] fn test_push_entry_to_hsts_list_should_update_existing_domain_entrys_include_subdomains() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap())); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], + ); let mut list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(list.is_host_secure("servo.mozilla.org")); - list.push(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()); + list.push( + HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap(), + ); assert!(!list.is_host_secure("servo.mozilla.org")) } @@ -130,14 +177,27 @@ fn test_push_entry_to_hsts_list_should_update_existing_domain_entrys_include_sub #[test] fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap())); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap()], + ); let mut list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; - list.push(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()); + list.push( + HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap(), + ); assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 1) } @@ -145,16 +205,16 @@ fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() { #[test] fn test_push_multiple_entrie_to_hsts_list_should_add_them_all() { let mut list = HstsList { - entries_map: HashMap::new() + entries_map: HashMap::new(), }; assert!(!list.is_host_secure("mozilla.org")); assert!(!list.is_host_secure("bugzilla.org")); - list.push(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap()); - list.push(HstsEntry::new("bugzilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap()); + list.push(HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()); + list.push( + HstsEntry::new("bugzilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap(), + ); assert!(list.is_host_secure("mozilla.org")); assert!(list.is_host_secure("bugzilla.org")); @@ -163,13 +223,12 @@ fn test_push_multiple_entrie_to_hsts_list_should_add_them_all() { #[test] fn test_push_entry_to_hsts_list_should_add_an_entry() { let mut list = HstsList { - entries_map: HashMap::new() + entries_map: HashMap::new(), }; assert!(!list.is_host_secure("mozilla.org")); - list.push(HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap()); + list.push(HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()); assert!(list.is_host_secure("mozilla.org")); } @@ -177,34 +236,43 @@ fn test_push_entry_to_hsts_list_should_add_an_entry() { #[test] fn test_parse_hsts_preload_should_return_none_when_json_invalid() { let mock_preload_content = "derp"; - assert!(HstsList::from_preload(mock_preload_content).is_none(), "invalid preload list should not have parsed") + assert!( + HstsList::from_preload(mock_preload_content).is_none(), + "invalid preload list should not have parsed" + ) } #[test] fn test_parse_hsts_preload_should_return_none_when_json_contains_no_entries_map_key() { let mock_preload_content = "{\"nothing\": \"to see here\"}"; - assert!(HstsList::from_preload(mock_preload_content).is_none(), "invalid preload list should not have parsed") + assert!( + HstsList::from_preload(mock_preload_content).is_none(), + "invalid preload list should not have parsed" + ) } #[test] fn test_parse_hsts_preload_should_decode_host_and_includes_subdomains() { let mock_preload_content = "{\ - \"entries\": [\ - {\"host\": \"mozilla.org\",\ - \"include_subdomains\": false}\ - ]\ + \"entries\": [\ + {\"host\": \"mozilla.org\",\ + \"include_subdomains\": false}\ + ]\ }"; let hsts_list = HstsList::from_preload(mock_preload_content); let entries_map = hsts_list.unwrap().entries_map; - assert_eq!(entries_map.get("mozilla.org").unwrap()[0].host, "mozilla.org"); + assert_eq!( + entries_map.get("mozilla.org").unwrap()[0].host, + "mozilla.org" + ); assert!(!entries_map.get("mozilla.org").unwrap()[0].include_subdomains); } #[test] fn test_hsts_list_with_no_entries_map_does_not_is_host_secure() { let hsts_list = HstsList { - entries_map: HashMap::new() + entries_map: HashMap::new(), }; assert!(!hsts_list.is_host_secure("mozilla.org")); @@ -213,11 +281,18 @@ fn test_hsts_list_with_no_entries_map_does_not_is_host_secure() { #[test] fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()]); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap()], + ); let hsts_list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(hsts_list.is_host_secure("mozilla.org")); @@ -226,10 +301,12 @@ fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() { #[test] fn test_hsts_list_with_subdomain_when_include_subdomains_is_true_is_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap()]); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], + ); let hsts_list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(hsts_list.is_host_secure("servo.mozilla.org")); @@ -238,10 +315,17 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_true_is_is_host_secu #[test] fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, None).unwrap()]); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new( + "mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, + None, + ) + .unwrap()], + ); let hsts_list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(!hsts_list.is_host_secure("servo.mozilla.org")); @@ -250,10 +334,12 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host #[test] fn test_hsts_list_with_subdomain_when_host_is_not_a_subdomain_is_not_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap()]); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], + ); let hsts_list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(!hsts_list.is_host_secure("servo-mozilla.org")); @@ -262,10 +348,12 @@ fn test_hsts_list_with_subdomain_when_host_is_not_a_subdomain_is_not_is_host_sec #[test] fn test_hsts_list_with_subdomain_when_host_is_exact_match_is_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), - IncludeSubdomains::Included, None).unwrap()]); + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], + ); let hsts_list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(hsts_list.is_host_secure("mozilla.org")); @@ -274,14 +362,17 @@ fn test_hsts_list_with_subdomain_when_host_is_exact_match_is_is_host_secure() { #[test] fn test_hsts_list_with_expired_entry_is_not_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry { + entries_map.insert( + "mozilla.org".to_owned(), + vec![HstsEntry { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: Some(20), - timestamp: Some(time::get_time().sec as u64 - 100u64) - }]); + timestamp: Some(time::get_time().sec as u64 - 100u64), + }], + ); let hsts_list = HstsList { - entries_map: entries_map + entries_map: entries_map, }; assert!(!hsts_list.is_host_secure("mozilla.org")); diff --git a/components/net/tests/http_loader.rs b/components/net/tests/http_loader.rs index 4d327029ccd..c0bdc57b357 100644 --- a/components/net/tests/http_loader.rs +++ b/components/net/tests/http_loader.rs @@ -42,28 +42,31 @@ fn mock_origin() -> ImmutableOrigin { ServoUrl::parse("http://servo.org").unwrap().origin() } -fn read_response(req: HyperRequest) -> impl Future { +fn read_response(req: HyperRequest) -> impl Future { req.into_body() - .concat2() - .and_then(|body| futures::future::ok(str::from_utf8(&body).unwrap().to_owned())) - .map_err(|_| ()) + .concat2() + .and_then(|body| futures::future::ok(str::from_utf8(&body).unwrap().to_owned())) + .map_err(|_| ()) } -fn assert_cookie_for_domain(cookie_jar: &RwLock, domain: &str, cookie: Option<&str>) { +fn assert_cookie_for_domain( + cookie_jar: &RwLock, + domain: &str, + cookie: Option<&str>, +) { let mut cookie_jar = cookie_jar.write().unwrap(); let url = ServoUrl::parse(&*domain).unwrap(); let cookies = cookie_jar.cookies_for_url(&url, CookieSource::HTTP); assert_eq!(cookies.as_ref().map(|c| &**c), cookie); } -pub fn expect_devtools_http_request(devtools_port: &Receiver) -> DevtoolsHttpRequest { +pub fn expect_devtools_http_request( + devtools_port: &Receiver, +) -> DevtoolsHttpRequest { match devtools_port.recv().unwrap() { - DevtoolsControlMsg::FromChrome( - ChromeToDevtoolsControlMsg::NetworkEvent(_, net_event)) => { + DevtoolsControlMsg::FromChrome(ChromeToDevtoolsControlMsg::NetworkEvent(_, net_event)) => { match net_event { - NetworkEvent::HttpRequest(httprequest) => { - httprequest - }, + NetworkEvent::HttpRequest(httprequest) => httprequest, _ => panic!("No HttpRequest Received"), } @@ -72,17 +75,17 @@ pub fn expect_devtools_http_request(devtools_port: &Receiver } } -pub fn expect_devtools_http_response(devtools_port: &Receiver) -> DevtoolsHttpResponse { +pub fn expect_devtools_http_response( + devtools_port: &Receiver, +) -> DevtoolsHttpResponse { match devtools_port.recv().unwrap() { - DevtoolsControlMsg::FromChrome( - ChromeToDevtoolsControlMsg::NetworkEvent(_, net_event_response)) => { - match net_event_response { - NetworkEvent::HttpResponse(httpresponse) => { - httpresponse - }, + DevtoolsControlMsg::FromChrome(ChromeToDevtoolsControlMsg::NetworkEvent( + _, + net_event_response, + )) => match net_event_response { + NetworkEvent::HttpResponse(httpresponse) => httpresponse, - _ => panic!("No HttpResponse Received"), - } + _ => panic!("No HttpResponse Received"), }, _ => panic!("No HttpResponse Received"), } @@ -93,21 +96,37 @@ fn test_check_default_headers_loaded_in_every_request() { let expected_headers = Arc::new(Mutex::new(None)); let expected_headers_clone = expected_headers.clone(); let handler = move |request: HyperRequest, _: &mut HyperResponse| { - assert_eq!(request.headers().clone(), expected_headers_clone.lock().unwrap().take().unwrap()); + assert_eq!( + request.headers().clone(), + expected_headers_clone.lock().unwrap().take().unwrap() + ); }; let (server, url) = make_server(handler); let mut headers = HeaderMap::new(); - headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("gzip, deflate, br")); + headers.insert( + header::ACCEPT_ENCODING, + HeaderValue::from_static("gzip, deflate, br"), + ); - headers.typed_insert( - Host::from(format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()).parse::().unwrap())); + headers.typed_insert(Host::from( + format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()) + .parse::() + .unwrap(), + )); - headers.insert(header::ACCEPT, - HeaderValue::from_static("text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8")); + headers.insert( + header::ACCEPT, + HeaderValue::from_static( + "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8", + ), + ); - headers.insert(header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US, en; q=0.5")); + headers.insert( + header::ACCEPT_LANGUAGE, + HeaderValue::from_static("en-US, en; q=0.5"), + ); headers.typed_insert::(::DEFAULT_USER_AGENT.parse().unwrap()); @@ -120,10 +139,16 @@ fn test_check_default_headers_loaded_in_every_request() { destination: Destination::Document, origin: url.clone().origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); // Testing for method.POST let mut post_headers = headers.clone(); @@ -131,7 +156,10 @@ fn test_check_default_headers_loaded_in_every_request() { let url_str = url.as_str(); // request gets header "Origin: http://example.com" but expected_headers has // "Origin: http://example.com/" which do not match for equality so strip trailing '/' - post_headers.insert(header::ORIGIN, HeaderValue::from_str(&url_str[..url_str.len()-1]).unwrap()); + post_headers.insert( + header::ORIGIN, + HeaderValue::from_str(&url_str[..url_str.len() - 1]).unwrap(), + ); *expected_headers.lock().unwrap() = Some(post_headers); let mut request = Request::from_init(RequestInit { url: url.clone(), @@ -139,18 +167,28 @@ fn test_check_default_headers_loaded_in_every_request() { destination: Destination::Document, origin: url.clone().origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); let _ = server.close(); } #[test] -fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length_should_be_set_to_0() { +fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length_should_be_set_to_0( +) { let handler = move |request: HyperRequest, _: &mut HyperResponse| { - assert_eq!(request.headers().typed_get::(), Some(ContentLength(0))); + assert_eq!( + request.headers().typed_get::(), + Some(ContentLength(0)) + ); }; let (server, url) = make_server(handler); @@ -161,10 +199,16 @@ fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); let _ = server.close(); } @@ -172,7 +216,9 @@ fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length #[test] fn test_request_and_response_data_with_network_messages() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().typed_insert(Host::from("foo.bar".parse::().unwrap())); + response + .headers_mut() + .typed_insert(Host::from("foo.bar".parse::().unwrap())); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -187,11 +233,17 @@ fn test_request_and_response_data_with_network_messages() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let (devtools_chan, devtools_port) = channel(); let response = fetch(&mut request, Some(devtools_chan)); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); let _ = server.close(); @@ -202,14 +254,27 @@ fn test_request_and_response_data_with_network_messages() { //Creating default headers for request let mut headers = HeaderMap::new(); - headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("gzip, deflate, br")); - headers.typed_insert( - Host::from(format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()).parse::().unwrap())); + headers.insert( + header::ACCEPT_ENCODING, + HeaderValue::from_static("gzip, deflate, br"), + ); + headers.typed_insert(Host::from( + format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()) + .parse::() + .unwrap(), + )); - headers.insert(header::ACCEPT, - HeaderValue::from_static("text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8")); + headers.insert( + header::ACCEPT, + HeaderValue::from_static( + "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8", + ), + ); - headers.insert(header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US, en; q=0.5")); + headers.insert( + header::ACCEPT_LANGUAGE, + HeaderValue::from_static("en-US, en; q=0.5"), + ); headers.typed_insert::(::DEFAULT_USER_AGENT.parse().unwrap()); let httprequest = DevtoolsHttpRequest { @@ -229,7 +294,15 @@ fn test_request_and_response_data_with_network_messages() { let mut response_headers = HeaderMap::new(); response_headers.typed_insert(ContentLength(content.len() as u64)); response_headers.typed_insert(Host::from("foo.bar".parse::().unwrap())); - response_headers.typed_insert(devhttpresponse.headers.as_ref().unwrap().typed_get::().unwrap().clone()); + response_headers.typed_insert( + devhttpresponse + .headers + .as_ref() + .unwrap() + .typed_get::() + .unwrap() + .clone(), + ); let httpresponse = DevtoolsHttpResponse { headers: Some(response_headers), @@ -245,7 +318,9 @@ fn test_request_and_response_data_with_network_messages() { #[test] fn test_request_and_response_message_from_devtool_without_pipeline_id() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().typed_insert(Host::from("foo.bar".parse::().unwrap())); + response + .headers_mut() + .typed_insert(Host::from("foo.bar".parse::().unwrap())); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -256,11 +331,17 @@ fn test_request_and_response_message_from_devtool_without_pipeline_id() { destination: Destination::Document, origin: mock_origin(), pipeline_id: None, - .. RequestInit::default() + ..RequestInit::default() }); let (devtools_chan, devtools_port) = channel(); let response = fetch(&mut request, Some(devtools_chan)); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); let _ = server.close(); @@ -279,7 +360,10 @@ fn test_redirected_request_to_devtools() { let post_redirect_url = post_url.clone(); let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { assert_eq!(request.method(), Method::POST); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&post_redirect_url.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (pre_server, pre_url) = make_server(pre_handler); @@ -289,7 +373,7 @@ fn test_redirected_request_to_devtools() { method: Method::POST, destination: Destination::Document, pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let (devtools_chan, devtools_port) = channel(); fetch(&mut request, Some(devtools_chan)); @@ -302,7 +386,10 @@ fn test_redirected_request_to_devtools() { assert_eq!(devhttprequest.method, Method::POST); assert_eq!(devhttprequest.url, pre_url); - assert_eq!(devhttpresponse.status, Some((301, b"Moved Permanently".to_vec()))); + assert_eq!( + devhttpresponse.status, + Some((301, b"Moved Permanently".to_vec())) + ); let devhttprequest = expect_devtools_http_request(&devtools_port); let devhttpresponse = expect_devtools_http_response(&devtools_port); @@ -312,8 +399,6 @@ fn test_redirected_request_to_devtools() { assert_eq!(devhttpresponse.status, Some((200, b"OK".to_vec()))); } - - #[test] fn test_load_when_redirecting_from_a_post_should_rewrite_next_request_as_get() { let post_handler = move |request: HyperRequest, response: &mut HyperResponse| { @@ -325,7 +410,10 @@ fn test_load_when_redirecting_from_a_post_should_rewrite_next_request_as_get() { let post_redirect_url = post_url.clone(); let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { assert_eq!(request.method(), Method::POST); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&post_redirect_url.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (pre_server, pre_url) = make_server(pre_handler); @@ -336,7 +424,7 @@ fn test_load_when_redirecting_from_a_post_should_rewrite_next_request_as_get() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -347,9 +435,13 @@ fn test_load_when_redirecting_from_a_post_should_rewrite_next_request_as_get() { } #[test] -fn test_load_should_decode_the_response_as_deflate_when_response_headers_have_content_encoding_deflate() { +fn test_load_should_decode_the_response_as_deflate_when_response_headers_have_content_encoding_deflate( +) { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::CONTENT_ENCODING, HeaderValue::from_static("deflate")); + response.headers_mut().insert( + header::CONTENT_ENCODING, + HeaderValue::from_static("deflate"), + ); let mut e = DeflateEncoder::new(Vec::new(), Compression::default()); e.write(b"Yay!").unwrap(); let encoded_content = e.finish().unwrap(); @@ -364,7 +456,7 @@ fn test_load_should_decode_the_response_as_deflate_when_response_headers_have_co destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -372,14 +464,18 @@ fn test_load_should_decode_the_response_as_deflate_when_response_headers_have_co let internal_response = response.internal_response.unwrap(); assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!(*internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec())); + assert_eq!( + *internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec()) + ); } #[test] fn test_load_should_decode_the_response_as_gzip_when_response_headers_have_content_encoding_gzip() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip")); + response + .headers_mut() + .insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip")); let mut e = GzEncoder::new(Vec::new(), Compression::default()); e.write(b"Yay!").unwrap(); let encoded_content = e.finish().unwrap(); @@ -394,7 +490,7 @@ fn test_load_should_decode_the_response_as_gzip_when_response_headers_have_conte destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -402,27 +498,40 @@ fn test_load_should_decode_the_response_as_gzip_when_response_headers_have_conte let internal_response = response.internal_response.unwrap(); assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!(*internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec())); + assert_eq!( + *internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec()) + ); } #[test] fn test_load_doesnt_send_request_body_on_any_redirect() { let post_handler = move |request: HyperRequest, response: &mut HyperResponse| { assert_eq!(request.method(), Method::GET); - read_response(request).and_then(|data| { - assert_eq!(data, ""); futures::future::ok(()) - }).poll().unwrap(); + read_response(request) + .and_then(|data| { + assert_eq!(data, ""); + futures::future::ok(()) + }) + .poll() + .unwrap(); *response.body_mut() = b"Yay!".to_vec().into(); }; let (post_server, post_url) = make_server(post_handler); let post_redirect_url = post_url.clone(); let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { - read_response(request).and_then(|data| { - assert_eq!(data, "Body on POST"); futures::future::ok(()) - }).poll().unwrap(); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&post_redirect_url.to_string()).unwrap()); + read_response(request) + .and_then(|data| { + assert_eq!(data, "Body on POST"); + futures::future::ok(()) + }) + .poll() + .unwrap(); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (pre_server, pre_url) = make_server(pre_handler); @@ -434,7 +543,7 @@ fn test_load_doesnt_send_request_body_on_any_redirect() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -447,8 +556,11 @@ fn test_load_doesnt_send_request_body_on_any_redirect() { #[test] fn test_load_doesnt_add_host_to_sts_list_when_url_is_http_even_if_sts_headers_are_present() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().typed_insert( - StrictTransportSecurity::excluding_subdomains(Duration::from_secs(31536000))); + response + .headers_mut() + .typed_insert(StrictTransportSecurity::excluding_subdomains( + Duration::from_secs(31536000), + )); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -460,21 +572,38 @@ fn test_load_doesnt_add_host_to_sts_list_when_url_is_http_even_if_sts_headers_ar destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let context = new_fetch_context(None, None); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); - assert_eq!(context.state.hsts_list.read().unwrap().is_host_secure(url.host_str().unwrap()), false); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); + assert_eq!( + context + .state + .hsts_list + .read() + .unwrap() + .is_host_secure(url.host_str().unwrap()), + false + ); } #[test] fn test_load_sets_cookies_in_the_resource_manager_when_it_get_set_cookie_header_in_response() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static("mozillaIs=theBest")); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static("mozillaIs=theBest"), + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -491,21 +620,34 @@ fn test_load_sets_cookies_in_the_resource_manager_when_it_get_set_cookie_header_ origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); - assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), Some("mozillaIs=theBest")); + assert_cookie_for_domain( + &context.state.cookie_jar, + url.as_str(), + Some("mozillaIs=theBest"), + ); } #[test] fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_resource_manager() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.headers().get(header::COOKIE).unwrap().as_bytes(), b"mozillaIs=theBest"); + assert_eq!( + request.headers().get(header::COOKIE).unwrap().as_bytes(), + b"mozillaIs=theBest" + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -517,8 +659,9 @@ fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_re let cookie = Cookie::new_wrapped( CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), &url, - CookieSource::HTTP - ).unwrap(); + CookieSource::HTTP, + ) + .unwrap(); cookie_jar.push(cookie, &url, CookieSource::HTTP); } @@ -530,19 +673,28 @@ fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_re origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] fn test_load_sends_cookie_if_nonhttp() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.headers().get(header::COOKIE).unwrap().as_bytes(), b"mozillaIs=theBest"); + assert_eq!( + request.headers().get(header::COOKIE).unwrap().as_bytes(), + b"mozillaIs=theBest" + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -554,8 +706,9 @@ fn test_load_sends_cookie_if_nonhttp() { let cookie = Cookie::new_wrapped( CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), &url, - CookieSource::NonHTTP - ).unwrap(); + CookieSource::NonHTTP, + ) + .unwrap(); cookie_jar.push(cookie, &url, CookieSource::HTTP); } @@ -567,19 +720,28 @@ fn test_load_sends_cookie_if_nonhttp() { origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] fn test_cookie_set_with_httponly_should_not_be_available_using_getcookiesforurl() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static("mozillaIs=theBest; HttpOnly")); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static("mozillaIs=theBest; HttpOnly"), + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -596,23 +758,38 @@ fn test_cookie_set_with_httponly_should_not_be_available_using_getcookiesforurl( origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); - assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), Some("mozillaIs=theBest")); + assert_cookie_for_domain( + &context.state.cookie_jar, + url.as_str(), + Some("mozillaIs=theBest"), + ); let mut cookie_jar = context.state.cookie_jar.write().unwrap(); - assert!(cookie_jar.cookies_for_url(&url, CookieSource::NonHTTP).is_none()); + assert!(cookie_jar + .cookies_for_url(&url, CookieSource::NonHTTP) + .is_none()); } #[test] fn test_when_cookie_received_marked_secure_is_ignored_for_http() { let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static("mozillaIs=theBest; Secure")); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static("mozillaIs=theBest; Secure"), + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -629,13 +806,19 @@ fn test_when_cookie_received_marked_secure_is_ignored_for_http() { origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), None); } @@ -645,7 +828,10 @@ fn test_load_sets_content_length_to_length_of_request_body() { let content = b"This is a request body"; let handler = move |request: HyperRequest, response: &mut HyperResponse| { let content_length = ContentLength(content.len() as u64); - assert_eq!(request.headers().typed_get::(), Some(content_length)); + assert_eq!( + request.headers().typed_get::(), + Some(content_length) + ); *response.body_mut() = content.to_vec().into(); }; let (server, url) = make_server(handler); @@ -657,19 +843,33 @@ fn test_load_sets_content_length_to_length_of_request_body() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] fn test_load_uses_explicit_accept_from_headers_in_load_data() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.headers().get(header::ACCEPT).unwrap().to_str().unwrap(), "text/html"); + assert_eq!( + request + .headers() + .get(header::ACCEPT) + .unwrap() + .to_str() + .unwrap(), + "text/html" + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -683,20 +883,33 @@ fn test_load_uses_explicit_accept_from_headers_in_load_data() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] fn test_load_sets_default_accept_to_html_xhtml_xml_and_then_anything_else() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.headers().get(header::ACCEPT).unwrap().to_str().unwrap(), - "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8"); + assert_eq!( + request + .headers() + .get(header::ACCEPT) + .unwrap() + .to_str() + .unwrap(), + "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8" + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -707,19 +920,33 @@ fn test_load_sets_default_accept_to_html_xhtml_xml_and_then_anything_else() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] fn test_load_uses_explicit_accept_encoding_from_load_data_headers() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.headers().get(header::ACCEPT_ENCODING).unwrap().to_str().unwrap(), "chunked"); + assert_eq!( + request + .headers() + .get(header::ACCEPT_ENCODING) + .unwrap() + .to_str() + .unwrap(), + "chunked" + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -733,19 +960,33 @@ fn test_load_uses_explicit_accept_encoding_from_load_data_headers() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] fn test_load_sets_default_accept_encoding_to_gzip_and_deflate() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.headers().get(header::ACCEPT_ENCODING).unwrap().to_str().unwrap(), "gzip, deflate, br"); + assert_eq!( + request + .headers() + .get(header::ACCEPT_ENCODING) + .unwrap() + .to_str() + .unwrap(), + "gzip, deflate, br" + ); *response.body_mut() = b"Yay!".to_vec().into(); }; let (server, url) = make_server(handler); @@ -756,13 +997,19 @@ fn test_load_sets_default_accept_encoding_to_gzip_and_deflate() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] @@ -770,15 +1017,28 @@ fn test_load_errors_when_there_a_redirect_loop() { let url_b_for_a = Arc::new(Mutex::new(None::)); let url_b_for_a_clone = url_b_for_a.clone(); let handler_a = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::LOCATION, - HeaderValue::from_str(&url_b_for_a_clone.lock().unwrap().as_ref().unwrap().to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str( + &url_b_for_a_clone + .lock() + .unwrap() + .as_ref() + .unwrap() + .to_string(), + ) + .unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (server_a, url_a) = make_server(handler_a); let url_a_for_b = url_a.clone(); let handler_b = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&url_a_for_b.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&url_a_for_b.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (server_b, url_b) = make_server(handler_b); @@ -791,15 +1051,17 @@ fn test_load_errors_when_there_a_redirect_loop() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server_a.close(); let _ = server_b.close(); - assert_eq!(response.get_network_error(), - Some(&NetworkError::Internal("Too many redirects".to_owned()))); + assert_eq!( + response.get_network_error(), + Some(&NetworkError::Internal("Too many redirects".to_owned())) + ); } #[test] @@ -809,8 +1071,18 @@ fn test_load_succeeds_with_a_redirect_loop() { let handled_a = AtomicBool::new(false); let handler_a = move |_: HyperRequest, response: &mut HyperResponse| { if !handled_a.swap(true, Ordering::SeqCst) { - response.headers_mut().insert(header::LOCATION, - HeaderValue::from_str(&url_b_for_a_clone.lock().unwrap().as_ref().unwrap().to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str( + &url_b_for_a_clone + .lock() + .unwrap() + .as_ref() + .unwrap() + .to_string(), + ) + .unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; } else { *response.body_mut() = b"Success".to_vec().into() @@ -820,7 +1092,10 @@ fn test_load_succeeds_with_a_redirect_loop() { let url_a_for_b = url_a.clone(); let handler_b = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&url_a_for_b.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&url_a_for_b.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (server_b, url_b) = make_server(handler_b); @@ -833,7 +1108,7 @@ fn test_load_succeeds_with_a_redirect_loop() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -842,8 +1117,10 @@ fn test_load_succeeds_with_a_redirect_loop() { let response = response.to_actual(); assert_eq!(response.url_list, [url_a.clone(), url_b, url_a]); - assert_eq!(*response.body.lock().unwrap(), - ResponseBody::Done(b"Success".to_vec())); + assert_eq!( + *response.body.lock().unwrap(), + ResponseBody::Done(b"Success".to_vec()) + ); } #[test] @@ -857,7 +1134,10 @@ fn test_load_follows_a_redirect() { let post_redirect_url = post_url.clone(); let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { assert_eq!(request.method(), Method::GET); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&post_redirect_url.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; }; let (pre_server, pre_url) = make_server(pre_handler); @@ -868,7 +1148,7 @@ fn test_load_follows_a_redirect() { destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -877,8 +1157,10 @@ fn test_load_follows_a_redirect() { let internal_response = response.internal_response.unwrap(); assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!(*internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec())); + assert_eq!( + *internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec()) + ); } #[test] @@ -888,12 +1170,21 @@ fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { let path = request.uri().path(); if path == "/com/" { - assert_eq!(request.headers().get(header::COOKIE).unwrap().as_bytes(), b"mozillaIsNot=dotOrg"); + assert_eq!( + request.headers().get(header::COOKIE).unwrap().as_bytes(), + b"mozillaIsNot=dotOrg" + ); let location = shared_url_y.lock().unwrap().as_ref().unwrap().to_string(); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&location.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&location.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; } else if path == "/org/" { - assert_eq!(request.headers().get(header::COOKIE).unwrap().as_bytes(), b"mozillaIs=theBest"); + assert_eq!( + request.headers().get(header::COOKIE).unwrap().as_bytes(), + b"mozillaIs=theBest" + ); *response.body_mut() = b"Yay!".to_vec().into(); } else { panic!("unexpected path {:?}", path) @@ -920,16 +1211,18 @@ fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { let cookie_x = Cookie::new_wrapped( CookiePair::new("mozillaIsNot".to_owned(), "dotOrg".to_owned()), &url_x, - CookieSource::HTTP - ).unwrap(); + CookieSource::HTTP, + ) + .unwrap(); cookie_jar.push(cookie_x, &url_x, CookieSource::HTTP); let cookie_y = Cookie::new_wrapped( CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), &url_y, - CookieSource::HTTP - ).unwrap(); + CookieSource::HTTP, + ) + .unwrap(); cookie_jar.push(cookie_y, &url_y, CookieSource::HTTP); } @@ -940,7 +1233,7 @@ fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch_with_context(&mut request, &context); @@ -948,8 +1241,10 @@ fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { let internal_response = response.internal_response.unwrap(); assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!(*internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec())); + assert_eq!( + *internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec()) + ); } #[test] @@ -957,12 +1252,21 @@ fn test_redirect_from_x_to_x_provides_x_with_cookie_from_first_response() { let handler = move |request: HyperRequest, response: &mut HyperResponse| { let path = request.uri().path(); if path == "/initial/" { - response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static("mozillaIs=theBest; path=/;")); + response.headers_mut().insert( + header::SET_COOKIE, + HeaderValue::from_static("mozillaIs=theBest; path=/;"), + ); let location = "/subsequent/".to_string(); - response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&location.to_string()).unwrap()); + response.headers_mut().insert( + header::LOCATION, + HeaderValue::from_str(&location.to_string()).unwrap(), + ); *response.status_mut() = StatusCode::MOVED_PERMANENTLY; } else if path == "/subsequent/" { - assert_eq!(request.headers().get(header::COOKIE).unwrap().as_bytes(), b"mozillaIs=theBest"); + assert_eq!( + request.headers().get(header::COOKIE).unwrap().as_bytes(), + b"mozillaIs=theBest" + ); *response.body_mut() = b"Yay!".to_vec().into(); } else { panic!("unexpected path {:?}", path) @@ -979,7 +1283,7 @@ fn test_redirect_from_x_to_x_provides_x_with_cookie_from_first_response() { origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); @@ -987,15 +1291,20 @@ fn test_redirect_from_x_to_x_provides_x_with_cookie_from_first_response() { let internal_response = response.internal_response.unwrap(); assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!(*internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec())); + assert_eq!( + *internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec()) + ); } #[test] fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { let handler = move |request: HyperRequest, _response: &mut HyperResponse| { let expected = Authorization::basic("username", "test"); - assert_eq!(request.headers().typed_get::>(), Some(expected)); + assert_eq!( + request.headers().typed_get::>(), + Some(expected) + ); }; let (server, url) = make_server(handler); @@ -1007,7 +1316,7 @@ fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let context = new_fetch_context(None, None); @@ -1016,13 +1325,25 @@ fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { password: "test".to_owned(), }; - context.state.auth_cache.write().unwrap().entries.insert(url.origin().clone().ascii_serialization(), auth_entry); + context + .state + .auth_cache + .write() + .unwrap() + .entries + .insert(url.origin().clone().ascii_serialization(), auth_entry); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); } #[test] @@ -1040,14 +1361,17 @@ fn test_auth_ui_needs_www_auth() { origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert_eq!(response.internal_response.unwrap().status.unwrap().0, StatusCode::UNAUTHORIZED); + assert_eq!( + response.internal_response.unwrap().status.unwrap().0, + StatusCode::UNAUTHORIZED + ); } #[test] @@ -1056,7 +1380,8 @@ fn test_origin_set() { let origin_header_clone = origin_header.clone(); let handler = move |request: HyperRequest, resp: &mut HyperResponse| { let origin_header_clone = origin_header.clone(); - resp.headers_mut().typed_insert(AccessControlAllowOrigin::ANY); + resp.headers_mut() + .typed_insert(AccessControlAllowOrigin::ANY); match request.headers().typed_get::() { None => assert_eq!(origin_header_clone.lock().unwrap().take(), None), Some(h) => assert_eq!(h, origin_header_clone.lock().unwrap().take().unwrap()), @@ -1064,29 +1389,33 @@ fn test_origin_set() { }; let (server, url) = make_server(handler); - let mut origin = Origin::try_from_parts( - url.scheme(), - url.host_str().unwrap(), - url.port() - ).unwrap(); + let mut origin = + Origin::try_from_parts(url.scheme(), url.host_str().unwrap(), url.port()).unwrap(); *origin_header_clone.lock().unwrap() = Some(origin.clone()); let mut request = Request::from_init(RequestInit { url: url.clone(), method: Method::POST, body: None, origin: url.clone().origin(), - .. RequestInit::default() + ..RequestInit::default() }); let response = fetch(&mut request, None); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); let origin_url = ServoUrl::parse("http://example.com").unwrap(); // XXX: Not sure about the Some(80) here. origin_url.origin() returns 80 for the port but origin_url returns None. origin = Origin::try_from_parts( origin_url.scheme(), origin_url.host_str().unwrap(), - Some(80) - ).unwrap(); + Some(80), + ) + .unwrap(); // Test Origin header is set on Get request with CORS mode let mut request = Request::from_init(RequestInit { url: url.clone(), @@ -1094,12 +1423,18 @@ fn test_origin_set() { mode: RequestMode::CorsMode, body: None, origin: origin_url.clone().origin(), - .. RequestInit::default() + ..RequestInit::default() }); *origin_header_clone.lock().unwrap() = Some(origin.clone()); let response = fetch(&mut request, None); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); // Test Origin header is not set on method Head let mut request = Request::from_init(RequestInit { @@ -1107,12 +1442,18 @@ fn test_origin_set() { method: Method::HEAD, body: None, origin: url.clone().origin(), - .. RequestInit::default() + ..RequestInit::default() }); *origin_header_clone.lock().unwrap() = None; let response = fetch(&mut request, None); - assert!(response.internal_response.unwrap().status.unwrap().0.is_success()); + assert!(response + .internal_response + .unwrap() + .status + .unwrap() + .0 + .is_success()); let _ = server.close(); } diff --git a/components/net/tests/main.rs b/components/net/tests/main.rs index ad666198a07..c20c846bf7d 100644 --- a/components/net/tests/main.rs +++ b/components/net/tests/main.rs @@ -70,9 +70,7 @@ use tokio::runtime::Runtime; use tokio_openssl::SslAcceptorExt; lazy_static! { - pub static ref HANDLE: Mutex = { - Mutex::new(Runtime::new().unwrap()) - }; + pub static ref HANDLE: Mutex = { Mutex::new(Runtime::new().unwrap()) }; } const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; @@ -83,18 +81,17 @@ struct FetchResponseCollector { fn create_embedder_proxy() -> EmbedderProxy { let (sender, _) = channel(); - let event_loop_waker = | | { - struct DummyEventLoopWaker { - } + let event_loop_waker = || { + struct DummyEventLoopWaker {} impl DummyEventLoopWaker { fn new() -> DummyEventLoopWaker { - DummyEventLoopWaker { } + DummyEventLoopWaker {} } } impl EventLoopWaker for DummyEventLoopWaker { - fn wake(&self) { } + fn wake(&self) {} fn clone(&self) -> Box { - Box::new(DummyEventLoopWaker { }) + Box::new(DummyEventLoopWaker {}) } } @@ -103,12 +100,16 @@ fn create_embedder_proxy() -> EmbedderProxy { EmbedderProxy { sender: sender, - event_loop_waker: event_loop_waker() + event_loop_waker: event_loop_waker(), } } -fn new_fetch_context(dc: Option>, fc: Option) -> FetchContext { - let ssl_connector = create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates)); +fn new_fetch_context( + dc: Option>, + fc: Option, +) -> FetchContext { + let ssl_connector = + create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates)); let sender = fc.unwrap_or_else(|| create_embedder_proxy()); FetchContext { state: Arc::new(HttpState::new(ssl_connector)), @@ -135,9 +136,7 @@ fn fetch(request: &mut Request, dc: Option>) -> Respo fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); - let mut target = FetchResponseCollector { - sender: sender, - }; + let mut target = FetchResponseCollector { sender: sender }; methods::fetch(request, &mut target, context); @@ -146,9 +145,7 @@ fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); - let mut target = FetchResponseCollector { - sender: sender, - }; + let mut target = FetchResponseCollector { sender: sender }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None, None)); @@ -166,7 +163,7 @@ impl Server { } fn make_server(handler: H) -> (Server, ServoUrl) - where +where H: Fn(HyperRequest, &mut HyperResponse) + Send + Sync + 'static, { let handler = Arc::new(handler); @@ -174,18 +171,18 @@ fn make_server(handler: H) -> (Server, ServoUrl) let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); let (tx, rx) = futures::sync::oneshot::channel::<()>(); - let server = HyperServer::from_tcp(listener).unwrap().serve( - move || { + let server = HyperServer::from_tcp(listener) + .unwrap() + .serve(move || { let handler = handler.clone(); service_fn_ok(move |req: HyperRequest| { let mut response = HyperResponse::new(Vec::::new().into()); handler(req, &mut response); response }) - } - ) - .with_graceful_shutdown(rx) - .map_err(|_|()); + }) + .with_graceful_shutdown(rx) + .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); let server = Server { close_channel: tx }; @@ -193,7 +190,7 @@ fn make_server(handler: H) -> (Server, ServoUrl) } fn make_ssl_server(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl) - where +where H: Fn(HyperRequest, &mut HyperResponse) + Send + Sync + 'static, { let handler = Arc::new(handler); @@ -202,28 +199,39 @@ fn make_ssl_server(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Ser let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwrap(); - let server = listener.incoming() - .map_err(|_| ()) - .for_each(move |sock| { - let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap(); - ssl_builder.set_certificate_file(&cert_path, SslFiletype::PEM).unwrap(); - ssl_builder.set_private_key_file(&key_path, SslFiletype::PEM).unwrap(); + let server = listener.incoming().map_err(|_| ()).for_each(move |sock| { + let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap(); + ssl_builder + .set_certificate_file(&cert_path, SslFiletype::PEM) + .unwrap(); + ssl_builder + .set_private_key_file(&key_path, SslFiletype::PEM) + .unwrap(); - let handler = handler.clone(); - ssl_builder.build().accept_async(sock).map_err(|_| ()).and_then(move |ssl| { - Http::new().serve_connection(ssl, + let handler = handler.clone(); + ssl_builder + .build() + .accept_async(sock) + .map_err(|_| ()) + .and_then(move |ssl| { + Http::new() + .serve_connection( + ssl, service_fn_ok(move |req: HyperRequest| { let mut response = HyperResponse::new(Vec::::new().into()); handler(req, &mut response); response - }) - ) - .map_err(|_|()) + }), + ) + .map_err(|_| ()) }) - }); + }); let (tx, rx) = futures::sync::oneshot::channel::<()>(); - let server = server.select(rx.map_err(|_| ())).map(|_| ()).map_err(|_| ()); + let server = server + .select(rx.map_err(|_| ())) + .map(|_| ()) + .map_err(|_| ()); HANDLE.lock().unwrap().spawn(server); diff --git a/components/net/tests/mime_classifier.rs b/components/net/tests/mime_classifier.rs index 593017c7f2c..d2568a9a8be 100644 --- a/components/net/tests/mime_classifier.rs +++ b/components/net/tests/mime_classifier.rs @@ -33,7 +33,7 @@ fn test_sniff_mp4_matcher() { panic!("Didn't read mime type") } }, - Err(e) => panic!("Couldn't read from file with error {}", e) + Err(e) => panic!("Couldn't read from file with error {}", e), } } @@ -43,9 +43,9 @@ fn test_sniff_mp4_matcher_long() { let matcher = Mp4Matcher; let mut data: [u8; 260] = [0; 260]; - &data[.. 11].clone_from_slice( - &[0x00, 0x00, 0x01, 0x04, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34] - ); + &data[..11].clone_from_slice(&[ + 0x00, 0x00, 0x01, 0x04, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, + ]); assert!(matcher.matches(&data)); } @@ -57,13 +57,18 @@ fn test_validate_classifier() { } #[cfg(test)] -fn test_sniff_with_flags(filename_orig: &path::Path, - expected_mime: Mime, - supplied_type: Option, - no_sniff_flag: NoSniffFlag, - apache_bug_flag: ApacheBugFlag) { +fn test_sniff_with_flags( + filename_orig: &path::Path, + expected_mime: Mime, + supplied_type: Option, + no_sniff_flag: NoSniffFlag, + apache_bug_flag: ApacheBugFlag, +) { let current_working_directory = env::current_dir().unwrap(); - println!("The current directory is {}", current_working_directory.display()); + println!( + "The current directory is {}", + current_working_directory.display() + ); let mut filename = PathBuf::from("tests/parsable_mime/"); filename.push(filename_orig); @@ -74,30 +79,35 @@ fn test_sniff_with_flags(filename_orig: &path::Path, match read_result { Ok(data) => { - let parsed_mime = classifier.classify(LoadContext::Browsing, - no_sniff_flag, - apache_bug_flag, - &supplied_type, - &data); + let parsed_mime = classifier.classify( + LoadContext::Browsing, + no_sniff_flag, + apache_bug_flag, + &supplied_type, + &data, + ); if (parsed_mime.type_() != expected_mime.type_()) || - (parsed_mime.subtype() != expected_mime.subtype()) { - panic!("File {:?} parsed incorrectly should be {:?}, parsed as {:?}", - filename, expected_mime, parsed_mime); + (parsed_mime.subtype() != expected_mime.subtype()) + { + panic!( + "File {:?} parsed incorrectly should be {:?}, parsed as {:?}", + filename, expected_mime, parsed_mime + ); } - } - Err(e) => panic!("Couldn't read from file {:?} with error {}", - filename, e), + }, + Err(e) => panic!("Couldn't read from file {:?} with error {}", filename, e), } } #[cfg(test)] -fn test_sniff_full(filename_orig: &path::Path, expected_mime: Mime, - supplied_type: Option) { - test_sniff_with_flags(filename_orig, - expected_mime, - supplied_type, - NoSniffFlag::Off, - ApacheBugFlag::Off) +fn test_sniff_full(filename_orig: &path::Path, expected_mime: Mime, supplied_type: Option) { + test_sniff_with_flags( + filename_orig, + expected_mime, + supplied_type, + NoSniffFlag::Off, + ApacheBugFlag::Off, + ) } #[cfg(test)] @@ -198,32 +208,50 @@ fn test_sniff_wave() { #[test] fn test_sniff_ogg() { test_sniff_classification("small.ogg", "application/ogg".parse().unwrap(), None); - test_sniff_classification("small.ogg", "application/ogg".parse().unwrap(), Some("audio/".parse().unwrap())); + test_sniff_classification( + "small.ogg", + "application/ogg".parse().unwrap(), + Some("audio/".parse().unwrap()), + ); } #[test] #[should_panic] fn test_sniff_vsn_ms_fontobject() { - test_sniff_classification_sup("vnd.ms-fontobject", "application/vnd.ms-fontobject".parse().unwrap()); + test_sniff_classification_sup( + "vnd.ms-fontobject", + "application/vnd.ms-fontobject".parse().unwrap(), + ); } #[test] #[should_panic] fn test_sniff_true_type() { - test_sniff_full(&PathBuf::from("unknown/true_type.ttf"), "(TrueType)/".parse().unwrap(), None); + test_sniff_full( + &PathBuf::from("unknown/true_type.ttf"), + "(TrueType)/".parse().unwrap(), + None, + ); } #[test] #[should_panic] fn test_sniff_open_type() { - test_sniff_full(&PathBuf::from("unknown/open_type"), "(OpenType)/".parse().unwrap(), None); + test_sniff_full( + &PathBuf::from("unknown/open_type"), + "(OpenType)/".parse().unwrap(), + None, + ); } #[test] #[should_panic] fn test_sniff_true_type_collection() { - test_sniff_full(&PathBuf::from("unknown/true_type_collection.ttc"), "(TrueType Collection)/".parse().unwrap(), - None); + test_sniff_full( + &PathBuf::from("unknown/true_type_collection.ttc"), + "(TrueType Collection)/".parse().unwrap(), + None, + ); } #[test] @@ -244,7 +272,11 @@ fn test_sniff_zip() { #[test] fn test_sniff_rar() { - test_sniff_classification("test.rar", "application/x-rar-compressed".parse().unwrap(), None); + test_sniff_classification( + "test.rar", + "application/x-rar-compressed".parse().unwrap(), + None, + ); } #[test] @@ -466,86 +498,130 @@ fn test_sniff_utf_8_bom() { #[test] fn test_sniff_rss_feed() { // RSS feeds - test_sniff_full(&PathBuf::from("text/xml/feed.rss"), "application/rss+xml".parse().unwrap(), Some(mime::TEXT_HTML)); - test_sniff_full(&PathBuf::from("text/xml/rdf_rss.xml"), "application/rss+xml".parse().unwrap(), - Some(mime::TEXT_HTML)); + test_sniff_full( + &PathBuf::from("text/xml/feed.rss"), + "application/rss+xml".parse().unwrap(), + Some(mime::TEXT_HTML), + ); + test_sniff_full( + &PathBuf::from("text/xml/rdf_rss.xml"), + "application/rss+xml".parse().unwrap(), + Some(mime::TEXT_HTML), + ); // Not RSS feeds - test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_1.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML)); - test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_2.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML)); - test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_3.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML)); - test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_4.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML)); + test_sniff_full( + &PathBuf::from("text/xml/rdf_rss_ko_1.xml"), + mime::TEXT_HTML, + Some(mime::TEXT_HTML), + ); + test_sniff_full( + &PathBuf::from("text/xml/rdf_rss_ko_2.xml"), + mime::TEXT_HTML, + Some(mime::TEXT_HTML), + ); + test_sniff_full( + &PathBuf::from("text/xml/rdf_rss_ko_3.xml"), + mime::TEXT_HTML, + Some(mime::TEXT_HTML), + ); + test_sniff_full( + &PathBuf::from("text/xml/rdf_rss_ko_4.xml"), + mime::TEXT_HTML, + Some(mime::TEXT_HTML), + ); } #[test] fn test_sniff_atom_feed() { - test_sniff_full(&PathBuf::from("text/xml/feed.atom"), "application/atom+xml".parse().unwrap(), - Some(mime::TEXT_HTML)); + test_sniff_full( + &PathBuf::from("text/xml/feed.atom"), + "application/atom+xml".parse().unwrap(), + Some(mime::TEXT_HTML), + ); } #[test] fn test_sniff_binary_file() { - test_sniff_full(&PathBuf::from("unknown/binary_file"), mime::APPLICATION_OCTET_STREAM, None); + test_sniff_full( + &PathBuf::from("unknown/binary_file"), + mime::APPLICATION_OCTET_STREAM, + None, + ); } #[test] fn test_sniff_atom_feed_with_no_sniff_flag_on() { - test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - NoSniffFlag::On, - ApacheBugFlag::Off); + test_sniff_with_flags( + &PathBuf::from("text/xml/feed.atom"), + mime::TEXT_HTML, + Some(mime::TEXT_HTML), + NoSniffFlag::On, + ApacheBugFlag::Off, + ); } #[test] fn test_sniff_with_no_sniff_flag_on_and_apache_flag_on() { - test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - NoSniffFlag::On, - ApacheBugFlag::On); + test_sniff_with_flags( + &PathBuf::from("text/xml/feed.atom"), + mime::TEXT_HTML, + Some(mime::TEXT_HTML), + NoSniffFlag::On, + ApacheBugFlag::On, + ); } #[test] fn test_sniff_utf_8_bom_with_apache_flag_on() { - test_sniff_with_flags(&PathBuf::from("text/plain/utf8bom.txt"), - mime::TEXT_PLAIN, - Some("dummy/text".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On); + test_sniff_with_flags( + &PathBuf::from("text/plain/utf8bom.txt"), + mime::TEXT_PLAIN, + Some("dummy/text".parse().unwrap()), + NoSniffFlag::Off, + ApacheBugFlag::On, + ); } #[test] fn test_sniff_utf_16be_bom_with_apache_flag_on() { - test_sniff_with_flags(&PathBuf::from("text/plain/utf16bebom.txt"), - mime::TEXT_PLAIN, - Some("dummy/text".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On); + test_sniff_with_flags( + &PathBuf::from("text/plain/utf16bebom.txt"), + mime::TEXT_PLAIN, + Some("dummy/text".parse().unwrap()), + NoSniffFlag::Off, + ApacheBugFlag::On, + ); } #[test] fn test_sniff_utf_16le_bom_with_apache_flag_on() { - test_sniff_with_flags(&PathBuf::from("text/plain/utf16lebom.txt"), - mime::TEXT_PLAIN, - Some("dummy/text".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On); + test_sniff_with_flags( + &PathBuf::from("text/plain/utf16lebom.txt"), + mime::TEXT_PLAIN, + Some("dummy/text".parse().unwrap()), + NoSniffFlag::Off, + ApacheBugFlag::On, + ); } #[test] fn test_sniff_octet_stream_apache_flag_on() { - test_sniff_with_flags(&PathBuf::from("unknown/binary_file"), - mime::APPLICATION_OCTET_STREAM, - Some("dummy/binary".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On); + test_sniff_with_flags( + &PathBuf::from("unknown/binary_file"), + mime::APPLICATION_OCTET_STREAM, + Some("dummy/binary".parse().unwrap()), + NoSniffFlag::Off, + ApacheBugFlag::On, + ); } #[test] fn test_sniff_mp4_video_apache_flag_on() { - test_sniff_with_flags(&PathBuf::from("video/mp4/test.mp4"), - mime::APPLICATION_OCTET_STREAM, - Some("video/mp4".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On); + test_sniff_with_flags( + &PathBuf::from("video/mp4/test.mp4"), + mime::APPLICATION_OCTET_STREAM, + Some("video/mp4".parse().unwrap()), + NoSniffFlag::Off, + ApacheBugFlag::On, + ); } diff --git a/components/net/tests/resource_thread.rs b/components/net/tests/resource_thread.rs index 575b67dc7de..d9f09270f21 100644 --- a/components/net/tests/resource_thread.rs +++ b/components/net/tests/resource_thread.rs @@ -21,7 +21,13 @@ fn test_exit() { let (mtx, _mrx) = ipc::channel().unwrap(); let (sender, receiver) = ipc::channel().unwrap(); let (resource_thread, _private_resource_thread) = new_core_resource_thread( - "".into(), None, ProfilerChan(tx), MemProfilerChan(mtx), create_embedder_proxy(), None); + "".into(), + None, + ProfilerChan(tx), + MemProfilerChan(mtx), + create_embedder_proxy(), + None, + ); resource_thread.send(CoreResourceMsg::Exit(sender)).unwrap(); receiver.recv().unwrap(); } @@ -32,12 +38,16 @@ fn test_parse_hostsfile() { let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(2, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); + assert_eq!( + ip("127.0.0.2"), + *hosts_table.get("servo.test.server").unwrap() + ); } #[test] fn test_parse_malformed_hostsfile() { - let mock_hosts_file_content = "malformed file\n127.0.0.1 foo.bar.com\nservo.test.server 127.0.0.1"; + let mock_hosts_file_content = + "malformed file\n127.0.0.1 foo.bar.com\nservo.test.server 127.0.0.1"; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(1, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); @@ -45,7 +55,8 @@ fn test_parse_malformed_hostsfile() { #[test] fn test_parse_hostsfile_with_line_comment() { - let mock_hosts_file_content = "# this is a line comment\n127.0.0.1 foo.bar.com\n# anothercomment"; + let mock_hosts_file_content = + "# this is a line comment\n127.0.0.1 foo.bar.com\n# anothercomment"; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(1, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); @@ -53,11 +64,15 @@ fn test_parse_hostsfile_with_line_comment() { #[test] fn test_parse_hostsfile_with_end_of_line_comment() { - let mock_hosts_file_content = "127.0.0.1 foo.bar.com # line ending comment\n127.0.0.2 servo.test.server #comment"; + let mock_hosts_file_content = + "127.0.0.1 foo.bar.com # line ending comment\n127.0.0.2 servo.test.server #comment"; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(2, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); + assert_eq!( + ip("127.0.0.2"), + *hosts_table.get("servo.test.server").unwrap() + ); } #[test] @@ -86,12 +101,14 @@ fn test_parse_hostsfile_with_tabs_instead_spaces() { let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(2, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); + assert_eq!( + ip("127.0.0.2"), + *hosts_table.get("servo.test.server").unwrap() + ); } #[test] -fn test_parse_hostsfile_with_valid_ipv4_addresses() -{ +fn test_parse_hostsfile_with_valid_ipv4_addresses() { let mock_hosts_file_content = "255.255.255.255 foo.bar.com\n169.0.1.201 servo.test.server\n192.168.5.0 servo.foo.com"; let hosts_table = parse_hostsfile(mock_hosts_file_content); @@ -99,8 +116,7 @@ fn test_parse_hostsfile_with_valid_ipv4_addresses() } #[test] -fn test_parse_hostsfile_with_invalid_ipv4_addresses() -{ +fn test_parse_hostsfile_with_invalid_ipv4_addresses() { let mock_hosts_file_content = "256.255.255.255 foo.bar.com\n169.0.1000.201 servo.test.server \ \n192.168.5.500 servo.foo.com\n192.abc.100.2 test.servo.com"; let hosts_table = parse_hostsfile(mock_hosts_file_content); @@ -108,8 +124,7 @@ fn test_parse_hostsfile_with_invalid_ipv4_addresses() } #[test] -fn test_parse_hostsfile_with_valid_ipv6_addresses() -{ +fn test_parse_hostsfile_with_valid_ipv6_addresses() { let mock_hosts_file_content = "2001:0db8:0000:0000:0000:ff00:0042:8329 foo.bar.com\n\ 2001:db8:0:0:0:ff00:42:8329 moz.foo.com\n\ 2001:db8::ff00:42:8329 foo.moz.com moz.moz.com\n\ @@ -122,8 +137,7 @@ fn test_parse_hostsfile_with_valid_ipv6_addresses() } #[test] -fn test_parse_hostsfile_with_invalid_ipv6_addresses() -{ +fn test_parse_hostsfile_with_invalid_ipv6_addresses() { let mock_hosts_file_content = "12001:0db8:0000:0000:0000:ff00:0042:8329 foo.bar.com\n\ 2001:zdb8:0:0:0:gg00:42:t329 moz.foo.com\n\ 2002:0DB8:85A3:0042:1000:8A2E:0370:7334/1289 baz3.bar.moz"; @@ -132,14 +146,19 @@ fn test_parse_hostsfile_with_invalid_ipv6_addresses() } #[test] -fn test_parse_hostsfile_with_end_of_line_whitespace() -{ +fn test_parse_hostsfile_with_end_of_line_whitespace() { let mock_hosts_file_content = "127.0.0.1 foo.bar.com \n\ 2001:db8:0:0:0:ff00:42:8329 moz.foo.com\n \ 127.0.0.2 servo.test.server "; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(3, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!(ip("2001:db8:0:0:0:ff00:42:8329"), *hosts_table.get("moz.foo.com").unwrap()); - assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); + assert_eq!( + ip("2001:db8:0:0:0:ff00:42:8329"), + *hosts_table.get("moz.foo.com").unwrap() + ); + assert_eq!( + ip("127.0.0.2"), + *hosts_table.get("servo.test.server").unwrap() + ); } diff --git a/components/net/tests/subresource_integrity.rs b/components/net/tests/subresource_integrity.rs index d67da9c1775..7607fc378b7 100644 --- a/components/net/tests/subresource_integrity.rs +++ b/components/net/tests/subresource_integrity.rs @@ -72,7 +72,8 @@ fn test_response_integrity_valid() { let url: ServoUrl = ServoUrl::parse("http://servo.org").unwrap(); let response: Response = Response::new(url); - let integrity_metadata = "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; + let integrity_metadata = + "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; let response_body = "alert('Hello, world.');".to_owned().into_bytes(); *response.body.lock().unwrap() = ResponseBody::Done(response_body); @@ -84,7 +85,8 @@ fn test_response_integrity_invalid() { let url: ServoUrl = ServoUrl::parse("http://servo.org").unwrap(); let response: Response = Response::new(url); - let integrity_metadata = "sha256-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; + let integrity_metadata = + "sha256-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; let response_body = "alert('Hello, world.');".to_owned().into_bytes(); *response.body.lock().unwrap() = ResponseBody::Done(response_body); diff --git a/components/net/websocket_loader.rs b/components/net/websocket_loader.rs index 8440e0b3c63..963874684b2 100644 --- a/components/net/websocket_loader.rs +++ b/components/net/websocket_loader.rs @@ -51,20 +51,25 @@ impl<'a> Factory for Client<'a> { } } - impl<'a> Handler for Client<'a> { fn build_request(&mut self, url: &Url) -> WebSocketResult { let mut req = Request::from_url(url)?; - req.headers_mut().push(("Origin".to_string(), self.origin.as_bytes().to_owned())); - req.headers_mut().push(("Host".to_string(), format!("{}", self.host).as_bytes().to_owned())); + req.headers_mut() + .push(("Origin".to_string(), self.origin.as_bytes().to_owned())); + req.headers_mut().push(( + "Host".to_string(), + format!("{}", self.host).as_bytes().to_owned(), + )); for protocol in self.protocols { req.add_protocol(protocol); - }; + } let mut cookie_jar = self.http_state.cookie_jar.write().unwrap(); - if let Some(cookie_list) = cookie_jar.cookies_for_url(self.resource_url, CookieSource::HTTP) { - req.headers_mut().push(("Cookie".into(), cookie_list.as_bytes().to_owned())) + if let Some(cookie_list) = cookie_jar.cookies_for_url(self.resource_url, CookieSource::HTTP) + { + req.headers_mut() + .push(("Cookie".into(), cookie_list.as_bytes().to_owned())) } Ok(req) @@ -83,41 +88,48 @@ impl<'a> Handler for Client<'a> { // TODO(eijebong): Replace thise once typed headers settled on a cookie impl for cookie in headers.get_all(header::SET_COOKIE) { if let Ok(s) = cookie.to_str() { - if let Some(cookie) = Cookie::from_cookie_string(s.into(), self.resource_url, CookieSource::HTTP) { + if let Some(cookie) = + Cookie::from_cookie_string(s.into(), self.resource_url, CookieSource::HTTP) + { jar.push(cookie, self.resource_url, CookieSource::HTTP); } } } - let _ = self.event_sender.send( - WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use: self.protocol_in_use.clone() }); + let _ = self + .event_sender + .send(WebSocketNetworkEvent::ConnectionEstablished { + protocol_in_use: self.protocol_in_use.clone(), + }); Ok(()) } - fn on_message(&mut self, message: Message) -> WebSocketResult<()> { + fn on_message(&mut self, message: Message) -> WebSocketResult<()> { let message = match message { Message::Text(message) => MessageData::Text(message), Message::Binary(message) => MessageData::Binary(message), }; - let _ = self.event_sender.send(WebSocketNetworkEvent::MessageReceived(message)); + let _ = self + .event_sender + .send(WebSocketNetworkEvent::MessageReceived(message)); Ok(()) } - fn on_error(&mut self, err: WebSocketError) { debug!("Error in WebSocket communication: {:?}", err); let _ = self.event_sender.send(WebSocketNetworkEvent::Fail); } - fn on_response(&mut self, res: &WsResponse) -> WebSocketResult<()> { let protocol_in_use = res.protocol()?; if let Some(protocol_name) = protocol_in_use { if !self.protocols.is_empty() && !self.protocols.iter().any(|p| protocol_name == (*p)) { - let error = WebSocketError::new(WebSocketErrorKind::Protocol, - "Protocol in Use not in client-supplied protocol list"); + let error = WebSocketError::new( + WebSocketErrorKind::Protocol, + "Protocol in Use not in client-supplied protocol list", + ); return Err(error); } self.protocol_in_use = Some(protocol_name.into()); @@ -127,7 +139,10 @@ impl<'a> Handler for Client<'a> { fn on_close(&mut self, code: CloseCode, reason: &str) { debug!("Connection closing due to ({:?}) {}", code, reason); - let _ = self.event_sender.send(WebSocketNetworkEvent::Close(Some(code.into()), reason.to_owned())); + let _ = self.event_sender.send(WebSocketNetworkEvent::Close( + Some(code.into()), + reason.to_owned(), + )); } fn upgrade_ssl_client( @@ -136,106 +151,120 @@ impl<'a> Handler for Client<'a> { url: &Url, ) -> WebSocketResult> { let certs = match opts::get().certificate_path { - Some(ref path) => { - fs::read_to_string(path).expect("Couldn't not find certificate file") - } - None => { - resources::read_string(Resource::SSLCertificates) - }, + Some(ref path) => fs::read_to_string(path).expect("Couldn't not find certificate file"), + None => resources::read_string(Resource::SSLCertificates), }; - let domain = self.resource_url.as_url().domain().ok_or(WebSocketError::new( - WebSocketErrorKind::Protocol, - format!("Unable to parse domain from {}. Needed for SSL.", url), - ))?; + let domain = self + .resource_url + .as_url() + .domain() + .ok_or(WebSocketError::new( + WebSocketErrorKind::Protocol, + format!("Unable to parse domain from {}. Needed for SSL.", url), + ))?; let connector = create_ssl_connector_builder(&certs).build(); - connector.connect(domain, stream).map_err(WebSocketError::from) + connector + .connect(domain, stream) + .map_err(WebSocketError::from) } - } pub fn init( req_init: RequestInit, resource_event_sender: IpcSender, dom_action_receiver: IpcReceiver, - http_state: Arc + http_state: Arc, ) { - thread::Builder::new().name(format!("WebSocket connection to {}", req_init.url)).spawn(move || { - let protocols = match req_init.mode { - RequestMode::WebSocket { protocols } => protocols.clone(), - _ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"), - }; + thread::Builder::new() + .name(format!("WebSocket connection to {}", req_init.url)) + .spawn(move || { + let protocols = match req_init.mode { + RequestMode::WebSocket { protocols } => protocols.clone(), + _ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"), + }; - let scheme = req_init.url.scheme(); - let mut req_url = req_init.url.clone(); - if scheme == "ws" { - req_url.as_mut_url().set_scheme("http").unwrap(); - } else if scheme == "wss" { - req_url.as_mut_url().set_scheme("https").unwrap(); - } - - if should_be_blocked_due_to_bad_port(&req_url) { - debug!("Failed to establish a WebSocket connection: port blocked"); - let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); - return; - } - - let host = replace_host(req_init.url.host_str().unwrap()); - let mut net_url = req_init.url.clone().into_url(); - net_url.set_host(Some(&host)).unwrap(); - - let host = Host::from( - format!("{}{}", req_init.url.host_str().unwrap(), - req_init.url.port_or_known_default().map(|v| format!(":{}", v)).unwrap_or("".into()) - ).parse::().unwrap() - ); - - let client = Client { - origin: &req_init.origin.ascii_serialization(), - host: &host, - protocols: &protocols, - http_state: &http_state, - resource_url: &req_init.url, - event_sender: &resource_event_sender, - protocol_in_use: None, - }; - let mut ws = WebSocket::new(client).unwrap(); - - if let Err(e) = ws.connect(net_url) { - debug!("Failed to establish a WebSocket connection: {:?}", e); - return; - }; - - let ws_sender = ws.broadcaster(); - let initiated_close = Arc::new(AtomicBool::new(false)); - - thread::spawn(move || { - while let Ok(dom_action) = dom_action_receiver.recv() { - match dom_action { - WebSocketDomAction::SendMessage(MessageData::Text(data)) => { - ws_sender.send(Message::text(data)).unwrap(); - }, - WebSocketDomAction::SendMessage(MessageData::Binary(data)) => { - ws_sender.send(Message::binary(data)).unwrap(); - }, - WebSocketDomAction::Close(code, reason) => { - if !initiated_close.fetch_or(true, Ordering::SeqCst) { - match code { - Some(code) => { - ws_sender.close_with_reason(code.into(), reason.unwrap_or("".to_owned())).unwrap() - }, - None => ws_sender.close(CloseCode::Status).unwrap(), - }; - } - }, - } + let scheme = req_init.url.scheme(); + let mut req_url = req_init.url.clone(); + if scheme == "ws" { + req_url.as_mut_url().set_scheme("http").unwrap(); + } else if scheme == "wss" { + req_url.as_mut_url().set_scheme("https").unwrap(); } - }); - if let Err(e) = ws.run() { - debug!("Failed to run WebSocket: {:?}", e); - let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); - }; - }).expect("Thread spawning failed"); + if should_be_blocked_due_to_bad_port(&req_url) { + debug!("Failed to establish a WebSocket connection: port blocked"); + let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); + return; + } + + let host = replace_host(req_init.url.host_str().unwrap()); + let mut net_url = req_init.url.clone().into_url(); + net_url.set_host(Some(&host)).unwrap(); + + let host = Host::from( + format!( + "{}{}", + req_init.url.host_str().unwrap(), + req_init + .url + .port_or_known_default() + .map(|v| format!(":{}", v)) + .unwrap_or("".into()) + ) + .parse::() + .unwrap(), + ); + + let client = Client { + origin: &req_init.origin.ascii_serialization(), + host: &host, + protocols: &protocols, + http_state: &http_state, + resource_url: &req_init.url, + event_sender: &resource_event_sender, + protocol_in_use: None, + }; + let mut ws = WebSocket::new(client).unwrap(); + + if let Err(e) = ws.connect(net_url) { + debug!("Failed to establish a WebSocket connection: {:?}", e); + return; + }; + + let ws_sender = ws.broadcaster(); + let initiated_close = Arc::new(AtomicBool::new(false)); + + thread::spawn(move || { + while let Ok(dom_action) = dom_action_receiver.recv() { + match dom_action { + WebSocketDomAction::SendMessage(MessageData::Text(data)) => { + ws_sender.send(Message::text(data)).unwrap(); + }, + WebSocketDomAction::SendMessage(MessageData::Binary(data)) => { + ws_sender.send(Message::binary(data)).unwrap(); + }, + WebSocketDomAction::Close(code, reason) => { + if !initiated_close.fetch_or(true, Ordering::SeqCst) { + match code { + Some(code) => ws_sender + .close_with_reason( + code.into(), + reason.unwrap_or("".to_owned()), + ) + .unwrap(), + None => ws_sender.close(CloseCode::Status).unwrap(), + }; + } + }, + } + } + }); + + if let Err(e) = ws.run() { + debug!("Failed to run WebSocket: {:?}", e); + let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); + }; + }) + .expect("Thread spawning failed"); } - diff --git a/components/net_traits/filemanager_thread.rs b/components/net_traits/filemanager_thread.rs index 5dd37953995..a2cb6cce29d 100644 --- a/components/net_traits/filemanager_thread.rs +++ b/components/net_traits/filemanager_thread.rs @@ -114,21 +114,46 @@ pub struct SelectedFile { #[derive(Debug, Deserialize, Serialize)] pub enum FileManagerThreadMsg { /// Select a single file. Last field is pre-selected file path for testing - SelectFile(Vec, IpcSender>, FileOrigin, Option), + SelectFile( + Vec, + IpcSender>, + FileOrigin, + Option, + ), /// Select multiple files. Last field is pre-selected file paths for testing - SelectFiles(Vec, IpcSender>>, FileOrigin, Option>), + SelectFiles( + Vec, + IpcSender>>, + FileOrigin, + Option>, + ), /// Read FileID-indexed file in chunks, optionally check URL validity based on boolean flag - ReadFile(IpcSender>, Uuid, bool, FileOrigin), + ReadFile( + IpcSender>, + Uuid, + bool, + FileOrigin, + ), /// Add an entry as promoted memory-based blob and send back the associated FileID /// as part of a valid/invalid Blob URL depending on the boolean flag - PromoteMemory(BlobBuf, bool, IpcSender>, FileOrigin), + PromoteMemory( + BlobBuf, + bool, + IpcSender>, + FileOrigin, + ), /// Add a sliced entry pointing to the parent FileID, and send back the associated FileID /// as part of a valid Blob URL - AddSlicedURLEntry(Uuid, RelativePos, IpcSender>, FileOrigin), + AddSlicedURLEntry( + Uuid, + RelativePos, + IpcSender>, + FileOrigin, + ), /// Decrease reference count and send back the acknowledgement DecRef(Uuid, FileOrigin, IpcSender>), diff --git a/components/net_traits/image/base.rs b/components/net_traits/image/base.rs index 40d79b9ea74..d09131341d3 100644 --- a/components/net_traits/image/base.rs +++ b/components/net_traits/image/base.rs @@ -33,8 +33,11 @@ pub struct Image { impl fmt::Debug for Image { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}", - self.width, self.height, self.format, self.id) + write!( + f, + "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}", + self.width, self.height, self.format, self.id + ) } } @@ -58,32 +61,29 @@ pub fn load_from_memory(buffer: &[u8]) -> Option { debug!("{}", msg); None }, - Ok(_) => { - match piston_image::load_from_memory(buffer) { - Ok(image) => { - let mut rgba = match image { - DynamicImage::ImageRgba8(rgba) => rgba, - image => image.to_rgba(), - }; - pixels::byte_swap_colors_inplace(&mut *rgba); - Some(Image { - width: rgba.width(), - height: rgba.height(), - format: PixelFormat::BGRA8, - bytes: IpcSharedMemory::from_bytes(&*rgba), - id: None, - }) - }, - Err(e) => { - debug!("Image decoding error: {:?}", e); - None - }, - } + Ok(_) => match piston_image::load_from_memory(buffer) { + Ok(image) => { + let mut rgba = match image { + DynamicImage::ImageRgba8(rgba) => rgba, + image => image.to_rgba(), + }; + pixels::byte_swap_colors_inplace(&mut *rgba); + Some(Image { + width: rgba.width(), + height: rgba.height(), + format: PixelFormat::BGRA8, + bytes: IpcSharedMemory::from_bytes(&*rgba), + id: None, + }) + }, + Err(e) => { + debug!("Image decoding error: {:?}", e); + None + }, }, } } - // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img pub fn detect_image_format(buffer: &[u8]) -> Result { if is_gif(buffer) { diff --git a/components/net_traits/image_cache.rs b/components/net_traits/image_cache.rs index ca6df6ee516..6e7f55d2233 100644 --- a/components/net_traits/image_cache.rs +++ b/components/net_traits/image_cache.rs @@ -101,16 +101,19 @@ pub enum UsePlaceholder { // ====================================================================== pub trait ImageCache: Sync + Send { - fn new(webrender_api: webrender_api::RenderApi) -> Self where Self: Sized; + fn new(webrender_api: webrender_api::RenderApi) -> Self + where + Self: Sized; /// Return any available metadata or image for the given URL, /// or an indication that the image is not yet available if it is in progress, /// or else reserve a slot in the cache for the URL if the consumer can request images. - fn find_image_or_metadata(&self, - url: ServoUrl, - use_placeholder: UsePlaceholder, - can_request: CanRequestImages) - -> Result; + fn find_image_or_metadata( + &self, + url: ServoUrl, + use_placeholder: UsePlaceholder, + can_request: CanRequestImages, + ) -> Result; /// Add a new listener for the given pending image id. If the image is already present, /// the responder will still receive the expected response. diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index 5a6a1364fbf..f3e4a0c0858 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #![deny(unsafe_code)] extern crate cookie as cookie_rs; @@ -14,18 +13,24 @@ extern crate hyper; extern crate hyper_serde; extern crate image as piston_image; extern crate ipc_channel; -#[macro_use] extern crate lazy_static; -#[macro_use] extern crate log; -#[macro_use] extern crate malloc_size_of; -#[macro_use] extern crate malloc_size_of_derive; +#[macro_use] +extern crate lazy_static; +#[macro_use] +extern crate log; +#[macro_use] +extern crate malloc_size_of; +#[macro_use] +extern crate malloc_size_of_derive; extern crate mime; extern crate msg; extern crate num_traits; extern crate pixels; -#[macro_use] extern crate serde; +#[macro_use] +extern crate serde; extern crate servo_arc; extern crate servo_url; -#[macro_use] extern crate url; +#[macro_use] +extern crate url; extern crate uuid; extern crate webrender_api; @@ -86,18 +91,26 @@ pub enum LoadContext { #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] pub struct CustomResponse { #[ignore_malloc_size_of = "Defined in hyper"] - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] + #[serde( + deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize" + )] pub headers: HeaderMap, #[ignore_malloc_size_of = "Defined in hyper"] - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] + #[serde( + deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize" + )] pub raw_status: (StatusCode, String), pub body: Vec, } impl CustomResponse { - pub fn new(headers: HeaderMap, raw_status: (StatusCode, String), body: Vec) -> CustomResponse { + pub fn new( + headers: HeaderMap, + raw_status: (StatusCode, String), + body: Vec, + ) -> CustomResponse { CustomResponse { headers: headers, raw_status: raw_status, @@ -137,22 +150,18 @@ pub enum ReferrerPolicy { impl From for ReferrerPolicy { fn from(policy: ReferrerPolicyHeader) -> Self { match policy { - ReferrerPolicyHeader::NO_REFERRER => - ReferrerPolicy::NoReferrer, - ReferrerPolicyHeader::NO_REFERRER_WHEN_DOWNGRADE => - ReferrerPolicy::NoReferrerWhenDowngrade, - ReferrerPolicyHeader::SAME_ORIGIN => - ReferrerPolicy::SameOrigin, - ReferrerPolicyHeader::ORIGIN => - ReferrerPolicy::Origin, - ReferrerPolicyHeader::ORIGIN_WHEN_CROSS_ORIGIN => - ReferrerPolicy::OriginWhenCrossOrigin, - ReferrerPolicyHeader::UNSAFE_URL => - ReferrerPolicy::UnsafeUrl, - ReferrerPolicyHeader::STRICT_ORIGIN => - ReferrerPolicy::StrictOrigin, - ReferrerPolicyHeader::STRICT_ORIGIN_WHEN_CROSS_ORIGIN => - ReferrerPolicy::StrictOriginWhenCrossOrigin, + ReferrerPolicyHeader::NO_REFERRER => ReferrerPolicy::NoReferrer, + ReferrerPolicyHeader::NO_REFERRER_WHEN_DOWNGRADE => { + ReferrerPolicy::NoReferrerWhenDowngrade + }, + ReferrerPolicyHeader::SAME_ORIGIN => ReferrerPolicy::SameOrigin, + ReferrerPolicyHeader::ORIGIN => ReferrerPolicy::Origin, + ReferrerPolicyHeader::ORIGIN_WHEN_CROSS_ORIGIN => ReferrerPolicy::OriginWhenCrossOrigin, + ReferrerPolicyHeader::UNSAFE_URL => ReferrerPolicy::UnsafeUrl, + ReferrerPolicyHeader::STRICT_ORIGIN => ReferrerPolicy::StrictOrigin, + ReferrerPolicyHeader::STRICT_ORIGIN_WHEN_CROSS_ORIGIN => { + ReferrerPolicy::StrictOriginWhenCrossOrigin + }, } } } @@ -198,7 +207,7 @@ pub enum FilteredMetadata { Basic(Metadata), Cors(Metadata), Opaque, - OpaqueRedirect + OpaqueRedirect, } #[derive(Clone, Debug, Deserialize, Serialize)] @@ -244,7 +253,6 @@ impl FetchTaskTarget for IpcSender { } } - pub trait Action { fn process(self, listener: &mut Listener); } @@ -271,7 +279,8 @@ pub type IpcSendResult = Result<(), IpcError>; /// used by net_traits::ResourceThreads to ease the use its IpcSender sub-fields /// XXX: If this trait will be used more in future, some auto derive might be appealing pub trait IpcSend - where T: serde::Serialize + for<'de> serde::Deserialize<'de>, +where + T: serde::Serialize + for<'de> serde::Deserialize<'de>, { /// send message T fn send(&self, T) -> IpcSendResult; @@ -342,9 +351,7 @@ pub enum WebSocketDomAction { #[derive(Debug, Deserialize, Serialize)] pub enum WebSocketNetworkEvent { - ConnectionEstablished { - protocol_in_use: Option, - }, + ConnectionEstablished { protocol_in_use: Option }, MessageReceived(MessageData), Close(Option, String), Fail, @@ -353,18 +360,26 @@ pub enum WebSocketNetworkEvent { #[derive(Debug, Deserialize, Serialize)] /// IPC channels to communicate with the script thread about network or DOM events. pub enum FetchChannels { - ResponseMsg(IpcSender, /* cancel_chan */ Option>), + ResponseMsg( + IpcSender, + /* cancel_chan */ Option>, + ), WebSocket { event_sender: IpcSender, action_receiver: IpcReceiver, - } + }, } #[derive(Debug, Deserialize, Serialize)] pub enum CoreResourceMsg { Fetch(RequestInit, FetchChannels), /// Initiate a fetch in response to processing a redirection - FetchRedirect(RequestInit, ResponseInit, IpcSender, /* cancel_chan */ Option>), + FetchRedirect( + RequestInit, + ResponseInit, + IpcSender, + /* cancel_chan */ Option>, + ), /// Store a cookie for a given originating URL SetCookieForUrl(ServoUrl, Serde>, CookieSource), /// Store a set of cookies for a given originating URL @@ -372,7 +387,11 @@ pub enum CoreResourceMsg { /// Retrieve the stored cookies for a given URL GetCookiesForUrl(ServoUrl, IpcSender>, CookieSource), /// Get a cookie by name for a given originating URL - GetCookiesDataForUrl(ServoUrl, IpcSender>>>, CookieSource), + GetCookiesDataForUrl( + ServoUrl, + IpcSender>>>, + CookieSource, + ), /// Get a history state by a given history state id GetHistoryState(HistoryStateId, IpcSender>>), /// Set a history state for a given history state id @@ -392,13 +411,20 @@ pub enum CoreResourceMsg { /// Instruct the resource thread to make a new request. pub fn fetch_async(request: RequestInit, core_resource_thread: &CoreResourceThread, f: F) - where F: Fn(FetchResponseMsg) + Send + 'static, +where + F: Fn(FetchResponseMsg) + Send + 'static, { let (action_sender, action_receiver) = ipc::channel().unwrap(); - ROUTER.add_route(action_receiver.to_opaque(), - Box::new(move |message| f(message.to().unwrap()))); - core_resource_thread.send( - CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, None))).unwrap(); + ROUTER.add_route( + action_receiver.to_opaque(), + Box::new(move |message| f(message.to().unwrap())), + ); + core_resource_thread + .send(CoreResourceMsg::Fetch( + request, + FetchChannels::ResponseMsg(action_sender, None), + )) + .unwrap(); } #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] @@ -466,7 +492,10 @@ impl Metadata { } if let Some(mime) = content_type { - self.headers.as_mut().unwrap().typed_insert(ContentType::from(mime.clone())); + self.headers + .as_mut() + .unwrap() + .typed_insert(ContentType::from(mime.clone())); self.content_type = Some(Serde(ContentType::from(mime.clone()))); for (name, value) in mime.params() { if mime::CHARSET == name { @@ -487,19 +516,23 @@ pub enum CookieSource { } /// Convenience function for synchronously loading a whole resource. -pub fn load_whole_resource(request: RequestInit, - core_resource_thread: &CoreResourceThread) - -> Result<(Metadata, Vec), NetworkError> { +pub fn load_whole_resource( + request: RequestInit, + core_resource_thread: &CoreResourceThread, +) -> Result<(Metadata, Vec), NetworkError> { let (action_sender, action_receiver) = ipc::channel().unwrap(); - core_resource_thread.send( - CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, None))).unwrap(); + core_resource_thread + .send(CoreResourceMsg::Fetch( + request, + FetchChannels::ResponseMsg(action_sender, None), + )) + .unwrap(); let mut buf = vec![]; let mut metadata = None; loop { match action_receiver.recv().unwrap() { - FetchResponseMsg::ProcessRequestBody | - FetchResponseMsg::ProcessRequestEOF => (), + FetchResponseMsg::ProcessRequestBody | FetchResponseMsg::ProcessRequestEOF => (), FetchResponseMsg::ProcessResponse(Ok(m)) => { metadata = Some(match m { FetchMetadata::Unfiltered(m) => m, @@ -534,7 +567,6 @@ impl NetworkError { } } - /// Normalize `slice`, as defined by /// [the Fetch Spec](https://fetch.spec.whatwg.org/#concept-header-value-normalize). pub fn trim_http_whitespace(mut slice: &[u8]) -> &[u8] { @@ -569,4 +601,3 @@ pub fn http_percent_encode(bytes: &[u8]) -> String { url::percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string() } - diff --git a/components/net_traits/pub_domains.rs b/components/net_traits/pub_domains.rs index afe70023856..636790f8ea4 100644 --- a/components/net_traits/pub_domains.rs +++ b/components/net_traits/pub_domains.rs @@ -32,7 +32,8 @@ lazy_static! { impl<'a> FromIterator<&'a str> for PubDomainRules { fn from_iter(iter: T) -> Self - where T: IntoIterator, + where + T: IntoIterator, { let mut result = PubDomainRules::new(); for item in iter { @@ -57,7 +58,8 @@ impl PubDomainRules { } } pub fn parse(content: &str) -> PubDomainRules { - content.lines() + content + .lines() .map(str::trim) .filter(|s| !s.is_empty()) .filter(|s| !s.starts_with("//")) @@ -99,7 +101,7 @@ impl PubDomainRules { None => !domain.is_empty(), Some(index) => { !self.exceptions.contains(domain) && self.wildcards.contains(&domain[index + 1..]) || - self.rules.contains(domain) + self.rules.contains(domain) }, } } @@ -112,8 +114,9 @@ impl PubDomainRules { None => false, Some(index) => { self.exceptions.contains(domain) || - !self.wildcards.contains(&domain[index + 1..]) && !self.rules.contains(domain) && - self.is_public_suffix(&domain[index + 1..]) + !self.wildcards.contains(&domain[index + 1..]) && + !self.rules.contains(domain) && + self.is_public_suffix(&domain[index + 1..]) }, } } @@ -145,7 +148,9 @@ pub fn is_reg_domain(domain: &str) -> bool { /// Leaves the host name alone if it is an IP address. pub fn reg_host(url: &ServoUrl) -> Option { match url.origin() { - ImmutableOrigin::Tuple(_, Host::Domain(domain), _) => Some(Host::Domain(String::from(reg_suffix(&*domain)))), + ImmutableOrigin::Tuple(_, Host::Domain(domain), _) => { + Some(Host::Domain(String::from(reg_suffix(&*domain)))) + }, ImmutableOrigin::Tuple(_, ip, _) => Some(ip), ImmutableOrigin::Opaque(_) => None, } diff --git a/components/net_traits/quality.rs b/components/net_traits/quality.rs index 72fed2304ca..6543cb11e8d 100644 --- a/components/net_traits/quality.rs +++ b/components/net_traits/quality.rs @@ -70,11 +70,17 @@ where let s = str::from_utf8(&digits[..]).unwrap(); fmt.write_str(s.trim_right_matches('0')) - } + }, } } } pub fn quality_to_value(q: Vec>) -> HeaderValue { - HeaderValue::from_str(&q.iter().map(|q| q.to_string()).collect::>().join(", ")).unwrap() + HeaderValue::from_str( + &q.iter() + .map(|q| q.to_string()) + .collect::>() + .join(", "), + ) + .unwrap() } diff --git a/components/net_traits/request.rs b/components/net_traits/request.rs index 4113037a672..998740efbcc 100644 --- a/components/net_traits/request.rs +++ b/components/net_traits/request.rs @@ -46,9 +46,9 @@ impl Destination { #[inline] pub fn is_script_like(&self) -> bool { *self == Destination::Script || - *self == Destination::ServiceWorker || - *self == Destination::SharedWorker || - *self == Destination::Worker + *self == Destination::ServiceWorker || + *self == Destination::SharedWorker || + *self == Destination::Worker } } @@ -75,7 +75,7 @@ pub enum RequestMode { SameOrigin, NoCors, CorsMode, - WebSocket { protocols: Vec } + WebSocket { protocols: Vec }, } /// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode) @@ -137,13 +137,17 @@ pub enum CorsSettings { #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] pub struct RequestInit { - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] + #[serde( + deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize" + )] #[ignore_malloc_size_of = "Defined in hyper"] pub method: Method, pub url: ServoUrl, - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] + #[serde( + deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize" + )] #[ignore_malloc_size_of = "Defined in hyper"] pub headers: HeaderMap, pub unsafe_request: bool, @@ -259,10 +263,7 @@ pub struct Request { } impl Request { - pub fn new(url: ServoUrl, - origin: Option, - pipeline_id: Option) - -> Request { + pub fn new(url: ServoUrl, origin: Option, pipeline_id: Option) -> Request { Request { method: Method::GET, local_urls_only: false, @@ -294,9 +295,11 @@ impl Request { } pub fn from_init(init: RequestInit) -> Request { - let mut req = Request::new(init.url.clone(), - Some(Origin::Origin(init.origin)), - init.pipeline_id); + let mut req = Request::new( + init.url.clone(), + Some(Origin::Origin(init.origin)), + init.pipeline_id, + ); req.method = init.method; req.headers = init.headers; req.unsafe_request = init.unsafe_request; @@ -350,9 +353,16 @@ impl Request { /// pub fn is_subresource_request(&self) -> bool { match self.destination { - Destination::Audio | Destination::Font | Destination::Image | Destination::Manifest | - Destination::Script | Destination::Style | Destination::Track | Destination::Video | - Destination::Xslt | Destination::None => true, + Destination::Audio | + Destination::Font | + Destination::Image | + Destination::Manifest | + Destination::Script | + Destination::Style | + Destination::Track | + Destination::Video | + Destination::Xslt | + Destination::None => true, _ => false, } } diff --git a/components/net_traits/response.rs b/components/net_traits/response.rs index e7f39358c5a..05729e1a05c 100644 --- a/components/net_traits/response.rs +++ b/components/net_traits/response.rs @@ -46,13 +46,11 @@ impl ResponseBody { pub fn is_done(&self) -> bool { match *self { ResponseBody::Done(..) => true, - ResponseBody::Empty | - ResponseBody::Receiving(..) => false, + ResponseBody::Empty | ResponseBody::Receiving(..) => false, } } } - /// [Cache state](https://fetch.spec.whatwg.org/#concept-response-cache-state) #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] pub enum CacheState { @@ -79,8 +77,10 @@ pub enum ResponseMsg { #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] pub struct ResponseInit { pub url: ServoUrl, - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] + #[serde( + deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize" + )] #[ignore_malloc_size_of = "Defined in hyper"] pub headers: HeaderMap, pub status_code: u16, @@ -149,7 +149,9 @@ impl Response { res.location_url = init.location_url; res.headers = init.headers; res.referrer = init.referrer; - res.status = StatusCode::from_u16(init.status_code).map(|s| (s, s.to_string())).ok(); + res.status = StatusCode::from_u16(init.status_code) + .map(|s| (s, s.to_string())) + .ok(); res } @@ -292,7 +294,13 @@ impl Response { pub fn metadata(&self) -> Result { fn init_metadata(response: &Response, url: &ServoUrl) -> Metadata { let mut metadata = Metadata::default(url.clone()); - metadata.set_content_type(response.headers.typed_get::().map(|v| v.into()).as_ref()); + metadata.set_content_type( + response + .headers + .typed_get::() + .map(|v| v.into()) + .as_ref(), + ); metadata.location_url = response.location_url.clone(); metadata.headers = Some(Serde(response.headers.clone())); metadata.status = response.raw_status.clone(); @@ -316,26 +324,27 @@ impl Response { match self.response_type { ResponseType::Basic => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(metadata.unwrap()), - unsafe_: unsafe_metadata + unsafe_: unsafe_metadata, }), ResponseType::Cors => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Cors(metadata.unwrap()), - unsafe_: unsafe_metadata + unsafe_: unsafe_metadata, }), ResponseType::Default => unreachable!(), - ResponseType::Error(ref network_err) => - Err(network_err.clone()), + ResponseType::Error(ref network_err) => Err(network_err.clone()), ResponseType::Opaque => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Opaque, - unsafe_: unsafe_metadata + unsafe_: unsafe_metadata, }), ResponseType::OpaqueRedirect => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::OpaqueRedirect, - unsafe_: unsafe_metadata - }) + unsafe_: unsafe_metadata, + }), } }, - None => Err(NetworkError::Internal("No url found in unsafe response".to_owned())) + None => Err(NetworkError::Internal( + "No url found in unsafe response".to_owned(), + )), } } else { assert_eq!(self.response_type, ResponseType::Default); diff --git a/components/net_traits/storage_thread.rs b/components/net_traits/storage_thread.rs index af7a8cbde92..ec636a810a6 100644 --- a/components/net_traits/storage_thread.rs +++ b/components/net_traits/storage_thread.rs @@ -27,7 +27,13 @@ pub enum StorageThreadMsg { GetItem(IpcSender>, ServoUrl, StorageType, String), /// sets the value of the given key in the associated storage data - SetItem(IpcSender), ()>>, ServoUrl, StorageType, String, String), + SetItem( + IpcSender), ()>>, + ServoUrl, + StorageType, + String, + String, + ), /// removes the key/value pair for the given key in the associated storage data RemoveItem(IpcSender>, ServoUrl, StorageType, String), diff --git a/components/net_traits/tests/pub_domains.rs b/components/net_traits/tests/pub_domains.rs index fa298633f6c..307dd2d81dc 100644 --- a/components/net_traits/tests/pub_domains.rs +++ b/components/net_traits/tests/pub_domains.rs @@ -116,6 +116,9 @@ fn test_reg_suffix() { #[test] fn test_weirdness() { // These are weird results, but AFAICT they are spec-compliant. - assert_ne!(pub_suffix("city.yokohama.jp"), pub_suffix(pub_suffix("city.yokohama.jp"))); + assert_ne!( + pub_suffix("city.yokohama.jp"), + pub_suffix(pub_suffix("city.yokohama.jp")) + ); assert!(!is_pub_domain(pub_suffix("city.yokohama.jp"))); }