diff options
| author | Linus Färnstrand <linus@mullvad.net> | 2025-07-09 12:51:42 +0200 |
|---|---|---|
| committer | Linus Färnstrand <linus@mullvad.net> | 2025-07-09 12:51:42 +0200 |
| commit | bef9cb8441e1369865ff345550ebb9c528dd3aca (patch) | |
| tree | fcac2cea9e6f7c6e270bedbdc5a81b0c0096f555 | |
| parent | b21c24e98078145b19b6fc0eb75163e4b4364253 (diff) | |
| parent | 485d6b1b81ddf9a038dc93c4ed0f000d9aff107b (diff) | |
| download | mullvadvpn-bef9cb8441e1369865ff345550ebb9c528dd3aca.tar.xz mullvadvpn-bef9cb8441e1369865ff345550ebb9c528dd3aca.zip | |
Merge branch 'fix-rust-warnings-prepare-1.88'
63 files changed, 233 insertions, 412 deletions
diff --git a/android/translations-converter/src/android/plurals.rs b/android/translations-converter/src/android/plurals.rs index 91b2395d3a..6b6c9da06b 100644 --- a/android/translations-converter/src/android/plurals.rs +++ b/android/translations-converter/src/android/plurals.rs @@ -58,11 +58,11 @@ impl TryFrom<&Path> for PluralResources { type Error = String; fn try_from(value: &Path) -> Result<Self, Self::Error> { - let strings_file = File::open(value) - .map_err(|e| format!("Failed to open plural resources file: {}", e))?; + let strings_file = + File::open(value).map_err(|e| format!("Failed to open plural resources file: {e}"))?; quick_xml::de::from_reader(BufReader::new(strings_file)) - .map_err(|e| format!("Failed to parse plural resources file: {}", e)) + .map_err(|e| format!("Failed to parse plural resources file: {e}")) } } diff --git a/android/translations-converter/src/android/string_value.rs b/android/translations-converter/src/android/string_value.rs index d7f56de35c..31c753e3cf 100644 --- a/android/translations-converter/src/android/string_value.rs +++ b/android/translations-converter/src/android/string_value.rs @@ -94,7 +94,7 @@ impl StringValue { panic!("Parameter index is less than 1") } - write!(&mut output, "%{}$", parameter_index).expect("formatting failed"); + write!(&mut output, "%{parameter_index}$").expect("formatting failed"); } output.push_str(part); diff --git a/android/translations-converter/src/android/strings.rs b/android/translations-converter/src/android/strings.rs index 04f379e82c..e0330ab362 100644 --- a/android/translations-converter/src/android/strings.rs +++ b/android/translations-converter/src/android/strings.rs @@ -53,11 +53,11 @@ impl TryFrom<&Path> for StringResources { type Error = String; fn try_from(value: &Path) -> Result<Self, Self::Error> { - let strings_file = File::open(value) - .map_err(|e| format!("Failed to open string resources file: {}", e))?; + let strings_file = + File::open(value).map_err(|e| format!("Failed to open string resources file: {e}"))?; quick_xml::de::from_reader(BufReader::new(strings_file)) - .map_err(|e| format!("Failed to parse string resources file: {}", e)) + .map_err(|e| format!("Failed to parse string resources file: {e}")) } } diff --git a/ci/ios/test-router/raas/src/capture/cleanup.rs b/ci/ios/test-router/raas/src/capture/cleanup.rs index 13189da464..43ec07590b 100644 --- a/ci/ios/test-router/raas/src/capture/cleanup.rs +++ b/ci/ios/test-router/raas/src/capture/cleanup.rs @@ -23,7 +23,7 @@ async fn delete_old_captures_inner(dir: &Path) -> std::io::Result<()> { let path = path.clone(); delete_tasks.push(tokio::spawn(async move { if let Err(e) = fs::remove_file(&path).await { - eprintln!("Failed to delete {:?}: {}", path, e); + eprintln!("Failed to delete {path:?}: {e}"); } })); } diff --git a/installer-downloader/tests/mock.rs b/installer-downloader/tests/mock.rs index e20e5375f7..d514a06320 100644 --- a/installer-downloader/tests/mock.rs +++ b/installer-downloader/tests/mock.rs @@ -302,9 +302,7 @@ impl AppDelegate for FakeAppDelegate { } fn set_status_text(&mut self, text: &str) { - self.state - .call_log - .push(format!("set_status_text: {}", text)); + self.state.call_log.push(format!("set_status_text: {text}")); self.state.status_text = text.to_owned(); } @@ -316,7 +314,7 @@ impl AppDelegate for FakeAppDelegate { fn set_download_text(&mut self, text: &str) { self.state .call_log - .push(format!("set_download_text: {}", text)); + .push(format!("set_download_text: {text}")); self.state.download_text = text.to_owned(); } @@ -338,7 +336,7 @@ impl AppDelegate for FakeAppDelegate { fn set_download_progress(&mut self, complete: u32) { self.state .call_log - .push(format!("set_download_progress: {}", complete)); + .push(format!("set_download_progress: {complete}")); self.state.download_progress = complete; } diff --git a/mullvad-api/src/access_mode.rs b/mullvad-api/src/access_mode.rs index ecd90b9d82..3cdb59c9c2 100644 --- a/mullvad-api/src/access_mode.rs +++ b/mullvad-api/src/access_mode.rs @@ -92,7 +92,7 @@ pub enum Error { #[error("Could not resolve access method {access_method:#?}")] Resolve { access_method: AccessMethod }, #[error("AccessModeSelector is not receiving any messages.")] - SendFailed(#[from] mpsc::TrySendError<Message>), + SendFailed(#[from] Box<mpsc::TrySendError<Message>>), #[error("AccessModeSelector is not receiving any messages.")] OneshotSendFailed, #[error("AccessModeSelector is not responding.")] @@ -135,7 +135,7 @@ pub struct AccessModeSelectorHandle { impl AccessModeSelectorHandle { async fn send_command<T>(&self, make_cmd: impl FnOnce(ResponseTx<T>) -> Message) -> Result<T> { let (tx, rx) = oneshot::channel(); - self.cmd_tx.unbounded_send(make_cmd(tx))?; + self.cmd_tx.unbounded_send(make_cmd(tx)).map_err(Box::new)?; rx.await.map_err(Error::NotRunning)? } diff --git a/mullvad-api/src/https_client_with_sni.rs b/mullvad-api/src/https_client_with_sni.rs index f86c538a67..d5e595e373 100644 --- a/mullvad-api/src/https_client_with_sni.rs +++ b/mullvad-api/src/https_client_with_sni.rs @@ -148,9 +148,7 @@ impl InnerConnectionMode { .await } } - .map_err(|error| { - io::Error::new(io::ErrorKind::Other, format!("SOCKS error: {error}")) - }) + .map_err(|error| io::Error::other(format!("SOCKS error: {error}"))) }; Self::connect_proxied( first_hop, @@ -415,7 +413,7 @@ impl HttpsConnectorWithSni { let addrs = dns_resolver.resolve(hostname.to_owned()).await?; let addr = addrs .first() - .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Empty DNS response"))?; + .ok_or_else(|| io::Error::other("Empty DNS response"))?; let port = match (addr.port(), port) { (_, Some(port)) => port, (0, None) => DEFAULT_PORT, diff --git a/mullvad-api/src/lib.rs b/mullvad-api/src/lib.rs index 4ba91a28c6..4acbff321c 100644 --- a/mullvad-api/src/lib.rs +++ b/mullvad-api/src/lib.rs @@ -139,12 +139,11 @@ impl ApiEndpoint { api_addr = env::API_ADDR_VAR, api_host = env::API_HOST_VAR ); - api.address = format!("{}:{}", host, API_PORT_DEFAULT) + api.address = format!("{host}:{API_PORT_DEFAULT}") .to_socket_addrs() .unwrap_or_else(|_| { panic!( - "Unable to resolve API IP address from host {host}:{port}", - port = API_PORT_DEFAULT, + "Unable to resolve API IP address from host {host}:{API_PORT_DEFAULT}" ) }) .next(); @@ -714,7 +713,7 @@ impl ProblemReportProxy { message: &str, log: &str, metadata: &BTreeMap<String, String>, - ) -> impl Future<Output = Result<(), rest::Error>> { + ) -> impl Future<Output = Result<(), rest::Error>> + use<> { #[derive(serde::Serialize)] struct ProblemReport { address: String, diff --git a/mullvad-api/src/proxy.rs b/mullvad-api/src/proxy.rs index 106449bb30..2a4406d7f0 100644 --- a/mullvad-api/src/proxy.rs +++ b/mullvad-api/src/proxy.rs @@ -129,7 +129,7 @@ impl ApiConnectionMode { "Failed to deserialize \"{CURRENT_CONFIG_FILENAME}\"" )) ); - io::Error::new(io::ErrorKind::Other, "deserialization failed") + io::Error::other("deserialization failed") }), Err(error) => { if error.kind() == io::ErrorKind::NotFound { @@ -145,7 +145,7 @@ impl ApiConnectionMode { pub async fn save(&self, cache_dir: &Path) -> io::Result<()> { let mut file = mullvad_fs::AtomicFile::new(cache_dir.join(CURRENT_CONFIG_FILENAME)).await?; let json = serde_json::to_string_pretty(self) - .map_err(|_| io::Error::new(io::ErrorKind::Other, "serialization failed"))?; + .map_err(|_| io::Error::other("serialization failed"))?; file.write_all(json.as_bytes()).await?; file.write_all(b"\n").await?; file.finalize().await diff --git a/mullvad-cli/src/cmds/account.rs b/mullvad-cli/src/cmds/account.rs index 91711d6f3a..4be492d15b 100644 --- a/mullvad-cli/src/cmds/account.rs +++ b/mullvad-cli/src/cmds/account.rs @@ -122,7 +122,7 @@ impl Account { if verbose { println!("{:<20}{}", "Device id:", device.device.id); println!("{:<20}{}", "Device pubkey:", device.device.pubkey); - println!("{:<20}{}", "Device created:", device.device.created,); + println!("{:<20}{}", "Device created:", device.device.created); } } DeviceState::LoggedOut => { diff --git a/mullvad-cli/src/cmds/api_access.rs b/mullvad-cli/src/cmds/api_access.rs index 74ff935f88..00a268ca7f 100644 --- a/mullvad-cli/src/cmds/api_access.rs +++ b/mullvad-cli/src/cmds/api_access.rs @@ -246,7 +246,7 @@ impl ApiAccess { .await? .get(item.as_array_index()?) .cloned() - .ok_or(anyhow!(format!("Access method {} does not exist", item))) + .ok_or(anyhow!(format!("Access method {item} does not exist"))) } } diff --git a/mullvad-daemon/src/lib.rs b/mullvad-daemon/src/lib.rs index c33ecf542b..d35ce7678e 100644 --- a/mullvad-daemon/src/lib.rs +++ b/mullvad-daemon/src/lib.rs @@ -1149,7 +1149,7 @@ impl Daemon { locked_down, }, #[cfg(target_os = "android")] - TunnelStateTransition::Disconnected => TunnelState::Disconnected { location: None }, + TunnelStateTransition::Disconnected {} => TunnelState::Disconnected { location: None }, TunnelStateTransition::Connecting(endpoint) => { let feature_indicators = compute_feature_indicators( self.settings.settings(), diff --git a/mullvad-daemon/src/management_interface.rs b/mullvad-daemon/src/management_interface.rs index d6a34a3155..282dd8e397 100644 --- a/mullvad-daemon/src/management_interface.rs +++ b/mullvad-daemon/src/management_interface.rs @@ -1236,6 +1236,7 @@ impl ManagementService for ManagementServiceImpl { } } +#[allow(clippy::result_large_err)] impl ManagementServiceImpl { /// Sends a command to the daemon and maps the error to an RPC error. fn send_command_to_daemon(&self, command: DaemonCommand) -> Result<(), Status> { @@ -1459,7 +1460,7 @@ fn map_split_tunnel_error(error: talpid_core::split_tunnel::Error) -> Status { match &error { Error::RegisterIps(io_error) | Error::SetConfiguration(io_error) => { if io_error.kind() == std::io::ErrorKind::NotFound { - Status::not_found(format!("{}: {}", error, io_error)) + Status::not_found(format!("{error}: {io_error}")) } else { Status::unknown(error.to_string()) } diff --git a/mullvad-daemon/src/version/check.rs b/mullvad-daemon/src/version/check.rs index de2bbb7117..f977e829bd 100644 --- a/mullvad-daemon/src/version/check.rs +++ b/mullvad-daemon/src/version/check.rs @@ -373,7 +373,7 @@ fn do_version_check_in_background( fn version_check_inner( api: &ApiContext, min_metadata_version: usize, -) -> impl Future<Output = Result<VersionCache, Error>> { +) -> impl Future<Output = Result<VersionCache, Error>> + use<> { use mullvad_api::version::{AppVersionResponse, AppVersionResponse2}; let v1_endpoint = api.version_proxy.version_check( @@ -422,7 +422,7 @@ fn version_check_inner( api: &ApiContext, // NOTE: This is unused when `update` is disabled _min_metadata_version: usize, -) -> impl Future<Output = Result<VersionCache, Error>> { +) -> impl Future<Output = Result<VersionCache, Error>> + use<> { let v1_endpoint = api.version_proxy.version_check( mullvad_version::VERSION.to_owned(), PLATFORM, diff --git a/mullvad-daemon/src/version/router.rs b/mullvad-daemon/src/version/router.rs index a1b81ebabe..93498ca3dd 100644 --- a/mullvad-daemon/src/version/router.rs +++ b/mullvad-daemon/src/version/router.rs @@ -389,7 +389,10 @@ where let version_cache = match mem::replace(&mut self.state, State::NoVersion) { #[cfg(in_app_upgrade)] State::Downloaded { version_cache, .. } | State::Downloading { version_cache, .. } => { - log::warn!("Switching beta after updating resulted in new suggested upgrade: {:?}, aborting", new_app_version.suggested_upgrade); + log::warn!( + "Switching beta after updating resulted in new suggested upgrade: {:?}, aborting", + new_app_version.suggested_upgrade + ); version_cache } State::HasVersion { version_cache } => version_cache, @@ -500,7 +503,7 @@ async fn wait_for_update(state: &mut State) -> Option<AppVersionInfo> { match state { State::Downloading { version_cache, - ref mut downloader_handle, + downloader_handle, upgrading_to_version, .. } => match downloader_handle.await { @@ -866,7 +869,7 @@ mod test { .daemon_tx .unbounded_send(Message::GetLatestVersion(tx)) .unwrap(); - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); // Here, we play the role of `VersionUpdater`. // It should receive a version check request and send a version in response @@ -882,7 +885,7 @@ mod test { // On the next step, the router should receive the version info // and send it to as a response to the oneshot from `GetLatestVersion` // and to the daemon in the `version_event_receiver` channel. - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); let version_info = get_latest_version_rx .try_recv() .expect("Sender should not be dropped") @@ -940,7 +943,7 @@ mod test { ); // Drive the download to completion, and get the verified installer path - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); let verified_installer_path = match &version_router.state { State::Downloaded { version_cache, @@ -1080,7 +1083,7 @@ mod test { assert!(matches!(version_router.state, State::Downloading { .. }),); // Drive the download to completion - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); assert_eq!( app_upgrade_listener.try_recv().unwrap(), AppUpgradeEvent::DownloadStarting @@ -1093,7 +1096,7 @@ mod test { version_router.update_application(); // Verify that we can restart the download again - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); assert_eq!( app_upgrade_listener.try_recv().unwrap(), AppUpgradeEvent::DownloadStarting @@ -1114,7 +1117,7 @@ mod test { assert!(matches!(version_router.state, State::Downloading { .. }),); // Drive the download to completion - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); assert_eq!( app_upgrade_listener.try_recv().unwrap(), AppUpgradeEvent::DownloadStarting @@ -1131,7 +1134,7 @@ mod test { version_router.update_application(); // Verify that we can restart the download again - version_router.run_step().await; + assert_eq!(version_router.run_step().await, ControlFlow::Continue(())); assert_eq!( app_upgrade_listener.try_recv().unwrap(), AppUpgradeEvent::DownloadStarting diff --git a/mullvad-encrypted-dns-proxy/examples/forwarder.rs b/mullvad-encrypted-dns-proxy/examples/forwarder.rs index 00302886a2..cfa351f3b8 100644 --- a/mullvad-encrypted-dns-proxy/examples/forwarder.rs +++ b/mullvad-encrypted-dns-proxy/examples/forwarder.rs @@ -21,7 +21,7 @@ async fn main() { .into_iter() .find(|c| c.obfuscation.is_some()) .expect("No XOR config"); - println!("Proxy config in use: {:?}", proxy_config); + println!("Proxy config in use: {proxy_config:?}"); let listener = TcpListener::bind(bind_addr) .await diff --git a/mullvad-ios/src/ephemeral_peer_proxy/ios_tcp_connection.rs b/mullvad-ios/src/ephemeral_peer_proxy/ios_tcp_connection.rs index 9e52227208..ee31f5a38b 100644 --- a/mullvad-ios/src/ephemeral_peer_proxy/ios_tcp_connection.rs +++ b/mullvad-ios/src/ephemeral_peer_proxy/ios_tcp_connection.rs @@ -157,7 +157,7 @@ impl AsyncWrite for IosTcpConnection { let result = match ready!(handle.as_mut().poll(cx)) { Ok(Ok(written)) => Ok(written.len()), Ok(Err(e)) => Err(e), - Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Write task panicked")), + Err(_) => Err(io::Error::other("Write task panicked")), }; // important to clear the in flight write here. self.in_flight_write = None; @@ -175,10 +175,7 @@ impl AsyncWrite for IosTcpConnection { // `funcs.send_fn` must be a valid function pointer. let result = unsafe { funcs.send(tunnel_handle, socket_handle, data.as_slice()) }; if result < 0 { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Write error: {}", result), - )) + Err(io::Error::other(format!("Write error: {result}"))) } else { Ok(data[..result as usize].to_vec()) } @@ -223,7 +220,7 @@ impl AsyncRead for IosTcpConnection { Ok(()) } Ok(Err(e)) => Err(e), - Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Read task panicked")), + Err(_) => Err(io::Error::other("Read task panicked")), }; // Clear the in-flight read, since the read task finished self.in_flight_read = None; @@ -245,10 +242,7 @@ impl AsyncRead for IosTcpConnection { Ok(buffer) } - errval @ ..0 => Err(io::Error::new( - io::ErrorKind::Other, - format!("Read error: {}", errval), - )), + errval @ ..0 => Err(io::Error::other(format!("Read error: {errval}"))), 0 => Err(connection_closed_err()), } diff --git a/mullvad-ios/src/shadowsocks_proxy/mod.rs b/mullvad-ios/src/shadowsocks_proxy/mod.rs index f0eedeeacc..3e3b7b151f 100644 --- a/mullvad-ios/src/shadowsocks_proxy/mod.rs +++ b/mullvad-ios/src/shadowsocks_proxy/mod.rs @@ -74,7 +74,6 @@ impl ShadowsocksService { let _ = Server::new(config) .await - .map_err(io::Error::from) .expect("Could not create Shadowsocks server") .run() .await; @@ -99,7 +98,7 @@ impl ShadowsocksService { Err(err) => { return Err(io::Error::new( io::ErrorKind::InvalidInput, - format!("Invalid cipher specified: {}", err), + format!("Invalid cipher specified: {err}"), )); } }; diff --git a/mullvad-management-interface/src/client.rs b/mullvad-management-interface/src/client.rs index 93a31a5042..1ea9578993 100644 --- a/mullvad-management-interface/src/client.rs +++ b/mullvad-management-interface/src/client.rs @@ -97,64 +97,36 @@ impl MullvadProxyClient { } pub async fn connect_tunnel(&mut self) -> Result<bool> { - Ok(self - .0 - .connect_tunnel(()) - .await - .map_err(Error::Rpc)? - .into_inner()) + Ok(self.0.connect_tunnel(()).await?.into_inner()) } pub async fn disconnect_tunnel(&mut self) -> Result<bool> { - Ok(self - .0 - .disconnect_tunnel(()) - .await - .map_err(Error::Rpc)? - .into_inner()) + Ok(self.0.disconnect_tunnel(()).await?.into_inner()) } pub async fn reconnect_tunnel(&mut self) -> Result<bool> { - Ok(self - .0 - .reconnect_tunnel(()) - .await - .map_err(Error::Rpc)? - .into_inner()) + Ok(self.0.reconnect_tunnel(()).await?.into_inner()) } pub async fn get_tunnel_state(&mut self) -> Result<TunnelState> { - let state = self - .0 - .get_tunnel_state(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let state = self.0.get_tunnel_state(()).await?.into_inner(); TunnelState::try_from(state).map_err(Error::InvalidResponse) } pub async fn events_listen<'a>( &mut self, ) -> Result<impl Stream<Item = Result<DaemonEvent>> + 'a> { - let listener = self - .0 - .events_listen(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let listener = self.0.events_listen(()).await?.into_inner(); Ok(listener.map(|item| { - let event = item - .map_err(Error::Rpc)? - .event - .ok_or(Error::MissingDaemonEvent)?; + let event = item?.event.ok_or(Error::MissingDaemonEvent)?; DaemonEvent::try_from(event) })) } /// DEPRECATED: Prefer to use `prepare_restart_v2`. pub async fn prepare_restart(&mut self) -> Result<()> { - self.0.prepare_restart(()).await.map_err(Error::Rpc)?; + self.0.prepare_restart(()).await?; Ok(()) } @@ -164,44 +136,26 @@ impl MullvadProxyClient { /// - `shutdown`: Whether the daemon should shutdown immediately after its prepare-for-restart /// routine. pub async fn prepare_restart_v2(&mut self, shutdown: bool) -> Result<()> { - self.0 - .prepare_restart_v2(shutdown) - .await - .map_err(Error::Rpc)?; + self.0.prepare_restart_v2(shutdown).await?; Ok(()) } pub async fn factory_reset(&mut self) -> Result<()> { - self.0.factory_reset(()).await.map_err(Error::Rpc)?; + self.0.factory_reset(()).await?; Ok(()) } pub async fn get_current_version(&mut self) -> Result<String> { - Ok(self - .0 - .get_current_version(()) - .await - .map_err(Error::Rpc)? - .into_inner()) + Ok(self.0.get_current_version(()).await?.into_inner()) } pub async fn get_version_info(&mut self) -> Result<AppVersionInfo> { - let version_info = self - .0 - .get_version_info(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let version_info = self.0.get_version_info(()).await?.into_inner(); AppVersionInfo::try_from(version_info).map_err(Error::InvalidResponse) } pub async fn get_relay_locations(&mut self) -> Result<RelayList> { - let list = self - .0 - .get_relay_locations(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let list = self.0.get_relay_locations(()).await?.into_inner(); mullvad_types::relay_list::RelayList::try_from(list).map_err(Error::InvalidResponse) } @@ -209,8 +163,7 @@ impl MullvadProxyClient { let access_method_settings = self .0 .get_settings(()) - .await - .map_err(Error::Rpc)? + .await? .into_inner() .api_access_methods .ok_or(Error::ApiAccessMethodSettingsNotFound) @@ -237,7 +190,7 @@ impl MullvadProxyClient { self.0 .get_current_api_access_method(()) .await - .map_err(Error::Rpc) + .map_err(Error::from) .map(tonic::Response::into_inner) .and_then(|access_method| { AccessMethodSetting::try_from(access_method).map_err(Error::InvalidResponse) @@ -248,8 +201,7 @@ impl MullvadProxyClient { let result = self .0 .test_api_access_method_by_id(types::Uuid::from(id)) - .await - .map_err(Error::Rpc)?; + .await?; Ok(result.into_inner()) } @@ -260,111 +212,85 @@ impl MullvadProxyClient { let result = self .0 .test_custom_api_access_method(types::CustomProxy::from(config)) - .await - .map_err(Error::Rpc)?; + .await?; Ok(result.into_inner()) } pub async fn update_relay_locations(&mut self) -> Result<()> { - self.0 - .update_relay_locations(()) - .await - .map_err(Error::Rpc)?; + self.0.update_relay_locations(()).await?; Ok(()) } pub async fn set_relay_settings(&mut self, update: RelaySettings) -> Result<()> { let update = types::RelaySettings::from(update); - self.0 - .set_relay_settings(update) - .await - .map_err(Error::Rpc)?; + self.0.set_relay_settings(update).await?; Ok(()) } pub async fn set_bridge_settings(&mut self, settings: BridgeSettings) -> Result<()> { let settings = types::BridgeSettings::from(settings); - self.0 - .set_bridge_settings(settings) - .await - .map_err(Error::Rpc)?; + self.0.set_bridge_settings(settings).await?; Ok(()) } pub async fn set_bridge_state(&mut self, state: BridgeState) -> Result<()> { let state = types::BridgeState::from(state); - self.0.set_bridge_state(state).await.map_err(Error::Rpc)?; + self.0.set_bridge_state(state).await?; Ok(()) } pub async fn set_obfuscation_settings(&mut self, settings: ObfuscationSettings) -> Result<()> { let settings = types::ObfuscationSettings::from(&settings); - self.0 - .set_obfuscation_settings(settings) - .await - .map_err(Error::Rpc)?; + self.0.set_obfuscation_settings(settings).await?; Ok(()) } pub async fn get_settings(&mut self) -> Result<Settings> { - let settings = self - .0 - .get_settings(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let settings = self.0.get_settings(()).await?.into_inner(); Settings::try_from(settings).map_err(Error::InvalidResponse) } pub async fn reset_settings(&mut self) -> Result<()> { - self.0.reset_settings(()).await.map_err(Error::Rpc)?; + self.0.reset_settings(()).await?; Ok(()) } pub async fn set_allow_lan(&mut self, state: bool) -> Result<()> { - self.0.set_allow_lan(state).await.map_err(Error::Rpc)?; + self.0.set_allow_lan(state).await?; Ok(()) } pub async fn set_show_beta_releases(&mut self, state: bool) -> Result<()> { - self.0 - .set_show_beta_releases(state) - .await - .map_err(Error::Rpc)?; + self.0.set_show_beta_releases(state).await?; Ok(()) } pub async fn set_block_when_disconnected(&mut self, state: bool) -> Result<()> { - self.0 - .set_block_when_disconnected(state) - .await - .map_err(Error::Rpc)?; + self.0.set_block_when_disconnected(state).await?; Ok(()) } pub async fn set_auto_connect(&mut self, state: bool) -> Result<()> { - self.0.set_auto_connect(state).await.map_err(Error::Rpc)?; + self.0.set_auto_connect(state).await?; Ok(()) } pub async fn set_openvpn_mssfix(&mut self, mssfix: Option<u16>) -> Result<()> { self.0 .set_openvpn_mssfix(mssfix.map(u32::from).unwrap_or(0)) - .await - .map_err(Error::Rpc)?; + .await?; Ok(()) } pub async fn set_wireguard_mtu(&mut self, mtu: Option<u16>) -> Result<()> { self.0 .set_wireguard_mtu(mtu.map(u32::from).unwrap_or(0)) - .await - .map_err(Error::Rpc)?; + .await?; Ok(()) } pub async fn set_enable_ipv6(&mut self, state: bool) -> Result<()> { - self.0.set_enable_ipv6(state).await.map_err(Error::Rpc)?; + self.0.set_enable_ipv6(state).await?; Ok(()) } @@ -373,58 +299,43 @@ impl MullvadProxyClient { state: QuantumResistantState, ) -> Result<()> { let state = types::QuantumResistantState::from(state); - self.0 - .set_quantum_resistant_tunnel(state) - .await - .map_err(Error::Rpc)?; + self.0.set_quantum_resistant_tunnel(state).await?; Ok(()) } #[cfg(daita)] pub async fn set_enable_daita(&mut self, value: bool) -> Result<()> { - self.0.set_enable_daita(value).await.map_err(Error::Rpc)?; + self.0.set_enable_daita(value).await?; Ok(()) } #[cfg(daita)] pub async fn set_daita_direct_only(&mut self, value: bool) -> Result<()> { - self.0 - .set_daita_direct_only(value) - .await - .map_err(Error::Rpc)?; + self.0.set_daita_direct_only(value).await?; Ok(()) } #[cfg(daita)] pub async fn set_daita_settings(&mut self, settings: DaitaSettings) -> Result<()> { let settings = types::DaitaSettings::from(settings); - self.0 - .set_daita_settings(settings) - .await - .map_err(Error::Rpc)?; + self.0.set_daita_settings(settings).await?; Ok(()) } pub async fn set_dns_options(&mut self, options: DnsOptions) -> Result<()> { let options = types::DnsOptions::from(&options); - self.0.set_dns_options(options).await.map_err(Error::Rpc)?; + self.0.set_dns_options(options).await?; Ok(()) } pub async fn set_relay_override(&mut self, relay_override: RelayOverride) -> Result<()> { let r#override = types::RelayOverride::from(relay_override); - self.0 - .set_relay_override(r#override) - .await - .map_err(Error::Rpc)?; + self.0.set_relay_override(r#override).await?; Ok(()) } pub async fn clear_all_relay_overrides(&mut self) -> Result<()> { - self.0 - .clear_all_relay_overrides(()) - .await - .map_err(Error::Rpc)?; + self.0.clear_all_relay_overrides(()).await?; Ok(()) } @@ -446,32 +357,22 @@ impl MullvadProxyClient { } pub async fn logout_account(&mut self) -> Result<()> { - self.0.logout_account(()).await.map_err(Error::Rpc)?; + self.0.logout_account(()).await?; Ok(()) } pub async fn get_account_data(&mut self, account: AccountNumber) -> Result<AccountData> { - let data = self - .0 - .get_account_data(account) - .await - .map_err(Error::Rpc)? - .into_inner(); + let data = self.0.get_account_data(account).await?.into_inner(); AccountData::try_from(data).map_err(Error::InvalidResponse) } pub async fn get_account_history(&mut self) -> Result<Option<AccountNumber>> { - let history = self - .0 - .get_account_history(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let history = self.0.get_account_history(()).await?.into_inner(); Ok(history.number) } pub async fn clear_account_history(&mut self) -> Result<()> { - self.0.clear_account_history(()).await.map_err(Error::Rpc)?; + self.0.clear_account_history(()).await?; Ok(()) } @@ -485,7 +386,7 @@ impl MullvadProxyClient { .map_err(|error| match error.code() { Code::NotFound => Error::InvalidVoucher, Code::ResourceExhausted => Error::UsedVoucher, - _other => Error::Rpc(error), + _other => Error::Rpc(Box::new(error)), })? .into_inner(); VoucherSubmission::try_from(result).map_err(Error::InvalidResponse) @@ -540,33 +441,22 @@ impl MullvadProxyClient { ) -> Result<()> { let duration = types::Duration::try_from(*interval.as_duration()) .map_err(|_| Error::DurationTooLarge)?; - self.0 - .set_wireguard_rotation_interval(duration) - .await - .map_err(Error::Rpc)?; + self.0.set_wireguard_rotation_interval(duration).await?; Ok(()) } pub async fn reset_wireguard_rotation_interval(&mut self) -> Result<()> { - self.0 - .reset_wireguard_rotation_interval(()) - .await - .map_err(Error::Rpc)?; + self.0.reset_wireguard_rotation_interval(()).await?; Ok(()) } pub async fn rotate_wireguard_key(&mut self) -> Result<()> { - self.0.rotate_wireguard_key(()).await.map_err(Error::Rpc)?; + self.0.rotate_wireguard_key(()).await?; Ok(()) } pub async fn get_wireguard_key(&mut self) -> Result<PublicKey> { - let key = self - .0 - .get_wireguard_key(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let key = self.0.get_wireguard_key(()).await?.into_inner(); PublicKey::try_from(key).map_err(Error::InvalidResponse) } @@ -620,11 +510,8 @@ impl MullvadProxyClient { enabled, access_method: Some(types::AccessMethod::from(access_method)), }; - self.0 - .add_api_access_method(request) - .await - .map_err(Error::Rpc) - .map(drop) + self.0.add_api_access_method(request).await?; + Ok(()) } pub async fn remove_access_method( @@ -633,9 +520,8 @@ impl MullvadProxyClient { ) -> Result<()> { self.0 .remove_api_access_method(types::Uuid::from(api_access_method)) - .await - .map_err(Error::Rpc) - .map(drop) + .await?; + Ok(()) } pub async fn update_access_method( @@ -644,107 +530,71 @@ impl MullvadProxyClient { ) -> Result<()> { self.0 .update_api_access_method(types::AccessMethodSetting::from(access_method_update)) - .await - .map_err(Error::Rpc) - .map(drop) + .await?; + Ok(()) } /// Remove all custom API access methods. pub async fn clear_custom_access_methods(&mut self) -> Result<()> { - self.0 - .clear_custom_api_access_methods(()) - .await - .map_err(Error::Rpc) - .map(drop) + self.0.clear_custom_api_access_methods(()).await?; + Ok(()) } /// Set the [`AccessMethod`] which `AccessModeSelector` should pick. pub async fn set_access_method(&mut self, api_access_method: access_method::Id) -> Result<()> { self.0 .set_api_access_method(types::Uuid::from(api_access_method)) - .await - .map_err(Error::Rpc) - .map(drop) + .await?; + Ok(()) } pub async fn get_split_tunnel_processes(&mut self) -> Result<Vec<i32>> { use futures::TryStreamExt; - let procs = self - .0 - .get_split_tunnel_processes(()) - .await - .map_err(Error::Rpc)? - .into_inner(); - procs.try_collect().await.map_err(Error::Rpc) + let procs = self.0.get_split_tunnel_processes(()).await?.into_inner(); + procs.try_collect().await.map_err(Error::from) } pub async fn add_split_tunnel_process(&mut self, pid: i32) -> Result<()> { - self.0 - .add_split_tunnel_process(pid) - .await - .map_err(Error::Rpc)?; + self.0.add_split_tunnel_process(pid).await?; Ok(()) } pub async fn remove_split_tunnel_process(&mut self, pid: i32) -> Result<()> { - self.0 - .remove_split_tunnel_process(pid) - .await - .map_err(Error::Rpc)?; + self.0.remove_split_tunnel_process(pid).await?; Ok(()) } pub async fn clear_split_tunnel_processes(&mut self) -> Result<()> { - self.0 - .clear_split_tunnel_processes(()) - .await - .map_err(Error::Rpc)?; + self.0.clear_split_tunnel_processes(()).await?; Ok(()) } pub async fn add_split_tunnel_app<P: AsRef<Path>>(&mut self, path: P) -> Result<()> { let path = path.as_ref().to_str().ok_or(Error::PathMustBeUtf8)?; - self.0 - .add_split_tunnel_app(path.to_owned()) - .await - .map_err(Error::Rpc)?; + self.0.add_split_tunnel_app(path.to_owned()).await?; Ok(()) } pub async fn remove_split_tunnel_app<P: AsRef<Path>>(&mut self, path: P) -> Result<()> { let path = path.as_ref().to_str().ok_or(Error::PathMustBeUtf8)?; - self.0 - .remove_split_tunnel_app(path.to_owned()) - .await - .map_err(Error::Rpc)?; + self.0.remove_split_tunnel_app(path.to_owned()).await?; Ok(()) } pub async fn clear_split_tunnel_apps(&mut self) -> Result<()> { - self.0 - .clear_split_tunnel_apps(()) - .await - .map_err(Error::Rpc)?; + self.0.clear_split_tunnel_apps(()).await?; Ok(()) } pub async fn set_split_tunnel_state(&mut self, state: bool) -> Result<()> { - self.0 - .set_split_tunnel_state(state) - .await - .map_err(Error::Rpc)?; + self.0.set_split_tunnel_state(state).await?; Ok(()) } #[cfg(target_os = "windows")] pub async fn get_excluded_processes(&mut self) -> Result<Vec<ExcludedProcess>> { - let procs = self - .0 - .get_excluded_processes(()) - .await - .map_err(Error::Rpc)? - .into_inner(); + let procs = self.0.get_excluded_processes(()).await?.into_inner(); Ok(procs .processes .into_iter() @@ -755,32 +605,29 @@ impl MullvadProxyClient { // check_volumes pub async fn apply_json_settings(&mut self, blob: String) -> Result<()> { - self.0.apply_json_settings(blob).await.map_err(Error::Rpc)?; + self.0.apply_json_settings(blob).await?; Ok(()) } pub async fn export_json_settings(&mut self) -> Result<String> { - let blob = self.0.export_json_settings(()).await.map_err(Error::Rpc)?; + let blob = self.0.export_json_settings(()).await?; Ok(blob.into_inner()) } pub async fn get_feature_indicators(&mut self) -> Result<FeatureIndicators> { - self.0 - .get_feature_indicators(()) - .await - .map_err(Error::Rpc) - .map(|response| response.into_inner()) - .map(FeatureIndicators::from) + Ok(FeatureIndicators::from( + self.0.get_feature_indicators(()).await?.into_inner(), + )) } // Debug features pub async fn disable_relay(&mut self, relay: String) -> Result<()> { - self.0.disable_relay(relay).await.map_err(Error::Rpc)?; + self.0.disable_relay(relay).await?; Ok(()) } pub async fn enable_relay(&mut self, relay: String) -> Result<()> { - self.0.enable_relay(relay).await.map_err(Error::Rpc)?; + self.0.enable_relay(relay).await?; Ok(()) } @@ -789,8 +636,7 @@ impl MullvadProxyClient { .set_wireguard_allowed_ips(types::AllowedIpsList { values: allowed_ips.0.iter().map(ToString::to_string).collect(), }) - .await - .map_err(Error::Rpc)?; + .await?; Ok(()) } } @@ -802,7 +648,7 @@ fn map_device_error(status: Status) -> Error { Code::Unauthenticated => Error::InvalidAccount, Code::AlreadyExists => Error::AlreadyLoggedIn, Code::NotFound => Error::DeviceNotFound, - _other => Error::Rpc(status), + _other => Error::Rpc(Box::new(status)), } } @@ -813,16 +659,16 @@ fn map_custom_list_error(status: Status) -> Error { if status.details() == crate::CUSTOM_LIST_LIST_NOT_FOUND_DETAILS { Error::CustomListListNotFound } else { - Error::Rpc(status) + Error::Rpc(Box::new(status)) } } Code::AlreadyExists => { if status.details() == crate::CUSTOM_LIST_LIST_EXISTS_DETAILS { Error::CustomListExists } else { - Error::Rpc(status) + Error::Rpc(Box::new(status)) } } - _other => Error::Rpc(status), + _other => Error::Rpc(Box::new(status)), } } diff --git a/mullvad-management-interface/src/lib.rs b/mullvad-management-interface/src/lib.rs index b26f29fe71..3ca10dfc57 100644 --- a/mullvad-management-interface/src/lib.rs +++ b/mullvad-management-interface/src/lib.rs @@ -59,8 +59,10 @@ pub enum Error { #[error("Failed to set group ID")] SetGidError(#[source] nix::Error), + // TODO: Remove box when upgrading tonic to a version with + // https://github.com/hyperium/tonic/pull/2282 #[error("gRPC call returned error")] - Rpc(#[source] tonic::Status), + Rpc(#[source] Box<tonic::Status>), #[error("Failed to parse gRPC response")] InvalidResponse(#[source] types::FromProtobufTypeError), @@ -114,6 +116,12 @@ pub enum Error { ApiAccessMethodNotFound, } +impl From<tonic::Status> for Error { + fn from(value: tonic::Status) -> Self { + Error::Rpc(Box::new(value)) + } +} + #[cfg(not(target_os = "android"))] #[deprecated(note = "Prefer MullvadProxyClient")] pub async fn new_rpc_client() -> Result<ManagementServiceClient, Error> { diff --git a/mullvad-paths/src/windows.rs b/mullvad-paths/src/windows.rs index 5bab1c68f3..5b1bd5758f 100644 --- a/mullvad-paths/src/windows.rs +++ b/mullvad-paths/src/windows.rs @@ -138,7 +138,7 @@ fn create_dir_recursive_with_permissions( return Err(Error::CreateDirFailed( format!("Could not create directory at {}", path.display()), e, - )) + )); } } @@ -150,10 +150,7 @@ fn create_dir_recursive_with_permissions( // reason return Err(Error::CreateDirFailed( path.display().to_string(), - io::Error::new( - io::ErrorKind::Other, - "reached top of directory tree but could not create directory", - ), + io::Error::other("reached top of directory tree but could not create directory"), )); } } diff --git a/mullvad-problem-report/src/lib.rs b/mullvad-problem-report/src/lib.rs index 415d0d617a..2c01523dbb 100644 --- a/mullvad-problem-report/src/lib.rs +++ b/mullvad-problem-report/src/lib.rs @@ -653,7 +653,7 @@ mod tests { #[cfg(windows)] fn redacts_home_dir() { let assert_redacts_home_dir = |home_dir, test_str| { - let input = format!(r"pre {}\remaining\path post", test_str); + let input = format!(r"pre {test_str}\remaining\path post"); let actual = redact_home_dir_inner(&input, Some(PathBuf::from(home_dir))); assert_eq!(r"pre ~\remaining\path post", actual); }; diff --git a/mullvad-relay-selector/tests/relay_selector.rs b/mullvad-relay-selector/tests/relay_selector.rs index 91cadb88a6..c104d84015 100644 --- a/mullvad-relay-selector/tests/relay_selector.rs +++ b/mullvad-relay-selector/tests/relay_selector.rs @@ -864,7 +864,7 @@ fn test_selecting_wireguard_over_shadowsocks_extra_ips() { } => { assert!(!exit.overridden_ipv4); assert!(!exit.overridden_ipv6); - assert!(SHADOWSOCKS_RELAY_EXTRA_ADDRS.contains(&endpoint.ip()), "{} is not an additional IP", endpoint); + assert!(SHADOWSOCKS_RELAY_EXTRA_ADDRS.contains(&endpoint.ip()), "{endpoint} is not an additional IP"); } wrong_relay => panic!( "Relay selector should have picked a Wireguard relay with Shadowsocks, instead chose {wrong_relay:?}" @@ -1084,8 +1084,7 @@ fn test_load_balancing() { RelayQueryBuilder::openvpn().location(location).build(), ] { // Collect the range of unique relay ports and IP addresses over a large number of queries. - let (ports, ips): (HashSet<u16>, HashSet<std::net::IpAddr>) = std::iter::repeat(query.clone()) - .take(ATTEMPTS) + let (ports, ips): (HashSet<u16>, HashSet<std::net::IpAddr>) = std::iter::repeat_n(query.clone(), ATTEMPTS) // Execute the query .map(|query| relay_selector.get_relay_by_query(query).unwrap()) // Perform some plumbing .. @@ -1624,7 +1623,7 @@ fn valid_user_setting_should_yield_relay() { let post_unification_result = relay_selector.get_relay(retry_attempt, talpid_types::net::IpAvailability::Ipv4); if user_result.is_ok() { - assert!(post_unification_result.is_ok(), "Expected Post-unification query to be valid because original query {:#?} yielded a connection configuration", user_query) + assert!(post_unification_result.is_ok(), "Expected Post-unification query to be valid because original query {user_query:#?} yielded a connection configuration") } } } diff --git a/mullvad-types/src/relay_constraints.rs b/mullvad-types/src/relay_constraints.rs index 192386ddec..6c33976f5e 100644 --- a/mullvad-types/src/relay_constraints.rs +++ b/mullvad-types/src/relay_constraints.rs @@ -105,7 +105,7 @@ impl From<GeographicLocationConstraint> for LocationConstraint { impl fmt::Display for LocationConstraintFormatter<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.constraint { - LocationConstraint::Location(location) => write!(f, "{}", location), + LocationConstraint::Location(location) => write!(f, "{location}"), LocationConstraint::CustomList { list_id } => self .custom_lists .iter() @@ -562,10 +562,10 @@ impl fmt::Display for WireguardConstraintsFormatter<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.constraints.port { Constraint::Any => write!(f, "any port")?, - Constraint::Only(port) => write!(f, "port {}", port)?, + Constraint::Only(port) => write!(f, "port {port}")?, } if let Constraint::Only(ip_version) = self.constraints.ip_version { - write!(f, ", {},", ip_version)?; + write!(f, ", {ip_version},")?; } if self.constraints.multihop() { let location = self.constraints.entry_location.as_ref().map(|location| { @@ -574,7 +574,7 @@ impl fmt::Display for WireguardConstraintsFormatter<'_> { custom_lists: self.custom_lists, } }); - write!(f, ", multihop entry {}", location)?; + write!(f, ", multihop entry {location}")?; } Ok(()) } @@ -743,7 +743,7 @@ impl fmt::Display for BridgeConstraintsFormatter<'_> { write!(f, " using ")?; match self.constraints.providers { Constraint::Any => write!(f, "any provider")?, - Constraint::Only(ref constraint) => write!(f, "{}", constraint)?, + Constraint::Only(ref constraint) => write!(f, "{constraint}")?, } match self.constraints.ownership { Constraint::Any => Ok(()), diff --git a/mullvad-update/mullvad-release/src/artifacts.rs b/mullvad-update/mullvad-release/src/artifacts.rs index 8617c0deaf..f70cd35ec7 100644 --- a/mullvad-update/mullvad-release/src/artifacts.rs +++ b/mullvad-update/mullvad-release/src/artifacts.rs @@ -56,7 +56,7 @@ fn derive_urls( .iter() .map(|base_url| { let url = base_url.strip_suffix("/").unwrap_or(base_url); - format!("{url}/{version}/{}", filename) + format!("{url}/{version}/{filename}") }) .collect() } diff --git a/talpid-core/build.rs b/talpid-core/build.rs index 65f7a9125e..d591cefb81 100644 --- a/talpid-core/build.rs +++ b/talpid-core/build.rs @@ -18,7 +18,7 @@ mod win { "i686-pc-windows-msvc" => format!("Win32-{}", get_build_mode()), "x86_64-pc-windows-msvc" => format!("x64-{}", get_build_mode()), "aarch64-pc-windows-msvc" => format!("ARM64-{}", get_build_mode()), - _ => panic!("unrecognized target: {}", target), + _ => panic!("unrecognized target: {target}"), }; target_dir.into() } @@ -33,12 +33,12 @@ mod win { } pub fn declare_library(env_var: &str, default_dir: &str, lib_name: &str) { - println!("cargo::rerun-if-env-changed={}", env_var); + println!("cargo::rerun-if-env-changed={env_var}"); let lib_dir = env::var_os(env_var) .map(PathBuf::from) .unwrap_or_else(|| default_windows_build_artifact_dir(default_dir)); println!("cargo::rustc-link-search={}", lib_dir.display()); - println!("cargo::rustc-link-lib=dylib={}", lib_name); + println!("cargo::rustc-link-lib=dylib={lib_name}"); } pub fn manifest_dir() -> PathBuf { diff --git a/talpid-core/src/connectivity_listener.rs b/talpid-core/src/connectivity_listener.rs index 57015fc9fe..8bba54d1cb 100644 --- a/talpid-core/src/connectivity_listener.rs +++ b/talpid-core/src/connectivity_listener.rs @@ -75,7 +75,7 @@ impl ConnectivityListener { return Err(Error::InvalidMethodResult( "MullvadVpnService", "getConnectivityListener", - format!("{:?}", value), + format!("{value:?}"), )) } }; @@ -126,7 +126,7 @@ impl ConnectivityListener { return Err(Error::InvalidMethodResult( "ConnectivityListener", "isConnected", - format!("{:?}", value), + format!("{value:?}"), )) } }; @@ -154,7 +154,7 @@ impl ConnectivityListener { value => Err(Error::InvalidMethodResult( "ConnectivityListener", "getCurrentDnsServers", - format!("{:?}", value), + format!("{value:?}"), )), } } diff --git a/talpid-core/src/dns/mod.rs b/talpid-core/src/dns/mod.rs index b3b3da1310..131344a2c0 100644 --- a/talpid-core/src/dns/mod.rs +++ b/talpid-core/src/dns/mod.rs @@ -128,7 +128,7 @@ impl ResolvedDnsConfig { if i > 0 { f.write_str(", ")?; } - write!(f, "{}", addr)?; + write!(f, "{addr}")?; } f.write_str("}") } diff --git a/talpid-core/src/firewall/windows/winfw/sys.rs b/talpid-core/src/firewall/windows/winfw/sys.rs index 3349205cf3..44631c0b54 100644 --- a/talpid-core/src/firewall/windows/winfw/sys.rs +++ b/talpid-core/src/firewall/windows/winfw/sys.rs @@ -201,7 +201,7 @@ pub extern "system" fn log_sink( &log::Record::builder() .level(level) .target(&target) - .args(format_args!("{}", managed_msg)) + .args(format_args!("{managed_msg}")) .build(), ); } diff --git a/talpid-core/src/split_tunnel/windows/driver.rs b/talpid-core/src/split_tunnel/windows/driver.rs index 9625e41406..ab0d73d6f0 100644 --- a/talpid-core/src/split_tunnel/windows/driver.rs +++ b/talpid-core/src/split_tunnel/windows/driver.rs @@ -350,8 +350,7 @@ impl DeviceHandle { let raw_state: u64 = unsafe { deserialize_buffer(&buffer[0..size_of::<u64>()]) }; - DriverState::try_from(raw_state) - .map_err(|error| io::Error::new(io::ErrorKind::Other, error)) + DriverState::try_from(raw_state).map_err(io::Error::other) } pub fn set_config<T: AsRef<OsStr>>(&self, apps: &[T]) -> io::Result<()> { @@ -864,10 +863,7 @@ pub unsafe fn device_io_control_buffer_async( }; if result != 0 { - return Err(io::Error::new( - io::ErrorKind::Other, - "Expected pending operation", - )); + return Err(io::Error::other("Expected pending operation")); } let last_error = io::Error::last_os_error(); @@ -926,7 +922,7 @@ pub unsafe fn wait_for_single_object(object: HANDLE, timeout: Option<Duration>) match result { WAIT_OBJECT_0 => Ok(()), WAIT_FAILED => Err(io::Error::last_os_error()), - WAIT_ABANDONED => Err(io::Error::new(io::ErrorKind::Other, "abandoned mutex")), + WAIT_ABANDONED => Err(io::Error::other("abandoned mutex")), error => Err(io::Error::from_raw_os_error(error as i32)), } } @@ -950,7 +946,7 @@ pub unsafe fn wait_for_multiple_objects(objects: &[HANDLE], wait_all: bool) -> i let signaled_index = if result < objects_len { result } else if result >= WAIT_ABANDONED_0 && result < WAIT_ABANDONED_0 + objects_len { - return Err(io::Error::new(io::ErrorKind::Other, "abandoned mutex")); + return Err(io::Error::other("abandoned mutex")); } else { return Err(io::Error::last_os_error()); }; diff --git a/talpid-core/src/split_tunnel/windows/mod.rs b/talpid-core/src/split_tunnel/windows/mod.rs index 4e87d5f113..82f86d0cbd 100644 --- a/talpid-core/src/split_tunnel/windows/mod.rs +++ b/talpid-core/src/split_tunnel/windows/mod.rs @@ -311,7 +311,7 @@ impl SplitTunnel { "{}", error.display_chain_with_msg("Failed to parse ST event buffer") ); - io::Error::new(io::ErrorKind::Other, "Failed to parse ST event buffer") + io::Error::other("Failed to parse ST event buffer") }) } @@ -521,7 +521,7 @@ impl SplitTunnel { std::thread::spawn(move || { while let Ok(()) = monitor_rx.recv() { let paths = monitored_paths_copy.lock().unwrap(); - let result = if paths.len() > 0 { + let result = if !paths.is_empty() { log::debug!("Re-resolving excluded paths"); handle_copy.set_config(&paths) } else { diff --git a/talpid-core/src/split_tunnel/windows/path_monitor.rs b/talpid-core/src/split_tunnel/windows/path_monitor.rs index ad8d9ca1a3..ed537578b7 100644 --- a/talpid-core/src/split_tunnel/windows/path_monitor.rs +++ b/talpid-core/src/split_tunnel/windows/path_monitor.rs @@ -686,7 +686,7 @@ impl PathMonitor { return None; } for (i, dir_context) in self.dir_contexts.iter().enumerate() { - if (&*dir_context.overlapped as *const _) == overlapped { + if std::ptr::eq(&*dir_context.overlapped, overlapped) { return Some(i); } } @@ -700,7 +700,7 @@ impl PathMonitor { } let mut was_discarded = false; self.discarded_contexts.retain(|ctx| { - if ((&*ctx.overlapped) as *const _) != overlapped { + if !std::ptr::eq(&*ctx.overlapped, overlapped) { true } else { was_discarded = true; @@ -795,7 +795,7 @@ impl PathMonitor { result } }; - contexts.retain(|ctx| ((&*ctx.overlapped) as *const _) != result.used_overlapped); + contexts.retain(|ctx| !std::ptr::eq(&*ctx.overlapped, result.used_overlapped)); } } } diff --git a/talpid-openvpn-plugin/src/lib.rs b/talpid-openvpn-plugin/src/lib.rs index 571991917d..2331278072 100644 --- a/talpid-openvpn-plugin/src/lib.rs +++ b/talpid-openvpn-plugin/src/lib.rs @@ -10,8 +10,10 @@ pub enum Error { #[error("No core server id given as first argument")] MissingCoreServerId, + // TODO: Remove box when upgrading tonic to a version with + // https://github.com/hyperium/tonic/pull/2282 #[error("Failed to send an event to daemon over the IPC channel")] - SendEvent(#[source] tonic::Status), + SendEvent(#[source] Box<tonic::Status>), #[error("Unable to start Tokio runtime")] CreateRuntime(#[source] io::Error), diff --git a/talpid-openvpn-plugin/src/processing.rs b/talpid-openvpn-plugin/src/processing.rs index cb2a422138..6a4bfced93 100644 --- a/talpid-openvpn-plugin/src/processing.rs +++ b/talpid-openvpn-plugin/src/processing.rs @@ -71,6 +71,9 @@ impl EventProcessor { .block_on(self.ipc_client.route_predown(details)), other => return Err(Error::UnhandledEvent(other)), }; - response.map(|_| ()).map_err(Error::SendEvent) + match response { + Ok(_) => Ok(()), + Err(e) => Err(Error::SendEvent(Box::new(e))), + } } } diff --git a/talpid-openvpn/src/lib.rs b/talpid-openvpn/src/lib.rs index 399bc3fa36..b923f75f09 100644 --- a/talpid-openvpn/src/lib.rs +++ b/talpid-openvpn/src/lib.rs @@ -905,12 +905,13 @@ mod event_server { Ok(Response::new(())) } + #[allow(clippy::result_large_err)] fn get_tunnel_metadata( env: &HashMap<String, String>, ) -> std::result::Result<TunnelMetadata, tonic::Status> { let tunnel_alias = env .get("dev") - .ok_or_else(|| tonic::Status::invalid_argument("missing tunnel alias"))? + .ok_or_else(|| (tonic::Status::invalid_argument("missing tunnel alias")))? .to_string(); let mut ips = vec![env @@ -1148,7 +1149,7 @@ mod tests { fn start(&self) -> io::Result<Self::ProcessHandle> { self.process_handle - .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "failed to start")) + .ok_or_else(|| io::Error::other("failed to start")) } } diff --git a/talpid-openvpn/src/proxy/shadowsocks.rs b/talpid-openvpn/src/proxy/shadowsocks.rs index 2b88f23068..2e795b62b2 100644 --- a/talpid-openvpn/src/proxy/shadowsocks.rs +++ b/talpid-openvpn/src/proxy/shadowsocks.rs @@ -61,12 +61,10 @@ impl ShadowsocksProxyMonitor { let server = ServerConfig::new( settings.endpoint, settings.password.clone(), - settings.cipher.parse().map_err(|_| { - io::Error::new( - io::ErrorKind::Other, - format!("Invalid cipher: {}", settings.cipher), - ) - })?, + settings + .cipher + .parse() + .map_err(|_| io::Error::other(format!("Invalid cipher: {}", settings.cipher)))?, ); config @@ -101,7 +99,7 @@ impl ShadowsocksProxyMonitor { } fn get_listener_addr(srv: &local::Server) -> io::Result<SocketAddr> { - let no_addr_err = || io::Error::new(io::ErrorKind::Other, "Missing listener address"); + let no_addr_err = || io::Error::other("Missing listener address"); let socks_server = srv.socks_servers().first().ok_or_else(no_addr_err)?; socks_server .tcp_server() diff --git a/talpid-platform-metadata/src/android.rs b/talpid-platform-metadata/src/android.rs index 1709223aa4..851c151080 100644 --- a/talpid-platform-metadata/src/android.rs +++ b/talpid-platform-metadata/src/android.rs @@ -12,16 +12,13 @@ pub fn version() -> String { get_prop("ro.product.manufacturer").unwrap_or_else(|| "Unknown brand".to_owned()); let product = get_prop("ro.product.model").unwrap_or_else(|| "Unknown model".to_owned()); - format!( - "Android {} (API: {}) - {} {}", - version, api_level, manufacturer, product - ) + format!("Android {version} (API: {api_level}) - {manufacturer} {product}") } pub fn short_version() -> String { let version = os_version(); - format!("Android {}", version) + format!("Android {version}") } fn os_version() -> String { diff --git a/talpid-platform-metadata/src/macos.rs b/talpid-platform-metadata/src/macos.rs index b4a279f0e1..97b6b14813 100644 --- a/talpid-platform-metadata/src/macos.rs +++ b/talpid-platform-metadata/src/macos.rs @@ -7,14 +7,14 @@ pub fn version() -> String { let version = MacosVersion::new() .map(|version| version.version()) .unwrap_or(String::from("N/A")); - format!("macOS {}", version) + format!("macOS {version}") } pub fn short_version() -> String { let version = MacosVersion::new() .map(|version| version.short_version()) .unwrap_or(String::from("N/A")); - format!("macOS {}", version) + format!("macOS {version}") } pub fn extra_metadata() -> impl Iterator<Item = (String, String)> { diff --git a/talpid-platform-metadata/src/windows.rs b/talpid-platform-metadata/src/windows.rs index 99e2f18b3c..ec2b7b82be 100644 --- a/talpid-platform-metadata/src/windows.rs +++ b/talpid-platform-metadata/src/windows.rs @@ -26,14 +26,14 @@ pub fn version() -> String { }) .unwrap_or_else(|_| ("N/A".to_owned(), "N/A".to_owned())); - format!("Windows {} Build {}", major, build) + format!("Windows {major} Build {build}") } pub fn short_version() -> String { let version_string = WindowsVersion::new() .map(|version| version.windows_version_string()) .unwrap_or("N/A".into()); - format!("Windows {}", version_string) + format!("Windows {version_string}") } pub fn extra_metadata() -> impl Iterator<Item = (String, String)> { diff --git a/talpid-routing/src/unix/android.rs b/talpid-routing/src/unix/android.rs index 4907d34c97..79d231b63c 100644 --- a/talpid-routing/src/unix/android.rs +++ b/talpid-routing/src/unix/android.rs @@ -231,7 +231,7 @@ fn current_network_state( return Err(JvmError::InvalidMethodResult( "MullvadVpnService", "getConnectivityListener", - format!("{:?}", value), + format!("{value:?}"), )) } }; diff --git a/talpid-routing/src/unix/linux.rs b/talpid-routing/src/unix/linux.rs index a43f0690bc..f258588c8a 100644 --- a/talpid-routing/src/unix/linux.rs +++ b/talpid-routing/src/unix/linux.rs @@ -804,7 +804,7 @@ impl RouteManagerImpl { let mut links = self.handle.link().get().execute(); let target_device = LinkNla::IfName(device); while let Some(msg) = links.try_next().await.map_err(|_| Error::LinkNotFound)? { - let found = msg.nlas.iter().any(|e| *e == target_device); + let found = msg.nlas.contains(&target_device); if found { if let Some(LinkNla::Mtu(mtu)) = msg.nlas.iter().find(|e| matches!(e, LinkNla::Mtu(_))) diff --git a/talpid-routing/src/unix/macos/watch.rs b/talpid-routing/src/unix/macos/watch.rs index e3f034a841..3cee2881aa 100644 --- a/talpid-routing/src/unix/macos/watch.rs +++ b/talpid-routing/src/unix/macos/watch.rs @@ -20,7 +20,7 @@ pub enum Error { Send(#[source] routing_socket::Error), /// Received unexpected response to route message #[error("Unexpected message type")] - UnexpectedMessageType(RouteSocketMessage, MessageType), + UnexpectedMessageType(Box<RouteSocketMessage>, MessageType), /// Route not found #[error("Route not found")] RouteNotFound, @@ -99,7 +99,7 @@ impl RoutingTable { Ok(anything_else) => { log::error!("Unexpected route message: {anything_else:?}"); Err(Error::UnexpectedMessageType( - anything_else, + Box::new(anything_else), MessageType::RTM_ADD, )) } @@ -145,7 +145,7 @@ impl RoutingTable { Err(Error::Deletion(route)) } anything_else => Err(Error::UnexpectedMessageType( - anything_else, + Box::new(anything_else), MessageType::RTM_DELETE, )), } @@ -178,7 +178,7 @@ impl RoutingTable { match data::RouteSocketMessage::parse_message(&response).map_err(Error::InvalidMessage)? { data::RouteSocketMessage::GetRoute(route) => Ok(Some(route)), unexpected_route_message => Err(Error::UnexpectedMessageType( - unexpected_route_message, + Box::new(unexpected_route_message), MessageType::RTM_GET, )), } diff --git a/talpid-routing/src/windows/default_route_monitor.rs b/talpid-routing/src/windows/default_route_monitor.rs index fd73684821..f70546fe5b 100644 --- a/talpid-routing/src/windows/default_route_monitor.rs +++ b/talpid-routing/src/windows/default_route_monitor.rs @@ -141,7 +141,7 @@ impl Drop for NotifyChangeHandle { if let Err(e) = win32_err!(unsafe { CancelMibChangeNotify2(self.0) }) { // If this callback is called after we free the context that could result in UB, in // order to avoid that we panic. - panic!("Could not cancel change notification callback: {}", e) + panic!("Could not cancel change notification callback: {e}") } } } diff --git a/talpid-routing/src/windows/route_manager.rs b/talpid-routing/src/windows/route_manager.rs index 5cfc4b72e7..d61c83b9a6 100644 --- a/talpid-routing/src/windows/route_manager.rs +++ b/talpid-routing/src/windows/route_manager.rs @@ -765,12 +765,9 @@ impl Adapters { log::error!( "Expecting IP_ADAPTER_ADDRESSES to have size {code_size} bytes. Found structure with size {system_size} bytes." ); - return Err(Error::Adapter(io::Error::new( - io::ErrorKind::Other, - format!( - "Expecting IP_ADAPTER_ADDRESSES to have size {code_size} bytes. Found structure with size {system_size} bytes." - ), - ))); + return Err(Error::Adapter(io::Error::other(format!( + "Expecting IP_ADAPTER_ADDRESSES to have size {code_size} bytes. Found structure with size {system_size} bytes." + )))); } // Initialize members. diff --git a/talpid-tunnel-config-client/src/lib.rs b/talpid-tunnel-config-client/src/lib.rs index 592a9bcaa9..a270314953 100644 --- a/talpid-tunnel-config-client/src/lib.rs +++ b/talpid-tunnel-config-client/src/lib.rs @@ -28,7 +28,9 @@ const DAITA_VERSION: u32 = 2; #[derive(Debug)] pub enum Error { GrpcConnectError(tonic::transport::Error), - GrpcError(tonic::Status), + // TODO: Remove box when upgrading tonic to a version with + // https://github.com/hyperium/tonic/pull/2282 + GrpcError(Box<tonic::Status>), MissingCiphertexts, InvalidCiphertextLength { algorithm: &'static str, @@ -156,7 +158,7 @@ pub async fn request_ephemeral_peer_with( }), }) .await - .map_err(Error::GrpcError)?; + .map_err(|status| Error::GrpcError(Box::new(status)))?; let response = response.into_inner(); diff --git a/talpid-tunnel/src/tun_provider/android/mod.rs b/talpid-tunnel/src/tun_provider/android/mod.rs index 590c19868a..5a4723031b 100644 --- a/talpid-tunnel/src/tun_provider/android/mod.rs +++ b/talpid-tunnel/src/tun_provider/android/mod.rs @@ -167,7 +167,7 @@ impl AndroidTunProvider { JValue::Object(result) => CreateTunResult::from_java(&env, result).into(), value => Err(Error::InvalidMethodResult( method_name, - format!("{:?}", value), + format!("{value:?}"), )), } } @@ -178,10 +178,7 @@ impl AndroidTunProvider { let error = match result { Ok(JValue::Void) => None, - Ok(value) => Some(Error::InvalidMethodResult( - "closeTun", - format!("{:?}", value), - )), + Ok(value) => Some(Error::InvalidMethodResult("closeTun", format!("{value:?}"))), Err(error) => Some(error), }; @@ -219,7 +216,7 @@ impl AndroidTunProvider { match result { JValue::Bool(0) => Err(Error::Bypass), JValue::Bool(_) => Ok(()), - value => Err(Error::InvalidMethodResult("bypass", format!("{:?}", value))), + value => Err(Error::InvalidMethodResult("bypass", format!("{value:?}"))), } } diff --git a/talpid-types/src/tunnel.rs b/talpid-types/src/tunnel.rs index ddd65d87b1..3dc7bdc308 100644 --- a/talpid-types/src/tunnel.rs +++ b/talpid-types/src/tunnel.rs @@ -16,7 +16,7 @@ pub enum TunnelStateTransition { }, #[cfg(target_os = "android")] /// No connection is established and network is unsecured. - Disconnected, + Disconnected {}, /// Network is secured but tunnel is still connecting. Connecting(TunnelEndpoint), /// Tunnel is connected. diff --git a/talpid-wireguard/src/lib.rs b/talpid-wireguard/src/lib.rs index 461a18eda4..217399e6be 100644 --- a/talpid-wireguard/src/lib.rs +++ b/talpid-wireguard/src/lib.rs @@ -898,7 +898,7 @@ impl WireguardMonitor { let gateway_routes = gateway_routes.map(|route| Self::apply_route_mtu_for_multihop(route, config)); - let routes = gateway_routes.chain( + gateway_routes.chain( config .get_tunnel_destinations() .filter(|allowed_ip| allowed_ip.prefix() != 0) @@ -909,9 +909,7 @@ impl WireguardMonitor { RequiredRoute::new(allowed_ip, node_v6.clone()) } }), - ); - - routes + ) } /// Return any 0.0.0.0/0 routes specified by the allowed IPs. diff --git a/talpid-wireguard/src/wireguard_nt/mod.rs b/talpid-wireguard/src/wireguard_nt/mod.rs index 43eb548491..34eee3b3d4 100644 --- a/talpid-wireguard/src/wireguard_nt/mod.rs +++ b/talpid-wireguard/src/wireguard_nt/mod.rs @@ -634,8 +634,7 @@ impl WgNtAdapter { fn name(&self) -> io::Result<U16CString> { net::alias_from_luid(&self.luid()).and_then(|alias| { - U16CString::from_os_str(alias) - .map_err(|_| io::Error::new(io::ErrorKind::Other, "unexpected null char")) + U16CString::from_os_str(alias).map_err(|_| io::Error::other("unexpected null char")) }) } diff --git a/test/test-manager/src/container.rs b/test/test-manager/src/container.rs index 19cde03ee4..88ba7d9a6b 100644 --- a/test/test-manager/src/container.rs +++ b/test/test-manager/src/container.rs @@ -29,7 +29,7 @@ pub async fn relaunch_with_rootlesskit(vnc_port: Option<u16>) { cmd.args(std::env::args()); let status = cmd.status().await.unwrap_or_else(|e| { - panic!("failed to execute [{:?}]: {}", cmd, e); + panic!("failed to execute [{cmd:?}]: {e}"); }); std::process::exit(status.code().unwrap_or(1)); diff --git a/test/test-manager/src/logging.rs b/test/test-manager/src/logging.rs index 4f7d6e1e91..75b3d3f5cd 100644 --- a/test/test-manager/src/logging.rs +++ b/test/test-manager/src/logging.rs @@ -219,7 +219,7 @@ impl TestOutput { format!( "TEST {} RETURNED ERROR: {}", self.test_name, - format!("{:?}", e).bold() + format!("{e:?}").bold() ) .red() ); diff --git a/test/test-manager/src/mullvad_daemon.rs b/test/test-manager/src/mullvad_daemon.rs index 8da149d329..f035c244bf 100644 --- a/test/test-manager/src/mullvad_daemon.rs +++ b/test/test-manager/src/mullvad_daemon.rs @@ -38,7 +38,7 @@ impl<Request> Service<Request> for DummyService { Box::pin(async move { notifier_tx .unbounded_send(TokioIo::new(channel_in)) - .map_err(|_| io::Error::new(io::ErrorKind::Other, "stream receiver is down"))?; + .map_err(|_| io::Error::other("stream receiver is down"))?; Ok(TokioIo::new(channel_out)) }) } diff --git a/test/test-manager/src/run_tests.rs b/test/test-manager/src/run_tests.rs index 54e563f704..513a10be71 100644 --- a/test/test-manager/src/run_tests.rs +++ b/test/test-manager/src/run_tests.rs @@ -232,7 +232,7 @@ where output.append(&mut output_after_test); } Err(e) => { - output.push(Output::Other(format!("could not get logs: {:?}", e))); + output.push(Output::Other(format!("could not get logs: {e:?}"))); } } } diff --git a/test/test-manager/src/summary.rs b/test/test-manager/src/summary.rs index f0c0723c48..373235caf6 100644 --- a/test/test-manager/src/summary.rs +++ b/test/test-manager/src/summary.rs @@ -210,7 +210,7 @@ pub async fn print_summary_table<P: AsRef<Path>>(summary_files: &[P]) { let counter_text = if total_passed == total_tests { String::from(TestResult::PASS_STR) } else { - format!("({}/{})", total_passed, total_tests) + format!("({total_passed}/{total_tests})") }; println!( "<td style='text-align: center;'>{} {}</td>", @@ -266,7 +266,7 @@ pub async fn print_summary_table<P: AsRef<Path>>(summary_files: &[P]) { } TestResult::Pass | TestResult::Skip => (), } - println!("<td style='text-align: center;'>{}</td>", result); + println!("<td style='text-align: center;'>{result}</td>"); } // Print a summary of all OSes at the end of the table // For each test, collect the result for each platform. diff --git a/test/test-manager/src/tests/helpers.rs b/test/test-manager/src/tests/helpers.rs index 5dcb8d0d0c..aef29578d0 100644 --- a/test/test-manager/src/tests/helpers.rs +++ b/test/test-manager/src/tests/helpers.rs @@ -488,12 +488,12 @@ pub async fn wait_for_tunnel_state( let events = rpc .events_listen() .await - .map_err(|status| Error::Daemon(format!("Failed to get event stream: {}", status)))?; + .map_err(|status| Error::Daemon(format!("Failed to get event stream: {status}")))?; let state = rpc .get_tunnel_state() .await - .map_err(|error| Error::Daemon(format!("Failed to get tunnel state: {:?}", error)))?; + .map_err(|error| Error::Daemon(format!("Failed to get tunnel state: {error:?}")))?; if accept_state_fn(&state) { return Ok(state); @@ -533,10 +533,7 @@ where None => continue, }, Some(Err(status)) => { - break Err(Error::Daemon(format!( - "Failed to get next event: {}", - status - ))); + break Err(Error::Daemon(format!("Failed to get next event: {status}"))); } None => break Err(Error::Daemon(String::from("Lost daemon event stream"))), } @@ -646,7 +643,7 @@ pub async fn set_custom_endpoint( mullvad_client .set_relay_settings(RelaySettings::CustomTunnelEndpoint(custom_endpoint)) .await - .map_err(|error| Error::Daemon(format!("Failed to set relay settings: {}", error))) + .map_err(|error| Error::Daemon(format!("Failed to set relay settings: {error}"))) } pub async fn update_relay_constraints( @@ -1322,7 +1319,7 @@ pub async fn set_location( let mut settings = mullvad_client .get_settings() .await - .map_err(|error| Error::Daemon(format!("Failed to set relay settings: {}", error)))?; + .map_err(|error| Error::Daemon(format!("Failed to set relay settings: {error}")))?; settings.bridge_settings.normal.location = Constraint::Only(location_constraint.clone()); mullvad_client diff --git a/test/test-manager/src/tests/install.rs b/test/test-manager/src/tests/install.rs index 0639694986..4c0195f3a5 100644 --- a/test/test-manager/src/tests/install.rs +++ b/test/test-manager/src/tests/install.rs @@ -230,8 +230,7 @@ pub async fn test_uninstall_app( assert!( !devices.iter().any(|device| device.id == uninstalled_device), - "device id {} still exists after uninstall", - uninstalled_device, + "device id {uninstalled_device} still exists after uninstall", ); Ok(()) @@ -280,8 +279,7 @@ pub async fn test_detect_app_removal( .expect("failed to list devices"); assert!( !devices.iter().any(|device| device.id == uninstalled_device), - "device id {} still exists after uninstall", - uninstalled_device, + "device id {uninstalled_device} still exists after uninstall", ); return Ok(()); diff --git a/test/test-manager/src/tests/tunnel_state.rs b/test/test-manager/src/tests/tunnel_state.rs index 60f266721e..9b83e65ff8 100644 --- a/test/test-manager/src/tests/tunnel_state.rs +++ b/test/test-manager/src/tests/tunnel_state.rs @@ -210,8 +210,7 @@ pub async fn test_connecting_state( assert!( matches!(new_state, TunnelState::Connecting { .. }), - "failed to enter connecting state: {:?}", - new_state + "failed to enter connecting state: {new_state:?}" ); // Leak test @@ -373,7 +372,7 @@ pub async fn test_connected_state( } => { assert_eq!(*addr.ip(), relay.ipv4_addr_in); } - actual => panic!("unexpected tunnel state: {:?}", actual), + actual => panic!("unexpected tunnel state: {actual:?}"), } // Ping outside of tunnel while connected diff --git a/test/test-manager/src/vm/network/linux.rs b/test/test-manager/src/vm/network/linux.rs index f5ed523655..ef7eebeb2a 100644 --- a/test/test-manager/src/vm/network/linux.rs +++ b/test/test-manager/src/vm/network/linux.rs @@ -204,7 +204,7 @@ async fn start_dnsmasq() -> Result<DhcpProcHandle> { "-i", BRIDGE_NAME, "-F", - &format!("{},{}", TEST_SUBNET_DHCP_FIRST, TEST_SUBNET_DHCP_LAST), + &format!("{TEST_SUBNET_DHCP_FIRST},{TEST_SUBNET_DHCP_LAST}"), "--no-hosts", "--keep-in-foreground", "--log-facility=-", diff --git a/test/test-rpc/src/transport.rs b/test/test-rpc/src/transport.rs index f5f4617026..ffdefbf923 100644 --- a/test/test-rpc/src/transport.rs +++ b/test/test-rpc/src/transport.rs @@ -486,7 +486,7 @@ fn display_chain(error: impl std::error::Error) -> String { let mut s = error.to_string(); let mut error = &error as &dyn std::error::Error; while let Some(source) = error.source() { - write!(&mut s, "\nCaused by: {}", source).unwrap(); + write!(&mut s, "\nCaused by: {source}").unwrap(); error = source; } s diff --git a/test/test-runner/src/logging.rs b/test/test-runner/src/logging.rs index 6ca19c2c63..bab3693c34 100644 --- a/test/test-runner/src/logging.rs +++ b/test/test-runner/src/logging.rs @@ -76,7 +76,7 @@ pub async fn get_mullvad_app_logs() -> LogOutput { async fn read_settings_file() -> Result<String, Error> { let mut settings_path = mullvad_paths::get_default_settings_dir() - .map_err(|error| Error::Logs(format!("{}", error)))?; + .map_err(|error| Error::Logs(format!("{error}")))?; settings_path.push("settings.json"); read_truncated(&settings_path, None) .await @@ -85,10 +85,10 @@ async fn read_settings_file() -> Result<String, Error> { async fn read_log_files() -> Result<Vec<Result<LogFile, Error>>, Error> { let log_dir = - mullvad_paths::get_default_log_dir().map_err(|error| Error::Logs(format!("{}", error)))?; + mullvad_paths::get_default_log_dir().map_err(|error| Error::Logs(format!("{error}")))?; let paths = list_logs(log_dir) .await - .map_err(|error| Error::Logs(format!("{}", error)))?; + .map_err(|error| Error::Logs(format!("{error}")))?; let mut log_files = Vec::new(); for path in paths { let log_file = read_truncated(&path, Some(TRUNCATE_LOG_FILE_LINES)) diff --git a/test/test-runner/src/sys.rs b/test/test-runner/src/sys.rs index 5f461f9013..024e1153c9 100644 --- a/test/test-runner/src/sys.rs +++ b/test/test-runner/src/sys.rs @@ -505,11 +505,11 @@ pub async fn set_daemon_environment(env: HashMap<String, String>) -> Result<(), let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); let path = Path::new(MULLVAD_WIN_REGISTRY).join("Environment"); let (registry, _) = hklm.create_subkey(&path).map_err(|error| { - test_rpc::Error::Registry(format!("Failed to open Mullvad VPN subkey: {}", error)) + test_rpc::Error::Registry(format!("Failed to open Mullvad VPN subkey: {error}")) })?; for (k, v) in env { registry.set_value(k, &v).map_err(|error| { - test_rpc::Error::Registry(format!("Failed to set Environment var: {}", error)) + test_rpc::Error::Registry(format!("Failed to set Environment var: {error}")) })?; } @@ -528,12 +528,12 @@ pub fn get_system_path_var() -> Result<String, test_rpc::Error> { let key = hklm .open_subkey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment") .map_err(|error| { - test_rpc::Error::Registry(format!("Failed to open Environment subkey: {}", error)) + test_rpc::Error::Registry(format!("Failed to open Environment subkey: {error}")) })?; let path: String = key .get_value("Path") - .map_err(|error| test_rpc::Error::Registry(format!("Failed to get PATH: {}", error)))?; + .map_err(|error| test_rpc::Error::Registry(format!("Failed to get PATH: {error}")))?; Ok(path) } @@ -642,7 +642,7 @@ pub async fn get_daemon_environment() -> Result<HashMap<String, String>, test_rp tokio::task::spawn_blocking(|| -> Result<HashMap<String, String>, test_rpc::Error> { let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); let key = hklm.open_subkey(MULLVAD_WIN_REGISTRY).map_err(|error| { - test_rpc::Error::Registry(format!("Failed to open Mullvad VPN subkey: {}", error)) + test_rpc::Error::Registry(format!("Failed to open Mullvad VPN subkey: {error}")) })?; // The Strings will be quoted (surrounded by ") when read from the registry - we should @@ -651,10 +651,9 @@ pub async fn get_daemon_environment() -> Result<HashMap<String, String>, test_rp let env = key .open_subkey("Environment") .map_err(|error| { - test_rpc::Error::Registry(format!( - "Failed to open Environment subkey: {}", - error - )) + test_rpc::Error::Registry( + format!("Failed to open Environment subkey: {error}",), + ) })? .enum_values() .filter_map(|x| x.inspect_err(|err| log::trace!("{err}")).ok()) diff --git a/tunnel-obfuscation/src/main.rs b/tunnel-obfuscation/src/main.rs index d08329e0a1..2ed49c18ad 100644 --- a/tunnel-obfuscation/src/main.rs +++ b/tunnel-obfuscation/src/main.rs @@ -7,7 +7,7 @@ async fn main() { println!("Missing arguments"); } - let obfuscator = instantiate_requested(&args().last().unwrap()).await; + let obfuscator = instantiate_requested(&args().next_back().unwrap()).await; println!("endpoint() returns {:?}", obfuscator.endpoint()); diff --git a/wireguard-go-rs/build.rs b/wireguard-go-rs/build.rs index 8978bef7b5..f4325b6cbb 100644 --- a/wireguard-go-rs/build.rs +++ b/wireguard-go-rs/build.rs @@ -348,11 +348,7 @@ fn find_lib_exe() -> anyhow::Result<PathBuf> { Arch::Arm64 => "arm64", }; - let lib_exe_pattern = format!( - "{host}/{target}/lib.exe", - host = lib_exe_host, - target = lib_exe_target, - ); + let lib_exe_pattern = format!("{lib_exe_host}/{lib_exe_target}/lib.exe",); let path_is_lib_exe = |file: &Path| file.ends_with(&lib_exe_pattern); find_file(search_path, &path_is_lib_exe)?.context("No lib.exe relative to msbuild.exe") |
