Skip to content

Commit

Permalink
Toggle clippy::pedantic on neqo-crypto.
Browse files Browse the repository at this point in the history
  • Loading branch information
o0Ignition0o committed Dec 15, 2019
1 parent eb61c2a commit 7d791bf
Show file tree
Hide file tree
Showing 10 changed files with 92 additions and 72 deletions.
97 changes: 48 additions & 49 deletions neqo-crypto/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// except according to those terms.

#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(clippy::pedantic)]

use bindgen::Builder;
use serde_derive::Deserialize;
Expand Down Expand Up @@ -62,18 +63,17 @@ fn setup_clang() {
if env::var("LIBCLANG_PATH").is_ok() {
return;
}
let mozbuild_root = match env::var("MOZBUILD_STATE_PATH") {
Ok(dir) => PathBuf::from(dir.trim()),
_ => {
eprintln!("warning: Building without a gecko setup is not likely to work.");
eprintln!(" A working libclang is needed to build neqo.");
eprintln!(" Either LIBCLANG_PATH or MOZBUILD_STATE_PATH needs to be set.");
eprintln!("");
eprintln!(" We recommend checking out https://github.com/mozilla/gecko-dev");
eprintln!(" Then run `./mach bootstrap` which will retrieve clang.");
eprintln!(" Make sure to export MOZBUILD_STATE_PATH when building.");
return;
}
let mozbuild_root = if let Ok(dir) = env::var("MOZBUILD_STATE_PATH") {
PathBuf::from(dir.trim())
} else {
eprintln!("warning: Building without a gecko setup is not likely to work.");
eprintln!(" A working libclang is needed to build neqo.");
eprintln!(" Either LIBCLANG_PATH or MOZBUILD_STATE_PATH needs to be set.");
eprintln!("");
eprintln!(" We recommend checking out https://github.com/mozilla/gecko-dev");
eprintln!(" Then run `./mach bootstrap` which will retrieve clang.");
eprintln!(" Make sure to export MOZBUILD_STATE_PATH when building.");
return;
};
let libclang_dir = mozbuild_root.join("clang").join("lib");
if libclang_dir.is_dir() {
Expand All @@ -85,34 +85,33 @@ fn setup_clang() {
}

fn nss_dir() -> PathBuf {
let dir = match env::var("NSS_DIR") {
Ok(dir) => PathBuf::from(dir.trim()),
_ => {
let out_dir = env::var("OUT_DIR").unwrap();
let dir = Path::new(&out_dir).join("nss");
if !dir.exists() {
Command::new("hg")
.args(&[
"clone",
"https://hg.mozilla.org/projects/nss",
dir.to_str().unwrap(),
])
.status()
.expect("can't clone nss");
}
let nspr_dir = Path::new(&out_dir).join("nspr");
if !nspr_dir.exists() {
Command::new("hg")
.args(&[
"clone",
"https://hg.mozilla.org/projects/nspr",
nspr_dir.to_str().unwrap(),
])
.status()
.expect("can't clone nspr");
}
dir.to_path_buf()
let dir = if let Ok(dir) = env::var("NSS_DIR") {
PathBuf::from(dir.trim())
} else {
let out_dir = env::var("OUT_DIR").unwrap();
let dir = Path::new(&out_dir).join("nss");
if !dir.exists() {
Command::new("hg")
.args(&[
"clone",
"https://hg.mozilla.org/projects/nss",
dir.to_str().unwrap(),
])
.status()
.expect("can't clone nss");
}
let nspr_dir = Path::new(&out_dir).join("nspr");
if !nspr_dir.exists() {
Command::new("hg")
.args(&[
"clone",
"https://hg.mozilla.org/projects/nspr",
nspr_dir.to_str().unwrap(),
])
.status()
.expect("can't clone nspr");
}
dir.to_path_buf()
};
assert!(dir.is_dir());
// Note that this returns a relative path because UNC
Expand All @@ -136,12 +135,9 @@ fn build_nss(dir: PathBuf) {
} else {
build_nss.push(String::from("-o"));
}
match env::var("NSS_JOBS") {
Ok(d) => {
build_nss.push(String::from("-j"));
build_nss.push(d);
}
_ => (),
if let Ok(d) = env::var("NSS_JOBS") {
build_nss.push(String::from("-j"));
build_nss.push(d);
}
let status = Command::new(get_bash())
.args(build_nss)
Expand Down Expand Up @@ -321,12 +317,15 @@ fn setup_standalone() -> Vec<String> {
fn setup_for_gecko() -> Vec<String> {
let mut flags: Vec<String> = Vec::new();

let libs = match env::var("CARGO_CFG_TARGET_OS").as_ref().map(|x| x.as_str()) {
let libs = match env::var("CARGO_CFG_TARGET_OS")
.as_ref()
.map(std::string::String::as_str)
{
Ok("android") | Ok("macos") => vec!["nss3"],
_ => vec!["nssutil3", "nss3", "ssl3", "plds4", "plc4", "nspr4"],
};

for lib in libs.iter() {
for lib in &libs {
println!("cargo:rustc-link-lib=dylib={}", lib);
}

Expand Down Expand Up @@ -360,7 +359,7 @@ fn setup_for_gecko() -> Vec<String> {
flags = fs::read_to_string(flags_path)
.expect("Failed to read extra-bindgen-flags file")
.split_whitespace()
.map(|s| s.to_owned())
.map(std::borrow::ToOwned::to_owned)
.collect();

flags.push(String::from("-include"));
Expand All @@ -373,7 +372,7 @@ fn setup_for_gecko() -> Vec<String> {
.to_string(),
);
} else {
println!("cargo:warning={}", "MOZ_TOPOBJDIR should be set by default, otherwise the build is not guaranteed to finish.");
println!("cargo:warning=MOZ_TOPOBJDIR should be set by default, otherwise the build is not guaranteed to finish.");
}
flags
}
Expand Down
4 changes: 3 additions & 1 deletion neqo-crypto/src/aead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ impl Aead {
unsafe { Self::from_raw(version, cipher, s, prefix) }
}

pub fn expansion(&self) -> usize {
// We allow unused self here because
#[must_use]
pub fn expansion() -> usize {
16
}

Expand Down
33 changes: 23 additions & 10 deletions neqo-crypto/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub enum HandshakeState {
}

impl HandshakeState {
#[must_use]
pub fn connected(&self) -> bool {
match self {
HandshakeState::Complete(_) => true,
Expand Down Expand Up @@ -87,6 +88,7 @@ pub struct SecretAgentPreInfo {

macro_rules! preinfo_arg {
($v:ident, $m:ident, $f:ident: $t:ident $(,)?) => {
#[must_use]
pub fn $v(&self) -> Option<$t> {
match self.info.valuesSet & ssl::$m {
0 => None,
Expand Down Expand Up @@ -115,15 +117,15 @@ impl SecretAgentPreInfo {

preinfo_arg!(version, ssl_preinfo_version, protocolVersion: Version);
preinfo_arg!(cipher_suite, ssl_preinfo_cipher_suite, cipherSuite: Cipher);

#[must_use]
pub fn early_data(&self) -> bool {
self.info.canSendEarlyData != 0
}

#[must_use]
pub fn max_early_data(&self) -> usize {
self.info.maxEarlyDataSize as usize
}

#[must_use]
pub fn alpn(&self) -> Option<&String> {
self.alpn.as_ref()
}
Expand Down Expand Up @@ -167,25 +169,31 @@ impl SecretAgentInfo {
signature_scheme: SignatureScheme::try_from(info.signatureScheme)?,
})
}

#[must_use]
pub fn version(&self) -> Version {
self.version
}
#[must_use]
pub fn cipher_suite(&self) -> Cipher {
self.cipher
}
#[must_use]
pub fn key_exchange(&self) -> Group {
self.group
}
#[must_use]
pub fn resumed(&self) -> bool {
self.resumed
}
#[must_use]
pub fn early_data_accepted(&self) -> bool {
self.early_data
}
#[must_use]
pub fn alpn(&self) -> Option<&String> {
self.alpn.as_ref()
}
#[must_use]
pub fn signature_scheme(&self) -> SignatureScheme {
self.signature_scheme
}
Expand Down Expand Up @@ -397,12 +405,12 @@ impl SecretAgent {
self.set_option(ssl::Opt::EarlyData, true)
}

/// Disable the EndOfEarlyData message.
/// Disable the `EndOfEarlyData` message.
pub fn disable_end_of_early_data(&mut self) {
self.no_eoed = true;
}

/// set_alpn sets a list of preferred protocols, starting with the most preferred.
/// `set_alpn` sets a list of preferred protocols, starting with the most preferred.
/// Though ALPN [RFC7301] permits octet sequences, this only allows for UTF-8-encoded
/// strings.
///
Expand Down Expand Up @@ -479,6 +487,7 @@ impl SecretAgent {
/// This includes the version, ciphersuite, and ALPN.
///
/// Calling this function returns None until the connection is complete.
#[must_use]
pub fn info(&self) -> Option<&SecretAgentInfo> {
match self.state {
HandshakeState::Complete(ref info) => Some(info),
Expand All @@ -495,18 +504,20 @@ impl SecretAgent {
}

/// Get the peer's certificate chain.
#[must_use]
pub fn peer_certificate(&self) -> Option<CertificateInfo> {
CertificateInfo::new(self.fd)
}

/// Return any fatal alert that the TLS stack might have sent.
#[must_use]
pub fn alert(&self) -> Option<&Alert> {
(&*self.alert).as_ref()
}

/// Call this function to mark the peer as authenticated.
/// Only call this function if handshake/handshake_raw returns
/// HandshakeState::AuthenticationPending, or it will panic.
/// Only call this function if `handshake/handshake_raw` returns
/// `HandshakeState::AuthenticationPending`, or it will panic.
pub fn authenticated(&mut self, status: AuthenticationStatus) {
assert_eq!(self.state, HandshakeState::AuthenticationPending);
*self.auth_required = false;
Expand Down Expand Up @@ -632,14 +643,15 @@ impl SecretAgent {
}

// State returns the status of the handshake.
#[must_use]
pub fn state(&self) -> &HandshakeState {
&self.state
}

#[must_use]
pub fn read_secret(&self, epoch: Epoch) -> Option<&p11::SymKey> {
self.secrets.read().get(epoch)
}

#[must_use]
pub fn write_secret(&self, epoch: Epoch) -> Option<&p11::SymKey> {
self.secrets.write().get(epoch)
}
Expand Down Expand Up @@ -700,6 +712,7 @@ impl Client {
}

/// Return the resumption token.
#[must_use]
pub fn resumption_token(&self) -> Option<&Vec<u8>> {
(*self.resumption).as_ref()
}
Expand Down
3 changes: 2 additions & 1 deletion neqo-crypto/src/agentio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub struct Record {
}

impl Record {
#[must_use]
pub fn new(epoch: Epoch, ct: ssl::SSLContentType::Type, data: &[u8]) -> Self {
Self {
epoch,
Expand Down Expand Up @@ -88,7 +89,7 @@ impl RecordList {
self.records.push(Record::new(epoch, ct, data));
}

/// Filter out EndOfEarlyData messages.
/// Filter out `EndOfEarlyData` messages.
pub fn remove_eoed(&mut self) {
self.records.retain(|rec| rec.epoch != 1);
}
Expand Down
10 changes: 6 additions & 4 deletions neqo-crypto/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,12 @@ impl ExtensionTracker {
})
}

// Use the provided handler to manage an extension. This is quite unsafe.
// The holder of this ExtensionTracker needs to ensure that it lives at
// least as long as the file descriptor, as NSS provides no way to remove
// an extension handler once it is configured.
/// Use the provided handler to manage an extension. This is quite unsafe.
/// # Safety
///
/// The holder of this `ExtensionTracker` needs to ensure that it lives at
/// least as long as the file descriptor, as NSS provides no way to remove
/// an extension handler once it is configured.
pub unsafe fn new(
fd: *mut PRFileDesc,
extension: Extension,
Expand Down
1 change: 1 addition & 0 deletions neqo-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// except according to those terms.

#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(clippy::pedantic)]
// Bindgen auto generated code
// won't adhere to the clippy rules below
#![allow(clippy::module_name_repetitions)]
Expand Down
1 change: 1 addition & 0 deletions neqo-crypto/src/p11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ macro_rules! scoped_ptr {
}

impl $scoped {
#[must_use]
pub fn new(ptr: NonNull<$target>) -> Self {
Self { ptr: ptr.as_ptr() }
}
Expand Down
4 changes: 3 additions & 1 deletion neqo-crypto/src/selfencrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ impl SelfEncrypt {
/// the encrypted `plaintext`, plus a version number and salt.
/// `aad` is only used as input to the AEAD, it is not included in the output; the
/// caller is responsible for carrying the AAD as appropriate.
#[allow(clippy::similar_names)] // aad is similar to aead
pub fn seal(&self, aad: &[u8], plaintext: &[u8]) -> Res<Vec<u8>> {
// Format is:
// struct {
Expand All @@ -72,7 +73,7 @@ impl SelfEncrypt {
// AAD covers the entire header, plus the value of the AAD parameter that is provided.
let salt = random(SelfEncrypt::SALT_LENGTH)?;
let aead = self.make_aead(&self.key, &salt)?;
let encoded_len = 2 + salt.len() + plaintext.len() + aead.expansion();
let encoded_len = 2 + salt.len() + plaintext.len() + Aead::expansion();

let mut enc = Encoder::with_capacity(encoded_len);
enc.encode_byte(SelfEncrypt::VERSION);
Expand Down Expand Up @@ -110,6 +111,7 @@ impl SelfEncrypt {
}

/// Open the protected `ciphertext`.
#[allow(clippy::similar_names)] // aad is similar to aead
pub fn open(&self, aad: &[u8], ciphertext: &[u8]) -> Res<Vec<u8>> {
if ciphertext[0] != SelfEncrypt::VERSION {
return Err(Error::SelfEncryptFailure);
Expand Down
3 changes: 1 addition & 2 deletions neqo-transport/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1134,8 +1134,7 @@ impl Connection {
match &self.state {
State::Init | State::WaitInitial | State::Handshaking | State::Connected => {
loop {
let used =
out_bytes.len() + encoder.len() + hdr.overhead(&tx.aead, path.mtu());
let used = out_bytes.len() + encoder.len() + hdr.overhead(path.mtu());
let remaining = path.mtu() - used;
if remaining < 2 {
// All useful frames are at least 2 bytes.
Expand Down
Loading

0 comments on commit 7d791bf

Please sign in to comment.