From a584c168e958ef7b931846dc7f07903643c984c5 Mon Sep 17 00:00:00 2001 From: Fina Wilke Date: Sat, 9 Dec 2023 19:47:27 +0100 Subject: [PATCH] code: Fix most clippy warnings --- cli/src/main.rs | 29 ++++++++++++------------- cli/src/util.rs | 2 +- src/core.rs | 25 +++++++++++---------- src/core/key.rs | 6 +++--- src/core/server_messages.rs | 2 ++ src/core/wordlist.rs | 11 +++++----- src/dilation/api.rs | 2 ++ src/dilation/manager.rs | 6 +++--- src/forwarding.rs | 4 ++-- src/transfer.rs | 14 ++++++------ src/transfer/v1.rs | 19 +++++++--------- src/transfer/v2.rs | 43 +++++++++++++++++-------------------- src/transit.rs | 2 -- src/transit/crypto.rs | 8 +++---- src/transit/transport.rs | 1 - src/uri.rs | 6 +++--- src/util.rs | 2 +- 17 files changed, 86 insertions(+), 96 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index ffef5a36..a04ff666 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -420,7 +420,7 @@ async fn main() -> eyre::Result<()> { } }; - if with_dilation && peer_allows_dilation(&wormhole.peer_version()) { + if with_dilation && peer_allows_dilation(wormhole.peer_version()) { log::debug!("dilate wormhole"); let mut dilated_wormhole = wormhole.dilate()?; // need to pass transit relay URL dilated_wormhole.run().await; @@ -570,7 +570,7 @@ async fn main() -> eyre::Result<()> { out, ); - std::io::stdout().write_all(&out.as_bytes())?; + std::io::stdout().write_all(out.as_bytes())?; }, shell => { let mut out = std::io::stdout(); @@ -601,6 +601,8 @@ fn parse_transit_args(args: &CommonArgs) -> transit::Abilities { } } +type PrintCodeFn = dyn Fn(&mut Term, &magic_wormhole::Code, &Option) -> eyre::Result<()>; + /** * Parse the necessary command line arguments to establish an initial server connection. * This is used over and over again by the different subcommands. @@ -616,9 +618,7 @@ async fn parse_and_connect( code_length: Option, is_send: bool, mut app_config: magic_wormhole::AppConfig, - print_code: Option< - &dyn Fn(&mut Term, &magic_wormhole::Code, &Option) -> eyre::Result<()>, - >, + print_code: Option<&PrintCodeFn>, clipboard: Option<&mut Clipboard>, ) -> eyre::Result<(Wormhole, magic_wormhole::Code, Vec)> { // TODO handle relay servers with multiple endpoints better @@ -1059,15 +1059,14 @@ async fn receive_inner_v1( .truncate(true) .open(&file_path) .await?; - Ok(req - .accept( - &transit::log_transit_connection, - &mut file, - create_progress_handler(pb), - ctrl_c(), - ) - .await - .context("Receive process failed")?) + req.accept( + &transit::log_transit_connection, + &mut file, + create_progress_handler(pb), + ctrl_c(), + ) + .await + .context("Receive process failed") } async fn receive_inner_v2( @@ -1107,7 +1106,7 @@ async fn receive_inner_v2( /* Create a temporary directory for receiving */ use rand::Rng; - let tmp_dir = target_dir.join(&format!( + let tmp_dir = target_dir.join(format!( "wormhole-tmp-{:06}", rand::thread_rng().gen_range(0..1_000_000) )); diff --git a/cli/src/util.rs b/cli/src/util.rs index 51d517ea..d76450bf 100644 --- a/cli/src/util.rs +++ b/cli/src/util.rs @@ -20,7 +20,7 @@ pub async fn ask_user(message: impl std::fmt::Display, default_answer: bool) -> let mut answer = String::new(); stdin.read_line(&mut answer).await.unwrap(); - match &*answer.to_lowercase().trim() { + match answer.to_lowercase().trim() { "y" | "yes" => break true, "n" | "no" => break false, "" => break default_answer, diff --git a/src/core.rs b/src/core.rs index d5d0b628..d7c43d20 100644 --- a/src/core.rs +++ b/src/core.rs @@ -5,12 +5,11 @@ use crate::core::protocol::{WormholeProtocol, WormholeProtocolDefault}; use crate::dilation::DilatedWormhole; use crypto_secretbox as secretbox; use log::*; -use serde; use serde_derive::{Deserialize, Serialize}; use serde_json::Value; use self::rendezvous::*; -pub(self) use self::server_messages::EncryptedMessage; +use self::server_messages::EncryptedMessage; pub(super) mod key; pub(crate) mod protocol; @@ -161,7 +160,7 @@ impl MailboxConnection { let (mut server, welcome) = RendezvousServer::connect(&config.id, &config.rendezvous_url).await?; let (nameplate, mailbox) = server.allocate_claim_open().await?; - let code = Code::new(&nameplate, &password); + let code = Code::new(&nameplate, password); Ok(MailboxConnection { config, @@ -303,13 +302,13 @@ impl Wormhole { ) -> Result<(WormholeWelcome, Self), WormholeError> { let mailbox_connection = MailboxConnection::connect(config, code.clone(), !expect_claimed_nameplate).await?; - return Ok(( + Ok(( WormholeWelcome { welcome: mailbox_connection.welcome.clone(), - code: code, + code, }, Self::connect(mailbox_connection).await?, - )); + )) } /// Set up a Wormhole which is the client-client part of the connection setup @@ -469,7 +468,7 @@ impl Wormhole { } pub fn our_version(&self) -> &Box { - &self.protocol.our_version() + self.protocol.our_version() } } @@ -643,7 +642,7 @@ impl> From for EitherSide { impl From for TheirSide { fn from(side: MySide) -> TheirSide { - TheirSide(side.0.into()) + TheirSide(side.0) } } @@ -660,7 +659,7 @@ impl Phase { } pub fn dilation(phase: u64) -> Self { - Phase(format!("dilate-{}", phase.to_string()).to_string().into()) + Phase(format!("dilate-{}", phase).into()) } pub fn is_version(&self) -> bool { @@ -694,9 +693,9 @@ impl Nameplate { } } -impl Into for Nameplate { - fn into(self) -> String { - self.0 +impl From for String { + fn from(value: Nameplate) -> Self { + value.0 } } @@ -723,7 +722,7 @@ impl Code { } pub fn nameplate(&self) -> Nameplate { - Nameplate::new(self.0.splitn(2, '-').next().unwrap()) + Nameplate::new(self.0.split('-').next().unwrap()) } } diff --git a/src/core/key.rs b/src/core/key.rs index 80f0aec9..cc52fdac 100644 --- a/src/core/key.rs +++ b/src/core/key.rs @@ -49,7 +49,7 @@ impl Key { */ #[cfg(feature = "transit")] pub fn derive_transit_key(&self, appid: &AppID) -> Key { - let transit_purpose = format!("{}/transit-key", &*appid); + let transit_purpose = format!("{}/transit-key", appid); let derived_key = self.derive_subkey_from_purpose(&transit_purpose); trace!( @@ -68,7 +68,7 @@ impl Key

{ } pub fn to_hex(&self) -> String { - hex::encode(&**self) + hex::encode(**self) } /** @@ -76,7 +76,7 @@ impl Key

{ */ pub fn derive_subkey_from_purpose(&self, purpose: &str) -> Key { Key( - Box::new(derive_key(&*self, purpose.as_bytes())), + Box::new(derive_key(self, purpose.as_bytes())), std::marker::PhantomData, ) } diff --git a/src/core/server_messages.rs b/src/core/server_messages.rs index 48ce9a81..ac2f45ce 100644 --- a/src/core/server_messages.rs +++ b/src/core/server_messages.rs @@ -132,6 +132,7 @@ impl EncryptedMessage { #[derive(Serialize, Debug, PartialEq, derive_more::Display)] #[serde(rename_all = "kebab-case")] #[serde(tag = "type")] +#[allow(dead_code)] pub enum OutboundMessage { #[display(fmt = "SubmitPermission({})", _0)] SubmitPermission(SubmitPermission), @@ -196,6 +197,7 @@ impl OutboundMessage { OutboundMessage::Open { mailbox } } + #[allow(dead_code)] pub fn add(phase: Phase, body: Vec) -> Self { OutboundMessage::Add { body, phase } } diff --git a/src/core/wordlist.rs b/src/core/wordlist.rs index 34bf5cb0..64f8c244 100644 --- a/src/core/wordlist.rs +++ b/src/core/wordlist.rs @@ -36,15 +36,15 @@ impl Wordlist { let mut suffix: String = prefix.to_owned(); if word.starts_with(last_partial_word.unwrap()) { if lp == 0 { - suffix.push_str(&word); + suffix.push_str(word); } else { let p = prefix.len() - lp; - suffix.truncate(p as usize); - suffix.push_str(&word); + suffix.truncate(p); + suffix.push_str(word); } if count_dashes + 1 < self.num_words { - suffix.push_str("-"); + suffix.push('-'); } completions.push(suffix); @@ -56,8 +56,7 @@ impl Wordlist { pub fn choose_words(&self) -> String { let mut rng = OsRng; - let components: Vec; - components = self + let components: Vec = self .words .iter() .cycle() diff --git a/src/dilation/api.rs b/src/dilation/api.rs index d790d5f4..e097a6a5 100644 --- a/src/dilation/api.rs +++ b/src/dilation/api.rs @@ -12,6 +12,7 @@ pub enum IOEvent { /// Commands to be executed #[derive(Debug, Clone, PartialEq, Display)] +#[allow(dead_code)] pub enum ManagerCommand { // XXX: include API calls to IO layer Protocol(ProtocolCommand), @@ -28,6 +29,7 @@ pub enum ProtocolCommand { /// Protocol level commands #[derive(Debug, Clone, PartialEq, Display)] +#[allow(dead_code)] pub enum IOCommand { CloseConnection, } diff --git a/src/dilation/manager.rs b/src/dilation/manager.rs index e3a5cbee..84722502 100644 --- a/src/dilation/manager.rs +++ b/src/dilation/manager.rs @@ -17,6 +17,7 @@ pub enum Role { } #[derive(Debug, PartialEq, Clone, Copy, Display)] +#[allow(dead_code)] pub enum State { Waiting, Wanting, @@ -38,12 +39,11 @@ pub struct ManagerMachine { #[cfg_attr(test, automock)] impl ManagerMachine { pub fn new(side: MySide) -> Self { - let machine = ManagerMachine { + ManagerMachine { side, role: Role::Follower, state: Some(State::Wanting), - }; - machine + } } pub fn current_state(&self) -> Option { diff --git a/src/forwarding.rs b/src/forwarding.rs index 8c055fd2..51892ea6 100644 --- a/src/forwarding.rs +++ b/src/forwarding.rs @@ -151,8 +151,8 @@ pub async fn serve( .to_owned(); let peer_version: AppVersion = serde_json::from_value(wormhole.peer_version().to_owned())?; let connector = transit::init( - our_version.transit_abilities.clone(), - Some(peer_version.transit_abilities.clone()), + our_version.transit_abilities, + Some(peer_version.transit_abilities), relay_hints, ) .await?; diff --git a/src/transfer.rs b/src/transfer.rs index 39c38514..dc1a11f1 100644 --- a/src/transfer.rs +++ b/src/transfer.rs @@ -457,13 +457,11 @@ impl Offer { "{name} and {} other files or directories", self.content.len() - 1 ) + } else if self.is_directory() { + let count = entry.iter_files().count(); + format!("{name} with {count} files inside") } else { - if self.is_directory() { - let count = entry.iter_files().count(); - format!("{name} with {count} files inside") - } else { - name.clone() - } + name.clone() } } @@ -731,11 +729,11 @@ impl OfferEntry { match self { OfferEntry::RegularFile { size, .. } => OfferEntry::RegularFile { size: *size, - content: f(&base_path), + content: f(base_path), }, OfferEntry::Directory { content } => OfferEntry::Directory { content: content - .into_iter() + .iter() .map(|(k, v)| { base_path.push(k.clone()); let v = v.set_content(base_path, f); diff --git a/src/transfer/v1.rs b/src/transfer/v1.rs index e7035811..51798e51 100644 --- a/src/transfer/v1.rs +++ b/src/transfer/v1.rs @@ -265,10 +265,10 @@ pub async fn send_folder( }; use std::io::Result as IoResult; + type WrappedDataFut = BoxFuture<'static, IoResult>>; + /* Type tetris :) */ - fn wrap( - buffer: impl AsRef<[u8]> + Unpin + Send + 'static, - ) -> BoxFuture<'static, IoResult>> { + fn wrap(buffer: impl AsRef<[u8]> + Unpin + Send + 'static) -> WrappedDataFut { Box::pin(ready(IoResult::Ok( Box::new(Cursor::new(buffer)) as Box ))) as _ @@ -276,14 +276,11 @@ pub async fn send_folder( /* Walk our offer recursively, concatenate all our readers into a stream that will build the tar file */ fn create_offer( - mut total_content: Vec< - BoxFuture<'static, IoResult>>, - >, + mut total_content: Vec, total_size: &mut u64, offer: OfferSendEntry, path: &mut Vec, - ) -> IoResult>>>> - { + ) -> IoResult> { match offer { OfferSendEntry::Directory { content } => { log::debug!("Adding directory {path:?}"); @@ -299,7 +296,7 @@ pub async fn send_folder( }, OfferSendEntry::RegularFile { size, content } => { log::debug!("Adding file {path:?}; {size} bytes"); - let header = tar_helper::create_header_file(&path, size)?; + let header = tar_helper::create_header_file(path, size)?; let padding = tar_helper::padding(size); *total_size += header.len() as u64; *total_size += padding.len() as u64; @@ -330,7 +327,7 @@ pub async fn send_folder( total_size += 1024; content.push(wrap([0; 1024])); - let content = futures::stream::iter(content).then(|content| async { content.await }); + let content = futures::stream::iter(content).then(|content| content); /* Convert to stream */ @@ -773,7 +770,7 @@ mod tar_helper { // long name extension by emitting an entry which indicates that it's the // filename. if let Err(e) = header.set_path(path) { - let data = path2bytes(&path); + let data = path2bytes(path); let max = header.as_old().name.len(); // Since `e` isn't specific enough to let us know the path is indeed too // long, verify it first before using the extension. diff --git a/src/transfer/v2.rs b/src/transfer/v2.rs index 7ecaa5b1..bfa6123d 100644 --- a/src/transfer/v2.rs +++ b/src/transfer/v2.rs @@ -69,7 +69,7 @@ pub struct AnswerMessage { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(rename_all = "kebab-case")] -pub(self) struct AnswerMessageInner { +struct AnswerMessageInner { pub file: Vec, pub offset: u64, pub sha256: Option<[u8; 32]>, @@ -108,9 +108,7 @@ async fn make_transit( /* Send our transit hints */ wormhole - .send_json(&PeerMessage::transit_v2( - (**connector.our_hints()).clone().into(), - )) + .send_json(&PeerMessage::transit_v2((**connector.our_hints()).clone())) .await?; /* Receive their transit hints */ @@ -118,7 +116,7 @@ async fn make_transit( match wormhole.receive_json::().await??.check_err()? { PeerMessage::TransitV2(transit) => { debug!("received transit message: {:?}", transit); - transit.hints_v2.into() + transit.hints_v2 }, other => { let error = TransferError::unexpected_message("transit-v2", other); @@ -210,8 +208,7 @@ async fn send_inner( ) -> Result<(), TransferError> { transit.send_record(&{ /* This must be split into two statements to appease the borrow checker (unfortunate side effect of borrow-through) */ - let message = PeerMessageV2::Offer((&offer).into()).ser_msgpack(); - message + PeerMessageV2::Offer((&offer).into()).ser_msgpack() }).await?; let files = match PeerMessageV2::de_msgpack(&transit.receive_record().await?)?.check_err()? { @@ -246,7 +243,7 @@ async fn send_inner( { let offset = *offset; /* This must be split into two statements to appease the borrow checker (unfortunate side effect of borrow-through) */ - let content = (offer.get_file(&file).unwrap().0)(); + let content = (offer.get_file(file).unwrap().0)(); let mut content = content.await?; let file = file.clone(); @@ -262,7 +259,7 @@ async fn send_inner( let our_hash = hasher.finalize_fixed(); /* If it doesn't match, start at 0 instead of the originally requested offset */ - if &*our_hash == &sha256[..] { + if *our_hash == sha256[..] { transit .send_record( &PeerMessageV2::FileStart(FileStart { @@ -585,20 +582,20 @@ async fn receive_inner( }; } - let _transfer_ack = match PeerMessageV2::de_msgpack(&transit.receive_record().await?)? - .check_err()? - { - PeerMessageV2::TransferAck(transfer_ack) => transfer_ack, - PeerMessageV2::FileStart(_) => { - bail!(TransferError::Protocol( - format!("Unexpected message: got 'file-start' but did not expect any more files") - .into_boxed_str() - )) - }, - other => { - bail!(TransferError::unexpected_message("transfer-ack", other)) - }, - }; + let _transfer_ack = + match PeerMessageV2::de_msgpack(&transit.receive_record().await?)?.check_err()? { + PeerMessageV2::TransferAck(transfer_ack) => transfer_ack, + PeerMessageV2::FileStart(_) => { + bail!(TransferError::Protocol( + "Unexpected message: got 'file-start' but did not expect any more files" + .to_string() + .into_boxed_str() + )) + }, + other => { + bail!(TransferError::unexpected_message("transfer-ack", other)) + }, + }; Ok(()) } diff --git a/src/transit.rs b/src/transit.rs index c2ea7404..d3d6d15a 100644 --- a/src/transit.rs +++ b/src/transit.rs @@ -584,8 +584,6 @@ pub struct TransitInfo { /// This says nothing about the actual transport protocol used. #[cfg(not(target_family = "wasm"))] pub peer_addr: SocketAddr, - // Prevent exhaustive destructuring for future proofing - _unused: (), } type TransitConnection = (Box, TransitInfo); diff --git a/src/transit/crypto.rs b/src/transit/crypto.rs index 2440b41f..3914e69d 100644 --- a/src/transit/crypto.rs +++ b/src/transit/crypto.rs @@ -263,7 +263,7 @@ impl TransitCryptoInit for NoiseInit { builder.set_is_initiator(true); builder.build_handshake_state() }; - handshake.push_psk(&*self.key); + handshake.push_psk(&self.key); // → psk, e socket @@ -279,7 +279,7 @@ impl TransitCryptoInit for NoiseInit { // ← "" let peer_confirmation_message = rx.decrypt_vec(&socket.read_transit_message().await?)?; ensure!( - peer_confirmation_message.len() == 0, + peer_confirmation_message.is_empty(), TransitHandshakeError::HandshakeFailed ); @@ -330,7 +330,7 @@ impl TransitCryptoInit for NoiseInit { builder.set_is_initiator(false); builder.build_handshake_state() }; - handshake.push_psk(&*self.key); + handshake.push_psk(&self.key); // ← psk, e handshake.read_message(&socket.read_transit_message().await?, &mut [])?; @@ -350,7 +350,7 @@ impl TransitCryptoInit for NoiseInit { // ← "" let peer_confirmation_message = rx.decrypt_vec(&socket.read_transit_message().await?)?; ensure!( - peer_confirmation_message.len() == 0, + peer_confirmation_message.is_empty(), TransitHandshakeError::HandshakeFailed ); diff --git a/src/transit/transport.rs b/src/transit/transport.rs index dd7ddfe3..b225f4bc 100644 --- a/src/transit/transport.rs +++ b/src/transit/transport.rs @@ -297,7 +297,6 @@ pub(super) fn wrap_tcp_connection( peer_addr: socket .peer_addr() .expect("Internal error: socket must be IP"), - _unused: (), }; Ok((Box::new(socket), info)) diff --git a/src/uri.rs b/src/uri.rs index 7713700e..3a72fe41 100644 --- a/src/uri.rs +++ b/src/uri.rs @@ -75,7 +75,7 @@ impl TryFrom<&url::Url> for WormholeTransferUri { .query_pairs() .collect::>(); match queries.get("version").map(Deref::deref).unwrap_or("0") { - version if version == "0" => {}, + "0" => {}, unsupported => return Err(ParseError::UnsupportedVersion(unsupported.into())), } let rendezvous_server = queries @@ -125,13 +125,13 @@ impl std::str::FromStr for WormholeTransferUri { impl From<&WormholeTransferUri> for url::Url { fn from(val: &WormholeTransferUri) -> Self { let mut url = url::Url::parse("wormhole-transfer:").unwrap(); - url.set_path(&*val.code); + url.set_path(&val.code); /* Only do this if there are any query parameteres at all, otherwise the URL will have an ugly trailing '?'. */ if val.rendezvous_server.is_some() || val.is_leader { let mut query = url.query_pairs_mut(); query.clear(); if let Some(rendezvous_server) = val.rendezvous_server.as_ref() { - query.append_pair("rendezvous", &rendezvous_server.to_string()); + query.append_pair("rendezvous", rendezvous_server.as_ref()); } if val.is_leader { query.append_pair("role", "leader"); diff --git a/src/util.rs b/src/util.rs index 35b27cc8..1bec0a2e 100644 --- a/src/util.rs +++ b/src/util.rs @@ -19,7 +19,7 @@ pub struct DisplayBytes<'a>(pub &'a [u8]); impl std::fmt::Display for DisplayBytes<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let hex_decode = hex::decode(&self.0); + let hex_decode = hex::decode(self.0); let (string, hex_param) = match hex_decode.as_ref().map(Vec::as_slice) { Ok(decoded_hex) => (decoded_hex, "hex-encoded "), Err(_) => (self.0, ""),