Skip to content

Commit

Permalink
Rustfmt net crate
Browse files Browse the repository at this point in the history
  • Loading branch information
pyfisch committed Nov 3, 2018
1 parent ba1ed11 commit 2481ad2
Show file tree
Hide file tree
Showing 30 changed files with 4,968 additions and 2,881 deletions.
54 changes: 35 additions & 19 deletions components/net/blob_loader.rs
Expand Up @@ -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<u8>), NetworkError> {
pub fn load_blob_sync(
url: ServoUrl,
filemanager: FileManager,
) -> Result<(HeaderMap, Vec<u8>), 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();
Expand All @@ -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);
Expand All @@ -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(),
);
}

Expand All @@ -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)));
}
},
}
}
}
70 changes: 39 additions & 31 deletions components/net/connector.rs
Expand Up @@ -20,17 +20,15 @@ use tokio::prelude::future::Executor;
pub const BUF_SIZE: usize = 32768;

pub struct HttpConnector {
inner: HyperHttpConnector
inner: HyperHttpConnector,
}

impl HttpConnector {
fn new() -> HttpConnector {
let mut inner = HyperHttpConnector::new(4);
inner.enforce_http(false);
inner.set_happy_eyeballs_timeout(None);
HttpConnector {
inner
}
HttpConnector { inner }
}
}

Expand Down Expand Up @@ -60,10 +58,7 @@ impl WrappedBody {
}

pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self {
WrappedBody {
body,
decoder,
}
WrappedBody { body, decoder }
}
}

Expand All @@ -90,29 +85,29 @@ 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()));
let len = decoder.read(&mut buf).ok()?;
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
Expand All @@ -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<Option<&str>> = 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<Option<&str>> = 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<E>(ssl_connector_builder: SslConnectorBuilder, executor: E)
-> Client<Connector, WrappedBody>
where
E: Executor<Box<Future<Error=(), Item=()> + Send + 'static>> + Sync + Send + 'static
pub fn create_http_client<E>(
ssl_connector_builder: SslConnectorBuilder,
executor: E,
) -> Client<Connector, WrappedBody>
where
E: Executor<Box<Future<Error = (), Item = ()> + 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
Expand Down
81 changes: 49 additions & 32 deletions components/net/cookie.rs
Expand Up @@ -19,39 +19,54 @@ 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<Serde<Tm>>,
}

impl Cookie {
pub fn from_cookie_string(cookie_str: String, request: &ServoUrl,
source: CookieSource) -> Option<Cookie> {
pub fn from_cookie_string(
cookie_str: String,
request: &ServoUrl,
source: CookieSource,
) -> Option<Cookie> {
cookie_rs::Cookie::parse(cookie_str)
.ok()
.map(|cookie| Cookie::new_wrapped(cookie, request, source))
.unwrap_or(None)
}

/// <http://tools.ietf.org/html/rfc6265#section-5.3>
pub fn new_wrapped(mut cookie: cookie_rs::Cookie<'static>, request: &ServoUrl, source: CookieSource)
-> Option<Cookie> {
pub fn new_wrapped(
mut cookie: cookie_rs::Cookie<'static>,
request: &ServoUrl,
source: CookieSource,
) -> Option<Cookie> {
// 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();
Expand All @@ -64,7 +79,7 @@ impl Cookie {
if domain == url_host {
domain = "".to_string();
} else {
return None
return None;
}
}

Expand All @@ -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;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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
Expand All @@ -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::<Ipv4Addr>().is_err() &&
string.parse::<Ipv6Addr>().is_err())
(string.ends_with(domain_string) &&
string.as_bytes()[string.len() - domain_string.len() - 1] == b'.' &&
string.parse::<Ipv4Addr>().is_err() &&
string.parse::<Ipv6Addr>().is_err())
}

// http://tools.ietf.org/html/rfc6265#section-5.4 step 1
Expand Down

0 comments on commit 2481ad2

Please sign in to comment.