From 0b158867de5ad3625b6b27f31156c85a0c69b3df Mon Sep 17 00:00:00 2001 From: Gijs Kwakkel Date: Tue, 17 Sep 2024 15:38:03 +0200 Subject: [PATCH 01/22] mbedtls-sys clippy fix --- mbedtls-sys/build/bindgen.rs | 43 +++++++++++++++++++++++++---------- mbedtls-sys/build/build.rs | 7 +++--- mbedtls-sys/build/cmake.rs | 4 +--- mbedtls-sys/build/config.rs | 35 +++++++++++++++------------- mbedtls-sys/build/features.rs | 12 ++++++---- mbedtls-sys/build/headers.rs | 4 ++-- mbedtls-sys/src/lib.rs | 1 + mbedtls-sys/src/types.rs | 2 +- 8 files changed, 66 insertions(+), 42 deletions(-) diff --git a/mbedtls-sys/build/bindgen.rs b/mbedtls-sys/build/bindgen.rs index a69f84d09..992179384 100644 --- a/mbedtls-sys/build/bindgen.rs +++ b/mbedtls-sys/build/bindgen.rs @@ -35,7 +35,7 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks { } fn int_macro(&self, _name: &str, value: i64) -> Option { - if value < (i32::MIN as i64) || value > (i32::MAX as i64) { + if value < i64::from(i32::MIN) || value > i64::from(i32::MAX) { Some(bindgen::callbacks::IntKind::LongLong) } else { Some(bindgen::callbacks::IntKind::Int) @@ -87,7 +87,7 @@ fn generate_deprecated_union_accessors(bindings: &str) -> String { } let mut impl_builder = UnionImplBuilder::default(); - syn::visit::visit_file(&mut impl_builder, &syn::parse_file(&bindings).unwrap()); + syn::visit::visit_file(&mut impl_builder, &syn::parse_file(bindings).unwrap()); impl_builder.impls } @@ -96,7 +96,7 @@ impl super::BuildConfig { pub fn bindgen(&self) { let mut input = String::new(); for h in headers::enabled_ordered() { - let _ = writeln!(input, "#include ", h); + let _ = writeln!(input, "#include "); } let mut cc = cc::Build::new(); @@ -115,14 +115,12 @@ impl super::BuildConfig { // uses the correct headers let compiler = cc.get_compiler(); if compiler.is_like_gnu() { - let output = compiler.to_command().args(&["--print-sysroot"]).output(); - match output { - Ok(sysroot) => { - let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot"); - let trimmed_path = path.strip_suffix("\r\n").or(path.strip_suffix("\n")).unwrap_or(&path); - cc.flag(&format!("--sysroot={}", trimmed_path)); - } - _ => {} // skip toolchains without a configured sysroot + let output = compiler.to_command().args(["--print-sysroot"]).output(); + // skip toolchains without a configured sysroot + if let Ok(sysroot) = output { + let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot"); + let trimmed_path = path.strip_suffix("\r\n").or_else(|| path.strip_suffix("\n")).unwrap_or(path); + cc.flag(&format!("--sysroot={trimmed_path}")); }; } @@ -146,7 +144,28 @@ impl super::BuildConfig { .derive_default(true) .prepend_enum_name(false) .translate_enum_integer_types(true) - .raw_line("#![allow(dead_code, deref_nullptr, non_snake_case, non_camel_case_types, non_upper_case_globals, invalid_value)]") + .raw_line("#![allow(") + .raw_line(" dead_code,") + .raw_line(" deref_nullptr,") + .raw_line(" invalid_value,") + .raw_line(" non_snake_case,") + .raw_line(" non_camel_case_types,") + .raw_line(" non_upper_case_globals") + .raw_line(")]") + .raw_line("#![allow(") + .raw_line(" clippy::cast_lossless,") + .raw_line(" clippy::cast_possible_truncation,") + .raw_line(" clippy::default_trait_access,") + .raw_line(" clippy::missing_safety_doc,") + .raw_line(" clippy::must_use_candidate,") + .raw_line(" clippy::pub_underscore_fields,") + .raw_line(" clippy::unreadable_literal,") + .raw_line(" clippy::used_underscore_binding,") + .raw_line(" clippy::useless_transmute,") + .raw_line(" clippy::semicolon_if_nothing_returned,") + .raw_line(" clippy::type_complexity,") + .raw_line(" clippy::wildcard_imports") + .raw_line(")]") .generate() .expect("bindgen error") .to_string(); diff --git a/mbedtls-sys/build/build.rs b/mbedtls-sys/build/build.rs index 0cacf32c2..619deffc1 100644 --- a/mbedtls-sys/build/build.rs +++ b/mbedtls-sys/build/build.rs @@ -5,6 +5,7 @@ * 2.0 , at your * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(clippy::unwrap_used)] extern crate bindgen; extern crate cmake; @@ -82,7 +83,7 @@ impl BuildConfig { fn new() -> Self { let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR environment not set?")); let config_h = out_dir.join("config.h"); - let mbedtls_src = PathBuf::from(env::var("RUST_MBEDTLS_SYS_SOURCE").unwrap_or("vendor".to_owned())); + let mbedtls_src = PathBuf::from(env::var("RUST_MBEDTLS_SYS_SOURCE").unwrap_or_else(|_| "vendor".to_owned())); let mbedtls_include = mbedtls_src.join("include"); let mut cflags = vec![]; @@ -93,11 +94,11 @@ impl BuildConfig { cflags.push("-fno-stack-protector".into()); } - BuildConfig { - config_h, + Self { out_dir, mbedtls_src, mbedtls_include, + config_h, cflags, } } diff --git a/mbedtls-sys/build/cmake.rs b/mbedtls-sys/build/cmake.rs index 92232fe71..4e0d07d1f 100644 --- a/mbedtls-sys/build/cmake.rs +++ b/mbedtls-sys/build/cmake.rs @@ -29,9 +29,7 @@ impl super::BuildConfig { } println!("cargo:rerun-if-env-changed=RUST_MBED_C_COMPILER_BAREMETAL"); - let c_compiler_baremetal = std::env::var("RUST_MBED_C_COMPILER_BAREMETAL") - .map(|val| val == "1") - .unwrap_or_default(); + let c_compiler_baremetal = std::env::var("RUST_MBED_C_COMPILER_BAREMETAL").is_ok_and(|val| val == "1"); let target = std::env::var("TARGET").expect("TARGET environment variable should be set in build scripts"); // thumbv6m-none-eabi, thumbv7em-none-eabi, thumbv7em-none-eabihf, diff --git a/mbedtls-sys/build/config.rs b/mbedtls-sys/build/config.rs index f7bcdac5a..7388b020f 100644 --- a/mbedtls-sys/build/config.rs +++ b/mbedtls-sys/build/config.rs @@ -15,28 +15,28 @@ pub enum Macro { #[allow(dead_code)] DefinedAs(&'static str), } -use self::Macro::*; +use self::Macro::{Defined, DefinedAs, Undefined}; impl Macro { pub fn define(self, name: &'static str) -> String { match self { Undefined => String::new(), - Defined => format!("#define {}\n", name), - DefinedAs(v) => format!("#define {} {}\n", name, v), + Defined => format!("#define {name}\n"), + DefinedAs(v) => format!("#define {name} {v}\n"), } } } pub type CDefine = (&'static str, Macro); -pub const PREFIX: &'static str = r#" +pub const PREFIX: &str = r" #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) #define _CRT_SECURE_NO_DEPRECATE 1 #endif -"#; +"; /* @@ -64,8 +64,8 @@ for line in open('vendor/include/mbedtls/config.h').readlines(): print format(match.group(1), "Undefined") + (" // default: %s" % (match.group(2))) */ -#[cfg_attr(rustfmt, rustfmt_skip)] -const DEFAULT_DEFINES: &'static [CDefine] = &[ +#[rustfmt::skip] +const DEFAULT_DEFINES: &[CDefine] = &[ ("MBEDTLS_HAVE_ASM", Defined), ("MBEDTLS_NO_UDBL_DIVISION", Undefined), ("MBEDTLS_NO_64BIT_MULTIPLICATION", Undefined), @@ -408,17 +408,20 @@ const DEFAULT_DEFINES: &'static [CDefine] = &[ pub fn default_defines() -> HashMap<&'static str, Macro> { let mut defines = HashMap::new(); - for (key, value) in DEFAULT_DEFINES.iter() { - if defines.insert(*key, *value).is_some() { - panic!("Duplicate default define in {}: {}", file!(), key); - } + for (key, value) in DEFAULT_DEFINES { + assert!( + defines.insert(*key, *value).is_none(), + "Duplicate default define in {}: {}", + file!(), + key + ); } defines } -#[cfg_attr(rustfmt, rustfmt_skip)] -pub const FEATURE_DEFINES: &'static [(&'static str, CDefine)] = &[ +#[rustfmt::skip] +pub const FEATURE_DEFINES: &[(&str, CDefine)] = &[ ("time", ("MBEDTLS_HAVE_TIME", Defined)), ("time", ("MBEDTLS_HAVE_TIME_DATE", Defined)), ("havege", ("MBEDTLS_HAVEGE_C", Defined)), @@ -442,8 +445,8 @@ pub const FEATURE_DEFINES: &'static [(&'static str, CDefine)] = &[ ("trusted_cert_callback", ("MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK", Defined)), ]; -#[cfg_attr(rustfmt, rustfmt_skip)] -pub const PLATFORM_DEFINES: &'static [(&'static str, &'static str, CDefine)] = &[ +#[rustfmt::skip] +pub const PLATFORM_DEFINES: &[(&str, &str, CDefine)] = &[ ("time", "libc", ("MBEDTLS_TIMING_C", Defined)), ("time", "custom", ("MBEDTLS_PLATFORM_TIME_MACRO", DefinedAs("mbedtls_time"))), ("time", "custom", ("MBEDTLS_PLATFORM_TIME_TYPE_MACRO", DefinedAs("long long"))), @@ -456,7 +459,7 @@ pub const PLATFORM_DEFINES: &'static [(&'static str, &'static str, CDefine)] = & ("std", "entropy", ("MBEDTLS_ENTROPY_C", Defined)), ]; -pub const SUFFIX: &'static str = r#" +pub const SUFFIX: &str = r#" #if defined(TARGET_LIKE_MBED) #include "mbedtls/target_config.h" #endif diff --git a/mbedtls-sys/build/features.rs b/mbedtls-sys/build/features.rs index 6006bc0b6..05156e022 100644 --- a/mbedtls-sys/build/features.rs +++ b/mbedtls-sys/build/features.rs @@ -59,7 +59,7 @@ impl Features { for (feature, components) in &self.platform_components { for component in components { - println!(r#"cargo:rustc-cfg={}_component="{}""#, feature, component); + println!(r#"cargo:rustc-cfg={feature}_component="{component}""#); } } println!( @@ -69,7 +69,7 @@ impl Features { .flat_map(|(feature, components)| { components .iter() - .map(move |component| format!(r#"{}_component={}"#, feature, component)) + .map(move |component| format!(r#"{feature}_component={component}"#)) }) .collect::>() .join(",") @@ -78,7 +78,9 @@ impl Features { fn with_feature(&mut self, feature: &'static str) -> Option<&mut HashSet<&'static str>> { if self.have_feature(feature) { - Some(self.platform_components.entry(feature).or_insert_with(HashSet::new)) + Some(self.platform_components.entry(feature).or_default()) + //This should be the same + //Some(self.platform_components.entry(feature).or_insert_with(HashSet::new)) } else { None } @@ -96,11 +98,11 @@ impl Features { } fn env_have_target_cfg(var: &'static str, value: &'static str) -> bool { - let env = format!("CARGO_CFG_TARGET_{}", var).to_uppercase().replace("-", "_"); + let env = format!("CARGO_CFG_TARGET_{var}").to_uppercase().replace('-', "_"); env::var_os(env).map_or(false, |s| s == value) } fn env_have_feature(feature: &'static str) -> bool { - let env = format!("CARGO_FEATURE_{}", feature).to_uppercase().replace("-", "_"); + let env = format!("CARGO_FEATURE_{feature}").to_uppercase().replace('-', "_"); env::var_os(env).is_some() } diff --git a/mbedtls-sys/build/headers.rs b/mbedtls-sys/build/headers.rs index 8af3f0271..46441a625 100644 --- a/mbedtls-sys/build/headers.rs +++ b/mbedtls-sys/build/headers.rs @@ -25,8 +25,8 @@ use crate::features::FEATURES; * ) */ -#[cfg_attr(rustfmt, rustfmt_skip)] -pub const ORDERED: &'static [(Option<&'static str>, &'static str)] = &[ +#[rustfmt::skip] +pub const ORDERED: &[(Option<&'static str>, &str)] = &[ (None, "config_psa.h"), (None, "platform_time.h"), (None, "platform_util.h"), diff --git a/mbedtls-sys/src/lib.rs b/mbedtls-sys/src/lib.rs index e25f70274..e0e2b0be3 100644 --- a/mbedtls-sys/src/lib.rs +++ b/mbedtls-sys/src/lib.rs @@ -6,6 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(unexpected_cfgs)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate core; diff --git a/mbedtls-sys/src/types.rs b/mbedtls-sys/src/types.rs index 8672febd7..dc62cc832 100644 --- a/mbedtls-sys/src/types.rs +++ b/mbedtls-sys/src/types.rs @@ -6,7 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ -#![allow(non_camel_case_types)] +#![allow(non_camel_case_types, clippy::module_name_repetitions)] pub type int8_t = i8; pub type int16_t = i16; From 0ff2f52bc79ecb9f14f835dbb1690e4042f30388 Mon Sep 17 00:00:00 2001 From: Gijs Kwakkel Date: Tue, 17 Sep 2024 15:40:29 +0200 Subject: [PATCH 02/22] mbedtls cipher clippy fix --- mbedtls/src/cipher/mod.rs | 44 ++++++++++++------------ mbedtls/src/cipher/raw/mod.rs | 60 ++++++++++++++++----------------- mbedtls/src/cipher/raw/serde.rs | 55 +++++++++++++++++------------- 3 files changed, 83 insertions(+), 76 deletions(-) diff --git a/mbedtls/src/cipher/mod.rs b/mbedtls/src/cipher/mod.rs index acdd038b5..439080c71 100644 --- a/mbedtls/src/cipher/mod.rs +++ b/mbedtls/src/cipher/mod.rs @@ -6,6 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(non_local_definitions)] use core::marker::PhantomData; use core::ops::Range; pub mod raw; @@ -41,34 +42,31 @@ pub trait Type { pub enum TraditionalNoIv {} impl Type for TraditionalNoIv { fn is_valid_mode(mode: raw::CipherMode) -> bool { - match mode { - raw::CipherMode::ECB => true, - _ => false, - } + matches!(mode, raw::CipherMode::ECB) } } pub enum Traditional {} impl Type for Traditional { fn is_valid_mode(mode: raw::CipherMode) -> bool { - match mode { - raw::CipherMode::CBC | raw::CipherMode::CFB | raw::CipherMode::OFB | raw::CipherMode::CTR => true, - _ => false, - } + matches!( + mode, + raw::CipherMode::CBC | raw::CipherMode::CFB | raw::CipherMode::OFB | raw::CipherMode::CTR + ) } } pub enum Authenticated {} impl Type for Authenticated { fn is_valid_mode(mode: raw::CipherMode) -> bool { - match mode { + matches!( + mode, raw::CipherMode::GCM - | raw::CipherMode::CCM - | raw::CipherMode::KW - | raw::CipherMode::KWP - | raw::CipherMode::CHACHAPOLY => true, - _ => false, - } + | raw::CipherMode::CCM + | raw::CipherMode::KW + | raw::CipherMode::KWP + | raw::CipherMode::CHACHAPOLY + ) } } @@ -112,14 +110,17 @@ impl Cipher { } } + #[must_use] pub fn block_size(&self) -> usize { self.raw_cipher.block_size() } + #[must_use] pub fn iv_size(&self) -> usize { self.raw_cipher.iv_size() } + #[must_use] pub fn tag_size(&self) -> Option> { if self.raw_cipher.is_authenticated() { Some(32..129) @@ -128,21 +129,22 @@ impl Cipher { } } + #[must_use] pub fn cipher_mode(&self) -> raw::CipherMode { self.raw_cipher.cipher_mode() } } impl Cipher { - pub fn new(cipher_id: raw::CipherId, cipher_mode: raw::CipherMode, key_bit_len: u32) -> Result> { + pub fn new(cipher_id: raw::CipherId, cipher_mode: raw::CipherMode, key_bit_len: u32) -> Result { assert!(T::is_valid_mode(cipher_mode)); // Create raw cipher object let raw_cipher = raw::Cipher::setup(cipher_id, cipher_mode, key_bit_len)?; // Put together the structure to return - Ok(Cipher { - raw_cipher: raw_cipher, + Ok(Self { + raw_cipher, padding: raw::CipherPadding::Pkcs7, _op: PhantomData, _type: PhantomData, @@ -308,7 +310,7 @@ impl Cipher { } impl Cipher { - pub fn update(mut self, in_data: &[u8], out_data: &mut [u8]) -> Result<(usize, Cipher)> { + pub fn update(mut self, in_data: &[u8], out_data: &mut [u8]) -> Result<(usize, Self)> { // Call the wrapper function to do update operation (multi part) let len = self.raw_cipher.update(in_data, out_data)?; @@ -326,14 +328,14 @@ impl Cipher { } impl Cipher { - pub fn write_tag(mut self, out_tag: &mut [u8]) -> Result> { + pub fn write_tag(mut self, out_tag: &mut [u8]) -> Result { self.raw_cipher.write_tag(out_tag)?; // Put together the structure to return Ok(self.change_state()) } - pub fn check_tag(mut self, tag: &[u8]) -> Result> { + pub fn check_tag(mut self, tag: &[u8]) -> Result { self.raw_cipher.check_tag(tag)?; // Put together the structure to return diff --git a/mbedtls/src/cipher/raw/mod.rs b/mbedtls/src/cipher/raw/mod.rs index 2a25e3435..7930c504d 100644 --- a/mbedtls/src/cipher/raw/mod.rs +++ b/mbedtls/src/cipher/raw/mod.rs @@ -32,16 +32,16 @@ define!( impl From for CipherId { fn from(inner: cipher_id_t) -> Self { match inner { - CIPHER_ID_NONE => CipherId::None, - CIPHER_ID_NULL => CipherId::Null, - CIPHER_ID_AES => CipherId::Aes, - CIPHER_ID_DES => CipherId::Des, - CIPHER_ID_3DES => CipherId::Des3, - CIPHER_ID_CAMELLIA => CipherId::Camellia, - CIPHER_ID_BLOWFISH => CipherId::Blowfish, - CIPHER_ID_ARC4 => CipherId::Arc4, - CIPHER_ID_ARIA => CipherId::Aria, - CIPHER_ID_CHACHA20 => CipherId::Chacha20, + CIPHER_ID_NONE => Self::None, + CIPHER_ID_NULL => Self::Null, + CIPHER_ID_AES => Self::Aes, + CIPHER_ID_DES => Self::Des, + CIPHER_ID_3DES => Self::Des3, + CIPHER_ID_CAMELLIA => Self::Camellia, + CIPHER_ID_BLOWFISH => Self::Blowfish, + CIPHER_ID_ARC4 => Self::Arc4, + CIPHER_ID_ARIA => Self::Aria, + CIPHER_ID_CHACHA20 => Self::Chacha20, // This should be replaced with TryFrom once it is stable. _ => panic!("Invalid cipher_id_t"), } @@ -71,19 +71,19 @@ define!( impl From for CipherMode { fn from(inner: cipher_mode_t) -> Self { match inner { - MODE_NONE => CipherMode::None, - MODE_ECB => CipherMode::ECB, - MODE_CBC => CipherMode::CBC, - MODE_CFB => CipherMode::CFB, - MODE_OFB => CipherMode::OFB, - MODE_CTR => CipherMode::CTR, - MODE_GCM => CipherMode::GCM, - MODE_STREAM => CipherMode::STREAM, - MODE_CCM => CipherMode::CCM, - MODE_XTS => CipherMode::XTS, - MODE_CHACHAPOLY => CipherMode::CHACHAPOLY, - MODE_KW => CipherMode::KW, - MODE_KWP => CipherMode::KWP, + MODE_NONE => Self::None, + MODE_ECB => Self::ECB, + MODE_CBC => Self::CBC, + MODE_CFB => Self::CFB, + MODE_OFB => Self::OFB, + MODE_CTR => Self::CTR, + MODE_GCM => Self::GCM, + MODE_STREAM => Self::STREAM, + MODE_CCM => Self::CCM, + MODE_XTS => Self::XTS, + MODE_CHACHAPOLY => Self::CHACHAPOLY, + MODE_KW => Self::KW, + MODE_KWP => Self::KWP, // This should be replaced with TryFrom once it is stable. _ => panic!("Invalid cipher_mode_t"), } @@ -210,7 +210,7 @@ impl Cipher { // Setup routine - this should be the first function called // it combines several steps into one call here, they are // Cipher init, Cipher setup - pub fn setup(cipher_id: CipherId, cipher_mode: CipherMode, key_bit_len: u32) -> Result { + pub fn setup(cipher_id: CipherId, cipher_mode: CipherMode, key_bit_len: u32) -> Result { let mut ret = Self::init(); unsafe { // Do setup with proper cipher_info based on algorithm, key length and mode @@ -293,28 +293,26 @@ impl Cipher { } // Utility function to get block size for the selected / setup cipher_info + #[must_use] pub fn block_size(&self) -> usize { unsafe { (*self.inner.cipher_info).block_size as usize } } // Utility function to get IV size for the selected / setup cipher_info + #[must_use] pub fn iv_size(&self) -> usize { unsafe { (*self.inner.cipher_info).iv_size as usize } } + #[must_use] pub fn cipher_mode(&self) -> CipherMode { unsafe { (*self.inner.cipher_info).mode.into() } } // Utility function to get mode for the selected / setup cipher_info + #[must_use] pub fn is_authenticated(&self) -> bool { - unsafe { - if (*self.inner.cipher_info).mode == MODE_GCM || (*self.inner.cipher_info).mode == MODE_CCM { - return true; - } else { - return false; - } - } + unsafe { (*self.inner.cipher_info).mode == MODE_GCM || (*self.inner.cipher_info).mode == MODE_CCM } } // Utility function to set odd parity - used for DES keys diff --git a/mbedtls/src/cipher/raw/serde.rs b/mbedtls/src/cipher/raw/serde.rs index 987f9920d..295cb5a5f 100644 --- a/mbedtls/src/cipher/raw/serde.rs +++ b/mbedtls/src/cipher/raw/serde.rs @@ -64,9 +64,10 @@ impl Serialize for Cipher { serialize_raw_cipher(cipher_context).map_err(ser::Error::custom)? }; - match Op::is_encrypt() { - true => SavedCipher::Encryption(saved_raw_cipher, self.padding).serialize(s), - false => SavedCipher::Decryption(saved_raw_cipher, self.padding).serialize(s), + if Op::is_encrypt() { + SavedCipher::Encryption(saved_raw_cipher, self.padding).serialize(s) + } else { + SavedCipher::Decryption(saved_raw_cipher, self.padding).serialize(s) } } } @@ -82,23 +83,19 @@ unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) -> Result { + let algorithm_context = match (cipher_id, cipher_mode) { + (CIPHER_ID_AES, MODE_CBC | MODE_CTR | MODE_OFB | MODE_CFB | MODE_ECB) => { let mut aes_context = *(cipher_context.cipher_ctx as *const aes_context); aes_context.rk = ::core::ptr::null_mut(); AlgorithmContext::Aes(Bytes(aes_context)) } - (CIPHER_ID_ARIA, MODE_CBC) | (CIPHER_ID_ARIA, MODE_CTR) | (CIPHER_ID_ARIA, MODE_CFB) | (CIPHER_ID_ARIA, MODE_ECB) => { + (CIPHER_ID_ARIA, MODE_CBC | MODE_CTR | MODE_CFB | MODE_ECB) => { AlgorithmContext::Aria(Bytes(*(cipher_context.cipher_ctx as *const aria_context))) } - (CIPHER_ID_DES, MODE_CBC) | (CIPHER_ID_DES, MODE_CTR) | (CIPHER_ID_DES, MODE_OFB) | (CIPHER_ID_DES, MODE_CFB) => { + (CIPHER_ID_DES, MODE_CBC | MODE_CTR | MODE_OFB | MODE_CFB) => { AlgorithmContext::Des(Bytes(*(cipher_context.cipher_ctx as *const des_context))) } - (CIPHER_ID_3DES, MODE_CBC) | (CIPHER_ID_3DES, MODE_CTR) | (CIPHER_ID_3DES, MODE_OFB) | (CIPHER_ID_3DES, MODE_CFB) => { + (CIPHER_ID_3DES, MODE_CBC | MODE_CTR | MODE_OFB | MODE_CFB) => { AlgorithmContext::Des3(Bytes(*(cipher_context.cipher_ctx as *const des3_context))) } (CIPHER_ID_AES, MODE_GCM) => { @@ -117,6 +114,7 @@ unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) -> Result Result Deserialize<'de> for Cipher { - fn deserialize(d: D) -> Result, D::Error> + fn deserialize(d: D) -> Result where D: Deserializer<'de>, { @@ -160,9 +158,9 @@ impl<'de, Op: Operation, T: Type> Deserialize<'de> for Cipher unsafe { let raw_cipher = deserialize_raw_cipher(raw, padding) .map_err(|(e1, e2)| de::Error::invalid_value(Unexpected::Other(e1), &e2))?; - Ok(Cipher { - raw_cipher: raw_cipher, - padding: padding, + Ok(Self { + raw_cipher, + padding, _op: PhantomData, _type: PhantomData, _state: PhantomData, @@ -171,6 +169,7 @@ impl<'de, Op: Operation, T: Type> Deserialize<'de> for Cipher } } +#[allow(clippy::manual_let_else)] unsafe fn deserialize_raw_cipher( raw: SavedRawCipher, padding: raw::CipherPadding, @@ -200,11 +199,11 @@ unsafe fn deserialize_raw_cipher( (*ret_aes_ctx).rk = &mut (*ret_aes_ctx).buf[0]; } (CIPHER_ID_ARIA, AlgorithmContext::Aria(Bytes(aria_ctx))) => { - *(cipher_context.cipher_ctx as *mut aria_context) = aria_ctx + *(cipher_context.cipher_ctx as *mut aria_context) = aria_ctx; } (CIPHER_ID_DES, AlgorithmContext::Des(Bytes(des_ctx))) => *(cipher_context.cipher_ctx as *mut des_context) = des_ctx, (CIPHER_ID_3DES, AlgorithmContext::Des3(Bytes(des3_ctx))) => { - *(cipher_context.cipher_ctx as *mut des3_context) = des3_ctx + *(cipher_context.cipher_ctx as *mut des3_context) = des3_ctx; } ( CIPHER_ID_AES, @@ -267,7 +266,9 @@ unsafe trait BytesSerde: Sized { } fn as_slice(&self) -> &[u8] { - unsafe { from_raw_parts(self as *const Self as *const u8, size_of::()) } + // leaving the old one in, not sure if this does the same or not + //unsafe { from_raw_parts(self as *const Self as *const u8, size_of::()) } + unsafe { from_raw_parts(std::ptr::from_ref::(self) as *const u8, size_of::()) } } } @@ -281,7 +282,7 @@ impl Serialize for Bytes { } impl<'de, T: BytesSerde> Deserialize<'de> for Bytes { - fn deserialize(d: D) -> Result, D::Error> + fn deserialize(d: D) -> Result where D: Deserializer<'de>, { @@ -340,6 +341,8 @@ unsafe fn _check_cipher_context_t_size(ctx: cipher_context_t) -> [u8; _SIZE_OF_C ::core::mem::transmute(ctx) } +// I don't know if this should be ignored or not +#[allow(clippy::large_types_passed_by_value)] unsafe fn _check_aes_context_size(ctx: aes_context) -> [u8; _SIZE_OF_AES_CONTEXT] { ::core::mem::transmute(ctx) } @@ -348,10 +351,14 @@ unsafe fn _check_des_context_size(ctx: des_context) -> [u8; _SIZE_OF_DES_CONTEXT ::core::mem::transmute(ctx) } +// I don't know if this should be ignored or not +#[allow(clippy::large_types_passed_by_value)] unsafe fn _check_des3_context_size(ctx: des3_context) -> [u8; _SIZE_OF_DES3_CONTEXT] { ::core::mem::transmute(ctx) } +// I don't know if this should be ignored or not +#[allow(clippy::large_types_passed_by_value)] unsafe fn _check_gcm_context_size(ctx: gcm_context) -> [u8; _SIZE_OF_GCM_CONTEXT] { ::core::mem::transmute(ctx) } From 3df444c061210c58fc473b4ae329e1652dae937b Mon Sep 17 00:00:00 2001 From: Gijs Kwakkel Date: Tue, 17 Sep 2024 15:41:09 +0200 Subject: [PATCH 03/22] mbedtls platform support clippy fix --- mbedtls-platform-support/build.rs | 4 ++-- mbedtls-platform-support/src/lib.rs | 1 + mbedtls-platform-support/src/self_test.rs | 12 ++++++------ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/mbedtls-platform-support/build.rs b/mbedtls-platform-support/build.rs index 9e0431066..44126d7b7 100644 --- a/mbedtls-platform-support/build.rs +++ b/mbedtls-platform-support/build.rs @@ -12,11 +12,11 @@ use std::env; fn main() { let env_components = env::var("DEP_MBEDTLS_PLATFORM_COMPONENTS").unwrap(); let mut sys_platform_components = HashMap::<_, HashSet<_>>::new(); - for mut kv in env_components.split(",").map(|component| component.splitn(2, "=")) { + for mut kv in env_components.split(',').map(|component| component.splitn(2, '=')) { let k = kv.next().unwrap(); let v = kv.next().unwrap(); sys_platform_components.entry(k).or_insert_with(Default::default).insert(v); - println!(r#"cargo:rustc-cfg=sys_{}="{}""#, k, v); + println!(r#"cargo:rustc-cfg=sys_{k}="{v}""#); } let mut b = cc::Build::new(); diff --git a/mbedtls-platform-support/src/lib.rs b/mbedtls-platform-support/src/lib.rs index 5243b991a..25d229f9d 100644 --- a/mbedtls-platform-support/src/lib.rs +++ b/mbedtls-platform-support/src/lib.rs @@ -6,6 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(unexpected_cfgs)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] diff --git a/mbedtls-platform-support/src/self_test.rs b/mbedtls-platform-support/src/self_test.rs index 12806ce44..93b181c18 100644 --- a/mbedtls-platform-support/src/self_test.rs +++ b/mbedtls-platform-support/src/self_test.rs @@ -6,15 +6,15 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ -//! MbedTLS self tests. +//! `MbedTLS` self tests. //! -//! Calling MbedTLS self test functions before they're enabled using the +//! Calling `MbedTLS` self test functions before they're enabled using the //! `enable()` function here will result in a panic. //! //! Using this module in multithreaded or async environment will fail. The self //! test functions rely on global variables to track operations and anything //! non-self-test related operations will clobber these variables, resulting in -//! self test failures. Make sure no other code uses MbedTLS while running the +//! self test failures. Make sure no other code uses `MbedTLS` while running the //! self tests. Multiple self test operations done simultaneously may also //! return failures. @@ -53,7 +53,7 @@ pub unsafe extern "C" fn rand() -> c_int { rand_f.expect("Called self-test rand without enabling self-test")() } -/// Set callback functions to enable the MbedTLS self tests. +/// Set callback functions to enable the `MbedTLS` self tests. /// /// `rand` only needs to be set on platforms that don't have a `rand()` /// function in libc. `log` only needs to be set when using `no_std`, i.e. @@ -80,7 +80,7 @@ pub unsafe fn enable(rand: fn() -> c_int, log: Option) /// /// The caller needs to ensure this function is not called while any other /// function in this module is called. -pub unsafe fn disable() { +pub const unsafe fn disable() { #[cfg(any(not(feature = "std"), target_env = "sgx"))] { rand_f = None; @@ -94,7 +94,7 @@ pub unsafe fn disable() { /// # Safety /// /// The caller needs to ensure this function is not called while *any other* -/// MbedTLS function is called. See the module documentation for more +/// `MbedTLS` function is called. See the module documentation for more /// information. pub use mbedtls_sys::{ aes_self_test as aes, arc4_self_test as arc4, aria_self_test as aria, base64_self_test as base64, From 11c418e8afde0513fe70c8083387cd063ba2a963 Mon Sep 17 00:00:00 2001 From: Gijs Kwakkel Date: Tue, 17 Sep 2024 15:41:47 +0200 Subject: [PATCH 04/22] mbedlts build.rs clippy fix --- mbedtls/build.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/mbedtls/build.rs b/mbedtls/build.rs index 1c4fa76c9..3b21dd561 100644 --- a/mbedtls/build.rs +++ b/mbedtls/build.rs @@ -5,6 +5,7 @@ * 2.0 , at your * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(clippy::unwrap_used)] use std::collections::hash_map::DefaultHasher; use std::collections::{HashMap, HashSet}; @@ -14,8 +15,8 @@ use rustc_version::Channel; use std::env; /// Retrieves or generates a metadata value used for symbol name mangling to ensure unique C symbols. -/// When building with Cargo, the metadata value is extracted from the OUT_DIR environment variable. -/// For Bazel builds, this method generate the suffix by hashing part of the crate OUT_DIR, +/// When building with Cargo, the metadata value is extracted from the `OUT_DIR` environment variable. +/// For Bazel builds, this method generate the suffix by hashing part of the crate `OUT_DIR`, /// which are sufficient for ensuring symbol uniqueness. fn get_compilation_symbol_suffix() -> String { let out_dir: std::path::PathBuf = std::env::var_os("OUT_DIR").unwrap().into(); @@ -31,7 +32,7 @@ fn get_compilation_symbol_suffix() -> String { crate_.starts_with("mbedtls-"), "Expected second to last component of OUT_DIR to start with 'mbedtls-'" ); - return crate_[8..].to_owned(); // Return the part after "mbedtls-" + crate_[8..].to_owned() // Return the part after "mbedtls-" } else if out_dir.iter().rfind(|p| *p == "bazel-out").is_some() { // If Bazel is used as build system. let mut hasher = DefaultHasher::new(); @@ -39,7 +40,7 @@ fn get_compilation_symbol_suffix() -> String { for p in out_dir.iter().rev().take_while(|p| *p != "bazel-out") { p.hash(&mut hasher); } - return format!("{:016x}", hasher.finish()); + format!("{:016x}", hasher.finish()) } else { panic!("unexpected OUT_DIR format: {}", out_dir.display()); } @@ -51,16 +52,16 @@ fn main() { println!("cargo:rustc-cfg=nightly"); } let symbol_suffix = get_compilation_symbol_suffix(); - println!("cargo:rustc-env=RUST_MBEDTLS_SYMBOL_SUFFIX={}", symbol_suffix); + println!("cargo:rustc-env=RUST_MBEDTLS_SYMBOL_SUFFIX={symbol_suffix}"); println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION"); let env_components = env::var("DEP_MBEDTLS_PLATFORM_COMPONENTS").unwrap(); let mut sys_platform_components = HashMap::<_, HashSet<_>>::new(); - for mut kv in env_components.split(",").map(|component| component.splitn(2, "=")) { + for mut kv in env_components.split(',').map(|component| component.splitn(2, '=')) { let k = kv.next().unwrap(); let v = kv.next().unwrap(); sys_platform_components.entry(k).or_insert_with(Default::default).insert(v); - println!(r#"cargo:rustc-cfg=sys_{}="{}""#, k, v); + println!(r#"cargo:rustc-cfg=sys_{k}="{v}""#); } let mut b = cc::Build::new(); From 6eb3d819466eea1e04534a9aab3e37c9f0c28fc4 Mon Sep 17 00:00:00 2001 From: Gijs Kwakkel Date: Tue, 17 Sep 2024 15:42:46 +0200 Subject: [PATCH 05/22] mbedlts x509 clippy fix --- mbedtls/src/x509/certificate.rs | 166 +++++++++++++++++--------------- mbedtls/src/x509/mod.rs | 2 +- 2 files changed, 90 insertions(+), 78 deletions(-) diff --git a/mbedtls/src/x509/certificate.rs b/mbedtls/src/x509/certificate.rs index 80cb94754..75f0fee99 100644 --- a/mbedtls/src/x509/certificate.rs +++ b/mbedtls/src/x509/certificate.rs @@ -50,7 +50,7 @@ impl BERDecodable for Extension { let oid = reader.next().read_oid()?; let critical = reader.read_optional(|r| r.read_bool())?.unwrap_or(false); let value = reader.next().read_bytes()?; - Ok(Extension { oid, critical, value }) + Ok(Self { oid, critical, value }) }) } } @@ -93,15 +93,15 @@ fn x509_time_to_time(tm: &x509_time) -> Result