From 16e2378646a65a062c5f2b9cc344021112fd06f8 Mon Sep 17 00:00:00 2001 From: o0Ignition0o Date: Sun, 15 Dec 2019 11:03:26 +0100 Subject: [PATCH] Toggle clippy::pedantic on neqo-crypto. --- neqo-crypto/build.rs | 97 ++++++++++++++-------------- neqo-crypto/src/aead.rs | 3 +- neqo-crypto/src/agent.rs | 47 +++++++++----- neqo-crypto/src/agentio.rs | 13 ++-- neqo-crypto/src/auth.rs | 104 +++++++++++++------------------ neqo-crypto/src/err.rs | 4 +- neqo-crypto/src/ext.rs | 10 +-- neqo-crypto/src/lib.rs | 4 +- neqo-crypto/src/p11.rs | 1 + neqo-crypto/src/secrets.rs | 4 +- neqo-crypto/src/selfencrypt.rs | 16 ++--- neqo-crypto/src/ssl.rs | 22 +++---- neqo-crypto/src/time.rs | 4 ++ neqo-transport/src/connection.rs | 3 +- neqo-transport/src/packet.rs | 8 +-- 15 files changed, 174 insertions(+), 166 deletions(-) diff --git a/neqo-crypto/build.rs b/neqo-crypto/build.rs index d33e3e8b54..55ccfb7168 100644 --- a/neqo-crypto/build.rs +++ b/neqo-crypto/build.rs @@ -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; @@ -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() { @@ -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 @@ -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) @@ -321,12 +317,15 @@ fn setup_standalone() -> Vec { fn setup_for_gecko() -> Vec { let mut flags: Vec = 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); } @@ -360,7 +359,7 @@ fn setup_for_gecko() -> Vec { 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")); @@ -373,7 +372,7 @@ fn setup_for_gecko() -> Vec { .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 } diff --git a/neqo-crypto/src/aead.rs b/neqo-crypto/src/aead.rs index 1e31671232..4bd8cb3a1b 100644 --- a/neqo-crypto/src/aead.rs +++ b/neqo-crypto/src/aead.rs @@ -59,7 +59,8 @@ impl Aead { unsafe { Self::from_raw(version, cipher, s, prefix) } } - pub fn expansion(&self) -> usize { + #[must_use] + pub fn expansion() -> usize { 16 } diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index b7fb6c3cee..ad51186e9d 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -42,9 +42,10 @@ pub enum HandshakeState { } impl HandshakeState { + #[must_use] pub fn connected(&self) -> bool { match self { - HandshakeState::Complete(_) => true, + Self::Complete(_) => true, _ => false, } } @@ -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, @@ -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() } @@ -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 } @@ -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. /// @@ -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), @@ -495,18 +504,20 @@ impl SecretAgent { } /// Get the peer's certificate chain. + #[must_use] pub fn peer_certificate(&self) -> Option { 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; @@ -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) } @@ -700,6 +712,7 @@ impl Client { } /// Return the resumption token. + #[must_use] pub fn resumption_token(&self) -> Option<&Vec> { (*self.resumption).as_ref() } @@ -896,8 +909,8 @@ impl Deref for Agent { type Target = SecretAgent; fn deref(&self) -> &SecretAgent { match self { - Agent::Client(c) => &*c, - Agent::Server(s) => &*s, + Self::Client(c) => &*c, + Self::Server(s) => &*s, } } } @@ -905,20 +918,20 @@ impl Deref for Agent { impl DerefMut for Agent { fn deref_mut(&mut self) -> &mut SecretAgent { match self { - Agent::Client(c) => c.deref_mut(), - Agent::Server(s) => s.deref_mut(), + Self::Client(c) => c.deref_mut(), + Self::Server(s) => s.deref_mut(), } } } impl From for Agent { fn from(c: Client) -> Self { - Agent::Client(c) + Self::Client(c) } } impl From for Agent { fn from(s: Server) -> Self { - Agent::Server(s) + Self::Server(s) } } diff --git a/neqo-crypto/src/agentio.rs b/neqo-crypto/src/agentio.rs index f85dd0e08a..dcac47c42b 100644 --- a/neqo-crypto/src/agentio.rs +++ b/neqo-crypto/src/agentio.rs @@ -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, @@ -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); } @@ -101,7 +102,7 @@ impl RecordList { len: c_uint, arg: *mut c_void, ) -> ssl::SECStatus { - let a = arg as *mut RecordList; + let a = arg as *mut Self; let records = a.as_mut().unwrap(); let slice = std::slice::from_raw_parts(data, len as usize); @@ -110,10 +111,10 @@ impl RecordList { } /// Create a new record list. - pub(crate) fn setup(fd: *mut ssl::PRFileDesc) -> Res>> { - let mut records = Pin::new(Box::new(RecordList::default())); - let records_ptr = &mut *records as *mut RecordList as *mut c_void; - unsafe { ssl::SSL_RecordLayerWriteCallback(fd, Some(RecordList::ingest), records_ptr) }?; + pub(crate) fn setup(fd: *mut ssl::PRFileDesc) -> Res>> { + let mut records = Pin::new(Box::new(Self::default())); + let records_ptr = &mut *records as *mut Self as *mut c_void; + unsafe { ssl::SSL_RecordLayerWriteCallback(fd, Some(Self::ingest), records_ptr) }?; Ok(records) } } diff --git a/neqo-crypto/src/auth.rs b/neqo-crypto/src/auth.rs index 85f90117d3..44b5502ddf 100644 --- a/neqo-crypto/src/auth.rs +++ b/neqo-crypto/src/auth.rs @@ -36,38 +36,30 @@ pub enum AuthenticationStatus { impl Into for AuthenticationStatus { fn into(self) -> PRErrorCode { match self { - AuthenticationStatus::Ok => 0, - AuthenticationStatus::CaInvalid => sec::SEC_ERROR_CA_CERT_INVALID, - AuthenticationStatus::CaNotV3 => mozpkix::MOZILLA_PKIX_ERROR_V1_CERT_USED_AS_CA, - AuthenticationStatus::CertAlgorithmDisabled => { - sec::SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED - } - AuthenticationStatus::CertExpired => sec::SEC_ERROR_EXPIRED_CERTIFICATE, - AuthenticationStatus::CertInvalidTime => sec::SEC_ERROR_INVALID_TIME, - AuthenticationStatus::CertIsCa => { - mozpkix::MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY - } - AuthenticationStatus::CertKeyUsage => sec::SEC_ERROR_INADEQUATE_KEY_USAGE, - AuthenticationStatus::CertMitm => mozpkix::MOZILLA_PKIX_ERROR_MITM_DETECTED, - AuthenticationStatus::CertNotYetValid => { - mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_CERTIFICATE - } - AuthenticationStatus::CertRevoked => sec::SEC_ERROR_REVOKED_CERTIFICATE, - AuthenticationStatus::CertSelfSigned => mozpkix::MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT, - AuthenticationStatus::CertSubjectInvalid => ssl::SSL_ERROR_BAD_CERT_DOMAIN, - AuthenticationStatus::CertUntrusted => sec::SEC_ERROR_UNTRUSTED_CERT, - AuthenticationStatus::CertWeakKey => mozpkix::MOZILLA_PKIX_ERROR_INADEQUATE_KEY_SIZE, - AuthenticationStatus::IssuerEmptyName => mozpkix::MOZILLA_PKIX_ERROR_EMPTY_ISSUER_NAME, - AuthenticationStatus::IssuerExpired => sec::SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE, - AuthenticationStatus::IssuerNotYetValid => { - mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_ISSUER_CERTIFICATE - } - AuthenticationStatus::IssuerUnknown => sec::SEC_ERROR_UNKNOWN_ISSUER, - AuthenticationStatus::IssuerUntrusted => sec::SEC_ERROR_UNTRUSTED_ISSUER, - AuthenticationStatus::PolicyRejection => { + Self::Ok => 0, + Self::CaInvalid => sec::SEC_ERROR_CA_CERT_INVALID, + Self::CaNotV3 => mozpkix::MOZILLA_PKIX_ERROR_V1_CERT_USED_AS_CA, + Self::CertAlgorithmDisabled => sec::SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED, + Self::CertExpired => sec::SEC_ERROR_EXPIRED_CERTIFICATE, + Self::CertInvalidTime => sec::SEC_ERROR_INVALID_TIME, + Self::CertIsCa => mozpkix::MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY, + Self::CertKeyUsage => sec::SEC_ERROR_INADEQUATE_KEY_USAGE, + Self::CertMitm => mozpkix::MOZILLA_PKIX_ERROR_MITM_DETECTED, + Self::CertNotYetValid => mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_CERTIFICATE, + Self::CertRevoked => sec::SEC_ERROR_REVOKED_CERTIFICATE, + Self::CertSelfSigned => mozpkix::MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT, + Self::CertSubjectInvalid => ssl::SSL_ERROR_BAD_CERT_DOMAIN, + Self::CertUntrusted => sec::SEC_ERROR_UNTRUSTED_CERT, + Self::CertWeakKey => mozpkix::MOZILLA_PKIX_ERROR_INADEQUATE_KEY_SIZE, + Self::IssuerEmptyName => mozpkix::MOZILLA_PKIX_ERROR_EMPTY_ISSUER_NAME, + Self::IssuerExpired => sec::SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE, + Self::IssuerNotYetValid => mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_ISSUER_CERTIFICATE, + Self::IssuerUnknown => sec::SEC_ERROR_UNKNOWN_ISSUER, + Self::IssuerUntrusted => sec::SEC_ERROR_UNTRUSTED_ISSUER, + Self::PolicyRejection => { mozpkix::MOZILLA_PKIX_ERROR_ADDITIONAL_POLICY_CONSTRAINT_FAILED } - AuthenticationStatus::Unknown => sec::SEC_ERROR_LIBRARY_FAILURE, + Self::Unknown => sec::SEC_ERROR_LIBRARY_FAILURE, } } } @@ -77,38 +69,30 @@ impl Into for AuthenticationStatus { impl From for AuthenticationStatus { fn from(v: PRErrorCode) -> Self { match v { - 0 => AuthenticationStatus::Ok, - sec::SEC_ERROR_CA_CERT_INVALID => AuthenticationStatus::CaInvalid, - mozpkix::MOZILLA_PKIX_ERROR_V1_CERT_USED_AS_CA => AuthenticationStatus::CaNotV3, - sec::SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED => { - AuthenticationStatus::CertAlgorithmDisabled - } - sec::SEC_ERROR_EXPIRED_CERTIFICATE => AuthenticationStatus::CertExpired, - sec::SEC_ERROR_INVALID_TIME => AuthenticationStatus::CertInvalidTime, - mozpkix::MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY => { - AuthenticationStatus::CertIsCa - } - sec::SEC_ERROR_INADEQUATE_KEY_USAGE => AuthenticationStatus::CertKeyUsage, - mozpkix::MOZILLA_PKIX_ERROR_MITM_DETECTED => AuthenticationStatus::CertMitm, - mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_CERTIFICATE => { - AuthenticationStatus::CertNotYetValid - } - sec::SEC_ERROR_REVOKED_CERTIFICATE => AuthenticationStatus::CertRevoked, - mozpkix::MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT => AuthenticationStatus::CertSelfSigned, - ssl::SSL_ERROR_BAD_CERT_DOMAIN => AuthenticationStatus::CertSubjectInvalid, - sec::SEC_ERROR_UNTRUSTED_CERT => AuthenticationStatus::CertUntrusted, - mozpkix::MOZILLA_PKIX_ERROR_INADEQUATE_KEY_SIZE => AuthenticationStatus::CertWeakKey, - mozpkix::MOZILLA_PKIX_ERROR_EMPTY_ISSUER_NAME => AuthenticationStatus::IssuerEmptyName, - sec::SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE => AuthenticationStatus::IssuerExpired, - mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_ISSUER_CERTIFICATE => { - AuthenticationStatus::IssuerNotYetValid - } - sec::SEC_ERROR_UNKNOWN_ISSUER => AuthenticationStatus::IssuerUnknown, - sec::SEC_ERROR_UNTRUSTED_ISSUER => AuthenticationStatus::IssuerUntrusted, + 0 => Self::Ok, + sec::SEC_ERROR_CA_CERT_INVALID => Self::CaInvalid, + mozpkix::MOZILLA_PKIX_ERROR_V1_CERT_USED_AS_CA => Self::CaNotV3, + sec::SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED => Self::CertAlgorithmDisabled, + sec::SEC_ERROR_EXPIRED_CERTIFICATE => Self::CertExpired, + sec::SEC_ERROR_INVALID_TIME => Self::CertInvalidTime, + mozpkix::MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY => Self::CertIsCa, + sec::SEC_ERROR_INADEQUATE_KEY_USAGE => Self::CertKeyUsage, + mozpkix::MOZILLA_PKIX_ERROR_MITM_DETECTED => Self::CertMitm, + mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_CERTIFICATE => Self::CertNotYetValid, + sec::SEC_ERROR_REVOKED_CERTIFICATE => Self::CertRevoked, + mozpkix::MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT => Self::CertSelfSigned, + ssl::SSL_ERROR_BAD_CERT_DOMAIN => Self::CertSubjectInvalid, + sec::SEC_ERROR_UNTRUSTED_CERT => Self::CertUntrusted, + mozpkix::MOZILLA_PKIX_ERROR_INADEQUATE_KEY_SIZE => Self::CertWeakKey, + mozpkix::MOZILLA_PKIX_ERROR_EMPTY_ISSUER_NAME => Self::IssuerEmptyName, + sec::SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE => Self::IssuerExpired, + mozpkix::MOZILLA_PKIX_ERROR_NOT_YET_VALID_ISSUER_CERTIFICATE => Self::IssuerNotYetValid, + sec::SEC_ERROR_UNKNOWN_ISSUER => Self::IssuerUnknown, + sec::SEC_ERROR_UNTRUSTED_ISSUER => Self::IssuerUntrusted, mozpkix::MOZILLA_PKIX_ERROR_ADDITIONAL_POLICY_CONSTRAINT_FAILED => { - AuthenticationStatus::PolicyRejection + Self::PolicyRejection } - _ => AuthenticationStatus::Unknown, + _ => Self::Unknown, } } } diff --git a/neqo-crypto/src/err.rs b/neqo-crypto/src/err.rs index 87a6be9799..f97fae681a 100644 --- a/neqo-crypto/src/err.rs +++ b/neqo-crypto/src/err.rs @@ -69,12 +69,12 @@ impl std::fmt::Display for Error { impl From for Error { fn from(_: std::num::TryFromIntError) -> Self { - Error::IntegerOverflow + Self::IntegerOverflow } } impl From for Error { fn from(_: std::ffi::NulError) -> Self { - Error::InternalError + Self::InternalError } } diff --git a/neqo-crypto/src/ext.rs b/neqo-crypto/src/ext.rs index 3d68dc62b5..772eb46af7 100644 --- a/neqo-crypto/src/ext.rs +++ b/neqo-crypto/src/ext.rs @@ -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, diff --git a/neqo-crypto/src/lib.rs b/neqo-crypto/src/lib.rs index 6b37fd5623..ff79666aa2 100644 --- a/neqo-crypto/src/lib.rs +++ b/neqo-crypto/src/lib.rs @@ -5,10 +5,12 @@ // 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)] #![allow(clippy::unseparated_literal_suffix)] +#![allow(clippy::used_underscore_binding)] #[macro_use] mod exp; @@ -70,7 +72,7 @@ enum NssLoaded { impl Drop for NssLoaded { fn drop(&mut self) { match self { - NssLoaded::NoDb | NssLoaded::Db(_) => unsafe { + Self::NoDb | Self::Db(_) => unsafe { secstatus_to_res(nss::NSS_Shutdown()).expect("NSS Shutdown failed") }, _ => {} diff --git a/neqo-crypto/src/p11.rs b/neqo-crypto/src/p11.rs index ece196cb84..99dfb78785 100644 --- a/neqo-crypto/src/p11.rs +++ b/neqo-crypto/src/p11.rs @@ -31,6 +31,7 @@ macro_rules! scoped_ptr { } impl $scoped { + #[must_use] pub fn new(ptr: NonNull<$target>) -> Self { Self { ptr: ptr.as_ptr() } } diff --git a/neqo-crypto/src/secrets.rs b/neqo-crypto/src/secrets.rs index e72d5a0af2..9aeec1a9dd 100644 --- a/neqo-crypto/src/secrets.rs +++ b/neqo-crypto/src/secrets.rs @@ -29,8 +29,8 @@ pub enum SecretDirection { impl From for SecretDirection { fn from(dir: SSLSecretDirection::Type) -> Self { match dir { - SSLSecretDirection::ssl_secret_read => SecretDirection::Read, - SSLSecretDirection::ssl_secret_write => SecretDirection::Write, + SSLSecretDirection::ssl_secret_read => Self::Read, + SSLSecretDirection::ssl_secret_write => Self::Write, _ => unreachable!(), } } diff --git a/neqo-crypto/src/selfencrypt.rs b/neqo-crypto/src/selfencrypt.rs index cb99e1cf79..dc74eaaf3c 100644 --- a/neqo-crypto/src/selfencrypt.rs +++ b/neqo-crypto/src/selfencrypt.rs @@ -30,7 +30,7 @@ impl SelfEncrypt { pub fn new(version: Version, cipher: Cipher) -> Res { let sz = hkdf::key_size(version, cipher)?; let key = hkdf::generate_key(version, cipher, sz)?; - Ok(SelfEncrypt { + Ok(Self { version, cipher, key_id: 0, @@ -40,7 +40,7 @@ impl SelfEncrypt { } fn make_aead(&self, k: &SymKey, salt: &[u8]) -> Res { - debug_assert_eq!(salt.len(), SelfEncrypt::SALT_LENGTH); + debug_assert_eq!(salt.len(), Self::SALT_LENGTH); let salt = hkdf::import_key(self.version, self.cipher, salt)?; let secret = hkdf::extract(self.version, self.cipher, Some(&salt), k)?; Aead::new(self.version, self.cipher, &secret, "neqo self") @@ -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> { // Format is: // struct { @@ -70,12 +71,12 @@ impl SelfEncrypt { // opaque aead_encrypted(plaintext)[length as expanded]; // }; // AAD covers the entire header, plus the value of the AAD parameter that is provided. - let salt = random(SelfEncrypt::SALT_LENGTH)?; + let salt = random(Self::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); + enc.encode_byte(Self::VERSION); enc.encode_byte(self.key_id); enc.encode(&salt); @@ -110,8 +111,9 @@ impl SelfEncrypt { } /// Open the protected `ciphertext`. + #[allow(clippy::similar_names)] // aad is similar to aead pub fn open(&self, aad: &[u8], ciphertext: &[u8]) -> Res> { - if ciphertext[0] != SelfEncrypt::VERSION { + if ciphertext[0] != Self::VERSION { return Err(Error::SelfEncryptFailure); } let key = if let Some(k) = self.select_key(ciphertext[1]) { @@ -119,7 +121,7 @@ impl SelfEncrypt { } else { return Err(Error::SelfEncryptFailure); }; - let offset = 2 + SelfEncrypt::SALT_LENGTH; + let offset = 2 + Self::SALT_LENGTH; let mut extended_aad = Encoder::with_capacity(offset + aad.len()); extended_aad.encode(&ciphertext[0..offset]); diff --git a/neqo-crypto/src/ssl.rs b/neqo-crypto/src/ssl.rs index 55acfe481a..b4b1544213 100644 --- a/neqo-crypto/src/ssl.rs +++ b/neqo-crypto/src/ssl.rs @@ -47,16 +47,16 @@ impl Opt { #[allow(clippy::cast_possible_wrap)] pub fn as_int(self) -> PRInt32 { let i = match self { - Opt::Locking => SSLOption::SSL_NO_LOCKS, - Opt::Tickets => SSLOption::SSL_ENABLE_SESSION_TICKETS, - Opt::OcspStapling => SSLOption::SSL_ENABLE_OCSP_STAPLING, - Opt::Alpn => SSLOption::SSL_ENABLE_ALPN, - Opt::ExtendedMasterSecret => SSLOption::SSL_ENABLE_EXTENDED_MASTER_SECRET, - Opt::SignedCertificateTimestamps => SSLOption::SSL_ENABLE_SIGNED_CERT_TIMESTAMPS, - Opt::EarlyData => SSLOption::SSL_ENABLE_0RTT_DATA, - Opt::RecordSizeLimit => SSLOption::SSL_RECORD_SIZE_LIMIT, - Opt::Tls13CompatMode => SSLOption::SSL_ENABLE_TLS13_COMPAT_MODE, - Opt::HelloDowngradeCheck => SSLOption::SSL_ENABLE_HELLO_DOWNGRADE_CHECK, + Self::Locking => SSLOption::SSL_NO_LOCKS, + Self::Tickets => SSLOption::SSL_ENABLE_SESSION_TICKETS, + Self::OcspStapling => SSLOption::SSL_ENABLE_OCSP_STAPLING, + Self::Alpn => SSLOption::SSL_ENABLE_ALPN, + Self::ExtendedMasterSecret => SSLOption::SSL_ENABLE_EXTENDED_MASTER_SECRET, + Self::SignedCertificateTimestamps => SSLOption::SSL_ENABLE_SIGNED_CERT_TIMESTAMPS, + Self::EarlyData => SSLOption::SSL_ENABLE_0RTT_DATA, + Self::RecordSizeLimit => SSLOption::SSL_RECORD_SIZE_LIMIT, + Self::Tls13CompatMode => SSLOption::SSL_ENABLE_TLS13_COMPAT_MODE, + Self::HelloDowngradeCheck => SSLOption::SSL_ENABLE_HELLO_DOWNGRADE_CHECK, }; i as PRInt32 } @@ -64,7 +64,7 @@ impl Opt { // Some options are backwards, like SSL_NO_LOCKS, so use this to manage that. pub fn map_enabled(self, enabled: bool) -> PRIntn { let v = match self { - Opt::Locking => !enabled, + Self::Locking => !enabled, _ => enabled, }; PRIntn::from(v) diff --git a/neqo-crypto/src/time.rs b/neqo-crypto/src/time.rs index 6d9eef47dc..61eaee6fe4 100644 --- a/neqo-crypto/src/time.rs +++ b/neqo-crypto/src/time.rs @@ -200,6 +200,10 @@ mod test { } #[test] + // We allow replace_consts here beceuse + // std::u64::max_value() isn't available + // in all of our targets + #[allow(clippy::replace_consts)] fn overflow_interval() { init(); let interval = Interval::from(Duration::from_micros(std::u64::MAX)); diff --git a/neqo-transport/src/connection.rs b/neqo-transport/src/connection.rs index be1788ecc6..f781df4f50 100644 --- a/neqo-transport/src/connection.rs +++ b/neqo-transport/src/connection.rs @@ -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. diff --git a/neqo-transport/src/packet.rs b/neqo-transport/src/packet.rs index d2609ea1ef..10157dec21 100644 --- a/neqo-transport/src/packet.rs +++ b/neqo-transport/src/packet.rs @@ -159,14 +159,14 @@ impl PacketHdr { } // header length plus auth tag - pub fn overhead(&self, aead: &Aead, pmtu: usize) -> usize { + pub fn overhead(&self, pmtu: usize) -> usize { match &self.tipe { PacketType::Short => { // Leading byte. let mut len = 1; len += self.dcid.0.len(); len += pn_length(self.pn); - len + aead.expansion() + len + Aead::expansion() } PacketType::VN(_) => unimplemented!("Can't get overhead for VN"), PacketType::Retry { .. } => unimplemented!("Can't get overhead for Retry"), @@ -186,9 +186,9 @@ impl PacketHdr { len += token.len(); } - len += Encoder::varint_len((pnl + pmtu + aead.expansion()) as u64); + len += Encoder::varint_len((pnl + pmtu + Aead::expansion()) as u64); len += pnl; - len + aead.expansion() + len + Aead::expansion() } } }