diff options
author | Steven Fackler <sfackler@gmail.com> | 2020-05-24 14:16:49 -0700 |
---|---|---|
committer | Steven Fackler <sfackler@gmail.com> | 2020-05-24 16:31:04 -0700 |
commit | f401ba2ec1957cecbe98b81afd9a188f76052883 (patch) | |
tree | d7414f75961f84c1560a6d20c7289b3ef46fbd17 | |
parent | 406031991ff3d25e33ca7c74ac1c3790b303e67a (diff) | |
download | rust-openssl-f401ba2ec1957cecbe98b81afd9a188f76052883.zip |
Run clippy
42 files changed, 423 insertions, 239 deletions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14c0f9bd..5f611859 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,6 @@ on: push: branches: - master - - github-actions env: RUSTFLAGS: -Dwarnings @@ -23,3 +22,28 @@ jobs: run: rustup update stable && rustup default stable - name: Check formatting run: cargo fmt --all -- --check + + clippy: + name: clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Rust + run: rustup update stable && rustup default stable + - name: Get rust version + id: rust-version + run: echo "::set-output name=version::$(rustc --version)" + - name: Create lockfile + run: cargo generate-lockfile + - name: Cache cargo registry + uses: actions/cache@v1 + with: + path: ~/.cargo/registry/cache + key: registry-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }} + - name: Cache target directory + uses: actions/cache@v1 + with: + path: target + key: clippy-target-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }} + - name: Check clippy + run: cargo clippy --all --all-targets diff --git a/openssl-sys/build/cfgs.rs b/openssl-sys/build/cfgs.rs index b1ec33f5..13aa0895 100644 --- a/openssl-sys/build/cfgs.rs +++ b/openssl-sys/build/cfgs.rs @@ -1,3 +1,4 @@ +#[allow(clippy::inconsistent_digit_grouping)] pub fn get(openssl_version: Option<u64>, libressl_version: Option<u64>) -> Vec<&'static str> { let mut cfgs = vec![]; diff --git a/openssl-sys/build/find_normal.rs b/openssl-sys/build/find_normal.rs index 0623a409..f7978923 100644 --- a/openssl-sys/build/find_normal.rs +++ b/openssl-sys/build/find_normal.rs @@ -9,14 +9,15 @@ pub fn get_openssl(target: &str) -> (PathBuf, PathBuf) { let lib_dir = env("OPENSSL_LIB_DIR").map(PathBuf::from); let include_dir = env("OPENSSL_INCLUDE_DIR").map(PathBuf::from); - if lib_dir.is_none() || include_dir.is_none() { - let openssl_dir = env("OPENSSL_DIR").unwrap_or_else(|| find_openssl_dir(&target)); - let openssl_dir = Path::new(&openssl_dir); - let lib_dir = lib_dir.unwrap_or_else(|| openssl_dir.join("lib")); - let include_dir = include_dir.unwrap_or_else(|| openssl_dir.join("include")); - (lib_dir, include_dir) - } else { - (lib_dir.unwrap(), include_dir.unwrap()) + match (lib_dir, include_dir) { + (Some(lib_dir), Some(include_dir)) => (lib_dir, include_dir), + (lib_dir, include_dir) => { + let openssl_dir = env("OPENSSL_DIR").unwrap_or_else(|| find_openssl_dir(&target)); + let openssl_dir = Path::new(&openssl_dir); + let lib_dir = lib_dir.unwrap_or_else(|| openssl_dir.join("lib")); + let include_dir = include_dir.unwrap_or_else(|| openssl_dir.join("include")); + (lib_dir, include_dir) + } } } @@ -93,7 +94,7 @@ openssl-sys = {} if host.contains("apple-darwin") && target.contains("apple-darwin") { let system = Path::new("/usr/lib/libssl.0.9.8.dylib"); if system.exists() { - msg.push_str(&format!( + msg.push_str( " It looks like you're compiling on macOS, where the system contains a version of @@ -105,27 +106,28 @@ install the `openssl` package, or as a maintainer you can use the openssl-sys Unfortunately though the compile cannot continue, so aborting. -" - )); +", + ); } } - if host.contains("unknown-linux") && target.contains("unknown-linux-gnu") { - if Command::new("pkg-config").output().is_err() { - msg.push_str(&format!( - " + if host.contains("unknown-linux") + && target.contains("unknown-linux-gnu") + && Command::new("pkg-config").output().is_err() + { + msg.push_str( + " It looks like you're compiling on Linux and also targeting Linux. Currently this requires the `pkg-config` utility to find OpenSSL but unfortunately `pkg-config` could not be found. If you have OpenSSL installed you can likely fix this by installing `pkg-config`. -" - )); - } +", + ); } if host.contains("windows") && target.contains("windows-gnu") { - msg.push_str(&format!( + msg.push_str( " It looks like you're compiling for MinGW but you may not have either OpenSSL or pkg-config installed. You can install these two dependencies with: @@ -134,12 +136,12 @@ pacman -S openssl-devel pkg-config and try building this crate again. -" - )); +", + ); } if host.contains("windows") && target.contains("windows-msvc") { - msg.push_str(&format!( + msg.push_str( " It looks like you're compiling for MSVC but we couldn't detect an OpenSSL installation. If there isn't one installed then you can try the rust-openssl @@ -148,8 +150,8 @@ OpenSSL: https://github.com/sfackler/rust-openssl#windows -" - )); +", + ); } panic!(msg); @@ -234,5 +236,6 @@ fn execute_command_and_get_output(cmd: &str, args: &[&str]) -> Option<String> { } } } - return None; + + None } diff --git a/openssl-sys/build/main.rs b/openssl-sys/build/main.rs index 1933438a..67efb238 100644 --- a/openssl-sys/build/main.rs +++ b/openssl-sys/build/main.rs @@ -1,3 +1,5 @@ +#![allow(clippy::inconsistent_digit_grouping)] + extern crate autocfg; extern crate cc; #[cfg(feature = "vendored")] @@ -79,11 +81,11 @@ fn main() { ); println!("cargo:include={}", include_dir.to_string_lossy()); - let version = validate_headers(&[include_dir.clone().into()]); + let version = validate_headers(&[include_dir]); let libs_env = env("OPENSSL_LIBS"); let libs = match libs_env.as_ref().and_then(|s| s.to_str()) { - Some(ref v) => v.split(":").collect(), + Some(ref v) => v.split(':').collect(), None => match version { Version::Openssl10x if target.contains("windows") => vec!["ssleay32", "libeay32"], Version::Openssl11x if target.contains("windows-msvc") => vec!["libssl", "libcrypto"], diff --git a/openssl-sys/src/err.rs b/openssl-sys/src/err.rs index ecaec3ed..dc02b8f1 100644 --- a/openssl-sys/src/err.rs +++ b/openssl-sys/src/err.rs @@ -9,7 +9,7 @@ const_fn! { pub const fn ERR_PACK(l: c_int, f: c_int, r: c_int) -> c_ulong { ((l as c_ulong & 0x0FF) << 24) | ((f as c_ulong & 0xFFF) << 12) | - ((r as c_ulong & 0xFFF)) + (r as c_ulong & 0xFFF) } pub const fn ERR_GET_LIB(l: c_ulong) -> c_int { diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index bc2176e1..c30b70d4 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1,5 +1,13 @@ -#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] -#![allow(dead_code, overflowing_literals, unused_imports)] +#![allow( + clippy::missing_safety_doc, + clippy::unreadable_literal, + dead_code, + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + overflowing_literals, + unused_imports +)] #![doc(html_root_url = "https://docs.rs/openssl-sys/0.9")] extern crate libc; diff --git a/openssl/build.rs b/openssl/build.rs index c1a5ccff..5ec03a70 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -1,7 +1,9 @@ +#![allow(clippy::inconsistent_digit_grouping)] + use std::env; fn main() { - if let Ok(_) = env::var("DEP_OPENSSL_LIBRESSL") { + if env::var("DEP_OPENSSL_LIBRESSL").is_ok() { println!("cargo:rustc-cfg=libressl"); } @@ -10,7 +12,7 @@ fn main() { } if let Ok(vars) = env::var("DEP_OPENSSL_CONF") { - for var in vars.split(",") { + for var in vars.split(',') { println!("cargo:rustc-cfg=osslconf=\"{}\"", var); } } diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 842d595a..8c7f7b1a 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -124,17 +124,14 @@ impl Asn1TimeRef { #[cfg(ossl102)] pub fn diff(&self, compare: &Self) -> Result<TimeDiff, ErrorStack> { let mut days = 0; - let mut seconds = 0; + let mut secs = 0; let other = compare.as_ptr(); - let err = unsafe { ffi::ASN1_TIME_diff(&mut days, &mut seconds, self.as_ptr(), other) }; + let err = unsafe { ffi::ASN1_TIME_diff(&mut days, &mut secs, self.as_ptr(), other) }; match err { 0 => Err(ErrorStack::get()), - _ => Ok(TimeDiff { - days: days, - secs: seconds, - }), + _ => Ok(TimeDiff { days, secs }), } } @@ -256,6 +253,7 @@ impl Asn1Time { /// This corresponds to [`ASN1_TIME_set_string`]. /// /// [`ASN1_TIME_set_string`]: https://www.openssl.org/docs/manmaster/man3/ASN1_TIME_set_string.html + #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> Result<Asn1Time, ErrorStack> { unsafe { let s = CString::new(s).unwrap(); @@ -370,9 +368,9 @@ impl Asn1StringRef { } } - /// Return the string as an array of bytes + /// Return the string as an array of bytes. /// - /// The bytes do not directly corespond to UTF-8 encoding. To interact with + /// The bytes do not directly correspond to UTF-8 encoding. To interact with /// strings in rust, it is preferable to use [`as_utf8`] /// /// [`as_utf8`]: struct.Asn1String.html#method.as_utf8 @@ -380,10 +378,15 @@ impl Asn1StringRef { unsafe { slice::from_raw_parts(ASN1_STRING_get0_data(self.as_ptr()), self.len()) } } - /// Return the length of the Asn1String (number of bytes) + /// Returns the number of bytes in the string. pub fn len(&self) -> usize { unsafe { ffi::ASN1_STRING_length(self.as_ptr()) as usize } } + + /// Determines if the string is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } foreign_type_and_impl_send_sync! { @@ -467,14 +470,20 @@ foreign_type_and_impl_send_sync! { } impl Asn1BitStringRef { - /// Returns the Asn1BitString as a slice + /// Returns the Asn1BitString as a slice. pub fn as_slice(&self) -> &[u8] { unsafe { slice::from_raw_parts(ASN1_STRING_get0_data(self.as_ptr() as *mut _), self.len()) } } - /// Length of Asn1BitString in number of bytes. + + /// Returns the number of bytes in the string. pub fn len(&self) -> usize { unsafe { ffi::ASN1_STRING_length(self.as_ptr() as *const _) as usize } } + + /// Determines if the string is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } foreign_type_and_impl_send_sync! { diff --git a/openssl/src/base64.rs b/openssl/src/base64.rs index b432745f..59d2103a 100644 --- a/openssl/src/base64.rs +++ b/openssl/src/base64.rs @@ -63,7 +63,7 @@ pub fn decode_block(src: &str) -> Result<Vec<u8>, ErrorStack> { out.set_len(out_len as usize); } - if src.ends_with("=") { + if src.ends_with('=') { out.pop(); if src.ends_with("==") { out.pop(); diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 1f949a97..31a953e9 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -12,16 +12,13 @@ //! use openssl::bn::BigNum; //! use openssl::error::ErrorStack; //! -//! fn bignums() -> Result<(), ErrorStack> { +//! fn main() -> Result<(), ErrorStack> { //! let a = BigNum::new()?; // a = 0 //! let b = BigNum::from_dec_str("1234567890123456789012345")?; //! let c = &a * &b; //! assert_eq!(a, c); //! Ok(()) //! } -//! # fn main() { -//! # bignums(); -//! # } //! ``` //! //! [`BIGNUM`]: https://wiki.openssl.org/index.php/Manual:Bn_internal(3) @@ -191,6 +188,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_div_word`] /// /// [`BN_div_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div_word.html + #[allow(clippy::identity_conversion)] pub fn div_word(&mut self, w: u32) -> Result<u64, ErrorStack> { unsafe { let r = ffi::BN_div_word(self.as_ptr(), w.into()); @@ -207,6 +205,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_mod_word`] /// /// [`BN_mod_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_word.html + #[allow(clippy::identity_conversion)] pub fn mod_word(&self, w: u32) -> Result<u64, ErrorStack> { unsafe { let r = ffi::BN_mod_word(self.as_ptr(), w.into()); @@ -244,6 +243,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_set_bit`] /// /// [`BN_set_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_bit.html + #[allow(clippy::identity_conversion)] pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) } } @@ -255,6 +255,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_clear_bit`] /// /// [`BN_clear_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear_bit.html + #[allow(clippy::identity_conversion)] pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) } } @@ -264,6 +265,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_is_bit_set`] /// /// [`BN_is_bit_set`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_bit_set.html + #[allow(clippy::identity_conversion)] pub fn is_bit_set(&self, n: i32) -> bool { unsafe { ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 } } @@ -275,6 +277,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_mask_bits`] /// /// [`BN_mask_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mask_bits.html + #[allow(clippy::identity_conversion)] pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) } } @@ -322,6 +325,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_lshift`] /// /// [`BN_lshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift.html + #[allow(clippy::identity_conversion)] pub fn lshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_lshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } } @@ -331,6 +335,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_rshift`] /// /// [`BN_rshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift.html + #[allow(clippy::identity_conversion)] pub fn rshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } } @@ -416,6 +421,7 @@ impl BigNumRef { /// /// [`constants`]: index.html#constants /// [`BN_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand.html + #[allow(clippy::identity_conversion)] pub fn rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rand( @@ -433,6 +439,7 @@ impl BigNumRef { /// OpenSSL documentation at [`BN_psuedo_rand`] /// /// [`BN_psuedo_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand.html + #[allow(clippy::identity_conversion)] pub fn pseudo_rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_pseudo_rand( @@ -811,7 +818,7 @@ impl BigNumRef { /// # Return Value /// /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - + #[allow(clippy::identity_conversion)] pub fn is_prime(&self, checks: i32, ctx: &mut BigNumContextRef) -> Result<bool, ErrorStack> { unsafe { cvt_n(ffi::BN_is_prime_ex( @@ -837,6 +844,7 @@ impl BigNumRef { /// # Return Value /// /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. + #[allow(clippy::identity_conversion)] pub fn is_prime_fasttest( &self, checks: i32, @@ -1372,16 +1380,16 @@ mod tests { #[test] fn test_to_from_slice() { - let v0 = BigNum::from_u32(10203004).unwrap(); + let v0 = BigNum::from_u32(10_203_004).unwrap(); let vec = v0.to_vec(); let v1 = BigNum::from_slice(&vec).unwrap(); - assert!(v0 == v1); + assert_eq!(v0, v1); } #[test] fn test_negation() { - let a = BigNum::from_u32(909829283).unwrap(); + let a = BigNum::from_u32(909_829_283).unwrap(); assert!(!a.is_negative()); assert!((-a).is_negative()); @@ -1389,15 +1397,14 @@ mod tests { #[test] fn test_shift() { - let a = BigNum::from_u32(909829283).unwrap(); - use std::ops::{Shl, Shr}; + let a = BigNum::from_u32(909_829_283).unwrap(); - assert!(a == a.shl(1).shr(1)); + assert_eq!(a, &(&a << 1) >> 1); } #[test] fn test_rand_range() { - let range = BigNum::from_u32(909829283).unwrap(); + let range = BigNum::from_u32(909_829_283).unwrap(); let mut result = BigNum::from_dec_str(&range.to_dec_str().unwrap()).unwrap(); range.rand_range(&mut result).unwrap(); assert!(result >= BigNum::from_u32(0).unwrap() && result < range); @@ -1405,7 +1412,7 @@ mod tests { #[test] fn test_pseudo_rand_range() { - let range = BigNum::from_u32(909829283).unwrap(); + let range = BigNum::from_u32(909_829_283).unwrap(); let mut result = BigNum::from_dec_str(&range.to_dec_str().unwrap()).unwrap(); range.pseudo_rand_range(&mut result).unwrap(); assert!(result >= BigNum::from_u32(0).unwrap() && result < range); @@ -1413,7 +1420,7 @@ mod tests { #[test] fn test_prime_numbers() { - let a = BigNum::from_u32(19029017).unwrap(); + let a = BigNum::from_u32(19_029_017).unwrap(); let mut p = BigNum::new().unwrap(); p.generate_prime(128, true, None, Some(&a)).unwrap(); diff --git a/openssl/src/cms.rs b/openssl/src/cms.rs index bed17f02..8c5efd64 100644 --- a/openssl/src/cms.rs +++ b/openssl/src/cms.rs @@ -81,7 +81,6 @@ impl CmsContentInfoRef { let pkey = pkey.as_ptr(); let cert = cert.as_ptr(); let out = MemBio::new()?; - let flags: u32 = 0; cvt(ffi::CMS_decrypt( self.as_ptr(), @@ -89,7 +88,7 @@ impl CmsContentInfoRef { cert, ptr::null_mut(), out.as_ptr(), - flags.into(), + 0, ))?; Ok(out.get_buf().to_owned()) diff --git a/openssl/src/conf.rs b/openssl/src/conf.rs index fb5d4f3c..43ff3530 100644 --- a/openssl/src/conf.rs +++ b/openssl/src/conf.rs @@ -18,6 +18,10 @@ impl ConfMethod { } /// Construct from raw pointer. + /// + /// # Safety + /// + /// The caller must ensure that the pointer is valid. pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod { ConfMethod(ptr) } diff --git a/openssl/src/derive.rs b/openssl/src/derive.rs index 197e80dc..6c517553 100644 --- a/openssl/src/derive.rs +++ b/openssl/src/derive.rs @@ -14,6 +14,7 @@ pub struct Deriver<'a>(*mut ffi::EVP_PKEY_CTX, PhantomData<&'a ()>); unsafe impl<'a> Sync for Deriver<'a> {} unsafe impl<'a> Send for Deriver<'a> {} +#[allow(clippy::len_without_is_empty)] impl<'a> Deriver<'a> { /// Creates a new `Deriver` using the provided private key. /// diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index 6c71ed3a..2e4eda89 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -451,6 +451,7 @@ mod test { } #[test] + #[allow(clippy::redundant_clone)] fn clone() { let key = Dsa::generate(2048).unwrap(); drop(key.clone()); diff --git a/openssl/src/ec.rs b/openssl/src/ec.rs index 75786516..04ce564d 100644 --- a/openssl/src/ec.rs +++ b/openssl/src/ec.rs @@ -15,22 +15,6 @@ //! [`EcGroup`]: struct.EcGroup.html //! [`Nid`]: ../nid/struct.Nid.html //! [Eliptic Curve Cryptography]: https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography -//! -//! # Examples -//! -//! ``` -//! use openssl::ec::{EcGroup, EcPoint}; -//! use openssl::nid::Nid; -//! use openssl::error::ErrorStack; -//! fn get_ec_point() -> Result<EcPoint, ErrorStack> { -//! let group = EcGroup::from_curve_name(Nid::SECP224R1)?; -//! let point = EcPoint::new(&group)?; -//! Ok(point) -//! } -//! # fn main() { -//! # let _ = get_ec_point(); -//! # } -//! ``` use ffi; use foreign_types::{ForeignType, ForeignTypeRef}; use libc::c_int; @@ -347,6 +331,7 @@ impl EcPointRef { group: &EcGroupRef, q: &EcPointRef, m: &BigNumRef, + // FIXME should be &mut ctx: &BigNumContextRef, ) -> Result<(), ErrorStack> { unsafe { @@ -367,6 +352,7 @@ impl EcPointRef { &mut self, group: &EcGroupRef, n: &BigNumRef, + // FIXME should be &mut ctx: &BigNumContextRef, ) -> Result<(), ErrorStack> { unsafe { @@ -917,6 +903,7 @@ mod test { } #[test] + #[allow(clippy::redundant_clone)] fn dup() { let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); let key = EcKey::generate(&group).unwrap(); @@ -959,7 +946,7 @@ mod test { let mut ctx = BigNumContext::new().unwrap(); let mut public_key = EcPoint::new(&group).unwrap(); public_key - .mul_generator(&group, key.private_key(), &mut ctx) + .mul_generator(&group, key.private_key(), &ctx) .unwrap(); assert!(public_key.eq(&group, key.public_key(), &mut ctx).unwrap()); } @@ -971,7 +958,7 @@ mod test { let one = BigNum::from_u32(1).unwrap(); let mut ctx = BigNumContext::new().unwrap(); let mut ecp = EcPoint::new(&group).unwrap(); - ecp.mul_generator(&group, &one, &mut ctx).unwrap(); + ecp.mul_generator(&group, &one, &ctx).unwrap(); assert!(ecp.eq(&group, gen, &mut ctx).unwrap()); } @@ -998,9 +985,8 @@ mod test { let dup_key = EcKey::from_private_components(&group, key.private_key(), key.public_key()).unwrap(); - let res = dup_key.check_key().unwrap(); + dup_key.check_key().unwrap(); - assert!(res == ()); assert!(key.private_key() == dup_key.private_key()); } diff --git a/openssl/src/ecdsa.rs b/openssl/src/ecdsa.rs index 8dfb742c..adf1e659 100644 --- a/openssl/src/ecdsa.rs +++ b/openssl/src/ecdsa.rs @@ -197,11 +197,11 @@ mod test { let verification2 = res .verify(String::from("hello2").as_bytes(), &public_key) .unwrap(); - assert!(verification2 == false); + assert!(!verification2); // Signature will not be verified using the correct data but the incorrect public key let verification3 = res.verify(data.as_bytes(), &public_key2).unwrap(); - assert!(verification3 == false); + assert!(!verification3); } #[test] diff --git a/openssl/src/error.rs b/openssl/src/error.rs index 103baff2..c1ef043e 100644 --- a/openssl/src/error.rs +++ b/openssl/src/error.rs @@ -161,7 +161,7 @@ impl Error { None } else { ptr::copy_nonoverlapping(data.as_ptr(), ptr as *mut u8, data.len()); - *ptr.offset(data.len() as isize) = 0; + *ptr.add(data.len()) = 0; Some((ptr, ffi::ERR_TXT_MALLOCED)) } } diff --git a/openssl/src/ex_data.rs b/openssl/src/ex_data.rs index 450dd113..d4f00212 100644 --- a/openssl/src/ex_data.rs +++ b/openssl/src/ex_data.rs @@ -16,10 +16,16 @@ impl<T, U> Clone for Index<T, U> { } impl<T, U> Index<T, U> { + /// Creates an `Index` from a raw integer index. + /// + /// # Safety + /// + /// The caller must ensure that the index correctly maps to a `U` value stored in a `T`. pub unsafe fn from_raw(idx: c_int) -> Index<T, U> { Index(idx, PhantomData) } + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } diff --git a/openssl/src/hash.rs b/openssl/src/hash.rs index 73027f1f..1136b6b1 100644 --- a/openssl/src/hash.rs +++ b/openssl/src/hash.rs @@ -3,6 +3,7 @@ use std::fmt; use std::io; use std::io::prelude::*; use std::ops::{Deref, DerefMut}; +use std::ptr; use error::ErrorStack; use nid::Nid; @@ -20,6 +21,11 @@ cfg_if! { pub struct MessageDigest(*const ffi::EVP_MD); impl MessageDigest { + /// Creates a `MessageDigest` from a raw OpenSSL pointer. + /// + /// # Safety + /// + /// The caller must ensure the pointer is valid. pub unsafe fn from_ptr(x: *const ffi::EVP_MD) -> Self { MessageDigest(x) } @@ -102,16 +108,19 @@ impl MessageDigest { unsafe { MessageDigest(ffi::EVP_ripemd160()) } } + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_ptr(&self) -> *const ffi::EVP_MD { self.0 } - /// The size of the digest in bytes + /// The size of the digest in bytes. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn size(&self) -> usize { unsafe { ffi::EVP_MD_size(self.0) as usize } } - /// The name of the digest + /// The name of the digest. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn type_(&self) -> Nid { Nid::from_raw(unsafe { ffi::EVP_MD_type(self.0) }) } @@ -199,7 +208,7 @@ impl Hasher { let ctx = unsafe { cvt_p(EVP_MD_CTX_new())? }; let mut h = Hasher { - ctx: ctx, + ctx, md: ty.as_ptr(), type_: ty, state: Finalized, @@ -217,7 +226,7 @@ impl Hasher { Finalized => (), } unsafe { - cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))?; + cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, ptr::null_mut()))?; } self.state = Reset; Ok(()) @@ -254,7 +263,7 @@ impl Hasher { ))?; self.state = Finalized; Ok(DigestBytes { - buf: buf, + buf, len: len as usize, }) } @@ -301,7 +310,7 @@ impl Clone for Hasher { ctx }; Hasher { - ctx: ctx, + ctx, md: self.md, type_: self.type_, state: self.state, @@ -407,14 +416,13 @@ mod tests { } fn hash_recycle_test(h: &mut Hasher, hashtest: &(&str, &str)) { - let _ = h.write_all(&Vec::from_hex(hashtest.0).unwrap()).unwrap(); + h.write_all(&Vec::from_hex(hashtest.0).unwrap()).unwrap(); let res = h.finish().unwrap(); assert_eq!(hex::encode(res), hashtest.1); } // Test vectors from http://www.nsrl.nist.gov/testdata/ - #[allow(non_upper_case_globals)] - const md5_tests: [(&'static str, &'static str); 13] = [ + const MD5_TESTS: [(&str, &str); 13] = [ ("", "d41d8cd98f00b204e9800998ecf8427e"), ("7F", "83acb6e67e50e31db6ed341dd2de1595"), ("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"), @@ -435,7 +443,7 @@ mod tests { #[test] fn test_md5() { - for test in md5_tests.iter() { + for test in MD5_TESTS.iter() { hash_test(MessageDigest::md5(), test); } } @@ -443,7 +451,7 @@ mod tests { #[test] fn test_md5_recycle() { let mut h = Hasher::new(MessageDigest::md5()).unwrap(); - for test in md5_tests.iter() { + for test in MD5_TESTS.iter() { hash_recycle_test(&mut h, test); } } @@ -451,7 +459,7 @@ mod tests { #[test] fn test_finish_twice() { let mut h = Hasher::new(MessageDigest::md5()).unwrap(); - h.write_all(&Vec::from_hex(md5_tests[6].0).unwrap()) + h.write_all(&Vec::from_hex(MD5_TESTS[6].0).unwrap()) .unwrap(); h.finish().unwrap(); let res = h.finish().unwrap(); @@ -460,9 +468,10 @@ mod tests { } #[test] + #[allow(clippy::redundant_clone)] fn test_clone() { let i = 7; - let inp = Vec::from_hex(md5_tests[i].0).unwrap(); + let inp = Vec::from_hex(MD5_TESTS[i].0).unwrap(); assert!(inp.len() > 2); let p = inp.len() / 2; let h0 = Hasher::new(MessageDigest::md5()).unwrap(); @@ -475,18 +484,18 @@ mod tests { let mut h2 = h1.clone(); h2.write_all(&inp[p..]).unwrap(); let res = h2.finish().unwrap(); - assert_eq!(hex::encode(res), md5_tests[i].1); + assert_eq!(hex::encode(res), MD5_TESTS[i].1); } h1.write_all(&inp[p..]).unwrap(); let res = h1.finish().unwrap(); - assert_eq!(hex::encode(res), md5_tests[i].1); + assert_eq!(hex::encode(res), MD5_TESTS[i].1); println!("Clone a finished hasher"); let mut h3 = h1.clone(); - h3.write_all(&Vec::from_hex(md5_tests[i + 1].0).unwrap()) + h3.write_all(&Vec::from_hex(MD5_TESTS[i + 1].0).unwrap()) .unwrap(); let res = h3.finish().unwrap(); - assert_eq!(hex::encode(res), md5_tests[i + 1].1); + assert_eq!(hex::encode(res), MD5_TESTS[i + 1].1); } #[test] diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index 6f480254..cbff7f82 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -55,6 +55,7 @@ impl Nid { } /// Return the integer representation of a `Nid`. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } @@ -62,6 +63,7 @@ impl Nid { /// Returns the `Nid`s of the digest and public key algorithms associated with a signature ID. /// /// This corresponds to `OBJ_find_sigid_algs`. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn signature_algorithms(&self) -> Option<SignatureAlgorithms> { unsafe { let mut digest = 0; @@ -81,6 +83,7 @@ impl Nid { /// This corresponds to [`OBJ_nid2ln`] /// /// [`OBJ_nid2ln`]: https://www.openssl.org/docs/man1.1.0/crypto/OBJ_nid2ln.html + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn long_name(&self) -> Result<&'static str, ErrorStack> { unsafe { cvt_p(ffi::OBJ_nid2ln(self.0) as *mut c_char) @@ -92,6 +95,7 @@ impl Nid { /// This corresponds to [`OBJ_nid2sn`] /// /// [`OBJ_nid2sn`]: https://www.openssl.org/docs/man1.1.0/crypto/OBJ_nid2sn.html + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn short_name(&self) -> Result<&'static str, ErrorStack> { unsafe { cvt_p(ffi::OBJ_nid2sn(self.0) as *mut c_char) diff --git a/openssl/src/ocsp.rs b/openssl/src/ocsp.rs index 310c3dbe..fbe02993 100644 --- a/openssl/src/ocsp.rs +++ b/openssl/src/ocsp.rs @@ -32,14 +32,6 @@ bitflags! { pub struct OcspResponseStatus(c_int); impl OcspResponseStatus { - pub fn from_raw(raw: c_int) -> OcspResponseStatus { - OcspResponseStatus(raw) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } - pub const SUCCESSFUL: OcspResponseStatus = OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_SUCCESSFUL); pub const MALFORMED_REQUEST: OcspResponseStatus = @@ -52,37 +44,39 @@ impl OcspResponseStatus { OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_SIGREQUIRED); pub const UNAUTHORIZED: OcspResponseStatus = OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_UNAUTHORIZED); + + pub fn from_raw(raw: c_int) -> OcspResponseStatus { + OcspResponseStatus(raw) + } + + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn as_raw(&self) -> c_int { + self.0 + } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct OcspCertStatus(c_int); impl OcspCertStatus { + pub const GOOD: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_GOOD); + pub const REVOKED: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_REVOKED); + pub const UNKNOWN: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_UNKNOWN); + pub fn from_raw(raw: c_int) -> OcspCertStatus { OcspCertStatus(raw) } + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } - - pub const GOOD: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_GOOD); - pub const REVOKED: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_REVOKED); - pub const UNKNOWN: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_UNKNOWN); } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct OcspRevokedStatus(c_int); impl OcspRevokedStatus { - pub fn from_raw(raw: c_int) -> OcspRevokedStatus { - OcspRevokedStatus(raw) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } - pub const NO_STATUS: OcspRevokedStatus = OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_NOSTATUS); pub const UNSPECIFIED: OcspRevokedStatus = OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_UNSPECIFIED); @@ -100,6 +94,15 @@ impl OcspRevokedStatus { OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CERTIFICATEHOLD); pub const REMOVE_FROM_CRL: OcspRevokedStatus = OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_REMOVEFROMCRL); + + pub fn from_raw(raw: c_int) -> OcspRevokedStatus { + OcspRevokedStatus(raw) + } + + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn as_raw(&self) -> c_int { + self.0 + } } pub struct OcspStatus<'a> { @@ -190,10 +193,11 @@ impl OcspBasicResponseRef { } else { Some(Asn1GeneralizedTimeRef::from_ptr(revocation_time)) }; + Some(OcspStatus { status: OcspCertStatus(status), reason: OcspRevokedStatus(status), - revocation_time: revocation_time, + revocation_time, this_update: Asn1GeneralizedTimeRef::from_ptr(this_update), next_update: Asn1GeneralizedTimeRef::from_ptr(next_update), }) diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index f01a9b22..2656cb48 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -58,11 +58,7 @@ impl Pkcs12Ref { Some(Stack::from_ptr(chain)) }; - Ok(ParsedPkcs12 { - pkey: pkey, - cert: cert, - chain: chain, - }) + Ok(ParsedPkcs12 { pkey, cert, chain }) } } } diff --git a/openssl/src/pkcs5.rs b/openssl/src/pkcs5.rs index d9704b51..d21a98b1 100644 --- a/openssl/src/pkcs5.rs +++ b/openssl/src/pkcs5.rs @@ -23,6 +23,7 @@ pub struct KeyIvPair { /// /// New applications should not use this and instead use /// `pbkdf2_hmac` or another more modern key derivation algorithm. +#[allow(clippy::identity_conversion)] pub fn bytes_to_key( cipher: Cipher, digest: MessageDigest, @@ -75,7 +76,7 @@ pub fn bytes_to_key( iv_ptr, ))?; - Ok(KeyIvPair { key: key, iv: iv }) + Ok(KeyIvPair { key, iv }) } } diff --git a/openssl/src/pkcs7.rs b/openssl/src/pkcs7.rs index 7cb39f77..a4d93cf9 100644 --- a/openssl/src/pkcs7.rs +++ b/openssl/src/pkcs7.rs @@ -303,7 +303,7 @@ mod tests { let cert = include_bytes!("../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); let certs = Stack::new().unwrap(); - let message: String = String::from("foo"); + let message = "foo"; let flags = Pkcs7Flags::STREAM | Pkcs7Flags::DETACHED; let pkey = include_bytes!("../test/key.pem"); let pkey = PKey::private_key_from_pem(pkey).unwrap(); @@ -336,11 +336,8 @@ mod tests { ) .expect("should succeed"); - assert_eq!(message.clone().into_bytes(), output); - assert_eq!( - message.clone().into_bytes(), - content.expect("should be non-empty") - ); + assert_eq!(output, message.as_bytes()); + assert_eq!(content.expect("should be non-empty"), message.as_bytes()); } #[test] @@ -348,7 +345,7 @@ mod tests { let cert = include_bytes!("../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); let certs = Stack::new().unwrap(); - let message: String = String::from("foo"); + let message = "foo"; let flags = Pkcs7Flags::STREAM; let pkey = include_bytes!("../test/key.pem"); let pkey = PKey::private_key_from_pem(pkey).unwrap(); @@ -375,7 +372,7 @@ mod tests { .verify(&certs, &store, None, Some(&mut output), flags) .expect("should succeed"); - assert_eq!(message.clone().into_bytes(), output); + assert_eq!(output, message.as_bytes()); assert!(content.is_none()); } diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index c9d98643..2dfa95c6 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -58,6 +58,8 @@ use dsa::Dsa; use ec::EcKey; use error::ErrorStack; use rsa::Rsa; +#[cfg(ossl110)] +use symm::Cipher; use util::{invoke_passwd_cb, CallbackState}; use {cvt, cvt_p}; @@ -75,16 +77,6 @@ pub enum Private {} pub struct Id(c_int); impl Id { - /// Creates a `Id` from an integer representation. - pub fn from_raw(value: c_int) -> Id { - Id(value) - } - - /// Returns the integer representation of the `Id`. - pub fn as_raw(&self) -> c_int { - self.0 - } - pub const RSA: Id = Id(ffi::EVP_PKEY_RSA); pub const HMAC: Id = Id(ffi::EVP_PKEY_HMAC); pub const DSA: Id = Id(ffi::EVP_PKEY_DSA); @@ -95,6 +87,17 @@ impl Id { pub const ED25519: Id = Id(ffi::EVP_PKEY_ED25519); #[cfg(ossl111)] pub const ED448: Id = Id(ffi::EVP_PKEY_ED448); + + /// Creates a `Id` from an integer representation. + pub fn from_raw(value: c_int) -> Id { + Id(value) + } + + /// Returns the integer representation of the `Id`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn as_raw(&self) -> c_int { + self.0 + } } /// A trait indicating that a key has parameters. @@ -394,7 +397,8 @@ impl PKey<Private> { /// /// To compute CMAC values, use the `sign` module. #[cfg(ossl110)] - pub fn cmac(cipher: &::symm::Cipher, key: &[u8]) -> Result<PKey<Private>, ErrorStack> { + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn cmac(cipher: &Cipher, key: &[u8]) -> Result<PKey<Private>, ErrorStack> { unsafe { assert!(key.len() <= c_int::max_value() as usize); let kctx = cvt_p(ffi::EVP_PKEY_CTX_new_id( diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index f35b56e5..08a5d957 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -49,20 +49,21 @@ use {cvt, cvt_n, cvt_p}; pub struct Padding(c_int); impl Padding { + pub const NONE: Padding = Padding(ffi::RSA_NO_PADDING); + pub const PKCS1: Padding = Padding(ffi::RSA_PKCS1_PADDING); + pub const PKCS1_OAEP: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); + pub const PKCS1_PSS: Padding = Padding(ffi::RSA_PKCS1_PSS_PADDING); + /// Creates a `Padding` from an integer representation. pub fn from_raw(value: c_int) -> Padding { Padding(value) } /// Returns the integer representation of `Padding`. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } - - pub const NONE: Padding = Padding(ffi::RSA_NO_PADDING); - pub const PKCS1: Padding = Padding(ffi::RSA_PKCS1_PADDING); - pub const PKCS1_OAEP: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); - pub const PKCS1_PSS: Padding = Padding(ffi::RSA_PKCS1_PSS_PADDING); } generic_foreign_type_and_impl_send_sync! { @@ -579,6 +580,7 @@ impl Rsa<Private> { /// /// This a convenience method over /// `Rsa::build(n, e, d)?.set_factors(p, q)?.set_crt_params(dmp1, dmq1, iqmp)?.build()` + #[allow(clippy::too_many_arguments, clippy::many_single_char_names)] pub fn from_private_components( n: BigNum, e: BigNum, @@ -895,11 +897,11 @@ mod test { let keypair = super::Rsa::generate(2048).unwrap(); let pubkey_pem = keypair.public_key_to_pem_pkcs1().unwrap(); let pubkey = super::Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); - let msg = "Hello, world!".as_bytes(); + let msg = b"Hello, world!"; let mut encrypted = vec![0; pubkey.size() as usize]; let len = pubkey - .public_encrypt(&msg, &mut encrypted, Padding::PKCS1) + .public_encrypt(msg, &mut encrypted, Padding::PKCS1) .unwrap(); assert!(len > msg.len()); let mut decrypted = vec![0; keypair.size() as usize]; @@ -907,7 +909,7 @@ mod test { .private_decrypt(&encrypted, &mut decrypted, Padding::PKCS1) .unwrap(); assert_eq!(len, msg.len()); - assert_eq!("Hello, world!", String::from_utf8_lossy(&decrypted[..len])); + assert_eq!(&decrypted[..len], msg); } #[test] @@ -915,15 +917,15 @@ mod test { let keypair = super::Rsa::generate(2048).unwrap(); let pubkey_pem = keypair.public_key_to_pem_pkcs1().unwrap(); let pubkey = super::Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); - let msg = "foo".as_bytes(); + let msg = b"foo"; let mut encrypted1 = vec![0; pubkey.size() as usize]; let mut encrypted2 = vec![0; pubkey.size() as usize]; let len1 = pubkey - .public_encrypt(&msg, &mut encrypted1, Padding::PKCS1) + .public_encrypt(msg, &mut encrypted1, Padding::PKCS1) .unwrap(); let len2 = pubkey - .public_encrypt(&msg, &mut encrypted2, Padding::PKCS1) + .public_encrypt(msg, &mut encrypted2, Padding::PKCS1) .unwrap(); assert!(len1 > (msg.len() + 1)); assert_eq!(len1, len2); @@ -931,6 +933,7 @@ mod test { } #[test] + #[allow(clippy::redundant_clone)] fn clone() { let key = Rsa::generate(2048).unwrap(); drop(key.clone()); diff --git a/openssl/src/sha.rs b/openssl/src/sha.rs index 0cefaa93..d6e69385 100644 --- a/openssl/src/sha.rs +++ b/openssl/src/sha.rs @@ -118,6 +118,13 @@ pub fn sha512(data: &[u8]) -> [u8; 64] { #[derive(Clone)] pub struct Sha1(ffi::SHA_CTX); +impl Default for Sha1 { + #[inline] + fn default() -> Sha1 { + Sha1::new() + } +} + impl Sha1 { /// Creates a new hasher. #[inline] @@ -156,6 +163,13 @@ impl Sha1 { #[derive(Clone)] pub struct Sha224(ffi::SHA256_CTX); +impl Default for Sha224 { + #[inline] + fn default() -> Sha224 { + Sha224::new() + } +} + impl Sha224 { /// Creates a new hasher. #[inline] @@ -194,6 +208,13 @@ impl Sha224 { #[derive(Clone)] pub struct Sha256(ffi::SHA256_CTX); +impl Default for Sha256 { + #[inline] + fn default() -> Sha256 { + Sha256::new() + } +} + impl Sha256 { /// Creates a new hasher. #[inline] @@ -232,6 +253,13 @@ impl Sha256 { #[derive(Clone)] pub struct Sha384(ffi::SHA512_CTX); +impl Default for Sha384 { + #[inline] + fn default() -> Sha384 { + Sha384::new() + } +} + impl Sha384 { /// Creates a new hasher. #[inline] @@ -270,6 +298,13 @@ impl Sha384 { #[derive(Clone)] pub struct Sha512(ffi::SHA512_CTX); +impl Default for Sha512 { + #[inline] + fn default() -> Sha512 { + Sha512::new() + } +} + impl Sha512 { /// Creates a new hasher. #[inline] diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index 81ba7ee4..4c6ee3ca 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -123,6 +123,7 @@ impl<'a> Drop for Signer<'a> { } } +#[allow(clippy::len_without_is_empty)] impl<'a> Signer<'a> { /// Creates a new `Signer`. /// @@ -645,12 +646,12 @@ mod test { use rsa::{Padding, Rsa}; use sign::{RsaPssSaltlen, Signer, Verifier}; - const INPUT: &'static str = + const INPUT: &str = "65794a68624763694f694a53557a49314e694a392e65794a7063334d694f694a71623255694c41304b49434a6c\ 654841694f6a457a4d4441344d546b7a4f44417344516f67496d6830644841364c79396c654746746347786c4c\ 6d4e76625339706331397962323930496a7030636e566c6651"; - const SIGNATURE: &'static str = + const SIGNATURE: &str = "702e218943e88fd11eb5d82dbf7845f34106ae1b81fff7731116add1717d83656d420afd3c96eedd73a2663e51\ 66687b000b87226e0187ed1073f945e582adfcef16d85a798ee8c66ddb3db8975b17d09402beedd5d9d9700710\ 8db28160d5f8040ca7445762b81fbe7ff9d92e0ae76f24f25b33bbe6f44ae61eb1040acb20044d3ef9128ed401\ diff --git a/openssl/src/srtp.rs b/openssl/src/srtp.rs index 03b722ac..aef793c8 100644 --- a/openssl/src/srtp.rs +++ b/openssl/src/srtp.rs @@ -38,20 +38,21 @@ impl SrtpProtectionProfileRef { pub struct SrtpProfileId(c_ulong); impl SrtpProfileId { + pub const SRTP_AES128_CM_SHA1_80: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_CM_SHA1_80); + pub const SRTP_AES128_CM_SHA1_32: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_CM_SHA1_32); + pub const SRTP_AES128_F8_SHA1_80: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_F8_SHA1_80); + pub const SRTP_AES128_F8_SHA1_32: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_F8_SHA1_32); + pub const SRTP_NULL_SHA1_80: SrtpProfileId = SrtpProfileId(ffi::SRTP_NULL_SHA1_80); + pub const SRTP_NULL_SHA1_32: SrtpProfileId = SrtpProfileId(ffi::SRTP_NULL_SHA1_32); + /// Creates a `SrtpProfileId` from an integer representation. pub fn from_raw(value: c_ulong) -> SrtpProfileId { SrtpProfileId(value) } /// Returns the integer representation of `SrtpProfileId`. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_ulong { self.0 } - - pub const SRTP_AES128_CM_SHA1_80: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_CM_SHA1_80); - pub const SRTP_AES128_CM_SHA1_32: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_CM_SHA1_32); - pub const SRTP_AES128_F8_SHA1_80: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_F8_SHA1_80); - pub const SRTP_AES128_F8_SHA1_32: SrtpProfileId = SrtpProfileId(ffi::SRTP_AES128_F8_SHA1_32); - pub const SRTP_NULL_SHA1_80: SrtpProfileId = SrtpProfileId(ffi::SRTP_NULL_SHA1_80); - pub const SRTP_NULL_SHA1_32: SrtpProfileId = SrtpProfileId(ffi::SRTP_NULL_SHA1_32); } diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index 8f3ff228..cabe057b 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -6,7 +6,6 @@ use libc::{c_char, c_int, c_long, c_void, strlen}; use std::any::Any; use std::io; use std::io::prelude::*; -use std::mem; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::ptr; use std::slice; @@ -37,7 +36,7 @@ pub fn new<S: Read + Write>(stream: S) -> Result<(*mut BIO, BioMethod), ErrorSta let method = BioMethod::new::<S>(); let state = Box::new(StreamState { - stream: stream, + stream, error: None, panic: None, dtls_mtu_size: 0, @@ -48,7 +47,7 @@ pub fn new<S: Read + Write>(stream: S) -> Result<(*mut BIO, BioMethod), ErrorSta BIO_set_data(bio, Box::into_raw(state) as *mut _); BIO_set_init(bio, 1); - return Ok((bio, method)); + Ok((bio, method)) } } @@ -63,7 +62,7 @@ pub unsafe fn take_panic<S>(bio: *mut BIO) -> Option<Box<dyn Any + Send>> { } pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S { - let state: &'a StreamState<S> = mem::transmute(BIO_get_data(bio)); + let state = &*(BIO_get_data(bio) as *const StreamState<S>); &state.stream } @@ -73,7 +72,10 @@ pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S { pub unsafe fn set_dtls_mtu_size<S>(bio: *mut BIO, mtu_size: usize) { if mtu_size as u64 > c_long::max_value() as u64 { - panic!("Given MTU size {} can't be represented in a positive `c_long` range") + panic!( + "Given MTU size {} can't be represented in a positive `c_long` range", + mtu_size + ) } state::<S>(bio).dtls_mtu_size = mtu_size as c_long; } @@ -207,7 +209,7 @@ cfg_if! { assert!(ffi::BIO_meth_set_ctrl(ptr, ctrl::<S>) != 0); assert!(ffi::BIO_meth_set_create(ptr, create) != 0); assert!(ffi::BIO_meth_set_destroy(ptr, destroy::<S>) != 0); - return ret; + ret } } diff --git a/openssl/src/ssl/callbacks.rs b/openssl/src/ssl/callbacks.rs index 05f55932..5de21ccb 100644 --- a/openssl/src/ssl/callbacks.rs +++ b/openssl/src/ssl/callbacks.rs @@ -116,10 +116,10 @@ where .ssl_context() .ex_data(callback_idx) .expect("BUG: psk callback missing") as *const F; - let identity = if identity != ptr::null() { - Some(CStr::from_ptr(identity).to_bytes()) - } else { + let identity = if identity.is_null() { None + } else { + Some(CStr::from_ptr(identity).to_bytes()) }; // Give the callback mutable slices into which it can write the psk. let psk_sl = slice::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize); diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 67ddb2a9..17a3556a 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -20,6 +20,7 @@ ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== -----END DH PARAMETERS----- "; +#[allow(clippy::inconsistent_digit_grouping)] fn ctx(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> { let mut ctx = SslContextBuilder::new(method)?; diff --git a/openssl/src/ssl/error.rs b/openssl/src/ssl/error.rs index 6354409d..e397efde 100644 --- a/openssl/src/ssl/error.rs +++ b/openssl/src/ssl/error.rs @@ -14,14 +14,6 @@ use x509::X509VerifyResult; pub struct ErrorCode(c_int); impl ErrorCode { - pub fn from_raw(raw: c_int) -> ErrorCode { - ErrorCode(raw) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } - /// The SSL session has been closed. pub const ZERO_RETURN: ErrorCode = ErrorCode(ffi::SSL_ERROR_ZERO_RETURN); @@ -46,6 +38,15 @@ impl ErrorCode { /// Requires OpenSSL 1.1.1 or newer. #[cfg(ossl111)] pub const WANT_CLIENT_HELLO_CB: ErrorCode = ErrorCode(ffi::SSL_ERROR_WANT_CLIENT_HELLO_CB); + + pub fn from_raw(raw: c_int) -> ErrorCode { + ErrorCode(raw) + } + + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn as_raw(&self) -> c_int { + self.0 + } } #[derive(Debug)] diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 2561aaed..acb701a9 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -338,11 +338,16 @@ impl SslMethod { } /// Constructs an `SslMethod` from a pointer to the underlying OpenSSL value. + /// + /// # Safety + /// + /// The caller must ensure the pointer is valid. pub unsafe fn from_ptr(ptr: *const ffi::SSL_METHOD) -> SslMethod { SslMethod(ptr) } /// Returns a pointer to the underlying OpenSSL value. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_ptr(&self) -> *const ffi::SSL_METHOD { self.0 } @@ -444,16 +449,6 @@ bitflags! { pub struct SslFiletype(c_int); impl SslFiletype { - /// Constructs an `SslFiletype` from a raw OpenSSL value. - pub fn from_raw(raw: c_int) -> SslFiletype { - SslFiletype(raw) - } - - /// Returns the raw OpenSSL value represented by this type. - pub fn as_raw(&self) -> c_int { - self.0 - } - /// The PEM format. /// /// This corresponds to `SSL_FILETYPE_PEM`. @@ -463,6 +458,17 @@ impl SslFiletype { /// /// This corresponds to `SSL_FILETYPE_ASN1`. pub const ASN1: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_ASN1); + + /// Constructs an `SslFiletype` from a raw OpenSSL value. + pub fn from_raw(raw: c_int) -> SslFiletype { + SslFiletype(raw) + } + + /// Returns the raw OpenSSL value represented by this type. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn as_raw(&self) -> c_int { + self.0 + } } /// An identifier of a certificate status type. @@ -470,18 +476,19 @@ impl SslFiletype { pub struct StatusType(c_int); impl StatusType { + /// An OSCP status. + pub const OCSP: StatusType = StatusType(ffi::TLSEXT_STATUSTYPE_ocsp); + /// Constructs a `StatusType` from a raw OpenSSL value. pub fn from_raw(raw: c_int) -> StatusType { StatusType(raw) } /// Returns the raw OpenSSL value represented by this type. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } - - /// An OSCP status. - pub const OCSP: StatusType = StatusType(ffi::TLSEXT_STATUSTYPE_ocsp); } /// An identifier of a session name type. @@ -489,18 +496,19 @@ impl StatusType { pub struct NameType(c_int); impl NameType { + /// A host name. + pub const HOST_NAME: NameType = NameType(ffi::TLSEXT_NAMETYPE_host_name); + /// Constructs a `StatusType` from a raw OpenSSL value. pub fn from_raw(raw: c_int) -> StatusType { StatusType(raw) } /// Returns the raw OpenSSL value represented by this type. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } - - /// A host name. - pub const HOST_NAME: NameType = NameType(ffi::TLSEXT_NAMETYPE_host_name); } lazy_static! { @@ -658,6 +666,10 @@ impl SslContextBuilder { } /// Creates an `SslContextBuilder` from a pointer to a raw OpenSSL value. + /// + /// # Safety + /// + /// The caller must ensure that the pointer is valid and uniquely owned by the builder. pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder { SslContextBuilder(SslContext::from_ptr(ctx)) } @@ -1726,6 +1738,7 @@ impl SslContextBuilder { /// This corresponds to [`SSL_CTX_sess_get_cache_size`]. /// /// [`SSL_CTX_sess_get_cache_size`]: https://www.openssl.org/docs/man1.0.2/man3/SSL_CTX_sess_set_cache_size.html + #[allow(clippy::identity_conversion)] pub fn set_session_cache_size(&mut self, size: i32) -> i64 { unsafe { ffi::SSL_CTX_sess_set_cache_size(self.as_ptr(), size.into()).into() } } @@ -1967,6 +1980,7 @@ impl SslContextRef { /// This corresponds to [`SSL_CTX_sess_get_cache_size`]. /// /// [`SSL_CTX_sess_get_cache_size`]: https://www.openssl.org/docs/man1.0.2/man3/SSL_CTX_sess_set_cache_size.html + #[allow(clippy::identity_conversion)] pub fn session_cache_size(&self) -> i64 { unsafe { ffi::SSL_CTX_sess_get_cache_size(self.as_ptr()).into() } } @@ -2084,6 +2098,7 @@ impl SslCipherRef { /// This corresponds to [`SSL_CIPHER_get_bits`]. /// /// [`SSL_CIPHER_get_bits`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html + #[allow(clippy::identity_conversion)] pub fn bits(&self) -> CipherBits { unsafe { let mut algo_bits = 0; @@ -2242,6 +2257,7 @@ impl SslSessionRef { /// This corresponds to [`SSL_SESSION_get_time`]. /// /// [`SSL_SESSION_get_time`]: https://www.openssl.org/docs/man1.1.1/man3/SSL_SESSION_get_time.html + #[allow(clippy::identity_conversion)] pub fn time(&self) -> i64 { unsafe { ffi::SSL_SESSION_get_time(self.as_ptr()).into() } } @@ -2253,6 +2269,7 @@ impl SslSessionRef { /// This corresponds to [`SSL_SESSION_get_timeout`]. /// /// [`SSL_SESSION_get_timeout`]: https://www.openssl.org/docs/man1.1.1/man3/SSL_SESSION_get_time.html + #[allow(clippy::identity_conversion)] pub fn timeout(&self) -> i64 { unsafe { ffi::SSL_SESSION_get_timeout(self.as_ptr()).into() } } @@ -2868,7 +2885,7 @@ impl SslRef { pub fn servername_raw(&self, type_: NameType) -> Option<&[u8]> { unsafe { let name = ffi::SSL_get_servername(self.as_ptr(), type_.0); - if name == ptr::null() { + if name.is_null() { None } else { Some(CStr::from_ptr(name as *const _).to_bytes()) @@ -3464,7 +3481,7 @@ impl<S: Read + Write> SslStream<S> { // that it read zero bytes, but zero is also the sentinel for "error". // To avoid that confusion short-circuit that logic and return quickly // if `buf` has a length of zero. - if buf.len() == 0 { + if buf.is_empty() { return Ok(0); } @@ -3486,7 +3503,7 @@ impl<S: Read + Write> SslStream<S> { /// [`SSL_write`]: https://www.openssl.org/docs/manmaster/man3/SSL_write.html pub fn ssl_write(&mut self, buf: &[u8]) -> Result<usize, Error> { // See above for why we short-circuit on zero-length buffers - if buf.len() == 0 { + if buf.is_empty() { return Ok(0); } diff --git a/openssl/src/ssl/test/mod.rs b/openssl/src/ssl/test/mod.rs index a7d2780c..5e93adf9 100644 --- a/openssl/src/ssl/test/mod.rs +++ b/openssl/src/ssl/test/mod.rs @@ -41,9 +41,9 @@ use x509::{X509Name, X509StoreContext, X509VerifyResult, X509}; mod server; -static ROOT_CERT: &'static [u8] = include_bytes!("../../../test/root-ca.pem"); -static CERT: &'static [u8] = include_bytes!("../../../test/cert.pem"); -static KEY: &'static [u8] = include_bytes!("../../../test/key.pem"); +static ROOT_CERT: &[u8] = include_bytes!("../../../test/root-ca.pem"); +static CERT: &[u8] = include_bytes!("../../../test/cert.pem"); +static KEY: &[u8] = include_bytes!("../../../test/key.pem"); #[test] fn verify_untrusted() { @@ -385,7 +385,7 @@ fn test_connect_with_srtp_ssl() { .unwrap(); let mut profilenames = String::new(); for profile in ssl.srtp_profiles().unwrap() { - if profilenames.len() > 0 { + if !profilenames.is_empty() { profilenames.push(':'); } profilenames += profile.name(); @@ -1310,7 +1310,7 @@ fn stateless() { #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] #[test] fn psk_ciphers() { - const CIPHER: &'static str = "PSK-AES128-CBC-SHA"; + const CIPHER: &str = "PSK-AES128-CBC-SHA"; const PSK: &[u8] = b"thisisaverysecurekey"; const CLIENT_IDENT: &[u8] = b"thisisaclient"; static CLIENT_CALLED: AtomicBool = AtomicBool::new(false); diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index a1349092..fc2eafae 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -178,11 +178,16 @@ impl<T: Stackable> StackRef<T> { self.as_ptr() as *mut _ } - /// Returns the number of items in the stack + /// Returns the number of items in the stack. pub fn len(&self) -> usize { unsafe { OPENSSL_sk_num(self.as_stack()) as usize } } + /// Determines if the stack is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn iter(&self) -> Iter<T> { Iter { stack: self, diff --git a/openssl/src/symm.rs b/openssl/src/symm.rs index 8bad5c17..45c5dd9b 100644 --- a/openssl/src/symm.rs +++ b/openssl/src/symm.rs @@ -276,21 +276,29 @@ impl Cipher { unsafe { Cipher(ffi::EVP_chacha20_poly1305()) } } + /// Creates a `Cipher` from a raw pointer to its OpenSSL type. + /// + /// # Safety + /// + /// The caller must ensure the pointer is valid for the `'static` lifetime. pub unsafe fn from_ptr(ptr: *const ffi::EVP_CIPHER) -> Cipher { Cipher(ptr) } + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER { self.0 } /// Returns the length of keys used with this cipher. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn key_len(&self) -> usize { unsafe { EVP_CIPHER_key_length(self.0) as usize } } /// Returns the length of the IV used with this cipher, or `None` if the /// cipher does not use an IV. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn iv_len(&self) -> Option<usize> { unsafe { let len = EVP_CIPHER_iv_length(self.0) as usize; @@ -307,26 +315,27 @@ impl Cipher { /// # Note /// /// Stream ciphers such as RC4 have a block size of 1. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn block_size(&self) -> usize { unsafe { EVP_CIPHER_block_size(self.0) as usize } } /// Determines whether the cipher is using CCM mode - fn is_ccm(&self) -> bool { + fn is_ccm(self) -> bool { // NOTE: OpenSSL returns pointers to static structs, which makes this work as expected - *self == Cipher::aes_128_ccm() || *self == Cipher::aes_256_ccm() + self == Cipher::aes_128_ccm() || self == Cipher::aes_256_ccm() } /// Determines whether the cipher is using OCB mode #[cfg(ossl110)] - fn is_ocb(&self) -> bool { - *self == Cipher::aes_128_ocb() - || *self == Cipher::aes_192_ocb() - || *self == Cipher::aes_256_ocb() + fn is_ocb(self) -> bool { + self == Cipher::aes_128_ocb() + || self == Cipher::aes_192_ocb() + || self == Cipher::aes_256_ocb() } #[cfg(not(ossl110))] - const fn is_ocb(&self) -> bool { + const fn is_ocb(self) -> bool { false } } @@ -421,7 +430,7 @@ impl Crypter { unsafe { let ctx = cvt_p(ffi::EVP_CIPHER_CTX_new())?; let crypter = Crypter { - ctx: ctx, + ctx, block_size: t.block_size(), }; @@ -808,12 +817,13 @@ pub fn decrypt_aead( c.aad_update(aad)?; let count = c.update(data, &mut out)?; - let mut rest = 0; - if !t.is_ccm() { + let rest = if t.is_ccm() { + 0 + } else { c.set_tag(tag)?; - rest = c.finalize(&mut out[count..])?; - } + c.finalize(&mut out[count..])? + }; out.truncate(count + rest); Ok(out) diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 222bce50..a5018c1b 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -33,6 +33,12 @@ pub struct BasicConstraints { pathlen: Option<u32>, } +impl Default for BasicConstraints { + fn default() -> BasicConstraints { + BasicConstraints::new() + } +} + impl BasicConstraints { /// Construct a new `BasicConstraints` extension. pub fn new() -> BasicConstraints { @@ -95,6 +101,12 @@ pub struct KeyUsage { decipher_only: bool, } +impl Default for KeyUsage { + fn default() -> KeyUsage { + KeyUsage::new() + } +} + impl KeyUsage { /// Construct a new `KeyUsage` extension. pub fn new() -> KeyUsage { @@ -228,6 +240,12 @@ pub struct ExtendedKeyUsage { other: Vec<String>, } +impl Default for ExtendedKeyUsage { + fn default() -> ExtendedKeyUsage { + ExtendedKeyUsage::new() + } +} + impl ExtendedKeyUsage { /// Construct a new `ExtendedKeyUsage` extension. pub fn new() -> ExtendedKeyUsage { @@ -354,6 +372,12 @@ pub struct SubjectKeyIdentifier { critical: bool, } +impl Default for SubjectKeyIdentifier { + fn default() -> SubjectKeyIdentifier { + SubjectKeyIdentifier::new() + } +} + impl SubjectKeyIdentifier { /// Construct a new `SubjectKeyIdentifier` extension. pub fn new() -> SubjectKeyIdentifier { @@ -384,6 +408,12 @@ pub struct AuthorityKeyIdentifier { issuer: Option<bool>, } +impl Default for AuthorityKeyIdentifier { + fn default() -> AuthorityKeyIdentifier { + AuthorityKeyIdentifier::new() + } +} + impl AuthorityKeyIdentifier { /// Construct a new `AuthorityKeyIdentifier` extension. pub fn new() -> AuthorityKeyIdentifier { @@ -438,6 +468,12 @@ pub struct SubjectAlternativeName { names: Vec<String>, } +impl Default for SubjectAlternativeName { + fn default() -> SubjectAlternativeName { + SubjectAlternativeName::new() + } +} + impl SubjectAlternativeName { /// Construct a new `SubjectAlternativeName` extension. pub fn new() -> SubjectAlternativeName { diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 4ec47f4f..02063d0e 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -68,7 +68,7 @@ impl X509StoreContext { pub fn new() -> Result<X509StoreContext, ErrorStack> { unsafe { ffi::init(); - cvt_p(ffi::X509_STORE_CTX_new()).map(|p| X509StoreContext(p)) + cvt_p(ffi::X509_STORE_CTX_new()).map(X509StoreContext) } } } @@ -849,7 +849,7 @@ impl Stackable for X509Name { impl X509NameRef { /// Returns the name entries by the nid. - pub fn entries_by_nid<'a>(&'a self, nid: Nid) -> X509NameEntries<'a> { + pub fn entries_by_nid(&self, nid: Nid) -> X509NameEntries<'_> { X509NameEntries { name: self, nid: Some(nid), @@ -858,7 +858,7 @@ impl X509NameRef { } /// Returns an iterator over all `X509NameEntry` values - pub fn entries<'a>(&'a self) -> X509NameEntries<'a> { + pub fn entries(&self) -> X509NameEntries<'_> { X509NameEntries { name: self, nid: None, @@ -1213,6 +1213,7 @@ impl X509VerifyResult { } /// Return the integer representation of an `X509VerifyResult`. + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn as_raw(&self) -> c_int { self.0 } @@ -1222,6 +1223,7 @@ impl X509VerifyResult { /// This corresponds to [`X509_verify_cert_error_string`]. /// /// [`X509_verify_cert_error_string`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_verify_cert_error_string.html + #[allow(clippy::trivially_copy_pass_by_ref)] pub fn error_string(&self) -> &'static str { ffi::init(); diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 4bd3e5f3..a6baf45d 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -22,7 +22,7 @@ fn pkey() -> PKey<Private> { #[test] fn test_cert_loading() { let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let fingerprint = cert.digest(MessageDigest::sha1()).unwrap(); let hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; @@ -34,7 +34,7 @@ fn test_cert_loading() { #[test] fn test_cert_issue_validity() { let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let not_before = cert.not_before().to_string(); let not_after = cert.not_after().to_string(); @@ -45,7 +45,7 @@ fn test_cert_issue_validity() { #[test] fn test_save_der() { let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let der = cert.to_der().unwrap(); assert!(!der.is_empty()); @@ -101,8 +101,8 @@ fn test_nameref_iterator() { assert_eq!(friendly.object().nid().as_raw(), Nid::FRIENDLYNAME.as_raw()); assert_eq!(&**friendly.data().as_utf8().unwrap(), "Example"); - if let Some(_) = all_entries.next() { - assert!(false); + if all_entries.next().is_some() { + panic!(); } } @@ -136,7 +136,7 @@ fn test_subject_alt_name() { #[test] fn test_subject_alt_name_iter() { let cert = include_bytes!("../../test/alt_name_cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let subject_alt_names = cert.subject_alt_names().unwrap(); let mut subject_alt_names_iter = subject_alt_names.iter(); @@ -232,7 +232,7 @@ fn x509_builder() { .entries_by_nid(Nid::COMMONNAME) .next() .unwrap(); - assert_eq!("foobar.com".as_bytes(), cn.data().as_slice()); + assert_eq!(cn.data().as_slice(), b"foobar.com"); assert_eq!(serial, x509.serial_number().to_bn().unwrap()); } @@ -320,6 +320,7 @@ fn signature() { } #[test] +#[allow(clippy::redundant_clone)] fn clone_x509() { let cert = include_bytes!("../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); diff --git a/systest/build.rs b/systest/build.rs index e60e37ce..0c84bc33 100644 --- a/systest/build.rs +++ b/systest/build.rs @@ -40,7 +40,7 @@ fn main() { } if let Ok(vars) = env::var("DEP_OPENSSL_CONF") { - for var in vars.split(",") { + for var in vars.split(',') { cfg.cfg("osslconf", Some(var)); } } @@ -68,15 +68,16 @@ fn main() { cfg.header("openssl/cms.h"); } + #[allow(clippy::if_same_then_else)] cfg.type_name(|s, is_struct, _is_union| { // Add some `*` on some callback parameters to get function pointer to // typecheck in C, especially on MSVC. if s == "PasswordCallback" { - format!("pem_password_cb*") + "pem_password_cb*".to_string() } else if s == "bio_info_cb" { - format!("bio_info_cb*") + "bio_info_cb*".to_string() } else if s == "_STACK" { - format!("struct stack_st") + "struct stack_st".to_string() // This logic should really be cleaned up } else if is_struct && s != "point_conversion_form_t" @@ -86,7 +87,7 @@ fn main() { } else if s.starts_with("stack_st_") { format!("struct {}", s) } else { - format!("{}", s) + s.to_string() } }); cfg.skip_type(|s| { @@ -130,9 +131,9 @@ fn main() { }); cfg.field_name(|_s, field| { if field == "type_" { - format!("type") + "type".to_string() } else { - format!("{}", field) + field.to_string() } }); cfg.fn_cname(|rust, link_name| link_name.unwrap_or(rust).to_string()); diff --git a/systest/src/main.rs b/systest/src/main.rs index 7fec6ea1..3e5888c8 100644 --- a/systest/src/main.rs +++ b/systest/src/main.rs @@ -1,4 +1,4 @@ -#![allow(bad_style)] +#![allow(bad_style, clippy::all)] extern crate libc; extern crate openssl_sys; |