Update hyper to 0.12

This commit is contained in:
Bastien Orivel 2018-08-27 18:36:52 +02:00
parent 95bfaa0a77
commit 024b40b39d
122 changed files with 3835 additions and 3448 deletions

View file

@ -3,7 +3,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cookie_rs;
use hyper::header::{Header, SetCookie};
use net::cookie::Cookie;
use net::cookie_storage::CookieStorage;
use net_traits::CookieSource;
@ -90,7 +89,7 @@ fn fn_cookie_constructor() {
let cookie = Cookie::new_wrapped(cookie, url, CookieSource::HTTP).unwrap();
assert_eq!(cookie.cookie.value(), "bar");
assert_eq!(cookie.cookie.name(), "baz");
assert!(cookie.cookie.secure());
assert!(cookie.cookie.secure().unwrap_or(false));
assert_eq!(&cookie.cookie.path().as_ref().unwrap()[..], "/foo/bar/");
assert_eq!(&cookie.cookie.domain().as_ref().unwrap()[..], "example.com");
assert!(cookie.host_only);
@ -324,13 +323,8 @@ fn add_retrieve_cookies(set_location: &str,
// Add all cookies to the store
for str_cookie in set_cookies {
let bytes = str_cookie.to_string().into_bytes();
let header = Header::parse_header(&[bytes]).unwrap();
let SetCookie(cookies) = header;
for bare_cookie in cookies {
let cookie = Cookie::from_cookie_string(bare_cookie, &url, source).unwrap();
storage.push(cookie, &url, source);
}
let cookie = Cookie::from_cookie_string(str_cookie.to_owned(), &url, source).unwrap();
storage.push(cookie, &url, source);
}
// Get cookies for the test location

View file

@ -2,13 +2,11 @@
* 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/. */
use hyper::header::{Header, SetCookie};
use net::cookie::Cookie;
use net::cookie_storage::CookieStorage;
use net_traits::CookieSource;
use servo_url::ServoUrl;
fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String {
let mut storage = CookieStorage::new(150);
let url = ServoUrl::parse(set_location).unwrap();
@ -16,14 +14,8 @@ fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String
// Add all cookies to the store
for str_cookie in set_cookies {
let bytes = str_cookie.to_string().into_bytes();
let header = Header::parse_header(&[bytes]);
if let Ok(SetCookie(cookies)) = header {
for bare_cookie in cookies {
if let Some(cookie) = Cookie::from_cookie_string(bare_cookie, &url, source) {
storage.push(cookie, &url, source);
}
}
if let Some(cookie) = Cookie::from_cookie_string(str_cookie.to_owned().into(), &url, source) {
storage.push(cookie, &url, source);
}
}

View file

@ -3,9 +3,10 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use fetch;
use hyper::header::ContentType;
use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value};
use headers_core::HeaderMapExt;
use headers_ext::ContentType;
use hyper_serde::Serde;
use mime::{self, Mime};
use net_traits::{FetchMetadata, FilteredMetadata, NetworkError};
use net_traits::request::{Origin, Request};
use net_traits::response::ResponseBody;
@ -28,8 +29,8 @@ fn assert_parse(url: &'static str,
assert!(!response.is_network_error());
assert_eq!(response.headers.len(), 1);
let header_content_type = response.headers.get::<ContentType>();
assert_eq!(header_content_type, content_type.as_ref());
let header_content_type = response.headers.typed_get::<ContentType>();
assert_eq!(header_content_type, content_type);
let metadata = match response.metadata() {
Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m,
@ -62,9 +63,8 @@ fn empty_invalid() {
fn plain() {
assert_parse(
"data:,hello%20world",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("US-ASCII".to_owned())))))),
Some("US-ASCII"),
Some(ContentType::from("text/plain; charset=US-ASCII".parse::<Mime>().unwrap())),
Some("us-ascii"),
Some(b"hello world"));
}
@ -72,7 +72,7 @@ fn plain() {
fn plain_ct() {
assert_parse(
"data:text/plain,hello",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))),
Some(ContentType::from(mime::TEXT_PLAIN)),
None,
Some(b"hello"));
}
@ -81,7 +81,7 @@ fn plain_ct() {
fn plain_html() {
assert_parse(
"data:text/html,<p>Servo</p>",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec!()))),
Some(ContentType::from(mime::TEXT_HTML)),
None,
Some(b"<p>Servo</p>"));
}
@ -90,9 +90,7 @@ fn plain_html() {
fn plain_charset() {
assert_parse(
"data:text/plain;charset=latin1,hello",
Some(ContentType(Mime(TopLevel::Text,
SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))),
Some(ContentType::from("text/plain; charset=latin1".parse::<Mime>().unwrap())),
Some("latin1"),
Some(b"hello"));
}
@ -101,9 +99,7 @@ fn plain_charset() {
fn plain_only_charset() {
assert_parse(
"data:;charset=utf-8,hello",
Some(ContentType(Mime(TopLevel::Text,
SubLevel::Plain,
vec!((Attr::Charset, Value::Utf8))))),
Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)),
Some("utf-8"),
Some(b"hello"));
}
@ -112,10 +108,8 @@ fn plain_only_charset() {
fn base64() {
assert_parse(
"data:;base64,C62+7w==",
Some(ContentType(Mime(TopLevel::Text,
SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("US-ASCII".to_owned())))))),
Some("US-ASCII"),
Some(ContentType::from("text/plain; charset=US-ASCII".parse::<Mime>().unwrap())),
Some("us-ascii"),
Some(&[0x0B, 0xAD, 0xBE, 0xEF]));
}
@ -123,7 +117,7 @@ fn base64() {
fn base64_ct() {
assert_parse(
"data:application/octet-stream;base64,C62+7w==",
Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))),
Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)),
None,
Some(&[0x0B, 0xAD, 0xBE, 0xEF]));
}
@ -132,8 +126,7 @@ fn base64_ct() {
fn base64_charset() {
assert_parse(
"data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==",
Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))),
Some(ContentType::from("text/plain; charset=koi8-r".parse::<Mime>().unwrap())),
Some("koi8-r"),
Some(&[0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4]));
}

View file

@ -2,27 +2,24 @@
* 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/. */
use {DEFAULT_USER_AGENT, new_fetch_context, create_embedder_proxy, fetch, make_server};
use {DEFAULT_USER_AGENT, new_fetch_context, create_embedder_proxy, fetch, make_server, make_ssl_server};
use devtools_traits::HttpRequest as DevtoolsHttpRequest;
use devtools_traits::HttpResponse as DevtoolsHttpResponse;
use fetch_with_context;
use fetch_with_cors_cache;
use headers_core::HeaderMapExt;
use headers_ext::{AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowOrigin};
use headers_ext::{AccessControlAllowMethods, AccessControlMaxAge};
use headers_ext::{CacheControl, ContentLength, ContentType, Expires, Host, LastModified, Pragma, UserAgent};
use http::{Method, StatusCode};
use http::header::{self, HeaderMap, HeaderName, HeaderValue};
use http::uri::Authority;
use http_loader::{expect_devtools_http_request, expect_devtools_http_response};
use hyper::LanguageTag;
use hyper::header::{Accept, AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowOrigin};
use hyper::header::{AcceptEncoding, AcceptLanguage, AccessControlAllowMethods, AccessControlMaxAge};
use hyper::header::{AccessControlRequestHeaders, AccessControlRequestMethod, Date, UserAgent};
use hyper::header::{CacheControl, ContentLanguage, ContentLength, ContentType, Expires, LastModified};
use hyper::header::{Encoding, Location, Pragma, Quality, QualityItem, SetCookie, qitem};
use hyper::header::{Headers, Host, HttpDate, Referer as HyperReferer};
use hyper::method::Method;
use hyper::mime::{Mime, SubLevel, TopLevel};
use hyper::server::{Request as HyperRequest, Response as HyperResponse, Server};
use hyper::status::StatusCode;
use hyper::uri::RequestUri;
use hyper_openssl;
use hyper::{Request as HyperRequest, Response as HyperResponse};
use hyper::body::Body;
use mime::{self, Mime};
use msg::constellation_msg::TEST_PIPELINE_ID;
use net::connector::create_ssl_client;
use net::connector::create_ssl_connector_builder;
use net::fetch::cors_cache::CorsCache;
use net::fetch::methods::{CancellationListener, FetchContext};
use net::filemanager_thread::FileManager;
@ -37,21 +34,21 @@ use servo_channel::{channel, Sender};
use servo_url::{ImmutableOrigin, ServoUrl};
use std::fs::File;
use std::io::Read;
use std::iter::FromIterator;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use time::{self, Duration};
use unicase::UniCase;
use std::time::{SystemTime, Duration};
// TODO write a struct that impls Handler for storing test values
#[test]
fn test_fetch_response_is_not_network_error() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -79,10 +76,10 @@ fn test_fetch_on_bad_port_is_network_error() {
#[test]
fn test_fetch_response_body_matches_const_message() {
static MESSAGE: &'static [u8] = b"Hello World!";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -142,11 +139,11 @@ fn test_fetch_blob() {
assert_eq!(fetch_response.headers.len(), 2);
let content_type: &ContentType = fetch_response.headers.get().unwrap();
assert_eq!(**content_type, Mime(TopLevel::Text, SubLevel::Plain, vec![]));
let content_type: Mime = fetch_response.headers.typed_get::<ContentType>().unwrap().into();
assert_eq!(content_type, mime::TEXT_PLAIN);
let content_length: &ContentLength = fetch_response.headers.get().unwrap();
assert_eq!(**content_length, bytes.len() as u64);
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()));
@ -162,8 +159,8 @@ 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: &ContentType = fetch_response.headers.get().unwrap();
assert_eq!(**content_type, Mime(TopLevel::Text, SubLevel::Css, vec![]));
let content_type: Mime = fetch_response.headers.typed_get::<ContentType>().unwrap().into();
assert_eq!(content_type, mime::TEXT_CSS);
let resp_body = fetch_response.body.lock().unwrap();
let mut file = File::open(path).unwrap();
@ -202,20 +199,20 @@ fn test_fetch_bogus_scheme() {
fn test_cors_preflight_fetch() {
static ACK: &'static [u8] = b"ACK";
let state = Arc::new(AtomicUsize::new(0));
let handler = move |request: HyperRequest, mut response: HyperResponse| {
if request.method == Method::Options && state.clone().fetch_add(1, Ordering::SeqCst) == 0 {
assert!(request.headers.has::<AccessControlRequestMethod>());
assert!(!request.headers.has::<AccessControlRequestHeaders>());
assert!(!request.headers.get::<HyperReferer>().unwrap().contains("a.html"));
response.headers_mut().set(AccessControlAllowOrigin::Any);
response.headers_mut().set(AccessControlAllowCredentials);
response.headers_mut().set(AccessControlAllowMethods(vec![Method::Get]));
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
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().set(AccessControlAllowOrigin::Any);
response.send(ACK).unwrap();
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
*response.body_mut() = ACK.to_vec().into();
}
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let target_url = url.clone().join("a.html").unwrap();
@ -241,20 +238,20 @@ fn test_cors_preflight_cache_fetch() {
let state = Arc::new(AtomicUsize::new(0));
let counter = state.clone();
let mut cache = CorsCache::new();
let handler = move |request: HyperRequest, mut response: HyperResponse| {
if request.method == Method::Options && state.clone().fetch_add(1, Ordering::SeqCst) == 0 {
assert!(request.headers.has::<AccessControlRequestMethod>());
assert!(!request.headers.has::<AccessControlRequestHeaders>());
response.headers_mut().set(AccessControlAllowOrigin::Any);
response.headers_mut().set(AccessControlAllowCredentials);
response.headers_mut().set(AccessControlAllowMethods(vec![Method::Get]));
response.headers_mut().set(AccessControlMaxAge(6000));
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
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().set(AccessControlAllowOrigin::Any);
response.send(ACK).unwrap();
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
*response.body_mut() = ACK.to_vec().into();
}
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(ImmutableOrigin::new_opaque());
let mut request = Request::new(url.clone(), Some(origin.clone()), None);
@ -274,8 +271,8 @@ fn test_cors_preflight_cache_fetch() {
assert_eq!(1, counter.load(Ordering::SeqCst));
// The entry exists in the CORS-preflight cache
assert_eq!(true, cache.match_method(&wrapped_request0, Method::Get));
assert_eq!(true, cache.match_method(&wrapped_request1, Method::Get));
assert_eq!(true, cache.match_method(&wrapped_request0, Method::GET));
assert_eq!(true, cache.match_method(&wrapped_request1, Method::GET));
match *fetch_response0.body.lock().unwrap() {
ResponseBody::Done(ref body) => assert_eq!(&**body, ACK),
@ -291,23 +288,23 @@ fn test_cors_preflight_cache_fetch() {
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, mut response: HyperResponse| {
if request.method == Method::Options && state.clone().fetch_add(1, Ordering::SeqCst) == 0 {
assert!(request.headers.has::<AccessControlRequestMethod>());
assert!(!request.headers.has::<AccessControlRequestHeaders>());
response.headers_mut().set(AccessControlAllowOrigin::Any);
response.headers_mut().set(AccessControlAllowCredentials);
response.headers_mut().set(AccessControlAllowMethods(vec![Method::Get]));
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
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().set(AccessControlAllowOrigin::Any);
response.send(ACK).unwrap();
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
*response.body_mut() = ACK.to_vec().into();
}
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(ImmutableOrigin::new_opaque());
let mut request = Request::new(url, Some(origin), None);
request.method = Method::Extension("CHICKEN".to_owned());
request.method = Method::from_bytes(b"CHICKEN").unwrap();
request.referrer = Referrer::NoReferrer;
request.use_cors_preflight = true;
request.mode = RequestMode::CorsMode;
@ -320,14 +317,17 @@ fn test_cors_preflight_fetch_network_error() {
#[test]
fn test_fetch_response_is_basic_filtered() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, mut response: HyperResponse| {
response.headers_mut().set(SetCookie(vec![]));
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
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().set_raw("Set-Cookie2", vec![]);
response.headers_mut().insert(
HeaderName::from_static("set-cookie2"),
HeaderValue::from_bytes(&vec![]).unwrap()
);
response.send(MESSAGE).unwrap();
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -339,39 +339,42 @@ fn test_fetch_response_is_basic_filtered() {
assert_eq!(fetch_response.response_type, ResponseType::Basic);
let headers = fetch_response.headers;
assert!(!headers.has::<SetCookie>());
assert!(headers.get_raw("Set-Cookie2").is_none());
assert!(!headers.contains_key(header::SET_COOKIE));
assert!(headers.get(HeaderName::from_static("set-cookie2")).is_none());
}
#[test]
fn test_fetch_response_is_cors_filtered() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, mut response: HyperResponse| {
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
// this is mandatory for the Cors Check to pass
// TODO test using different url encodings with this value ie. punycode
response.headers_mut().set(AccessControlAllowOrigin::Any);
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
// these are the headers that should be kept after filtering
response.headers_mut().set(CacheControl(vec![]));
response.headers_mut().set(ContentLanguage(vec![]));
response.headers_mut().set(ContentType::html());
response.headers_mut().set(Expires(HttpDate(time::now() + Duration::days(1))));
response.headers_mut().set(LastModified(HttpDate(time::now())));
response.headers_mut().set(Pragma::NoCache);
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().typed_insert(Pragma::no_cache());
// these headers should not be kept after filtering, even though they are given a pass
response.headers_mut().set(SetCookie(vec![]));
response.headers_mut().set_raw("Set-Cookie2", vec![]);
response.headers_mut().set(
AccessControlAllowHeaders(vec![
UniCase("set-cookie".to_owned()),
UniCase("set-cookie2".to_owned())
response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static(""));
response.headers_mut().insert(
HeaderName::from_static("set-cookie2"),
HeaderValue::from_bytes(&vec![]).unwrap()
);
response.headers_mut().typed_insert(
AccessControlAllowHeaders::from_iter(vec![
HeaderName::from_static("set-cookie"),
HeaderName::from_static("set-cookie2")
])
);
response.send(MESSAGE).unwrap();
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
// an origin mis-match will stop it from defaulting to a basic filtered response
let origin = Origin::Origin(ImmutableOrigin::new_opaque());
@ -385,25 +388,25 @@ fn test_fetch_response_is_cors_filtered() {
assert_eq!(fetch_response.response_type, ResponseType::Cors);
let headers = fetch_response.headers;
assert!(headers.has::<CacheControl>());
assert!(headers.has::<ContentLanguage>());
assert!(headers.has::<ContentType>());
assert!(headers.has::<Expires>());
assert!(headers.has::<LastModified>());
assert!(headers.has::<Pragma>());
assert!(headers.contains_key(header::CACHE_CONTROL));
assert!(headers.contains_key(header::CONTENT_LANGUAGE));
assert!(headers.contains_key(header::CONTENT_TYPE));
assert!(headers.contains_key(header::EXPIRES));
assert!(headers.contains_key(header::LAST_MODIFIED));
assert!(headers.contains_key(header::PRAGMA));
assert!(!headers.has::<AccessControlAllowOrigin>());
assert!(!headers.has::<SetCookie>());
assert!(headers.get_raw("Set-Cookie2").is_none());
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());
}
#[test]
fn test_fetch_response_is_opaque_filtered() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
// an origin mis-match will fall through to an Opaque filtered response
let origin = Origin::Origin(ImmutableOrigin::new_opaque());
@ -419,7 +422,7 @@ fn test_fetch_response_is_opaque_filtered() {
assert!(fetch_response.url_list.is_empty());
// this also asserts that status message is "the empty byte sequence"
assert!(fetch_response.status.is_none());
assert_eq!(fetch_response.headers, Headers::new());
assert_eq!(fetch_response.headers, HeaderMap::new());
match *fetch_response.body.lock().unwrap() {
ResponseBody::Empty => { },
_ => panic!()
@ -433,25 +436,18 @@ fn test_fetch_response_is_opaque_filtered() {
#[test]
fn test_fetch_response_is_opaque_redirect_filtered() {
static MESSAGE: &'static [u8] = b"";
let handler = move |request: HyperRequest, mut response: HyperResponse| {
let redirects = match request.uri {
RequestUri::AbsolutePath(url) =>
url.split("/").collect::<String>().parse::<u32>().unwrap_or(0),
RequestUri::AbsoluteUri(url) =>
url.path_segments().unwrap().next_back().unwrap().parse::<u32>().unwrap_or(0),
_ => panic!()
};
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
if redirects == 1 {
response.send(MESSAGE).unwrap();
*response.body_mut() = MESSAGE.to_vec().into();
} else {
*response.status_mut() = StatusCode::Found;
let url = format!("{}", 1);
response.headers_mut().set(Location(url.to_owned()));
*response.status_mut() = StatusCode::FOUND;
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1"));
}
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -465,7 +461,7 @@ fn test_fetch_response_is_opaque_redirect_filtered() {
// this also asserts that status message is "the empty byte sequence"
assert!(fetch_response.status.is_none());
assert_eq!(fetch_response.headers, Headers::new());
assert_eq!(fetch_response.headers, HeaderMap::new());
match *fetch_response.body.lock().unwrap() {
ResponseBody::Empty => { },
_ => panic!()
@ -481,10 +477,10 @@ fn test_fetch_with_local_urls_only() {
// If flag `local_urls_only` is set, fetching a non-local URL must result in network error.
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, server_url) = make_server(handler);
let (server, server_url) = make_server(handler);
let do_fetch = |url: ServoUrl| {
let origin = Origin::Origin(url.origin());
@ -506,7 +502,6 @@ fn test_fetch_with_local_urls_only() {
assert!(!local_response.is_network_error());
assert!(server_response.is_network_error());
}
// NOTE(emilio): If this test starts failing:
//
// openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
@ -517,22 +512,17 @@ fn test_fetch_with_local_urls_only() {
#[test]
fn test_fetch_with_hsts() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*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 ssl = hyper_openssl::OpensslServer::from_files(key_path, cert_path.clone())
.unwrap();
//takes an address and something that implements hyper::net::Ssl
let mut server = Server::https("0.0.0.0:0", ssl).unwrap().handle_threads(handler, 1).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();
let ssl_client = create_ssl_client(&ca_content);
let ssl_client = create_ssl_connector_builder(&ca_content);
let context = FetchContext {
state: Arc::new(HttpState::new(ssl_client)),
@ -547,15 +537,13 @@ fn test_fetch_with_hsts() {
list.push(HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None)
.unwrap());
}
let url_string = format!("http://localhost:{}", server.socket.port());
let url = ServoUrl::parse(&url_string).unwrap();
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
request.referrer = Referrer::NoReferrer;
// Set the flag.
request.local_urls_only = false;
let response = fetch_with_context(&mut request, &context);
let _ = server.close();
server.close();
assert_eq!(response.internal_response.unwrap().url().unwrap().scheme(),
"https");
}
@ -563,10 +551,10 @@ fn test_fetch_with_hsts() {
#[test]
fn test_fetch_with_sri_network_error() {
static MESSAGE: &'static [u8] = b"alert('Hello, Network Error');";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -587,10 +575,10 @@ fn test_fetch_with_sri_network_error() {
#[test]
fn test_fetch_with_sri_sucess() {
static MESSAGE: &'static [u8] = b"alert('Hello, world.');";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -616,20 +604,20 @@ fn test_fetch_blocked_nosniff() {
mime: Mime,
should_error: bool) {
const MESSAGE: &'static [u8] = b"";
const HEADER: &'static str = "X-Content-Type-Options";
const HEADER: &'static str = "x-content-type-options";
const VALUE: &'static [u8] = b"nosniff";
let handler = move |_: HyperRequest, mut response: HyperResponse| {
let mime_header = ContentType(mime.clone());
response.headers_mut().set(mime_header);
assert!(response.headers().has::<ContentType>());
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let mime_header = ContentType::from(mime.clone());
response.headers_mut().typed_insert(mime_header);
assert!(response.headers().contains_key(header::CONTENT_TYPE));
// Add the nosniff header
response.headers_mut().set_raw(HEADER, vec![VALUE.to_vec()]);
response.headers_mut().insert(HeaderName::from_static(HEADER), HeaderValue::from_bytes(VALUE).unwrap());
response.send(MESSAGE).unwrap();
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -641,9 +629,9 @@ fn test_fetch_blocked_nosniff() {
}
let tests = vec![
(Destination::Script, Mime(TopLevel::Text, SubLevel::Javascript, vec![]), false),
(Destination::Script, Mime(TopLevel::Text, SubLevel::Css, vec![]), true),
(Destination::Style, Mime(TopLevel::Text, SubLevel::Css, vec![]), false),
(Destination::Script, mime::TEXT_JAVASCRIPT, false),
(Destination::Script, mime::TEXT_CSS, true),
(Destination::Style, mime::TEXT_CSS, false),
];
for test in tests {
@ -653,25 +641,19 @@ fn test_fetch_blocked_nosniff() {
}
fn setup_server_and_fetch(message: &'static [u8], redirect_cap: u32) -> Response {
let handler = move |request: HyperRequest, mut response: HyperResponse| {
let redirects = match request.uri {
RequestUri::AbsolutePath(url) =>
url.split("/").collect::<String>().parse::<u32>().unwrap_or(0),
RequestUri::AbsoluteUri(url) =>
url.path_segments().unwrap().next_back().unwrap().parse::<u32>().unwrap_or(0),
_ => panic!()
};
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
if redirects >= redirect_cap {
response.send(message).unwrap();
*response.body_mut() = message.to_vec().into();
} else {
*response.status_mut() = StatusCode::Found;
*response.status_mut() = StatusCode::FOUND;
let url = format!("{redirects}", redirects = redirects + 1);
response.headers_mut().set(Location(url.to_owned()));
response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&url).unwrap());
}
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -720,30 +702,24 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender<bool>, status_code: Stat
let handler_method = method.clone();
let handler_tx = Arc::new(Mutex::new(tx));
let handler = move |request: HyperRequest, mut response: HyperResponse| {
let redirects = match request.uri {
RequestUri::AbsolutePath(url) =>
url.split("/").collect::<String>().parse::<u32>().unwrap_or(0),
RequestUri::AbsoluteUri(url) =>
url.path_segments().unwrap().next_back().unwrap().parse::<u32>().unwrap_or(0),
_ => panic!()
};
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
let mut test_pass = true;
if redirects == 0 {
*response.status_mut() = StatusCode::TemporaryRedirect;
response.headers_mut().set(Location("1".to_owned()));
*response.status_mut() = StatusCode::TEMPORARY_REDIRECT;
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 {
if handler_method != Method::GET && request.method() == Method::GET {
test_pass = false;
}
*response.status_mut() = status_code;
response.headers_mut().set(Location("2".to_owned()));
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("2"));
} else if request.method != Method::Get {
} else if request.method() != Method::GET {
test_pass = false;
}
@ -754,7 +730,7 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender<bool>, status_code: Stat
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -769,36 +745,36 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender<bool>, status_code: Stat
fn test_fetch_redirect_updates_method() {
let (tx, rx) = channel();
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MovedPermanently, 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
assert_eq!(rx.try_recv().is_none(), true);
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::Found, Method::Post);
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::FOUND, Method::POST);
assert_eq!(rx.recv().unwrap(), true);
assert_eq!(rx.recv().unwrap(), true);
assert_eq!(rx.try_recv().is_none(), true);
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SeeOther, Method::Get);
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SEE_OTHER, Method::GET);
assert_eq!(rx.recv().unwrap(), true);
assert_eq!(rx.recv().unwrap(), true);
assert_eq!(rx.try_recv().is_none(), true);
let extension = Method::Extension("FOO".to_owned());
let extension = Method::from_bytes(b"FOO").unwrap();
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MovedPermanently, 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);
assert_eq!(rx.try_recv().is_none(), true);
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::Found, extension.clone());
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::FOUND, extension.clone());
assert_eq!(rx.recv().unwrap(), true);
assert_eq!(rx.recv().unwrap(), false);
assert_eq!(rx.try_recv().is_none(), true);
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SeeOther, extension.clone());
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SEE_OTHER, extension.clone());
assert_eq!(rx.recv().unwrap(), true);
// for SeeOther, Method should always be changed, so this should be true
assert_eq!(rx.recv().unwrap(), true);
@ -826,10 +802,10 @@ fn response_is_done(response: &Response) -> bool {
#[test]
fn test_fetch_async_returns_complete_response() {
static MESSAGE: &'static [u8] = b"this message should be retrieved in full";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -844,10 +820,10 @@ fn test_fetch_async_returns_complete_response() {
#[test]
fn test_opaque_filtered_fetch_async_returns_complete_response() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
// an origin mis-match will fall through to an Opaque filtered response
let origin = Origin::Origin(ImmutableOrigin::new_opaque());
@ -865,25 +841,18 @@ fn test_opaque_filtered_fetch_async_returns_complete_response() {
#[test]
fn test_opaque_redirect_filtered_fetch_async_returns_complete_response() {
static MESSAGE: &'static [u8] = b"";
let handler = move |request: HyperRequest, mut response: HyperResponse| {
let redirects = match request.uri {
RequestUri::AbsolutePath(url) =>
url.split("/").collect::<String>().parse::<u32>().unwrap_or(0),
RequestUri::AbsoluteUri(url) =>
url.path_segments().unwrap().last().unwrap().parse::<u32>().unwrap_or(0),
_ => panic!()
};
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
if redirects == 1 {
response.send(MESSAGE).unwrap();
*response.body_mut() = MESSAGE.to_vec().into();
} else {
*response.status_mut() = StatusCode::Found;
let url = format!("{}", 1);
response.headers_mut().set(Location(url.to_owned()));
*response.status_mut() = StatusCode::FOUND;
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1"));
}
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -901,11 +870,11 @@ fn test_opaque_redirect_filtered_fetch_async_returns_complete_response() {
#[test]
fn test_fetch_with_devtools() {
static MESSAGE: &'static [u8] = b"Yay!";
let handler = move |_: HyperRequest, response: HyperResponse| {
response.send(MESSAGE).unwrap();
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
*response.body_mut() = MESSAGE.to_vec().into();
};
let (mut server, url) = make_server(handler);
let (server, url) = make_server(handler);
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url.clone(), Some(origin), Some(TEST_PIPELINE_ID));
@ -921,36 +890,23 @@ fn test_fetch_with_devtools() {
let mut devhttpresponse = expect_devtools_http_response(&devtools_port);
//Creating default headers for request
let mut headers = Headers::new();
let mut headers = HeaderMap::new();
headers.set(AcceptEncoding(vec![
qitem(Encoding::Gzip),
qitem(Encoding::Deflate),
qitem(Encoding::EncodingExt("br".to_owned()))
]));
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::<Authority>().unwrap()));
headers.set(Host { hostname: url.host_str().unwrap().to_owned() , port: url.port().to_owned() });
headers.insert(header::ACCEPT, HeaderValue::from_static("*/*"));
let accept = Accept(vec![qitem(Mime(TopLevel::Star, SubLevel::Star, vec![]))]);
headers.set(accept);
headers.insert(header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US, en; q=0.5"));
let mut en_us: LanguageTag = Default::default();
en_us.language = Some("en".to_owned());
en_us.region = Some("US".to_owned());
let mut en: LanguageTag = Default::default();
en.language = Some("en".to_owned());
headers.set(AcceptLanguage(vec![
qitem(en_us),
QualityItem::new(en, Quality(500)),
]));
headers.set(UserAgent(DEFAULT_USER_AGENT.to_owned()));
headers.typed_insert::<UserAgent>(DEFAULT_USER_AGENT.parse().unwrap());
let httprequest = DevtoolsHttpRequest {
url: url,
method: Method::Get,
method: Method::GET,
headers: headers,
body: None,
body: Some(vec![]),
pipeline_id: TEST_PIPELINE_ID,
startedDateTime: devhttprequest.startedDateTime,
timeStamp: devhttprequest.timeStamp,
@ -960,9 +916,9 @@ fn test_fetch_with_devtools() {
};
let content = "Yay!";
let mut response_headers = Headers::new();
response_headers.set(ContentLength(content.len() as u64));
devhttpresponse.headers.as_mut().unwrap().remove::<Date>();
let mut response_headers = HeaderMap::new();
response_headers.typed_insert(ContentLength(content.len() as u64));
devhttpresponse.headers.as_mut().unwrap().remove(header::DATE);
let httpresponse = DevtoolsHttpResponse {
headers: Some(response_headers),

File diff suppressed because it is too large Load diff

View file

@ -8,19 +8,27 @@ extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate embedder_traits;
extern crate flate2;
extern crate futures;
extern crate headers_core;
extern crate headers_ext;
extern crate http;
extern crate hyper;
extern crate hyper_openssl;
extern crate hyper_serde;
extern crate ipc_channel;
#[macro_use]
extern crate lazy_static;
extern crate mime;
extern crate msg;
extern crate net;
extern crate net_traits;
extern crate openssl;
extern crate profile_traits;
extern crate servo_channel;
extern crate servo_config;
extern crate servo_url;
extern crate time;
extern crate unicase;
extern crate tokio;
extern crate tokio_openssl;
extern crate url;
mod cookie;
@ -38,8 +46,12 @@ mod subresource_integrity;
use devtools_traits::DevtoolsControlMsg;
use embedder_traits::{EmbedderProxy, EventLoopWaker};
use embedder_traits::resources::{self, Resource};
use hyper::server::{Handler, Listening, Server};
use net::connector::create_ssl_client;
use futures::{Future, Stream};
use hyper::{Body, Request as HyperRequest, Response as HyperResponse};
use hyper::server::Server as HyperServer;
use hyper::server::conn::Http;
use hyper::service::service_fn_ok;
use net::connector::create_ssl_connector_builder;
use net::fetch::cors_cache::CorsCache;
use net::fetch::methods::{self, CancellationListener, FetchContext};
use net::filemanager_thread::FileManager;
@ -47,9 +59,21 @@ use net::test::HttpState;
use net_traits::FetchTaskTarget;
use net_traits::request::Request;
use net_traits::response::Response;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use servo_channel::{channel, Sender};
use servo_url::ServoUrl;
use std::net::TcpListener as StdTcpListener;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tokio::net::TcpListener;
use tokio::runtime::Runtime;
use tokio_openssl::SslAcceptorExt;
lazy_static! {
pub static ref HANDLE: Mutex<Runtime> = {
Mutex::new(Runtime::new().unwrap())
};
}
const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow.";
@ -84,10 +108,10 @@ fn create_embedder_proxy() -> EmbedderProxy {
}
fn new_fetch_context(dc: Option<Sender<DevtoolsControlMsg>>, fc: Option<EmbedderProxy>) -> FetchContext {
let ssl_client = create_ssl_client(&resources::read_string(Resource::SSLCertificates));
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_client)),
state: Arc::new(HttpState::new(ssl_connector)),
user_agent: DEFAULT_USER_AGENT.into(),
devtools_chan: dc,
filemanager: FileManager::new(sender),
@ -131,10 +155,78 @@ fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Respon
receiver.recv().unwrap()
}
fn make_server<H: Handler + 'static>(handler: H) -> (Listening, ServoUrl) {
// this is a Listening server because of handle_threads()
let server = Server::http("0.0.0.0:0").unwrap().handle_threads(handler, 2).unwrap();
let url_string = format!("http://localhost:{}", server.socket.port());
pub(crate) struct Server {
pub close_channel: futures::sync::oneshot::Sender<()>,
}
impl Server {
fn close(self) {
self.close_channel.send(()).unwrap();
}
}
fn make_server<H>(handler: H) -> (Server, ServoUrl)
where
H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync + 'static,
{
let handler = Arc::new(handler);
let listener = StdTcpListener::bind("0.0.0.0:0").unwrap();
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 handler = handler.clone();
service_fn_ok(move |req: HyperRequest<Body>| {
let mut response = HyperResponse::new(Vec::<u8>::new().into());
handler(req, &mut response);
response
})
}
)
.with_graceful_shutdown(rx)
.map_err(|_|());
HANDLE.lock().unwrap().spawn(server);
let server = Server { close_channel: tx };
(server, url)
}
fn make_ssl_server<H>(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl)
where
H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync + 'static,
{
let handler = Arc::new(handler);
let listener = StdTcpListener::bind("[::0]:0").unwrap();
let listener = TcpListener::from_std(listener, &HANDLE.lock().unwrap().reactor()).unwrap();
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 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<Body>| {
let mut response = HyperResponse::new(Vec::<u8>::new().into());
handler(req, &mut response);
response
})
)
.map_err(|_|())
})
});
let (tx, rx) = futures::sync::oneshot::channel::<()>();
let server = server.select(rx.map_err(|_| ())).map(|_| ()).map_err(|_| ());
HANDLE.lock().unwrap().spawn(server);
let server = Server { close_channel: tx };
(server, url)
}

View file

@ -2,8 +2,8 @@
* 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/. */
use mime::{self, Mime};
use net::mime_classifier::{ApacheBugFlag, MimeClassifier, Mp4Matcher, NoSniffFlag};
use net::mime_classifier::as_string_option;
use net_traits::LoadContext;
use std::env;
use std::fs::File;
@ -58,11 +58,10 @@ fn test_validate_classifier() {
#[cfg(test)]
fn test_sniff_with_flags(filename_orig: &path::Path,
type_string: &str,
subtype_string: &str,
supplied_type: Option<(&'static str, &'static str)>,
no_sniff_flag: NoSniffFlag,
apache_bug_flag: ApacheBugFlag) {
expected_mime: Mime,
supplied_type: Option<Mime>,
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());
@ -75,17 +74,15 @@ fn test_sniff_with_flags(filename_orig: &path::Path,
match read_result {
Ok(data) => {
let supplied_type = supplied_type.map(|(x, y)| (x.parse().unwrap(), y));
let (parsed_type, parsed_subtp) = classifier.classify(LoadContext::Browsing,
no_sniff_flag,
apache_bug_flag,
&as_string_option(supplied_type),
&data);
if (&parsed_type[..] != type_string) ||
(&parsed_subtp[..] != subtype_string) {
panic!("File {:?} parsed incorrectly should be {}/{}, parsed as {}/{}",
filename, type_string, subtype_string,
parsed_type, parsed_subtp);
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);
}
}
Err(e) => panic!("Couldn't read from file {:?} with error {}",
@ -94,407 +91,407 @@ fn test_sniff_with_flags(filename_orig: &path::Path,
}
#[cfg(test)]
fn test_sniff_full(filename_orig: &path::Path, type_string: &str, subtype_string: &str,
supplied_type: Option<(&'static str, &'static str)>) {
fn test_sniff_full(filename_orig: &path::Path, expected_mime: Mime,
supplied_type: Option<Mime>) {
test_sniff_with_flags(filename_orig,
type_string,
subtype_string,
expected_mime,
supplied_type,
NoSniffFlag::Off,
ApacheBugFlag::Off)
}
#[cfg(test)]
fn test_sniff_classification(file: &str, type_string: &str, subtype_string: &str,
supplied_type: Option<(&'static str, &'static str)>) {
fn test_sniff_classification(file: &str, expected_mime: Mime, supplied_type: Option<Mime>) {
let mut x = PathBuf::from("./");
x.push(type_string);
x.push(subtype_string);
x.push(expected_mime.type_().as_str());
x.push(expected_mime.subtype().as_str());
x.push(file);
test_sniff_full(&x, type_string, subtype_string, supplied_type);
test_sniff_full(&x, expected_mime, supplied_type);
}
#[cfg(test)]
fn test_sniff_classification_sup(file: &str, type_string: &'static str, subtype_string: &str) {
test_sniff_classification(file, type_string, subtype_string, None);
let class_type = Some((type_string, ""));
test_sniff_classification(file, type_string, subtype_string, class_type);
fn test_sniff_classification_sup(file: &str, expected_mime: Mime) {
test_sniff_classification(file, expected_mime.clone(), None);
let no_sub = format!("{}/", expected_mime.type_()).parse().unwrap();
test_sniff_classification(file, expected_mime, Some(no_sub));
}
#[test]
fn test_sniff_x_icon() {
test_sniff_classification_sup("test.ico", "image", "x-icon");
test_sniff_classification_sup("test.ico", "image/x-icon".parse().unwrap());
}
#[test]
fn test_sniff_x_icon_cursor() {
test_sniff_classification_sup("test_cursor.ico", "image", "x-icon");
test_sniff_classification_sup("test_cursor.ico", "image/x-icon".parse().unwrap());
}
#[test]
fn test_sniff_bmp() {
test_sniff_classification_sup("test.bmp", "image", "bmp");
test_sniff_classification_sup("test.bmp", mime::IMAGE_BMP);
}
#[test]
fn test_sniff_gif87a() {
test_sniff_classification_sup("test87a", "image", "gif");
test_sniff_classification_sup("test87a", mime::IMAGE_GIF);
}
#[test]
fn test_sniff_gif89a() {
test_sniff_classification_sup("test89a.gif", "image", "gif");
test_sniff_classification_sup("test89a.gif", mime::IMAGE_GIF);
}
#[test]
fn test_sniff_webp() {
test_sniff_classification_sup("test.webp", "image", "webp");
test_sniff_classification_sup("test.webp", "image/webp".parse().unwrap());
}
#[test]
fn test_sniff_png() {
test_sniff_classification_sup("test.png", "image", "png");
test_sniff_classification_sup("test.png", mime::IMAGE_PNG);
}
#[test]
fn test_sniff_jpg() {
test_sniff_classification_sup("test.jpg", "image", "jpeg");
test_sniff_classification_sup("test.jpg", mime::IMAGE_JPEG);
}
#[test]
fn test_sniff_webm() {
test_sniff_classification_sup("test.webm", "video", "webm");
test_sniff_classification_sup("test.webm", "video/webm".parse().unwrap());
}
#[test]
fn test_sniff_mp4() {
test_sniff_classification_sup("test.mp4", "video", "mp4");
test_sniff_classification_sup("test.mp4", "video/mp4".parse().unwrap());
}
#[test]
fn test_sniff_avi() {
test_sniff_classification_sup("test.avi", "video", "avi");
test_sniff_classification_sup("test.avi", "video/avi".parse().unwrap());
}
#[test]
fn test_sniff_basic() {
test_sniff_classification_sup("test.au", "audio", "basic");
test_sniff_classification_sup("test.au", "audio/basic".parse().unwrap());
}
#[test]
fn test_sniff_aiff() {
test_sniff_classification_sup("test.aif", "audio", "aiff");
test_sniff_classification_sup("test.aif", "audio/aiff".parse().unwrap());
}
#[test]
fn test_sniff_mpeg() {
test_sniff_classification_sup("test.mp3", "audio", "mpeg");
test_sniff_classification_sup("test.mp3", "audio/mpeg".parse().unwrap());
}
#[test]
fn test_sniff_midi() {
test_sniff_classification_sup("test.mid", "audio", "midi");
test_sniff_classification_sup("test.mid", "audio/midi".parse().unwrap());
}
#[test]
fn test_sniff_wave() {
test_sniff_classification_sup("test.wav", "audio", "wave");
test_sniff_classification_sup("test.wav", "audio/wave".parse().unwrap());
}
#[test]
fn test_sniff_ogg() {
test_sniff_classification("small.ogg", "application", "ogg", None);
test_sniff_classification("small.ogg", "application", "ogg", Some(("audio", "")));
test_sniff_classification("small.ogg", "application/ogg".parse().unwrap(), None);
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");
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)", "", 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)", "", 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)", "", None);
test_sniff_full(&PathBuf::from("unknown/true_type_collection.ttc"), "(TrueType Collection)/".parse().unwrap(),
None);
}
#[test]
#[should_panic]
fn test_sniff_woff() {
test_sniff_classification_sup("test.wof", "application", "font-woff");
test_sniff_classification_sup("test.wof", "application/font-woff".parse().unwrap());
}
#[test]
fn test_sniff_gzip() {
test_sniff_classification("test.gz", "application", "x-gzip", None);
test_sniff_classification("test.gz", "application/x-gzip".parse().unwrap(), None);
}
#[test]
fn test_sniff_zip() {
test_sniff_classification("test.zip", "application", "zip", None);
test_sniff_classification("test.zip", "application/zip".parse().unwrap(), None);
}
#[test]
fn test_sniff_rar() {
test_sniff_classification("test.rar", "application", "x-rar-compressed", None);
test_sniff_classification("test.rar", "application/x-rar-compressed".parse().unwrap(), None);
}
#[test]
fn test_sniff_text_html_doctype_20() {
test_sniff_classification("text_html_doctype_20.html", "text", "html", None);
test_sniff_classification("text_html_doctype_20_u.html", "text", "html", None);
test_sniff_classification("text_html_doctype_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_doctype_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_doctype_3e() {
test_sniff_classification("text_html_doctype_3e.html", "text", "html", None);
test_sniff_classification("text_html_doctype_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_doctype_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_doctype_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_page_20() {
test_sniff_classification("text_html_page_20.html", "text", "html", None);
test_sniff_classification("text_html_page_20_u.html", "text", "html", None);
test_sniff_classification("text_html_page_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_page_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_page_3e() {
test_sniff_classification("text_html_page_3e.html", "text", "html", None);
test_sniff_classification("text_html_page_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_page_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_page_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_head_20() {
test_sniff_classification("text_html_head_20.html", "text", "html", None);
test_sniff_classification("text_html_head_20_u.html", "text", "html", None);
test_sniff_classification("text_html_head_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_head_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_head_3e() {
test_sniff_classification("text_html_head_3e.html", "text", "html", None);
test_sniff_classification("text_html_head_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_head_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_head_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_script_20() {
test_sniff_classification("text_html_script_20.html", "text", "html", None);
test_sniff_classification("text_html_script_20_u.html", "text", "html", None);
test_sniff_classification("text_html_script_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_script_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_script_3e() {
test_sniff_classification("text_html_script_3e.html", "text", "html", None);
test_sniff_classification("text_html_script_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_script_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_script_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_iframe_20() {
test_sniff_classification("text_html_iframe_20.html", "text", "html", None);
test_sniff_classification("text_html_iframe_20_u.html", "text", "html", None);
test_sniff_classification("text_html_iframe_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_iframe_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_iframe_3e() {
test_sniff_classification("text_html_iframe_3e.html", "text", "html", None);
test_sniff_classification("text_html_iframe_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_iframe_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_iframe_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_h1_20() {
test_sniff_classification("text_html_h1_20.html", "text", "html", None);
test_sniff_classification("text_html_h1_20_u.html", "text", "html", None);
test_sniff_classification("text_html_h1_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_h1_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_h1_3e() {
test_sniff_classification("text_html_h1_3e.html", "text", "html", None);
test_sniff_classification("text_html_h1_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_h1_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_h1_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_div_20() {
test_sniff_classification("text_html_div_20.html", "text", "html", None);
test_sniff_classification("text_html_div_20_u.html", "text", "html", None);
test_sniff_classification("text_html_div_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_div_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_div_3e() {
test_sniff_classification("text_html_div_3e.html", "text", "html", None);
test_sniff_classification("text_html_div_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_div_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_div_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_font_20() {
test_sniff_classification("text_html_font_20.html", "text", "html", None);
test_sniff_classification("text_html_font_20_u.html", "text", "html", None);
test_sniff_classification("text_html_font_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_font_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_font_3e() {
test_sniff_classification("text_html_font_3e.html", "text", "html", None);
test_sniff_classification("text_html_font_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_font_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_font_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_table_20() {
test_sniff_classification("text_html_table_20.html", "text", "html", None);
test_sniff_classification("text_html_table_20_u.html", "text", "html", None);
test_sniff_classification("text_html_table_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_table_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_table_3e() {
test_sniff_classification("text_html_table_3e.html", "text", "html", None);
test_sniff_classification("text_html_table_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_table_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_table_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_a_20() {
test_sniff_classification("text_html_a_20.html", "text", "html", None);
test_sniff_classification("text_html_a_20_u.html", "text", "html", None);
test_sniff_classification("text_html_a_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_a_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_a_3e() {
test_sniff_classification("text_html_a_3e.html", "text", "html", None);
test_sniff_classification("text_html_a_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_a_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_a_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_style_20() {
test_sniff_classification("text_html_style_20.html", "text", "html", None);
test_sniff_classification("text_html_style_20_u.html", "text", "html", None);
test_sniff_classification("text_html_style_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_style_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_style_3e() {
test_sniff_classification("text_html_style_3e.html", "text", "html", None);
test_sniff_classification("text_html_style_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_style_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_style_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_title_20() {
test_sniff_classification("text_html_title_20.html", "text", "html", None);
test_sniff_classification("text_html_title_20_u.html", "text", "html", None);
test_sniff_classification("text_html_title_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_title_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_title_3e() {
test_sniff_classification("text_html_title_3e.html", "text", "html", None);
test_sniff_classification("text_html_title_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_title_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_title_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_b_20() {
test_sniff_classification("text_html_b_20.html", "text", "html", None);
test_sniff_classification("text_html_b_20_u.html", "text", "html", None);
test_sniff_classification("text_html_b_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_b_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_b_3e() {
test_sniff_classification("text_html_b_3e.html", "text", "html", None);
test_sniff_classification("text_html_b_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_b_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_b_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_body_20() {
test_sniff_classification("text_html_body_20.html", "text", "html", None);
test_sniff_classification("text_html_body_20_u.html", "text", "html", None);
test_sniff_classification("text_html_body_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_body_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_body_3e() {
test_sniff_classification("text_html_body_3e.html", "text", "html", None);
test_sniff_classification("text_html_body_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_body_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_body_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_br_20() {
test_sniff_classification("text_html_br_20.html", "text", "html", None);
test_sniff_classification("text_html_br_20_u.html", "text", "html", None);
test_sniff_classification("text_html_br_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_br_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_br_3e() {
test_sniff_classification("text_html_br_3e.html", "text", "html", None);
test_sniff_classification("text_html_br_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_br_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_br_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_p_20() {
test_sniff_classification("text_html_p_20.html", "text", "html", None);
test_sniff_classification("text_html_p_20_u.html", "text", "html", None);
test_sniff_classification("text_html_p_20.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_p_20_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_p_3e() {
test_sniff_classification("text_html_p_3e.html", "text", "html", None);
test_sniff_classification("text_html_p_3e_u.html", "text", "html", None);
test_sniff_classification("text_html_p_3e.html", mime::TEXT_HTML, None);
test_sniff_classification("text_html_p_3e_u.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_comment_20() {
test_sniff_classification("text_html_comment_20.html", "text", "html", None);
test_sniff_classification("text_html_comment_20.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_text_html_comment_3e() {
test_sniff_classification("text_html_comment_3e.html", "text", "html", None);
test_sniff_classification("text_html_comment_3e.html", mime::TEXT_HTML, None);
}
#[test]
fn test_sniff_xml() {
test_sniff_classification("test.xml", "text", "xml", None);
test_sniff_classification("test.xml", mime::TEXT_XML, None);
}
#[test]
fn test_sniff_pdf() {
test_sniff_classification("test.pdf", "application", "pdf", None);
test_sniff_classification("test.pdf", mime::APPLICATION_PDF, None);
}
#[test]
fn test_sniff_postscript() {
test_sniff_classification("test.ps", "application", "postscript", None);
test_sniff_classification("test.ps", "application/postscript".parse().unwrap(), None);
}
#[test]
fn test_sniff_utf_16be_bom() {
test_sniff_classification("utf16bebom.txt", "text", "plain", None);
test_sniff_classification("utf16bebom.txt", mime::TEXT_PLAIN, None);
}
#[test]
fn test_sniff_utf_16le_bom() {
test_sniff_classification("utf16lebom.txt", "text", "plain", None);
test_sniff_classification("utf16lebom.txt", mime::TEXT_PLAIN, None);
}
#[test]
fn test_sniff_utf_8_bom() {
test_sniff_classification("utf8bom.txt", "text", "plain", None);
test_sniff_classification("utf8bom.txt", mime::TEXT_PLAIN, None);
}
#[test]
fn test_sniff_rss_feed() {
// RSS feeds
test_sniff_full(&PathBuf::from("text/xml/feed.rss"), "application", "rss+xml", Some(("text", "html")));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss.xml"), "application", "rss+xml", Some(("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"), "text", "html", Some(("text", "html")));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_2.xml"), "text", "html", Some(("text", "html")));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_3.xml"), "text", "html", Some(("text", "html")));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_4.xml"), "text", "html", Some(("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", Some(("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"), "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"),
"text",
"html",
Some(("text", "html")),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
NoSniffFlag::On,
ApacheBugFlag::Off);
}
@ -502,9 +499,8 @@ fn test_sniff_atom_feed_with_no_sniff_flag_on() {
#[test]
fn test_sniff_with_no_sniff_flag_on_and_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"),
"text",
"html",
Some(("text", "html")),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
NoSniffFlag::On,
ApacheBugFlag::On);
}
@ -512,9 +508,8 @@ fn test_sniff_with_no_sniff_flag_on_and_apache_flag_on() {
#[test]
fn test_sniff_utf_8_bom_with_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/plain/utf8bom.txt"),
"text",
"plain",
Some(("dummy", "text")),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
}
@ -522,9 +517,8 @@ fn test_sniff_utf_8_bom_with_apache_flag_on() {
#[test]
fn test_sniff_utf_16be_bom_with_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/plain/utf16bebom.txt"),
"text",
"plain",
Some(("dummy", "text")),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
}
@ -532,9 +526,8 @@ fn test_sniff_utf_16be_bom_with_apache_flag_on() {
#[test]
fn test_sniff_utf_16le_bom_with_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/plain/utf16lebom.txt"),
"text",
"plain",
Some(("dummy", "text")),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
}
@ -542,9 +535,8 @@ fn test_sniff_utf_16le_bom_with_apache_flag_on() {
#[test]
fn test_sniff_octet_stream_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("unknown/binary_file"),
"application",
"octet-stream",
Some(("dummy", "binary")),
mime::APPLICATION_OCTET_STREAM,
Some("dummy/binary".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
}
@ -552,9 +544,8 @@ fn test_sniff_octet_stream_apache_flag_on() {
#[test]
fn test_sniff_mp4_video_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("video/mp4/test.mp4"),
"application",
"octet-stream",
Some(("video", "mp4")),
mime::APPLICATION_OCTET_STREAM,
Some("video/mp4".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
}