diff options
| author | Markus Pettersson <markus.pettersson@mullvad.net> | 2025-07-15 15:02:14 +0200 |
|---|---|---|
| committer | Markus Pettersson <markus.pettersson@mullvad.net> | 2025-07-15 15:02:14 +0200 |
| commit | a3ec4507f0e0dcd35e1940e897eb1d3a51151940 (patch) | |
| tree | 788febabd1e92d50a4e2ab81cfbe6cff5c9340df | |
| parent | 3c1ec7e8acaaeddd4ed1ab739a499d9c0d197894 (diff) | |
| parent | 06d1b98949331e7576c4a8fa126682b221b39ab2 (diff) | |
| download | mullvadvpn-a3ec4507f0e0dcd35e1940e897eb1d3a51151940.tar.xz mullvadvpn-a3ec4507f0e0dcd35e1940e897eb1d3a51151940.zip | |
Merge branch 'fix-clippy-nightly-warnings'
30 files changed, 355 insertions, 369 deletions
diff --git a/mullvad-api/src/access.rs b/mullvad-api/src/access.rs index 6c875ad1e8..1ee6ea612d 100644 --- a/mullvad-api/src/access.rs +++ b/mullvad-api/src/access.rs @@ -155,12 +155,12 @@ impl AccessTokenStore { /// Remove an access token if the API response calls for it. pub fn check_response<T>(&self, account: &AccountNumber, response: &Result<T, rest::Error>) { - if let Err(rest::Error::ApiError(_status, code)) = response { - if code == crate::INVALID_ACCESS_TOKEN { - let _ = self - .tx - .unbounded_send(StoreAction::InvalidateToken(account.to_owned())); - } + if let Err(rest::Error::ApiError(_status, code)) = response + && code == crate::INVALID_ACCESS_TOKEN + { + let _ = self + .tx + .unbounded_send(StoreAction::InvalidateToken(account.to_owned())); } } } diff --git a/mullvad-api/src/proxy.rs b/mullvad-api/src/proxy.rs index 4ad842ee85..ab05e25021 100644 --- a/mullvad-api/src/proxy.rs +++ b/mullvad-api/src/proxy.rs @@ -154,13 +154,13 @@ impl ApiConnectionMode { /// Attempts to remove `CURRENT_CONFIG_FILENAME`, if it exists. pub async fn try_delete_cache(cache_dir: &Path) { let path = cache_dir.join(CURRENT_CONFIG_FILENAME); - if let Err(err) = fs::remove_file(path).await { - if err.kind() != std::io::ErrorKind::NotFound { - log::error!( - "{}", - err.display_chain_with_msg("Failed to remove old API config") - ); - } + if let Err(err) = fs::remove_file(path).await + && err.kind() != std::io::ErrorKind::NotFound + { + log::error!( + "{}", + err.display_chain_with_msg("Failed to remove old API config") + ); } } diff --git a/mullvad-api/src/relay_list.rs b/mullvad-api/src/relay_list.rs index 799a55dc1a..abca6dd2b7 100644 --- a/mullvad-api/src/relay_list.rs +++ b/mullvad-api/src/relay_list.rs @@ -209,26 +209,24 @@ impl OpenVpn { ) -> relay_list::OpenVpnEndpointData { for mut openvpn_relay in self.relays.into_iter() { openvpn_relay.convert_to_lowercase(); - if let Some((country_code, city_code)) = split_location_code(&openvpn_relay.location) { - if let Some(country) = countries.get_mut(country_code) { - if let Some(city) = country - .cities - .iter_mut() - .find(|city| city.code == city_code) - { - let location = location::Location { - country: country.name.clone(), - country_code: country.code.clone(), - city: city.name.clone(), - city_code: city.code.clone(), - latitude: city.latitude, - longitude: city.longitude, - }; - let relay = openvpn_relay.into_openvpn_mullvad_relay(location); - city.relays.push(relay); - } + if let Some((country_code, city_code)) = split_location_code(&openvpn_relay.location) + && let Some(country) = countries.get_mut(country_code) + && let Some(city) = country + .cities + .iter_mut() + .find(|city| city.code == city_code) + { + let location = location::Location { + country: country.name.clone(), + country_code: country.code.clone(), + city: city.name.clone(), + city_code: city.code.clone(), + latitude: city.latitude, + longitude: city.longitude, }; - } + let relay = openvpn_relay.into_openvpn_mullvad_relay(location); + city.relays.push(relay); + }; } self.ports } @@ -321,27 +319,24 @@ impl Wireguard { wireguard_relay.relay.convert_to_lowercase(); if let Some((country_code, city_code)) = split_location_code(&wireguard_relay.relay.location) + && let Some(country) = countries.get_mut(country_code) + && let Some(city) = country + .cities + .iter_mut() + .find(|city| city.code == city_code) { - if let Some(country) = countries.get_mut(country_code) { - if let Some(city) = country - .cities - .iter_mut() - .find(|city| city.code == city_code) - { - let location = location::Location { - country: country.name.clone(), - country_code: country.code.clone(), - city: city.name.clone(), - city_code: city.code.clone(), - latitude: city.latitude, - longitude: city.longitude, - }; - - let relay = wireguard_relay.into_mullvad_relay(location); - city.relays.push(relay); - } + let location = location::Location { + country: country.name.clone(), + country_code: country.code.clone(), + city: city.name.clone(), + city_code: city.code.clone(), + latitude: city.latitude, + longitude: city.longitude, }; - } + + let relay = wireguard_relay.into_mullvad_relay(location); + city.relays.push(relay); + }; } endpoint_data @@ -394,27 +389,25 @@ impl Bridges { ) -> relay_list::BridgeEndpointData { for mut bridge_relay in self.relays { bridge_relay.convert_to_lowercase(); - if let Some((country_code, city_code)) = split_location_code(&bridge_relay.location) { - if let Some(country) = countries.get_mut(country_code) { - if let Some(city) = country - .cities - .iter_mut() - .find(|city| city.code == city_code) - { - let location = location::Location { - country: country.name.clone(), - country_code: country.code.clone(), - city: city.name.clone(), - city_code: city.code.clone(), - latitude: city.latitude, - longitude: city.longitude, - }; - - let relay = bridge_relay.into_bridge_mullvad_relay(location); - city.relays.push(relay); - } + if let Some((country_code, city_code)) = split_location_code(&bridge_relay.location) + && let Some(country) = countries.get_mut(country_code) + && let Some(city) = country + .cities + .iter_mut() + .find(|city| city.code == city_code) + { + let location = location::Location { + country: country.name.clone(), + country_code: country.code.clone(), + city: city.name.clone(), + city_code: city.code.clone(), + latitude: city.latitude, + longitude: city.longitude, }; - } + + let relay = bridge_relay.into_bridge_mullvad_relay(location); + city.relays.push(relay); + }; } relay_list::BridgeEndpointData { diff --git a/mullvad-api/src/rest.rs b/mullvad-api/src/rest.rs index 5e7d13047e..3854f66ef4 100644 --- a/mullvad-api/src/rest.rs +++ b/mullvad-api/src/rest.rs @@ -101,11 +101,12 @@ impl Error { pub fn is_offline(&self) -> bool { match self { Error::LegacyHyperError(error) if error.is_connect() => { - if let Some(cause) = error.source() { - if let Some(err) = cause.downcast_ref::<std::io::Error>() { - return err.raw_os_error() == Some(libc::ENETUNREACH); - } + if let Some(cause) = error.source() + && let Some(err) = cause.downcast_ref::<std::io::Error>() + { + return err.raw_os_error() == Some(libc::ENETUNREACH); } + false } // TODO: Currently, we use the legacy hyper client for all REST requests. If this @@ -252,14 +253,14 @@ impl<T: ConnectionModeProvider + 'static> RequestService<T> { let response = request_future.await.map_err(|error| error.map_aborted()); // Switch API endpoint if the request failed due to a network error - if let Err(err) = &response { - if err.is_network_error() && !api_availability.is_offline() { - log::error!("{}", err.display_chain_with_msg("HTTP request failed")); - if let Some(tx) = tx { - let _ = tx.unbounded_send(RequestCommand::NextApiConfig( - connection_mode_generation, - )); - } + if let Err(err) = &response + && err.is_network_error() + && !api_availability.is_offline() + { + log::error!("{}", err.display_chain_with_msg("HTTP request failed")); + if let Some(tx) = tx { + let _ = tx + .unbounded_send(RequestCommand::NextApiConfig(connection_mode_generation)); } } diff --git a/mullvad-cli/src/cmds/tunnel_state.rs b/mullvad-cli/src/cmds/tunnel_state.rs index d746ae3e86..2db5765f54 100644 --- a/mullvad-cli/src/cmds/tunnel_state.rs +++ b/mullvad-cli/src/cmds/tunnel_state.rs @@ -16,15 +16,15 @@ pub async fn connect(wait: bool) -> Result<()> { None }; - if rpc.connect_tunnel().await? { - if let Some(receiver) = listener { - wait_for_tunnel_state(receiver, |state| match state { - TunnelState::Connected { .. } => Ok(true), - TunnelState::Error(_) => Err(anyhow!("Failed to connect")), - _ => Ok(false), - }) - .await?; - } + if rpc.connect_tunnel().await? + && let Some(receiver) = listener + { + wait_for_tunnel_state(receiver, |state| match state { + TunnelState::Connected { .. } => Ok(true), + TunnelState::Error(_) => Err(anyhow!("Failed to connect")), + _ => Ok(false), + }) + .await?; } Ok(()) @@ -39,10 +39,10 @@ pub async fn disconnect(wait: bool) -> Result<()> { None }; - if rpc.disconnect_tunnel().await? { - if let Some(receiver) = listener { - wait_for_tunnel_state(receiver, |state| Ok(state.is_disconnected())).await?; - } + if rpc.disconnect_tunnel().await? + && let Some(receiver) = listener + { + wait_for_tunnel_state(receiver, |state| Ok(state.is_disconnected())).await?; } Ok(()) @@ -60,15 +60,15 @@ pub async fn reconnect(wait: bool) -> Result<()> { None }; - if rpc.reconnect_tunnel().await? { - if let Some(receiver) = listener { - wait_for_tunnel_state(receiver, |state| match state { - TunnelState::Connected { .. } => Ok(true), - TunnelState::Error(_) => Err(anyhow!("Failed to reconnect")), - _ => Ok(false), - }) - .await?; - } + if rpc.reconnect_tunnel().await? + && let Some(receiver) = listener + { + wait_for_tunnel_state(receiver, |state| match state { + TunnelState::Connected { .. } => Ok(true), + TunnelState::Error(_) => Err(anyhow!("Failed to reconnect")), + _ => Ok(false), + }) + .await?; } Ok(()) diff --git a/mullvad-daemon/src/account_history.rs b/mullvad-daemon/src/account_history.rs index 5a8677e464..6a6c0e3ddc 100644 --- a/mullvad-daemon/src/account_history.rs +++ b/mullvad-daemon/src/account_history.rs @@ -73,13 +73,11 @@ impl AccountHistory { let file = io::BufWriter::new(reader.into_inner()); let mut history = AccountHistory { file, number }; - if should_save { - if let Err(error) = history.save_to_disk().await { - log::error!( - "{}", - error.display_chain_with_msg("Failed to save account history after opening it") - ); - } + if should_save && let Err(error) = history.save_to_disk().await { + log::error!( + "{}", + error.display_chain_with_msg("Failed to save account history after opening it") + ); } Ok(history) } diff --git a/mullvad-daemon/src/custom_list.rs b/mullvad-daemon/src/custom_list.rs index 06f5926a2c..ce079c2fff 100644 --- a/mullvad-daemon/src/custom_list.rs +++ b/mullvad-daemon/src/custom_list.rs @@ -129,28 +129,24 @@ impl Daemon { if let Some(endpoint) = self.tunnel_state.endpoint() { match endpoint.tunnel_type { TunnelType::Wireguard => { - if relay_settings.wireguard_constraints.multihop() { - if let Constraint::Only(LocationConstraint::CustomList { list_id }) = + if relay_settings.wireguard_constraints.multihop() + && let Constraint::Only(LocationConstraint::CustomList { list_id }) = &relay_settings.wireguard_constraints.entry_location - { - need_to_reconnect |= - custom_list_id.map(|id| &id == list_id).unwrap_or(true); - } + { + need_to_reconnect |= + custom_list_id.map(|id| &id == list_id).unwrap_or(true); } } TunnelType::OpenVpn => { - if !matches!(self.settings.bridge_state, BridgeState::Off) { - if let Ok(ResolvedBridgeSettings::Normal(bridge_settings)) = + if !matches!(self.settings.bridge_state, BridgeState::Off) + && let Ok(ResolvedBridgeSettings::Normal(bridge_settings)) = self.settings.bridge_settings.resolve() - { - if let Constraint::Only(LocationConstraint::CustomList { list_id }) = - &bridge_settings.location - { - need_to_reconnect |= - custom_list_id.map(|id| &id == list_id).unwrap_or(true); - } - } + && let Constraint::Only(LocationConstraint::CustomList { list_id }) = + &bridge_settings.location + { + need_to_reconnect |= + custom_list_id.map(|id| &id == list_id).unwrap_or(true); } } } diff --git a/mullvad-daemon/src/device/mod.rs b/mullvad-daemon/src/device/mod.rs index 7b0649a4d9..56b910d971 100644 --- a/mullvad-daemon/src/device/mod.rs +++ b/mullvad-daemon/src/device/mod.rs @@ -461,10 +461,10 @@ impl AccountManager { let mut current_api_call = api::CurrentApiCall::new(); loop { - if current_api_call.is_idle() { - if let Some(timed_rotation) = self.spawn_timed_key_rotation() { - current_api_call.set_timed_rotation(Box::pin(timed_rotation)) - } + if current_api_call.is_idle() + && let Some(timed_rotation) = self.spawn_timed_key_rotation() + { + current_api_call.set_timed_rotation(Box::pin(timed_rotation)) } futures::select! { @@ -849,15 +849,15 @@ impl AccountManager { } } - if !self.rotation_requests.is_empty() || !self.validation_requests.is_empty() { - if let Some(updated_config) = self.data.device() { - let device_service = self.device_service.clone(); - let number = updated_config.account_number.clone(); - let device_id = updated_config.device.id.clone(); - api_call.set_oneshot_rotation(Box::pin(async move { - device_service.rotate_key(number, device_id).await - })); - } + if (!self.rotation_requests.is_empty() || !self.validation_requests.is_empty()) + && let Some(updated_config) = self.data.device() + { + let device_service = self.device_service.clone(); + let number = updated_config.account_number.clone(); + let device_id = updated_config.device.id.clone(); + api_call.set_oneshot_rotation(Box::pin(async move { + device_service.rotate_key(number, device_id).await + })); } } @@ -1046,10 +1046,10 @@ impl AccountManager { self.cacher.write(&device_state).await?; self.last_validation = None; - if let Some(old_config) = self.data.logout() { - if device_state.device().map(|d| &d.device.id) != Some(&old_config.device.id) { - tokio::spawn(self.logout_api_call(old_config)); - } + if let Some(old_config) = self.data.logout() + && device_state.device().map(|d| &d.device.id) != Some(&old_config.device.id) + { + tokio::spawn(self.logout_api_call(old_config)); } self.data = device_state; @@ -1374,7 +1374,8 @@ impl TunnelStateChangeHandler { const fn should_check_device_validity_on_attempt(wireguard_retry_attempt: usize) -> bool { // Incorporate a debounce effect where every `WG_DEVICE_CHECK_THRESHOLD` attempt should be // able to trigger a device check. - wireguard_retry_attempt > 0 && (wireguard_retry_attempt % WG_DEVICE_CHECK_THRESHOLD == 0) + wireguard_retry_attempt > 0 + && wireguard_retry_attempt.is_multiple_of(WG_DEVICE_CHECK_THRESHOLD) } fn should_continue_retries(err: &Error) -> bool { diff --git a/mullvad-daemon/src/lib.rs b/mullvad-daemon/src/lib.rs index 61a3569ed5..9cdb61e942 100644 --- a/mullvad-daemon/src/lib.rs +++ b/mullvad-daemon/src/lib.rs @@ -1567,11 +1567,11 @@ impl Daemon { } AccountEvent::Expiry(expiry) if *self.target_state == TargetState::Secured => { if expiry >= &chrono::Utc::now() { - if let TunnelState::Error(ref state) = self.tunnel_state { - if matches!(state.cause(), ErrorStateCause::AuthFailed(_)) { - log::debug!("Reconnecting since the account has time on it"); - self.connect_tunnel(); - } + if let TunnelState::Error(ref state) = self.tunnel_state + && matches!(state.cause(), ErrorStateCause::AuthFailed(_)) + { + log::debug!("Reconnecting since the account has time on it"); + self.connect_tunnel(); } } else if self.get_target_tunnel_type() == Some(TunnelType::Wireguard) { log::debug!("Entering blocking state since the account is out of time"); @@ -1778,10 +1778,10 @@ impl Daemon { let account_manager = self.account_manager.clone(); tokio::spawn(async move { let result = async { - if let Ok(data) = account_manager.data().await { - if data.logged_in() { - return Err(Error::AlreadyLoggedIn); - } + if let Ok(data) = account_manager.data().await + && data.logged_in() + { + return Err(Error::AlreadyLoggedIn); } let token = account_manager .account_service @@ -2808,13 +2808,13 @@ impl Daemon { { Ok(settings_changed) => { Self::oneshot_send(tx, Ok(()), "set_wireguard_mtu response"); - if settings_changed { - if let Some(TunnelType::Wireguard) = self.get_connected_tunnel_type() { - log::info!( - "Initiating tunnel restart because the WireGuard MTU setting changed" - ); - self.reconnect_tunnel(); - } + if settings_changed + && let Some(TunnelType::Wireguard) = self.get_connected_tunnel_type() + { + log::info!( + "Initiating tunnel restart because the WireGuard MTU setting changed" + ); + self.reconnect_tunnel(); } } Err(e) => { @@ -2836,17 +2836,16 @@ impl Daemon { { Ok(settings_changed) => { Self::oneshot_send(tx, Ok(()), "set_wireguard_rotation_interval response"); - if settings_changed { - if let Err(error) = self + if settings_changed + && let Err(error) = self .account_manager .set_rotation_interval(interval.unwrap_or_default()) .await - { - log::error!( - "{}", - error.display_chain_with_msg("Failed to update rotation interval") - ); - } + { + log::error!( + "{}", + error.display_chain_with_msg("Failed to update rotation interval") + ); } } Err(e) => { @@ -2872,13 +2871,13 @@ impl Daemon { { Ok(settings_changed) => { Self::oneshot_send(tx, Ok(()), "set_wireguard_allowed_ips response"); - if settings_changed { - if let Some(TunnelType::Wireguard) = self.get_connected_tunnel_type() { - log::info!( - "Initiating tunnel restart because the WireGuard allowed IPs setting changed" - ); - self.reconnect_tunnel(); - } + if settings_changed + && let Some(TunnelType::Wireguard) = self.get_connected_tunnel_type() + { + log::info!( + "Initiating tunnel restart because the WireGuard allowed IPs setting changed" + ); + self.reconnect_tunnel(); } } Err(e) => { @@ -3491,9 +3490,9 @@ fn oneshot_map<T1: Send + 'static, T2: Send + 'static>( /// Remove any old RPC socket (if it exists). #[cfg(not(windows))] pub async fn cleanup_old_rpc_socket(rpc_socket_path: impl AsRef<std::path::Path>) { - if let Err(err) = tokio::fs::remove_file(rpc_socket_path).await { - if err.kind() != std::io::ErrorKind::NotFound { - log::error!("Failed to remove old RPC socket: {}", err); - } + if let Err(err) = tokio::fs::remove_file(rpc_socket_path).await + && err.kind() != std::io::ErrorKind::NotFound + { + log::error!("Failed to remove old RPC socket: {}", err); } } diff --git a/mullvad-daemon/src/main.rs b/mullvad-daemon/src/main.rs index 36af376ed3..2aac80f2b4 100644 --- a/mullvad-daemon/src/main.rs +++ b/mullvad-daemon/src/main.rs @@ -127,10 +127,10 @@ fn init_daemon_logging(config: &cli::Config) -> Result<Option<PathBuf>, String> fn init_early_boot_logging(config: &cli::Config) { // If it's possible to log to the filesystem - attempt to do so, but failing that mustn't stop // the daemon from starting here. - if let Ok(Some(log_dir)) = get_log_dir(config) { - if init_logger(config, Some(log_dir.join(EARLY_BOOT_LOG_FILENAME))).is_ok() { - return; - } + if let Ok(Some(log_dir)) = get_log_dir(config) + && init_logger(config, Some(log_dir.join(EARLY_BOOT_LOG_FILENAME))).is_ok() + { + return; } let _ = init_logger(config, None); diff --git a/mullvad-daemon/src/migrations/v1.rs b/mullvad-daemon/src/migrations/v1.rs index 44de9d1293..08d3a10d1a 100644 --- a/mullvad-daemon/src/migrations/v1.rs +++ b/mullvad-daemon/src/migrations/v1.rs @@ -44,23 +44,21 @@ pub fn migrate(settings: &mut serde_json::Value) -> Result<()> { .cloned() }(); - if let Some(relay_settings) = settings.get_mut("relay_settings") { - if let Some(normal_settings) = relay_settings.get_mut("normal") { - if let Some(openvpn_constraints) = openvpn_constraints { - normal_settings["openvpn_constraints"] = openvpn_constraints; - normal_settings["tunnel_protocol"] = - serde_json::json!(Constraint::<TunnelType>::Any); - } else if let Some(wireguard_constraints) = wireguard_constraints { - normal_settings["wireguard_constraints"] = wireguard_constraints; - normal_settings["tunnel_protocol"] = - serde_json::json!(Constraint::Only(TunnelType::Wireguard)); - } else { - normal_settings["tunnel_protocol"] = - serde_json::json!(Constraint::<TunnelType>::Any); - } - if let Some(object) = normal_settings.as_object_mut() { - object.remove("tunnel"); - } + if let Some(relay_settings) = settings.get_mut("relay_settings") + && let Some(normal_settings) = relay_settings.get_mut("normal") + { + if let Some(openvpn_constraints) = openvpn_constraints { + normal_settings["openvpn_constraints"] = openvpn_constraints; + normal_settings["tunnel_protocol"] = serde_json::json!(Constraint::<TunnelType>::Any); + } else if let Some(wireguard_constraints) = wireguard_constraints { + normal_settings["wireguard_constraints"] = wireguard_constraints; + normal_settings["tunnel_protocol"] = + serde_json::json!(Constraint::Only(TunnelType::Wireguard)); + } else { + normal_settings["tunnel_protocol"] = serde_json::json!(Constraint::<TunnelType>::Any); + } + if let Some(object) = normal_settings.as_object_mut() { + object.remove("tunnel"); } } diff --git a/mullvad-daemon/src/migrations/v3.rs b/mullvad-daemon/src/migrations/v3.rs index f59bc57b98..f4302568af 100644 --- a/mullvad-daemon/src/migrations/v3.rs +++ b/mullvad-daemon/src/migrations/v3.rs @@ -50,29 +50,29 @@ pub fn migrate(settings: &mut serde_json::Value) -> Result<()> { let dns_options = || -> Option<&serde_json::Value> { settings.get("tunnel_options")?.get("dns_options") }(); - if let Some(options) = dns_options { - if options.get("state").is_none() { - let new_state = if options - .get("custom") - .map(|custom| custom.as_bool().unwrap_or(false)) - .unwrap_or(false) - { - DnsState::Custom - } else { - DnsState::Default - }; - let addresses = if let Some(addrs) = options.get("addresses") { - serde_json::from_value(addrs.clone()).map_err(|_| Error::InvalidSettingsContent)? - } else { - vec![] - }; + if let Some(options) = dns_options + && options.get("state").is_none() + { + let new_state = if options + .get("custom") + .map(|custom| custom.as_bool().unwrap_or(false)) + .unwrap_or(false) + { + DnsState::Custom + } else { + DnsState::Default + }; + let addresses = if let Some(addrs) = options.get("addresses") { + serde_json::from_value(addrs.clone()).map_err(|_| Error::InvalidSettingsContent)? + } else { + vec![] + }; - settings["tunnel_options"]["dns_options"] = serde_json::json!(DnsOptions { - state: new_state, - default_options: DefaultDnsOptions::default(), - custom_options: CustomDnsOptions { addresses }, - }); - } + settings["tunnel_options"]["dns_options"] = serde_json::json!(DnsOptions { + state: new_state, + default_options: DefaultDnsOptions::default(), + custom_options: CustomDnsOptions { addresses }, + }); } settings["settings_version"] = serde_json::json!(SettingsVersion::V4); diff --git a/mullvad-daemon/src/migrations/v5.rs b/mullvad-daemon/src/migrations/v5.rs index 178832116a..920f43face 100644 --- a/mullvad-daemon/src/migrations/v5.rs +++ b/mullvad-daemon/src/migrations/v5.rs @@ -77,17 +77,17 @@ pub fn migrate(settings: &mut serde_json::Value) -> Result<Option<MigrationData> log::info!("Migrating settings format to V6"); if let Some(wireguard_constraints) = get_wireguard_constraints(settings) { - if let Some(location) = wireguard_constraints.get("entry_location") { - if wireguard_constraints.get("use_multihop").is_none() { - if location.is_null() { - // "Null" is no longer valid. It is not an option. - wireguard_constraints - .as_object_mut() - .ok_or(Error::InvalidSettingsContent)? - .remove("entry_location"); - } else { - wireguard_constraints["use_multihop"] = serde_json::json!(true); - } + if let Some(location) = wireguard_constraints.get("entry_location") + && wireguard_constraints.get("use_multihop").is_none() + { + if location.is_null() { + // "Null" is no longer valid. It is not an option. + wireguard_constraints + .as_object_mut() + .ok_or(Error::InvalidSettingsContent)? + .remove("entry_location"); + } else { + wireguard_constraints["use_multihop"] = serde_json::json!(true); } } // The field `pub port: Constraint<TransportPort>` is now `pub port: Constraint<u16>`. @@ -152,10 +152,10 @@ pub fn migrate(settings: &mut serde_json::Value) -> Result<Option<MigrationData> } fn get_wireguard_constraints(settings: &mut serde_json::Value) -> Option<&mut serde_json::Value> { - if let Some(relay_settings) = settings.get_mut("relay_settings") { - if let Some(normal) = relay_settings.get_mut("normal") { - return normal.get_mut("wireguard_constraints"); - } + if let Some(relay_settings) = settings.get_mut("relay_settings") + && let Some(normal) = relay_settings.get_mut("normal") + { + return normal.get_mut("wireguard_constraints"); } None } diff --git a/mullvad-daemon/src/migrations/v6.rs b/mullvad-daemon/src/migrations/v6.rs index c481be8d92..490558ce57 100644 --- a/mullvad-daemon/src/migrations/v6.rs +++ b/mullvad-daemon/src/migrations/v6.rs @@ -87,18 +87,15 @@ fn migrate_pq_setting(settings: &mut serde_json::Value) -> Result<()> { if let Some(tunnel_options) = settings .get_mut("tunnel_options") .and_then(|opt| opt.get_mut("wireguard")) - { - if let Some(psk_setting) = tunnel_options + && let Some(psk_setting) = tunnel_options .as_object_mut() .ok_or(Error::InvalidSettingsContent)? .remove("use_pq_safe_psk") - { - if let Some(true) = psk_setting.as_bool() { - tunnel_options["quantum_resistant"] = serde_json::json!(QuantumResistantState::On); - } else { - tunnel_options["quantum_resistant"] = - serde_json::json!(QuantumResistantState::Auto); - } + { + if let Some(true) = psk_setting.as_bool() { + tunnel_options["quantum_resistant"] = serde_json::json!(QuantumResistantState::On); + } else { + tunnel_options["quantum_resistant"] = serde_json::json!(QuantumResistantState::Auto); } } Ok(()) diff --git a/mullvad-daemon/src/migrations/v7.rs b/mullvad-daemon/src/migrations/v7.rs index 0cc29df04e..4223505a47 100644 --- a/mullvad-daemon/src/migrations/v7.rs +++ b/mullvad-daemon/src/migrations/v7.rs @@ -19,6 +19,7 @@ use talpid_types::net::{ /// bridge server. #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] +#[allow(unused)] pub enum BridgeSettings { /// Let the relay selection algorithm decide on bridges, based on the relay list. Normal(BridgeConstraints), diff --git a/mullvad-daemon/src/migrations/v9.rs b/mullvad-daemon/src/migrations/v9.rs index d8665a31d1..655b34acd4 100644 --- a/mullvad-daemon/src/migrations/v9.rs +++ b/mullvad-daemon/src/migrations/v9.rs @@ -33,6 +33,7 @@ const SPLIT_TUNNELING_STATE: &str = "split-tunnelling-enabled.txt"; /// Tunnel protocol #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename = "tunnel_type")] +#[allow(unused)] pub enum TunnelType { #[serde(rename = "openvpn")] OpenVpn, diff --git a/mullvad-daemon/src/settings/mod.rs b/mullvad-daemon/src/settings/mod.rs index 6a70074051..8a0c98478f 100644 --- a/mullvad-daemon/src/settings/mod.rs +++ b/mullvad-daemon/src/settings/mod.rs @@ -118,13 +118,11 @@ impl SettingsPersister { on_change_listeners: vec![], }; - if should_save { - if let Err(error) = persister.save().await { - log::error!( - "{}", - error.display_chain_with_msg("Failed to save updated settings") - ); - } + if should_save && let Err(error) = persister.save().await { + log::error!( + "{}", + error.display_chain_with_msg("Failed to save updated settings") + ); } persister diff --git a/mullvad-leak-checker/src/traceroute/unix/linux.rs b/mullvad-leak-checker/src/traceroute/unix/linux.rs index 6df2dbaa4a..30ed579adf 100644 --- a/mullvad-leak-checker/src/traceroute/unix/linux.rs +++ b/mullvad-leak-checker/src/traceroute/unix/linux.rs @@ -141,10 +141,10 @@ async fn recv_ttl_responses( // Call recvmsg in a loop let recv_packet = loop { - if let Some(timeout_at) = timeout_at { - if Instant::now() >= timeout_at { - break 'outer; - } + if let Some(timeout_at) = timeout_at + && Instant::now() >= timeout_at + { + break 'outer; } let recv_packet = match destination { diff --git a/mullvad-masque-proxy/src/server/mod.rs b/mullvad-masque-proxy/src/server/mod.rs index 205b7b912f..f8f224d485 100644 --- a/mullvad-masque-proxy/src/server/mod.rs +++ b/mullvad-masque-proxy/src/server/mod.rs @@ -186,26 +186,26 @@ impl Server { } } - if let Some(hostname) = &server_params.hostname { - if &proxy_uri.hostname != hostname { - let valid_uri = ProxyUri { - hostname: hostname.to_string(), - ..proxy_uri - }; + if let Some(hostname) = &server_params.hostname + && &proxy_uri.hostname != hostname + { + let valid_uri = ProxyUri { + hostname: hostname.to_string(), + ..proxy_uri + }; - respond_with_redirect(stream, valid_uri).await; + respond_with_redirect(stream, valid_uri).await; - // NOTE: Recursing like this makes us vulnerable to DoS if the client keeps - // sending the wrong hostname. This is fine since this is just an example server. - Box::pin(Self::accept_proxy_request( - quic_conn, - http_conn, - server_params, - )) - .await; + // NOTE: Recursing like this makes us vulnerable to DoS if the client keeps + // sending the wrong hostname. This is fine since this is just an example server. + Box::pin(Self::accept_proxy_request( + quic_conn, + http_conn, + server_params, + )) + .await; - return; - } + return; } if !server_params diff --git a/talpid-core/src/firewall/linux.rs b/talpid-core/src/firewall/linux.rs index 53dd63fe0b..1a418e8ca6 100644 --- a/talpid-core/src/firewall/linux.rs +++ b/talpid-core/src/firewall/linux.rs @@ -148,10 +148,10 @@ impl Firewall { fn apply_kernel_config(policy: &FirewallPolicy) { if *DONT_SET_SRC_VALID_MARK { log::debug!("Not setting src_valid_mark"); - } else if let FirewallPolicy::Connecting { .. } = policy { - if let Err(err) = set_src_valid_mark_sysctl() { - log::error!("Failed to apply src_valid_mark: {}", err); - } + } else if let FirewallPolicy::Connecting { .. } = policy + && let Err(err) = set_src_valid_mark_sysctl() + { + log::error!("Failed to apply src_valid_mark: {}", err); } // When we have a tunnel with an IP configured, we configure the system @@ -166,10 +166,9 @@ impl Firewall { if *DONT_SET_ARP_IGNORE { log::debug!("Not setting arp_ignore"); } else if let FirewallPolicy::Connecting { .. } | FirewallPolicy::Connected { .. } = policy + && let Err(err) = lock_down_arp_ignore_sysctl() { - if let Err(err) = lock_down_arp_ignore_sysctl() { - log::error!("Failed to apply arp_ignore: {}", err); - } + log::error!("Failed to apply arp_ignore: {}", err); } } diff --git a/talpid-core/src/logging/mod.rs b/talpid-core/src/logging/mod.rs index 0e15054dd4..bd09c9dc03 100644 --- a/talpid-core/src/logging/mod.rs +++ b/talpid-core/src/logging/mod.rs @@ -11,14 +11,14 @@ pub struct RotateLogError(#[from] io::Error); /// it is backed up with the extension changed to `.old.log`. pub fn rotate_log(file: &Path) -> Result<(), RotateLogError> { let backup = file.with_extension("old.log"); - if let Err(error) = fs::rename(file, &backup) { - if error.kind() != io::ErrorKind::NotFound { - log::warn!( - "Failed to rotate log file to {}: {}", - backup.display(), - error - ); - } + if let Err(error) = fs::rename(file, &backup) + && error.kind() != io::ErrorKind::NotFound + { + log::warn!( + "Failed to rotate log file to {}: {}", + backup.display(), + error + ); } fs::File::create(file).map(|_| ()).map_err(RotateLogError) diff --git a/talpid-core/src/tunnel_state_machine/connecting_state.rs b/talpid-core/src/tunnel_state_machine/connecting_state.rs index 9ce22a6285..8f26c92b9d 100644 --- a/talpid-core/src/tunnel_state_machine/connecting_state.rs +++ b/talpid-core/src/tunnel_state_machine/connecting_state.rs @@ -272,10 +272,10 @@ impl ConnectingState { } }; - if block_reason.is_none() { - if let Some(remaining_time) = MIN_TUNNEL_ALIVE_TIME.checked_sub(start.elapsed()) { - thread::sleep(remaining_time); - } + if block_reason.is_none() + && let Some(remaining_time) = MIN_TUNNEL_ALIVE_TIME.checked_sub(start.elapsed()) + { + thread::sleep(remaining_time); } if tunnel_close_event_tx.send(block_reason).is_err() { diff --git a/talpid-dbus/src/network_manager.rs b/talpid-dbus/src/network_manager.rs index df49c3cd2b..cd16677670 100644 --- a/talpid-dbus/src/network_manager.rs +++ b/talpid-dbus/src/network_manager.rs @@ -560,10 +560,10 @@ impl NetworkManager { Self::update_dns_config(&mut settings, "ipv6", v6_dns); } - if let Some(wg_config) = settings.get_mut("wireguard") { - if !wg_config.contains_key("fwmark") { - log::error!("WireGuard config doesn't contain the firewall mark"); - } + if let Some(wg_config) = settings.get_mut("wireguard") + && !wg_config.contains_key("fwmark") + { + log::error!("WireGuard config doesn't contain the firewall mark"); } self.reapply_settings(&device_path, settings, version_id)?; diff --git a/talpid-future/src/retry.rs b/talpid-future/src/retry.rs index f2d7d2a3e2..def46d5bc2 100644 --- a/talpid-future/src/retry.rs +++ b/talpid-future/src/retry.rs @@ -18,12 +18,13 @@ pub async fn retry_future< ) -> T { loop { let current_result = factory().await; - if should_retry(¤t_result) { - if let Some(delay) = delays.next() { - sleep(delay).await; - continue; - } + if should_retry(¤t_result) + && let Some(delay) = delays.next() + { + sleep(delay).await; + continue; } + return current_result; } } @@ -50,11 +51,12 @@ impl Iterator for ConstantInterval { type Item = Duration; fn next(&mut self) -> Option<Duration> { - if let Some(max_attempts) = self.max_attempts { - if self.attempt >= max_attempts { - return None; - } + if let Some(max_attempts) = self.max_attempts + && self.attempt >= max_attempts + { + return None; } + self.attempt = self.attempt.saturating_add(1); Some(self.interval) } @@ -92,10 +94,10 @@ impl ExponentialBackoff { fn next_delay(&mut self) -> Duration { let next = self.next; - if let Some(max_delay) = self.max_delay { - if next > max_delay { - return max_delay; - } + if let Some(max_delay) = self.max_delay + && next > max_delay + { + return max_delay; } self.next = next.saturating_mul(self.factor); diff --git a/talpid-openvpn/src/lib.rs b/talpid-openvpn/src/lib.rs index 29ec3d44bd..30103d59a4 100644 --- a/talpid-openvpn/src/lib.rs +++ b/talpid-openvpn/src/lib.rs @@ -543,14 +543,14 @@ impl<C: OpenVpnBuilder + Send + 'static> OpenVpnMonitor<C> { fn create_proxy_auth_file( proxy_settings: &Option<CustomProxy>, ) -> std::result::Result<Option<mktemp::TempFile>, io::Error> { - if let Some(CustomProxy::Socks5Remote(remote_proxy)) = proxy_settings { - if let Some(ref proxy_auth) = remote_proxy.auth { - return Ok(Some(Self::create_credentials_file( - proxy_auth.username(), - proxy_auth.password(), - )?)); - } + if let Some(CustomProxy::Socks5Remote(remote_proxy)) = proxy_settings + && let Some(ref proxy_auth) = remote_proxy.auth + { + let credentials_file = + Self::create_credentials_file(proxy_auth.username(), proxy_auth.password())?; + return Ok(Some(credentials_file)); } + Ok(None) } diff --git a/talpid-openvpn/src/mktemp.rs b/talpid-openvpn/src/mktemp.rs index 9e5709ce1f..c7c8454908 100644 --- a/talpid-openvpn/src/mktemp.rs +++ b/talpid-openvpn/src/mktemp.rs @@ -31,14 +31,14 @@ impl AsRef<Path> for TempFile { impl Drop for TempFile { fn drop(&mut self) { - if let Err(e) = fs::remove_file(&self.path) { - if e.kind() != io::ErrorKind::NotFound { - log::error!( - "Unable to remove temp file {}: {:?}", - self.path.display(), - e - ); - } + if let Err(e) = fs::remove_file(&self.path) + && e.kind() != io::ErrorKind::NotFound + { + log::error!( + "Unable to remove temp file {}: {:?}", + self.path.display(), + e + ); } } } diff --git a/talpid-platform-metadata/src/linux.rs b/talpid-platform-metadata/src/linux.rs index 664ba394af..e032daf97f 100644 --- a/talpid-platform-metadata/src/linux.rs +++ b/talpid-platform-metadata/src/linux.rs @@ -30,12 +30,11 @@ fn read_os_release_file_short() -> Option<String> { let os_name = os_release_info.remove("NAME"); let os_version_id = os_release_info.remove("VERSION_ID"); - if let Some(os_name) = os_name { - if os_name != "NixOS" { - if let Some(os_version_id) = os_version_id { - return Some(format!("{os_name} {os_version_id}")); - } - } + if let Some(os_name) = os_name + && os_name != "NixOS" + && let Some(os_version_id) = os_version_id + { + return Some(format!("{os_name} {os_version_id}")); } os_release_info.remove("PRETTY_NAME") diff --git a/talpid-routing/src/unix/linux.rs b/talpid-routing/src/unix/linux.rs index 8340e4534d..186fa07188 100644 --- a/talpid-routing/src/unix/linux.rs +++ b/talpid-routing/src/unix/linux.rs @@ -273,10 +273,10 @@ impl RouteManagerImpl { let mut response = self.handle.request(req).map_err(Error::Netlink)?; while let Some(message) = response.next().await { - if let NetlinkPayload::Error(error) = message.payload { - if error.to_io().kind() != io::ErrorKind::NotFound { - return Err(Error::Netlink(rtnetlink::Error::NetlinkError(error))); - } + if let NetlinkPayload::Error(error) = message.payload + && error.to_io().kind() != io::ErrorKind::NotFound + { + return Err(Error::Netlink(rtnetlink::Error::NetlinkError(error))); } } Ok(()) @@ -565,11 +565,12 @@ impl RouteManagerImpl { async fn delete_route_if_exists(&self, route: &Route) -> Result<()> { if let Err(error) = self.delete_route(route).await { - if let Error::Netlink(rtnetlink::Error::NetlinkError(msg)) = &error { - if msg.code == -libc::ESRCH { - return Ok(()); - } + if let Error::Netlink(rtnetlink::Error::NetlinkError(msg)) = &error + && msg.code == -libc::ESRCH + { + return Ok(()); } + Err(error) } else { Ok(()) @@ -617,10 +618,10 @@ impl RouteManagerImpl { route_message.nlas.push(RouteNla::Table(route.table_id)); } - if let Some(interface_name) = route.node.get_device() { - if let Some(iface_idx) = self.find_iface_idx(interface_name) { - route_message.nlas.push(RouteNla::Oif(iface_idx)); - } + if let Some(interface_name) = route.node.get_device() + && let Some(iface_idx) = self.find_iface_idx(interface_name) + { + route_message.nlas.push(RouteNla::Oif(iface_idx)); } if let Some(gateway) = route.node.get_address() { @@ -662,10 +663,10 @@ impl RouteManagerImpl { add_message = add_message.gateway(node_address); } - if let Some(interface_name) = route.node.get_device() { - if let Some(iface_idx) = self.find_iface_idx(interface_name) { - add_message = add_message.output_interface(iface_idx); - } + if let Some(interface_name) = route.node.get_device() + && let Some(iface_idx) = self.find_iface_idx(interface_name) + { + add_message = add_message.output_interface(iface_idx); } add_message.message_mut().clone() @@ -687,10 +688,10 @@ impl RouteManagerImpl { add_message = add_message.gateway(node_address); } - if let Some(interface_name) = route.node.get_device() { - if let Some(iface_idx) = self.find_iface_idx(interface_name) { - add_message = add_message.output_interface(iface_idx); - } + if let Some(interface_name) = route.node.get_device() + && let Some(iface_idx) = self.find_iface_idx(interface_name) + { + add_message = add_message.output_interface(iface_idx); } add_message.message_mut().clone() @@ -807,13 +808,13 @@ impl RouteManagerImpl { let target_device = LinkNla::IfName(device); while let Some(msg) = links.try_next().await.map_err(|_| Error::LinkNotFound)? { let found = msg.nlas.contains(&target_device); - if found { - if let Some(LinkNla::Mtu(mtu)) = + if found + && let Some(LinkNla::Mtu(mtu)) = msg.nlas.iter().find(|e| matches!(e, LinkNla::Mtu(_))) - { - return Ok(u16::try_from(*mtu) - .expect("MTU returned by device does not fit into a u16")); - } + { + return Ok( + u16::try_from(*mtu).expect("MTU returned by device does not fit into a u16") + ); } } Err(Error::LinkNotFound) diff --git a/talpid-wireguard/src/wireguard_kernel/mod.rs b/talpid-wireguard/src/wireguard_kernel/mod.rs index 90872afb94..eb2ebe0f5d 100644 --- a/talpid-wireguard/src/wireguard_kernel/mod.rs +++ b/talpid-wireguard/src/wireguard_kernel/mod.rs @@ -134,15 +134,16 @@ impl Handle { .request(message, SocketAddr::new(0, 0)) .map_err(Error::NetlinkRequest)?; let response = req.next().await; - if let Some(response) = response { - if let NetlinkPayload::InnerMessage(msg) = response.payload { - for nla in msg.nlas.into_iter() { - if let ControlNla::FamilyId(id) = nla { - return Ok(id); - } + if let Some(response) = response + && let NetlinkPayload::InnerMessage(msg) = response.payload + { + for nla in msg.nlas.into_iter() { + if let ControlNla::FamilyId(id) = nla { + return Ok(id); } } } + Err(Error::WireguardNetlinkInterfaceUnavailable) } .await; diff --git a/wireguard-go-rs/build.rs b/wireguard-go-rs/build.rs index f7a7d9d6a2..c1aaf71485 100644 --- a/wireguard-go-rs/build.rs +++ b/wireguard-go-rs/build.rs @@ -362,11 +362,12 @@ fn find_file( for path in std::fs::read_dir(dir).context("Failed to read dir")? { let entry = path.context("Failed to read dir entry")?; let path = entry.path(); - if path.is_dir() { - if let Some(result) = find_file(&path, condition)? { - return Ok(Some(result)); - } + if path.is_dir() + && let Some(result) = find_file(&path, condition)? + { + return Ok(Some(result)); } + if condition(&path) { return Ok(Some(path.to_owned())); } |
