diff options
| author | Linus Färnstrand <linus@mullvad.net> | 2023-08-04 10:59:28 +0200 |
|---|---|---|
| committer | Linus Färnstrand <linus@mullvad.net> | 2023-08-04 10:59:28 +0200 |
| commit | f5d5a5c7bf3889685c7c9fce9b53f85fd56e59b0 (patch) | |
| tree | 1adbfba78ea23c04f9ecfed60fd57eff683fec33 | |
| parent | c1ac80e985e92a74cc580fd85b2e4f5b57c8c96d (diff) | |
| parent | 6f64fb7cf49f23b0b00817ad2750dea860187140 (diff) | |
| download | mullvadvpn-f5d5a5c7bf3889685c7c9fce9b53f85fd56e59b0.tar.xz mullvadvpn-f5d5a5c7bf3889685c7c9fce9b53f85fd56e59b0.zip | |
Merge branch 'replace-lazy_static-with-std-alternatives-des-226'
41 files changed, 401 insertions, 417 deletions
diff --git a/.github/workflows/rust-unused-dependencies.yml b/.github/workflows/rust-unused-dependencies.yml index e8d708667f..b2c95bcd7a 100644 --- a/.github/workflows/rust-unused-dependencies.yml +++ b/.github/workflows/rust-unused-dependencies.yml @@ -9,7 +9,8 @@ on: - 'building/*-container-image.txt' workflow_dispatch: env: - RUST_NIGHTLY_TOOLCHAIN: nightly-2023-01-13 + # Pinning nightly just to avoid random breakage. It's fine to bump this at any time + RUST_NIGHTLY_TOOLCHAIN: nightly-2023-08-03 jobs: prepare-containers: runs-on: ubuntu-latest diff --git a/Cargo.lock b/Cargo.lock index a777d32a46..cc7ef30c80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1984,7 +1984,6 @@ dependencies = [ "err-derive", "fern", "futures", - "lazy_static", "libc", "log", "log-panics", @@ -1997,6 +1996,7 @@ dependencies = [ "mullvad-version", "nix 0.23.1", "objc", + "once_cell", "parking_lot", "rand 0.8.5", "regex", @@ -2062,11 +2062,11 @@ dependencies = [ "chrono", "err-derive", "futures", - "lazy_static", "log", "mullvad-paths", "mullvad-types", "nix 0.23.1", + "once_cell", "parity-tokio-ipc", "prost", "prost-types", @@ -2105,11 +2105,11 @@ dependencies = [ "duct", "env_logger 0.10.0", "err-derive", - "lazy_static", "log", "mullvad-api", "mullvad-paths", "mullvad-version", + "once_cell", "regex", "talpid-platform-metadata", "talpid-types", @@ -2127,10 +2127,10 @@ dependencies = [ "err-derive", "futures", "ipnetwork", - "lazy_static", "log", "mullvad-api", "mullvad-types", + "once_cell", "parking_lot", "rand 0.8.5", "serde_json", @@ -2146,13 +2146,13 @@ dependencies = [ "clap", "env_logger 0.10.0", "err-derive", - "lazy_static", "mullvad-api", "mullvad-daemon", "mullvad-management-interface", "mullvad-paths", "mullvad-types", "mullvad-version", + "once_cell", "talpid-core", "talpid-types", "tokio", @@ -2167,8 +2167,8 @@ dependencies = [ "err-derive", "ipnetwork", "jnix", - "lazy_static", "log", + "once_cell", "rand 0.8.5", "regex", "serde", @@ -3575,7 +3575,6 @@ dependencies = [ "inotify 0.10.0", "ipnetwork", "jnix", - "lazy_static", "libc", "log", "memoffset 0.6.4", @@ -3617,9 +3616,9 @@ version = "0.0.0" dependencies = [ "dbus", "err-derive", - "lazy_static", "libc", "log", + "once_cell", "tokio", ] @@ -3632,8 +3631,8 @@ dependencies = [ "err-derive", "futures", "is-terminal", - "lazy_static", "log", + "once_cell", "os_pipe", "parity-tokio-ipc", "parking_lot", @@ -3692,12 +3691,12 @@ dependencies = [ "err-derive", "futures", "ipnetwork", - "lazy_static", "libc", "log", "netlink-packet-route", "netlink-sys", "nix 0.26.1", + "once_cell", "rtnetlink", "system-configuration", "talpid-types", @@ -3792,7 +3791,6 @@ dependencies = [ "hex", "internet-checksum", "ipnetwork", - "lazy_static", "libc", "log", "netlink-packet-core", @@ -3800,6 +3798,7 @@ dependencies = [ "netlink-packet-utils", "netlink-proto", "nix 0.23.1", + "once_cell", "parking_lot", "rand 0.8.5", "rtnetlink", @@ -4130,7 +4129,7 @@ version = "0.0.0" dependencies = [ "err-derive", "htmlize", - "lazy_static", + "once_cell", "quick-xml", "regex", "serde", diff --git a/android/translations-converter/Cargo.toml b/android/translations-converter/Cargo.toml index 938f7503d8..8f3a7dca12 100644 --- a/android/translations-converter/Cargo.toml +++ b/android/translations-converter/Cargo.toml @@ -11,7 +11,7 @@ publish.workspace = true [dependencies] err-derive = "0.3.1" htmlize = { version = "1.0.2", features = ["unescape"] } -lazy_static = "1" +once_cell = "1.13" regex = "1" serde = { version = "1", features = ["derive"] } quick-xml = { version = "0.27.1", features = ["serialize"] } diff --git a/android/translations-converter/src/android/string_value.rs b/android/translations-converter/src/android/string_value.rs index c2f8e7a6ce..9513f3e096 100644 --- a/android/translations-converter/src/android/string_value.rs +++ b/android/translations-converter/src/android/string_value.rs @@ -1,4 +1,4 @@ -use lazy_static::lazy_static; +use once_cell::sync::Lazy; use regex::Regex; use serde::{Deserialize, Deserializer, Serialize}; use std::{ @@ -32,10 +32,7 @@ impl StringValue { /// The input XML file might have line breaks inside the string, and they should be collapsed /// into a single whitespace character. fn collapse_line_breaks(original: String) -> String { - lazy_static! { - static ref LINE_BREAKS: Regex = Regex::new(r"\s*\n\s*").unwrap(); - } - + static LINE_BREAKS: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s*\n\s*").unwrap()); LINE_BREAKS.replace_all(&original, " ").into_owned() } @@ -46,9 +43,7 @@ impl StringValue { /// would update the string so that all parameters have indices: `Things are %1$d, %3$s and /// %4$s`. fn ensure_parameters_are_indexed(original: String) -> String { - lazy_static! { - static ref PARAMETER_INDEX: Regex = Regex::new(r"^(\d+)\$").unwrap(); - } + static PARAMETER_INDEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(\d+)\$").unwrap()); let mut parts = original.split('%'); let mut output = parts.next().unwrap().to_owned(); diff --git a/android/translations-converter/src/normalize.rs b/android/translations-converter/src/normalize.rs index 3992004bd2..1ea0ae9440 100644 --- a/android/translations-converter/src/normalize.rs +++ b/android/translations-converter/src/normalize.rs @@ -1,4 +1,4 @@ -use lazy_static::lazy_static; +use once_cell::sync::Lazy; use regex::Regex; pub trait Normalize { @@ -12,11 +12,9 @@ mod android { use super::*; use crate::android::StringValue; - lazy_static! { - static ref APOSTROPHES: Regex = Regex::new(r"\\'").unwrap(); - static ref DOUBLE_QUOTES: Regex = Regex::new(r#"\\""#).unwrap(); - static ref PARAMETERS: Regex = Regex::new(r"%[0-9]*\$").unwrap(); - } + static APOSTROPHES: Lazy<Regex> = Lazy::new(|| Regex::new(r"\\'").unwrap()); + static DOUBLE_QUOTES: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\\""#).unwrap()); + static PARAMETERS: Lazy<Regex> = Lazy::new(|| Regex::new(r"%[0-9]*\$").unwrap()); impl Normalize for StringValue { fn normalize(&self) -> String { @@ -37,11 +35,9 @@ mod gettext { use super::*; use crate::gettext::MsgString; - lazy_static! { - static ref ESCAPED_SINGLE_QUOTES: Regex = Regex::new(r"\\'").unwrap(); - static ref ESCAPED_DOUBLE_QUOTES: Regex = Regex::new(r#"\\""#).unwrap(); - static ref PARAMETERS: Regex = Regex::new(r"%\([^)]*\)").unwrap(); - } + static ESCAPED_SINGLE_QUOTES: Lazy<Regex> = Lazy::new(|| Regex::new(r"\\'").unwrap()); + static ESCAPED_DOUBLE_QUOTES: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\\""#).unwrap()); + static PARAMETERS: Lazy<Regex> = Lazy::new(|| Regex::new(r"%\([^)]*\)").unwrap()); impl Normalize for MsgString { fn normalize(&self) -> String { diff --git a/mullvad-api/src/lib.rs b/mullvad-api/src/lib.rs index e304df1dec..37faf5c40c 100644 --- a/mullvad-api/src/lib.rs +++ b/mullvad-api/src/lib.rs @@ -9,8 +9,8 @@ use mullvad_types::{ account::{AccountToken, VoucherSubmission}, version::AppVersion, }; -use once_cell::sync::OnceCell; use proxy::ApiConnectionMode; +use std::sync::OnceLock; use std::{ cell::Cell, collections::BTreeMap, @@ -66,18 +66,18 @@ const APP_URL_PREFIX: &str = "app/v1"; pub static API: LazyManual<ApiEndpoint> = LazyManual::new(ApiEndpoint::from_env_vars); -unsafe impl<T, F: Send> Sync for LazyManual<T, F> where OnceCell<T>: Sync {} +unsafe impl<T, F: Send> Sync for LazyManual<T, F> where OnceLock<T>: Sync {} /// A value that is either initialized on access or explicitly. pub struct LazyManual<T, F = fn() -> T> { - cell: OnceCell<T>, + cell: OnceLock<T>, lazy_fn: Cell<Option<F>>, } impl<T, F> LazyManual<T, F> { const fn new(lazy_fn: F) -> Self { Self { - cell: OnceCell::new(), + cell: OnceLock::new(), lazy_fn: Cell::new(Some(lazy_fn)), } } diff --git a/mullvad-daemon/Cargo.toml b/mullvad-daemon/Cargo.toml index 273c5ab6f6..529e74b6e4 100644 --- a/mullvad-daemon/Cargo.toml +++ b/mullvad-daemon/Cargo.toml @@ -17,7 +17,7 @@ chrono = { workspace = true } err-derive = "0.3.1" fern = { version = "0.6", features = ["colored"] } futures = "0.3" -lazy_static = "1.0" +once_cell = "1.13" libc = "0.2" log = "0.4" parking_lot = "0.12.0" diff --git a/mullvad-daemon/src/account_history.rs b/mullvad-daemon/src/account_history.rs index ee3d9932e6..1df9180f34 100644 --- a/mullvad-daemon/src/account_history.rs +++ b/mullvad-daemon/src/account_history.rs @@ -1,4 +1,5 @@ use mullvad_types::account::AccountToken; +use once_cell::sync::Lazy; use regex::Regex; use std::path::Path; use talpid_types::ErrorExt; @@ -32,9 +33,7 @@ pub struct AccountHistory { token: Option<AccountToken>, } -lazy_static::lazy_static! { - static ref ACCOUNT_REGEX: Regex = Regex::new(r"^[0-9]+$").unwrap(); -} +static ACCOUNT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[0-9]+$").unwrap()); impl AccountHistory { pub async fn new( diff --git a/mullvad-daemon/src/cli.rs b/mullvad-daemon/src/cli.rs index 00552a611a..96416999bf 100644 --- a/mullvad-daemon/src/cli.rs +++ b/mullvad-daemon/src/cli.rs @@ -1,7 +1,8 @@ use clap::Parser; +use once_cell::sync::Lazy; -lazy_static::lazy_static! { - static ref ENV_DESC: String = format!( +static ENV_DESC: Lazy<String> = Lazy::new(|| { + format!( "ENV: MULLVAD_RESOURCE_DIR Resource directory (i.e used to locate a root CA certificate) @@ -18,8 +19,9 @@ lazy_static::lazy_static! { mullvad_paths::get_default_settings_dir().map(|dir| dir.display().to_string()).unwrap_or_else(|_| "N/A".to_string()), mullvad_paths::get_default_cache_dir().map(|dir| dir.display().to_string()).unwrap_or_else(|_| "N/A".to_string()), mullvad_paths::get_default_log_dir().map(|dir| dir.display().to_string()).unwrap_or_else(|_| "N/A".to_string()), - mullvad_paths::get_default_rpc_socket_path().display()); -} + mullvad_paths::get_default_rpc_socket_path().display() +) +}); #[derive(Debug, Parser)] #[command(author, version = mullvad_version::VERSION, about, long_about = None, after_help = &*ENV_DESC)] @@ -70,9 +72,7 @@ pub struct Config { } pub fn get_config() -> &'static Config { - lazy_static::lazy_static! { - static ref CONFIG: Config = create_config(); - } + static CONFIG: Lazy<Config> = Lazy::new(create_config); &CONFIG } diff --git a/mullvad-daemon/src/geoip.rs b/mullvad-daemon/src/geoip.rs index 9f4962efcd..527e06cf61 100644 --- a/mullvad-daemon/src/geoip.rs +++ b/mullvad-daemon/src/geoip.rs @@ -4,6 +4,7 @@ use mullvad_api::{ rest::{Error, RequestServiceHandle}, }; use mullvad_types::location::{AmIMullvad, GeoIpLocation}; +use once_cell::sync::Lazy; use talpid_types::ErrorExt; // Define the Mullvad connection checking api endpoint. @@ -15,27 +16,25 @@ use talpid_types::ErrorExt; // production build, a warning will be logged and the env variable *won´t* have // any effect on the api call. The default host name `am.i.mullvad.net` will // always be used in release mode. -lazy_static::lazy_static! { - static ref MULLVAD_CONNCHECK_HOST: String = { - const DEFAULT_CONNCHECK_HOST: &str = "am.i.mullvad.net"; - let conncheck_host_var = std::env::var("MULLVAD_CONNCHECK_HOST").ok(); - let host = if cfg!(feature = "api-override") { - match conncheck_host_var.as_deref() { - Some(host) => { - log::debug!("Overriding conncheck endpoint. Using {}", &host); - host - }, - None => DEFAULT_CONNCHECK_HOST, +static MULLVAD_CONNCHECK_HOST: Lazy<String> = Lazy::new(|| { + const DEFAULT_CONNCHECK_HOST: &str = "am.i.mullvad.net"; + let conncheck_host_var = std::env::var("MULLVAD_CONNCHECK_HOST").ok(); + let host = if cfg!(feature = "api-override") { + match conncheck_host_var.as_deref() { + Some(host) => { + log::debug!("Overriding conncheck endpoint. Using {}", &host); + host } - } else { - if conncheck_host_var.is_some() { - log::warn!("These variables are ignored in production builds: MULLVAD_CONNCHECK_HOST"); - }; - DEFAULT_CONNCHECK_HOST + None => DEFAULT_CONNCHECK_HOST, + } + } else { + if conncheck_host_var.is_some() { + log::warn!("These variables are ignored in production builds: MULLVAD_CONNCHECK_HOST"); }; - host.to_string() + DEFAULT_CONNCHECK_HOST }; -} + host.to_string() +}); pub async fn send_location_request( request_sender: RequestServiceHandle, diff --git a/mullvad-daemon/src/migrations/account_history.rs b/mullvad-daemon/src/migrations/account_history.rs index 520717e405..d007c1414f 100644 --- a/mullvad-daemon/src/migrations/account_history.rs +++ b/mullvad-daemon/src/migrations/account_history.rs @@ -1,5 +1,6 @@ use super::{Error, Result}; use mullvad_types::account::AccountToken; +use once_cell::sync::Lazy; use regex::Regex; use serde::Deserialize; use std::path::Path; @@ -16,9 +17,7 @@ use tokio::{ const ACCOUNT_HISTORY_FILE: &str = "account-history.json"; -lazy_static::lazy_static! { - static ref ACCOUNT_REGEX: Regex = Regex::new(r"^[0-9]+$").unwrap(); -} +static ACCOUNT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[0-9]+$").unwrap()); pub async fn migrate_location(old_dir: &Path, new_dir: &Path) { let old_path = old_dir.join(ACCOUNT_HISTORY_FILE); diff --git a/mullvad-daemon/src/system_service.rs b/mullvad-daemon/src/system_service.rs index 9432e8449b..11b3e88eac 100644 --- a/mullvad-daemon/src/system_service.rs +++ b/mullvad-daemon/src/system_service.rs @@ -1,6 +1,7 @@ use crate::cli; use libc::c_void; use mullvad_daemon::{runtime::new_runtime_builder, DaemonShutdownHandle}; +use once_cell::sync::Lazy; use std::{ env, ffi::OsString, @@ -39,12 +40,12 @@ static SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS; const SERVICE_RECOVERY_LAST_RESTART_DELAY: Duration = Duration::from_secs(60 * 10); const SERVICE_FAILURE_RESET_PERIOD: Duration = Duration::from_secs(60 * 15); -lazy_static::lazy_static! { - static ref SERVICE_ACCESS: ServiceAccess = ServiceAccess::QUERY_CONFIG - | ServiceAccess::CHANGE_CONFIG - | ServiceAccess::START - | ServiceAccess::DELETE; -} +static SERVICE_ACCESS: Lazy<ServiceAccess> = Lazy::new(|| { + ServiceAccess::QUERY_CONFIG + | ServiceAccess::CHANGE_CONFIG + | ServiceAccess::START + | ServiceAccess::DELETE +}); pub fn run() -> Result<(), String> { // Start the service dispatcher. diff --git a/mullvad-daemon/src/version_check.rs b/mullvad-daemon/src/version_check.rs index 1160ac3d7e..b488b0b324 100644 --- a/mullvad-daemon/src/version_check.rs +++ b/mullvad-daemon/src/version_check.rs @@ -6,6 +6,7 @@ use futures::{ }; use mullvad_api::{availability::ApiAvailabilityHandle, rest::MullvadRestHandle, AppVersionProxy}; use mullvad_types::version::{AppVersionInfo, ParsedAppVersion}; +use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use std::{ future::Future, @@ -20,10 +21,9 @@ use tokio::fs::{self, File}; const VERSION_INFO_FILENAME: &str = "version-info.json"; -lazy_static::lazy_static! { - static ref APP_VERSION: ParsedAppVersion = ParsedAppVersion::from_str(mullvad_version::VERSION).unwrap(); - static ref IS_DEV_BUILD: bool = APP_VERSION.is_dev(); -} +static APP_VERSION: Lazy<ParsedAppVersion> = + Lazy::new(|| ParsedAppVersion::from_str(mullvad_version::VERSION).unwrap()); +static IS_DEV_BUILD: Lazy<bool> = Lazy::new(|| APP_VERSION.is_dev()); const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15); diff --git a/mullvad-management-interface/Cargo.toml b/mullvad-management-interface/Cargo.toml index cb1d9b8293..9f5a520c5c 100644 --- a/mullvad-management-interface/Cargo.toml +++ b/mullvad-management-interface/Cargo.toml @@ -25,7 +25,7 @@ log = "0.4" [target.'cfg(unix)'.dependencies] nix = "0.23" -lazy_static = "1.0" +once_cell = "1.13" [build-dependencies] tonic-build = { workspace = true, default-features = false, features = ["transport", "prost"] } diff --git a/mullvad-management-interface/src/lib.rs b/mullvad-management-interface/src/lib.rs index 7009de0740..888cf7a318 100644 --- a/mullvad-management-interface/src/lib.rs +++ b/mullvad-management-interface/src/lib.rs @@ -21,10 +21,10 @@ pub type ManagementServiceClient = pub use types::management_service_server::{ManagementService, ManagementServiceServer}; #[cfg(unix)] -lazy_static::lazy_static! { - static ref MULLVAD_MANAGEMENT_SOCKET_GROUP: Option<String> = env::var("MULLVAD_MANAGEMENT_SOCKET_GROUP") - .ok(); -} +use once_cell::sync::Lazy; +#[cfg(unix)] +static MULLVAD_MANAGEMENT_SOCKET_GROUP: Lazy<Option<String>> = + Lazy::new(|| env::var("MULLVAD_MANAGEMENT_SOCKET_GROUP").ok()); pub const CUSTOM_LIST_LOCATION_NOT_FOUND_DETAILS: &[u8] = b"custom_list_location_not_found"; pub const CUSTOM_LIST_LIST_NOT_FOUND_DETAILS: &[u8] = b"custom_list_list_not_found"; diff --git a/mullvad-problem-report/Cargo.toml b/mullvad-problem-report/Cargo.toml index 08b20571b3..74a420e676 100644 --- a/mullvad-problem-report/Cargo.toml +++ b/mullvad-problem-report/Cargo.toml @@ -11,7 +11,7 @@ publish.workspace = true [dependencies] dirs = "5.0.1" err-derive = "0.3.1" -lazy_static = "1.0" +once_cell = "1.13" log = "0.4" regex = "1.0" uuid = { version = "0.8", features = ["v4"] } diff --git a/mullvad-problem-report/src/lib.rs b/mullvad-problem-report/src/lib.rs index 9cff4ce9fa..dcc446800f 100644 --- a/mullvad-problem-report/src/lib.rs +++ b/mullvad-problem-report/src/lib.rs @@ -1,7 +1,7 @@ #![deny(rust_2018_idioms)] -use lazy_static::lazy_static; use mullvad_api::proxy::ApiConnectionMode; +use once_cell::sync::Lazy; use regex::Regex; use std::{ borrow::Cow, @@ -413,9 +413,7 @@ impl ProblemReport { } fn redact_account_number(input: &str) -> Cow<'_, str> { - lazy_static! { - static ref RE: Regex = Regex::new("\\d{16}").unwrap(); - } + static RE: Lazy<Regex> = Lazy::new(|| Regex::new("\\d{16}").unwrap()); RE.replace_all(input, "[REDACTED ACCOUNT NUMBER]") } @@ -424,29 +422,25 @@ impl ProblemReport { } fn redact_network_info(input: &str) -> Cow<'_, str> { - lazy_static! { - static ref RE: Regex = { - let boundary = "[^0-9a-zA-Z.:]"; - let combined_pattern = format!( - "(?P<start>^|{})(?:{}|{}|{})", - boundary, - build_ipv4_regex(), - build_ipv6_regex(), - build_mac_regex(), - ); - Regex::new(&combined_pattern).unwrap() - }; - } + static RE: Lazy<Regex> = Lazy::new(|| { + let boundary = "[^0-9a-zA-Z.:]"; + let combined_pattern = format!( + "(?P<start>^|{})(?:{}|{}|{})", + boundary, + build_ipv4_regex(), + build_ipv6_regex(), + build_mac_regex(), + ); + Regex::new(&combined_pattern).unwrap() + }); RE.replace_all(input, "$start[REDACTED]") } fn redact_guids(input: &str) -> Cow<'_, str> { - lazy_static! { - static ref RE: Regex = Regex::new( - r#"(?i)\{?[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}?"# - ) - .unwrap(); - } + static RE: Lazy<Regex> = Lazy::new(|| { + Regex::new(r#"(?i)\{?[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}?"#) + .unwrap() + }); RE.replace_all(input, "[REDACTED]") } diff --git a/mullvad-relay-selector/Cargo.toml b/mullvad-relay-selector/Cargo.toml index 6a69062395..1d61c09586 100644 --- a/mullvad-relay-selector/Cargo.toml +++ b/mullvad-relay-selector/Cargo.toml @@ -25,4 +25,4 @@ mullvad-api = { path = "../mullvad-api" } mullvad-types = { path = "../mullvad-types" } [dev-dependencies] -lazy_static = "1.0" +once_cell = "1.13" diff --git a/mullvad-relay-selector/src/lib.rs b/mullvad-relay-selector/src/lib.rs index 2093ccf07e..843797c853 100644 --- a/mullvad-relay-selector/src/lib.rs +++ b/mullvad-relay-selector/src/lib.rs @@ -1299,6 +1299,7 @@ mod test { ShadowsocksEndpointData, WireguardEndpointData, WireguardRelayEndpointData, }, }; + use once_cell::sync::Lazy; use std::collections::HashSet; use talpid_types::net::{wireguard::PublicKey, Endpoint}; @@ -1313,135 +1314,135 @@ mod test { } } - lazy_static::lazy_static! { - static ref RELAYS: RelayList = RelayList { - etag: None, - countries: vec![ - RelayListCountry { - name: "Sweden".to_string(), - code: "se".to_string(), - cities: vec![ - RelayListCity { - name: "Gothenburg".to_string(), - code: "got".to_string(), - latitude: 57.70887, - longitude: 11.97456, - relays: vec![ - Relay { - hostname: "se9-wireguard".to_string(), - ipv4_addr_in: "185.213.154.68".parse().unwrap(), - ipv6_addr_in: Some("2a03:1b20:5:f011::a09f".parse().unwrap()), - include_in_country: true, - active: true, - owned: true, - provider: "provider0".to_string(), - weight: 1, - endpoint_data: RelayEndpointData::Wireguard(WireguardRelayEndpointData { - public_key: PublicKey::from_base64("BLNHNoGO88LjV/wDBa7CUUwUzPq/fO2UwcGLy56hKy4=").unwrap(), - }), - location: None, - }, - Relay { - hostname: "se10-wireguard".to_string(), - ipv4_addr_in: "185.213.154.69".parse().unwrap(), - ipv6_addr_in: Some("2a03:1b20:5:f011::a10f".parse().unwrap()), - include_in_country: true, - active: true, - owned: false, - provider: "provider1".to_string(), - weight: 1, - endpoint_data: RelayEndpointData::Wireguard(WireguardRelayEndpointData { - public_key: PublicKey::from_base64("BLNHNoGO88LjV/wDBa7CUUwUzPq/fO2UwcGLy56hKy4=").unwrap(), - }), - location: None, - }, - Relay { - hostname: "se-got-001".to_string(), - ipv4_addr_in: "185.213.154.131".parse().unwrap(), - ipv6_addr_in: None, - include_in_country: true, - active: true, - owned: true, - provider: "provider2".to_string(), - weight: 1, - endpoint_data: RelayEndpointData::Openvpn, - location: None, - }, - Relay { - hostname: "se-got-002".to_string(), - ipv4_addr_in: "1.2.3.4".parse().unwrap(), - ipv6_addr_in: None, - include_in_country: true, - active: true, - owned: true, - provider: "provider0".to_string(), - weight: 1, - endpoint_data: RelayEndpointData::Openvpn, - location: None, - }, - Relay { - hostname: "se-got-br-001".to_string(), - ipv4_addr_in: "1.3.3.7".parse().unwrap(), - ipv6_addr_in: None, - include_in_country: true, - active: true, - owned: true, - provider: "provider3".to_string(), - weight: 1, - endpoint_data: RelayEndpointData::Bridge, - location: None, - } - ], - }, - ], - } - ], - openvpn: OpenVpnEndpointData { - ports: vec![ - OpenVpnEndpoint { - port: 1194, - protocol: TransportProtocol::Udp, + static RELAYS: Lazy<RelayList> = Lazy::new(|| RelayList { + etag: None, + countries: vec![RelayListCountry { + name: "Sweden".to_string(), + code: "se".to_string(), + cities: vec![RelayListCity { + name: "Gothenburg".to_string(), + code: "got".to_string(), + latitude: 57.70887, + longitude: 11.97456, + relays: vec![ + Relay { + hostname: "se9-wireguard".to_string(), + ipv4_addr_in: "185.213.154.68".parse().unwrap(), + ipv6_addr_in: Some("2a03:1b20:5:f011::a09f".parse().unwrap()), + include_in_country: true, + active: true, + owned: true, + provider: "provider0".to_string(), + weight: 1, + endpoint_data: RelayEndpointData::Wireguard(WireguardRelayEndpointData { + public_key: PublicKey::from_base64( + "BLNHNoGO88LjV/wDBa7CUUwUzPq/fO2UwcGLy56hKy4=", + ) + .unwrap(), + }), + location: None, }, - OpenVpnEndpoint { - port: 443, - protocol: TransportProtocol::Tcp, + Relay { + hostname: "se10-wireguard".to_string(), + ipv4_addr_in: "185.213.154.69".parse().unwrap(), + ipv6_addr_in: Some("2a03:1b20:5:f011::a10f".parse().unwrap()), + include_in_country: true, + active: true, + owned: false, + provider: "provider1".to_string(), + weight: 1, + endpoint_data: RelayEndpointData::Wireguard(WireguardRelayEndpointData { + public_key: PublicKey::from_base64( + "BLNHNoGO88LjV/wDBa7CUUwUzPq/fO2UwcGLy56hKy4=", + ) + .unwrap(), + }), + location: None, }, - OpenVpnEndpoint { - port: 80, - protocol: TransportProtocol::Tcp, + Relay { + hostname: "se-got-001".to_string(), + ipv4_addr_in: "185.213.154.131".parse().unwrap(), + ipv6_addr_in: None, + include_in_country: true, + active: true, + owned: true, + provider: "provider2".to_string(), + weight: 1, + endpoint_data: RelayEndpointData::Openvpn, + location: None, }, - ], - }, - bridge: BridgeEndpointData { - shadowsocks: vec![ - ShadowsocksEndpointData { - port: 443, - cipher: "aes-256-gcm".to_string(), - password: "mullvad".to_string(), - protocol: TransportProtocol::Tcp, - }, - ShadowsocksEndpointData { - port: 1234, - cipher: "aes-256-cfb".to_string(), - password: "mullvad".to_string(), - protocol: TransportProtocol::Udp, + Relay { + hostname: "se-got-002".to_string(), + ipv4_addr_in: "1.2.3.4".parse().unwrap(), + ipv6_addr_in: None, + include_in_country: true, + active: true, + owned: true, + provider: "provider0".to_string(), + weight: 1, + endpoint_data: RelayEndpointData::Openvpn, + location: None, }, - ShadowsocksEndpointData { - port: 1236, - cipher: "aes-256-gcm".to_string(), - password: "mullvad".to_string(), - protocol: TransportProtocol::Udp, + Relay { + hostname: "se-got-br-001".to_string(), + ipv4_addr_in: "1.3.3.7".parse().unwrap(), + ipv6_addr_in: None, + include_in_country: true, + active: true, + owned: true, + provider: "provider3".to_string(), + weight: 1, + endpoint_data: RelayEndpointData::Bridge, + location: None, }, ], - }, - wireguard: WireguardEndpointData { - port_ranges: vec![(53, 53), (4000, 33433), (33565, 51820), (52000, 60000)], - ipv4_gateway: "10.64.0.1".parse().unwrap(), - ipv6_gateway: "fc00:bbbb:bbbb:bb01::1".parse().unwrap(), - udp2tcp_ports: vec![], - }, - }; - } + }], + }], + openvpn: OpenVpnEndpointData { + ports: vec![ + OpenVpnEndpoint { + port: 1194, + protocol: TransportProtocol::Udp, + }, + OpenVpnEndpoint { + port: 443, + protocol: TransportProtocol::Tcp, + }, + OpenVpnEndpoint { + port: 80, + protocol: TransportProtocol::Tcp, + }, + ], + }, + bridge: BridgeEndpointData { + shadowsocks: vec![ + ShadowsocksEndpointData { + port: 443, + cipher: "aes-256-gcm".to_string(), + password: "mullvad".to_string(), + protocol: TransportProtocol::Tcp, + }, + ShadowsocksEndpointData { + port: 1234, + cipher: "aes-256-cfb".to_string(), + password: "mullvad".to_string(), + protocol: TransportProtocol::Udp, + }, + ShadowsocksEndpointData { + port: 1236, + cipher: "aes-256-gcm".to_string(), + password: "mullvad".to_string(), + protocol: TransportProtocol::Udp, + }, + ], + }, + wireguard: WireguardEndpointData { + port_ranges: vec![(53, 53), (4000, 33433), (33565, 51820), (52000, 60000)], + ipv4_gateway: "10.64.0.1".parse().unwrap(), + ipv6_gateway: "fc00:bbbb:bbbb:bb01::1".parse().unwrap(), + udp2tcp_ports: vec![], + }, + }); fn default_tunnel_type() -> TunnelType { if cfg!(target_os = "windows") { diff --git a/mullvad-setup/Cargo.toml b/mullvad-setup/Cargo.toml index 5959a4d486..a81ea4f477 100644 --- a/mullvad-setup/Cargo.toml +++ b/mullvad-setup/Cargo.toml @@ -16,7 +16,7 @@ path = "src/main.rs" clap = { version = "4.2.7", features = ["cargo"] } env_logger = "0.10.0" err-derive = "0.3.1" -lazy_static = "1.1.0" +once_cell = "1.13" mullvad-management-interface = { path = "../mullvad-management-interface" } diff --git a/mullvad-setup/src/main.rs b/mullvad-setup/src/main.rs index 118b572414..a349554ca6 100644 --- a/mullvad-setup/src/main.rs +++ b/mullvad-setup/src/main.rs @@ -2,6 +2,7 @@ use clap::Parser; use mullvad_api::{self, proxy::ApiConnectionMode, DEVICE_NOT_FOUND}; use mullvad_management_interface::MullvadProxyClient; use mullvad_types::version::ParsedAppVersion; +use once_cell::sync::Lazy; use std::{path::PathBuf, process, str::FromStr, time::Duration}; use talpid_core::{ firewall::{self, Firewall}, @@ -9,10 +10,8 @@ use talpid_core::{ }; use talpid_types::ErrorExt; -lazy_static::lazy_static! { - static ref APP_VERSION: ParsedAppVersion = ParsedAppVersion::from_str(mullvad_version::VERSION).unwrap(); - static ref IS_DEV_BUILD: bool = APP_VERSION.is_dev(); -} +static APP_VERSION: Lazy<ParsedAppVersion> = + Lazy::new(|| ParsedAppVersion::from_str(mullvad_version::VERSION).unwrap()); const KEY_RETRY_INTERVAL: Duration = Duration::ZERO; const KEY_RETRY_MAX_RETRIES: usize = 4; diff --git a/mullvad-types/Cargo.toml b/mullvad-types/Cargo.toml index 33297ca3aa..54c6e7bff0 100644 --- a/mullvad-types/Cargo.toml +++ b/mullvad-types/Cargo.toml @@ -12,7 +12,7 @@ publish.workspace = true chrono = { workspace = true, features = ["clock", "serde"] } err-derive = "0.3.1" ipnetwork = "0.16" -lazy_static = "1.1.0" +once_cell = "1.13" log = "0.4" regex = "1" serde = { version = "1.0", features = ["derive"] } diff --git a/mullvad-types/src/auth_failed.rs b/mullvad-types/src/auth_failed.rs index 1aa788f6a1..6c118ff0eb 100644 --- a/mullvad-types/src/auth_failed.rs +++ b/mullvad-types/src/auth_failed.rs @@ -1,4 +1,4 @@ -use lazy_static::lazy_static; +use once_cell::sync::Lazy; use regex::Regex; use talpid_types::tunnel::ErrorStateCause; @@ -68,9 +68,7 @@ impl TryFrom<&ErrorStateCause> for AuthFailed { // * "This is not a valid Mullvad account" - human-readable message (ignored). // In the case that the message has preceding whitespace, it will be trimmed. fn parse_string(reason: &str) -> Option<&str> { - lazy_static! { - static ref REASON_REGEX: Regex = Regex::new(r"^\[(\w+)\]\s*").unwrap(); - } + static REASON_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\[(\w+)\]\s*").unwrap()); let captures = REASON_REGEX.captures(reason)?; captures.get(1).map(|m| m.as_str()) } diff --git a/mullvad-types/src/version.rs b/mullvad-types/src/version.rs index 97123725a6..b82499f02c 100644 --- a/mullvad-types/src/version.rs +++ b/mullvad-types/src/version.rs @@ -1,5 +1,6 @@ #[cfg(target_os = "android")] use jnix::IntoJava; +use once_cell::sync::Lazy; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{ @@ -7,11 +8,10 @@ use std::{ str::FromStr, }; -lazy_static::lazy_static! { - static ref STABLE_REGEX: Regex = Regex::new(r"^(\d{4})\.(\d+)$").unwrap(); - static ref BETA_REGEX: Regex = Regex::new(r"^(\d{4})\.(\d+)-beta(\d+)$").unwrap(); - static ref DEV_REGEX: Regex = Regex::new(r"^(\d{4})\.(\d+)(\.\d+)?(-beta(\d+))?-dev-(\w+)$").unwrap(); -} +static STABLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(\d{4})\.(\d+)$").unwrap()); +static BETA_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(\d{4})\.(\d+)-beta(\d+)$").unwrap()); +static DEV_REGEX: Lazy<Regex> = + Lazy::new(|| Regex::new(r"^(\d{4})\.(\d+)(\.\d+)?(-beta(\d+))?-dev-(\w+)$").unwrap()); /// AppVersionInfo represents the current stable and the current latest release versions of the /// Mullvad VPN app. diff --git a/talpid-core/Cargo.toml b/talpid-core/Cargo.toml index 34627fcfda..ec8031415b 100644 --- a/talpid-core/Cargo.toml +++ b/talpid-core/Cargo.toml @@ -13,7 +13,6 @@ duct = "0.13" err-derive = "0.3.1" futures = "0.3.15" ipnetwork = "0.16" -lazy_static = "1.0" once_cell = "1.13" libc = "0.2" log = "0.4" diff --git a/talpid-core/src/firewall/linux.rs b/talpid-core/src/firewall/linux.rs index 57a1d601df..3fe2e740bc 100644 --- a/talpid-core/src/firewall/linux.rs +++ b/talpid-core/src/firewall/linux.rs @@ -1,13 +1,13 @@ use super::{FirewallArguments, FirewallPolicy}; use crate::{split_tunnel, tunnel}; use ipnetwork::IpNetwork; -use lazy_static::lazy_static; use libc; use nftnl::{ self, expr::{self, IcmpCode, Payload, RejectionType, Verdict}, nft_expr, table, Batch, Chain, FinalizedBatch, ProtoFamily, Rule, Table, }; +use once_cell::sync::Lazy; use std::{ env, ffi::{CStr, CString}, @@ -56,27 +56,29 @@ pub enum Error { LookupIfaceIndexError(String, #[error(source)] crate::linux::IfaceIndexLookupError), } -lazy_static! { - /// TODO(linus): This crate is not supposed to be Mullvad-aware. So at some point this should be - /// replaced by allowing the table name to be configured from the public API of this crate. - static ref TABLE_NAME: CString = CString::new("mullvad").unwrap(); - static ref IN_CHAIN_NAME: CString = CString::new("input").unwrap(); - static ref OUT_CHAIN_NAME: CString = CString::new("output").unwrap(); - static ref FORWARD_CHAIN_NAME: CString = CString::new("forward").unwrap(); - static ref PREROUTING_CHAIN_NAME: CString = CString::new("prerouting").unwrap(); - static ref MANGLE_CHAIN_NAME: CString = CString::new("mangle").unwrap(); - static ref NAT_CHAIN_NAME: CString = CString::new("nat").unwrap(); +/// TODO(linus): This crate is not supposed to be Mullvad-aware. So at some point this should be +/// replaced by allowing the table name to be configured from the public API of this crate. +static TABLE_NAME: Lazy<CString> = Lazy::new(|| CString::new("mullvad").unwrap()); +static IN_CHAIN_NAME: Lazy<CString> = Lazy::new(|| CString::new("input").unwrap()); +static OUT_CHAIN_NAME: Lazy<CString> = Lazy::new(|| CString::new("output").unwrap()); +static FORWARD_CHAIN_NAME: Lazy<CString> = Lazy::new(|| CString::new("forward").unwrap()); +static PREROUTING_CHAIN_NAME: Lazy<CString> = Lazy::new(|| CString::new("prerouting").unwrap()); +static MANGLE_CHAIN_NAME: Lazy<CString> = Lazy::new(|| CString::new("mangle").unwrap()); +static NAT_CHAIN_NAME: Lazy<CString> = Lazy::new(|| CString::new("nat").unwrap()); - /// Allows controlling whether firewall rules should have packet counters or not from an env - /// variable. Useful for debugging the rules. - static ref ADD_COUNTERS: bool = env::var("TALPID_FIREWALL_DEBUG") +/// Allows controlling whether firewall rules should have packet counters or not from an env +/// variable. Useful for debugging the rules. +static ADD_COUNTERS: Lazy<bool> = Lazy::new(|| { + env::var("TALPID_FIREWALL_DEBUG") .map(|v| v != "0") - .unwrap_or(false); + .unwrap_or(false) +}); - static ref DONT_SET_SRC_VALID_MARK: bool = env::var("TALPID_FIREWALL_DONT_SET_SRC_VALID_MARK") +static DONT_SET_SRC_VALID_MARK: Lazy<bool> = Lazy::new(|| { + env::var("TALPID_FIREWALL_DONT_SET_SRC_VALID_MARK") .map(|v| v != "0") - .unwrap_or(false); -} + .unwrap_or(false) +}); #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] enum Direction { @@ -1027,10 +1029,10 @@ fn set_src_valid_mark_sysctl() -> io::Result<()> { /// Tables that are no longer used but need to be deleted due to upgrades. /// This can be removed when upgrades from 2023.3 are no longer supported. fn batch_deprecated_tables(batch: &mut Batch) { - lazy_static! { - static ref MANGLE_TABLE_NAME_V4: CString = CString::new("mullvadmangle4").unwrap(); - static ref MANGLE_TABLE_NAME_V6: CString = CString::new("mullvadmangle6").unwrap(); - } + static MANGLE_TABLE_NAME_V4: Lazy<CString> = + Lazy::new(|| CString::new("mullvadmangle4").unwrap()); + static MANGLE_TABLE_NAME_V6: Lazy<CString> = + Lazy::new(|| CString::new("mullvadmangle6").unwrap()); let tables = [ Table::new(&*MANGLE_TABLE_NAME_V4, ProtoFamily::Ipv4), Table::new(&*MANGLE_TABLE_NAME_V6, ProtoFamily::Ipv6), diff --git a/talpid-core/src/firewall/mod.rs b/talpid-core/src/firewall/mod.rs index e168ec3f39..5a35b1a7ae 100644 --- a/talpid-core/src/firewall/mod.rs +++ b/talpid-core/src/firewall/mod.rs @@ -1,5 +1,5 @@ use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network}; -use lazy_static::lazy_static; +use once_cell::sync::Lazy; #[cfg(windows)] use std::path::PathBuf; use std::{ @@ -26,18 +26,21 @@ mod imp; pub use self::imp::Error; -lazy_static! { - /// When "allow local network" is enabled the app will allow traffic to and from these networks. - pub(crate) static ref ALLOWED_LAN_NETS: [IpNetwork; 6] = [ +/// When "allow local network" is enabled the app will allow traffic to and from these networks. +pub(crate) static ALLOWED_LAN_NETS: Lazy<[IpNetwork; 6]> = Lazy::new(|| { + [ IpNetwork::V4(Ipv4Network::new(Ipv4Addr::new(10, 0, 0, 0), 8).unwrap()), IpNetwork::V4(Ipv4Network::new(Ipv4Addr::new(172, 16, 0, 0), 12).unwrap()), IpNetwork::V4(Ipv4Network::new(Ipv4Addr::new(192, 168, 0, 0), 16).unwrap()), IpNetwork::V4(Ipv4Network::new(Ipv4Addr::new(169, 254, 0, 0), 16).unwrap()), IpNetwork::V6(Ipv6Network::new(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0), 10).unwrap()), IpNetwork::V6(Ipv6Network::new(Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 0), 7).unwrap()), - ]; - /// When "allow local network" is enabled the app will allow traffic to these networks. - pub(crate) static ref ALLOWED_LAN_MULTICAST_NETS: [IpNetwork; 8] = [ + ] +}); +/// When "allow local network" is enabled the app will allow traffic to these networks. +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))] +pub(crate) static ALLOWED_LAN_MULTICAST_NETS: Lazy<[IpNetwork; 8]> = Lazy::new(|| { + [ // Local network broadcast. Not routable IpNetwork::V4(Ipv4Network::new(Ipv4Addr::new(255, 255, 255, 255), 32).unwrap()), // Local subnetwork multicast. Not routable @@ -54,20 +57,34 @@ lazy_static! { IpNetwork::V6(Ipv6Network::new(Ipv6Addr::new(0xff04, 0, 0, 0, 0, 0, 0, 0), 16).unwrap()), // Site-local IPv6 multicast. IpNetwork::V6(Ipv6Network::new(Ipv6Addr::new(0xff05, 0, 0, 0, 0, 0, 0, 0), 16).unwrap()), - ]; - static ref IPV6_LINK_LOCAL: Ipv6Network = Ipv6Network::new(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0), 10).unwrap(); - /// The allowed target addresses of outbound DHCPv6 requests - static ref DHCPV6_SERVER_ADDRS: [Ipv6Addr; 2] = [ + ] +}); +#[cfg(any(target_os = "linux", target_os = "macos"))] +static IPV6_LINK_LOCAL: Lazy<Ipv6Network> = + Lazy::new(|| Ipv6Network::new(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0), 10).unwrap()); +/// The allowed target addresses of outbound DHCPv6 requests +#[cfg(any(target_os = "linux", target_os = "macos"))] +static DHCPV6_SERVER_ADDRS: Lazy<[Ipv6Addr; 2]> = Lazy::new(|| { + [ Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 1, 2), Ipv6Addr::new(0xff05, 0, 0, 0, 0, 0, 1, 3), - ]; - static ref ROUTER_SOLICITATION_OUT_DST_ADDR: Ipv6Addr = Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 2); - static ref SOLICITED_NODE_MULTICAST: Ipv6Network = Ipv6Network::new(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 1, 0xFF00, 0), 104).unwrap(); - static ref LOOPBACK_NETS: [IpNetwork; 2] = [ + ] +}); +#[cfg(any(target_os = "linux", target_os = "macos"))] +static ROUTER_SOLICITATION_OUT_DST_ADDR: Lazy<Ipv6Addr> = + Lazy::new(|| Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 2)); +#[cfg(any(target_os = "linux", target_os = "macos"))] +static SOLICITED_NODE_MULTICAST: Lazy<Ipv6Network> = + Lazy::new(|| Ipv6Network::new(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 1, 0xFF00, 0), 104).unwrap()); +static LOOPBACK_NETS: Lazy<[IpNetwork; 2]> = Lazy::new(|| { + [ IpNetwork::V4(ipnetwork::Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 0), 8).unwrap()), - IpNetwork::V6(ipnetwork::Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 128).unwrap()), - ]; -} + IpNetwork::V6( + ipnetwork::Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 128).unwrap(), + ), + ] +}); + #[cfg(all(unix, not(target_os = "android")))] const DHCPV4_SERVER_PORT: u16 = 67; #[cfg(all(unix, not(target_os = "android")))] diff --git a/talpid-core/src/offline/mod.rs b/talpid-core/src/offline/mod.rs index 76f9b1c315..ca99c61774 100644 --- a/talpid-core/src/offline/mod.rs +++ b/talpid-core/src/offline/mod.rs @@ -1,4 +1,5 @@ use futures::channel::mpsc::UnboundedSender; +use once_cell::sync::Lazy; #[cfg(not(target_os = "android"))] use talpid_routing::RouteManagerHandle; #[cfg(target_os = "android")] @@ -20,12 +21,12 @@ mod imp; #[path = "android.rs"] mod imp; -lazy_static::lazy_static! { - /// Disables offline monitor - static ref FORCE_DISABLE_OFFLINE_MONITOR: bool = std::env::var("TALPID_DISABLE_OFFLINE_MONITOR") +/// Disables offline monitor +static FORCE_DISABLE_OFFLINE_MONITOR: Lazy<bool> = Lazy::new(|| { + std::env::var("TALPID_DISABLE_OFFLINE_MONITOR") .map(|v| v != "0") - .unwrap_or(false); -} + .unwrap_or(false) +}); pub use self::imp::Error; diff --git a/talpid-core/src/resolver.rs b/talpid-core/src/resolver.rs index d2c260ddff..bf2480e69b 100644 --- a/talpid-core/src/resolver.rs +++ b/talpid-core/src/resolver.rs @@ -12,6 +12,7 @@ use futures::{ SinkExt, StreamExt, }; +use once_cell::sync::Lazy; use trust_dns_server::{ authority::{ EmptyLookup, LookupObject, MessageRequest, MessageResponse, MessageResponseBuilder, @@ -32,13 +33,12 @@ use trust_dns_server::{ const ALLOWED_RECORD_TYPES: &[RecordType] = &[RecordType::A, RecordType::AAAA, RecordType::CNAME]; const CAPTIVE_PORTAL_DOMAINS: &[&str] = &["captive.apple.com", "netcts.cdn-apple.com"]; -lazy_static::lazy_static! { - static ref ALLOWED_DOMAINS: Vec<LowerName> = - CAPTIVE_PORTAL_DOMAINS - .iter() - .map(|domain| LowerName::from(Name::from_str(domain).unwrap())) - .collect(); -} +static ALLOWED_DOMAINS: Lazy<Vec<LowerName>> = Lazy::new(|| { + CAPTIVE_PORTAL_DOMAINS + .iter() + .map(|domain| LowerName::from(Name::from_str(domain).unwrap())) + .collect() +}); const TTL_SECONDS: u32 = 3; /// An IP address to be used in the DNS response to the captive domain query. The address itself diff --git a/talpid-dbus/Cargo.toml b/talpid-dbus/Cargo.toml index 4aac7f62ef..5370f6a38e 100644 --- a/talpid-dbus/Cargo.toml +++ b/talpid-dbus/Cargo.toml @@ -10,7 +10,7 @@ publish.workspace = true [target.'cfg(target_os = "linux")'.dependencies] dbus = "0.9" err-derive = "0.3.1" -lazy_static = "1.0" +once_cell = "1.13" log = "0.4" libc = "0.2" tokio = { workspace = true, features = ["rt"] } diff --git a/talpid-dbus/src/lib.rs b/talpid-dbus/src/lib.rs index f85581864a..d077c245e5 100644 --- a/talpid-dbus/src/lib.rs +++ b/talpid-dbus/src/lib.rs @@ -2,14 +2,13 @@ //! DBus system connection pub use dbus; use dbus::blocking::SyncConnection; +use once_cell::sync::Lazy; use std::sync::{Arc, Mutex}; pub mod network_manager; pub mod systemd; pub mod systemd_resolved; -lazy_static::lazy_static! { - static ref DBUS_CONNECTION: Mutex<Option<Arc<SyncConnection>>> = Mutex::new(None); -} +static DBUS_CONNECTION: Lazy<Mutex<Option<Arc<SyncConnection>>>> = Lazy::new(|| Mutex::new(None)); /// Reuse or create a system DBus connection. pub fn get_connection() -> Result<Arc<SyncConnection>, dbus::Error> { diff --git a/talpid-dbus/src/systemd_resolved.rs b/talpid-dbus/src/systemd_resolved.rs index 6ba8603508..0fe1a1a211 100644 --- a/talpid-dbus/src/systemd_resolved.rs +++ b/talpid-dbus/src/systemd_resolved.rs @@ -7,8 +7,8 @@ use dbus::{ }, message::{MatchRule, SignalArgs}, }; -use lazy_static::lazy_static; use libc::{AF_INET, AF_INET6}; +use once_cell::sync::Lazy; use std::{fs, io, net::IpAddr, path::Path, sync::Arc, time::Duration}; pub type Result<T> = std::result::Result<T, Error>; @@ -59,14 +59,14 @@ pub enum Error { AsyncTaskError(#[error(source)] tokio::task::JoinError), } -lazy_static! { - static ref RESOLVED_STUB_PATHS: Vec<&'static Path> = vec![ +static RESOLVED_STUB_PATHS: Lazy<Vec<&'static Path>> = Lazy::new(|| { + vec![ Path::new("/run/systemd/resolve/stub-resolv.conf"), Path::new("/run/systemd/resolve/resolv.conf"), Path::new("/var/run/systemd/resolve/stub-resolv.conf"), Path::new("/var/run/systemd/resolve/resolv.conf"), - ]; -} + ] +}); const RESOLV_CONF_PATH: &str = "/etc/resolv.conf"; const STATIC_STUB_PATH: &str = "/usr/lib/systemd/resolv.conf"; diff --git a/talpid-openvpn/Cargo.toml b/talpid-openvpn/Cargo.toml index 4ffc49eaed..9745e3ddc6 100644 --- a/talpid-openvpn/Cargo.toml +++ b/talpid-openvpn/Cargo.toml @@ -15,7 +15,7 @@ duct = "0.13" err-derive = "0.3.1" futures = "0.3.15" is-terminal = "0.4.2" -lazy_static = "1.0" +once_cell = "1.13" log = "0.4" os_pipe = "1.1.4" parking_lot = "0.12.0" diff --git a/talpid-openvpn/src/lib.rs b/talpid-openvpn/src/lib.rs index 87861e30a8..56224ab764 100644 --- a/talpid-openvpn/src/lib.rs +++ b/talpid-openvpn/src/lib.rs @@ -6,7 +6,7 @@ use crate::proxy::{ProxyMonitor, ProxyResourceData}; use futures::channel::oneshot; #[cfg(windows)] -use lazy_static::lazy_static; +use once_cell::sync::Lazy; use process::{ openvpn::{OpenVpnCommand, OpenVpnProcHandle}, stoppable_process::StoppableProcess, @@ -46,10 +46,10 @@ mod process; mod proxy; #[cfg(windows)] -lazy_static! { - static ref ADAPTER_ALIAS: U16CString = U16CString::from_str("Mullvad").unwrap(); - static ref ADAPTER_TUNNEL_TYPE: U16CString = U16CString::from_str("Mullvad").unwrap(); -} +static ADAPTER_ALIAS: Lazy<U16CString> = Lazy::new(|| U16CString::from_str("Mullvad").unwrap()); +#[cfg(windows)] +static ADAPTER_TUNNEL_TYPE: Lazy<U16CString> = + Lazy::new(|| U16CString::from_str("Mullvad").unwrap()); #[cfg(windows)] const ADAPTER_GUID: GUID = GUID { diff --git a/talpid-openvpn/src/wintun.rs b/talpid-openvpn/src/wintun.rs index 8b21ce9fd7..65b990693f 100644 --- a/talpid-openvpn/src/wintun.rs +++ b/talpid-openvpn/src/wintun.rs @@ -1,4 +1,4 @@ -use lazy_static::lazy_static; +use once_cell::sync::Lazy; use std::{ ffi::CStr, fmt, io, mem, @@ -28,10 +28,8 @@ use winreg::{ RegKey, }; -lazy_static! { - /// Shared `WintunDll` instance - static ref WINTUN_DLL: Mutex<Option<Arc<WintunDll>>> = Mutex::new(None); -} +/// Shared `WintunDll` instance +static WINTUN_DLL: Lazy<Mutex<Option<Arc<WintunDll>>>> = Lazy::new(|| Mutex::new(None)); type WintunCreateAdapterFn = unsafe extern "stdcall" fn( name: *const u16, diff --git a/talpid-routing/Cargo.toml b/talpid-routing/Cargo.toml index e21ec6da51..458acce5f1 100644 --- a/talpid-routing/Cargo.toml +++ b/talpid-routing/Cargo.toml @@ -21,7 +21,7 @@ talpid-types = { path = "../talpid-types" } [target.'cfg(target_os = "linux")'.dependencies] libc = "0.2" -lazy_static = "1.0" +once_cell = "1.13" rtnetlink = "0.11" netlink-packet-route = "0.13" netlink-sys = "0.8.3" diff --git a/talpid-routing/src/unix/linux.rs b/talpid-routing/src/unix/linux.rs index d2f98b0701..a2cf19d3b4 100644 --- a/talpid-routing/src/unix/linux.rs +++ b/talpid-routing/src/unix/linux.rs @@ -16,7 +16,6 @@ use futures::{ StreamExt, TryStream, TryStreamExt, }; use ipnetwork::IpNetwork; -use lazy_static::lazy_static; use libc::{AF_INET, AF_INET6}; use netlink_packet_route::{ constants::{ARPHRD_LOOPBACK, FIB_RULE_INVERT, FR_ACT_TO_TBL, NLM_F_REQUEST}, @@ -32,30 +31,29 @@ use netlink_packet_route::{ rule::{nlas::Nla as RuleNla, RuleHeader, RuleMessage}, NetlinkMessage, NetlinkPayload, RtnlMessage, }; +use once_cell::sync::Lazy; use rtnetlink::{ constants::{RTMGRP_IPV4_ROUTE, RTMGRP_IPV6_ROUTE, RTMGRP_LINK, RTMGRP_NOTIFY}, sys::SocketAddr, Handle, IpVersion, }; -lazy_static! { - static ref SUPPRESS_RULE_V4: RuleMessage = RuleMessage { - header: RuleHeader { - family: AF_INET as u8, - action: FR_ACT_TO_TBL, - ..RuleHeader::default() - }, - nlas: vec![ - RuleNla::SuppressPrefixLen(0), - RuleNla::Table(RT_TABLE_MAIN as u32), - ], - }; - static ref SUPPRESS_RULE_V6: RuleMessage = { - let mut v6_rule = SUPPRESS_RULE_V4.clone(); - v6_rule.header.family = AF_INET6 as u8; - v6_rule - }; -} +static SUPPRESS_RULE_V4: Lazy<RuleMessage> = Lazy::new(|| RuleMessage { + header: RuleHeader { + family: AF_INET as u8, + action: FR_ACT_TO_TBL, + ..RuleHeader::default() + }, + nlas: vec![ + RuleNla::SuppressPrefixLen(0), + RuleNla::Table(RT_TABLE_MAIN as u32), + ], +}); +static SUPPRESS_RULE_V6: Lazy<RuleMessage> = Lazy::new(|| { + let mut v6_rule = SUPPRESS_RULE_V4.clone(); + v6_rule.header.family = AF_INET6 as u8; + v6_rule +}); fn all_rules(fwmark: u32, table: u32) -> [RuleMessage; 4] { [ diff --git a/talpid-wireguard/Cargo.toml b/talpid-wireguard/Cargo.toml index 91f685e6ed..a71c2582ed 100644 --- a/talpid-wireguard/Cargo.toml +++ b/talpid-wireguard/Cargo.toml @@ -14,7 +14,7 @@ err-derive = "0.3.1" futures = "0.3.15" hex = "0.4" ipnetwork = "0.16" -lazy_static = "1.0" +once_cell = "1.13" libc = "0.2" log = "0.4" parking_lot = "0.12.0" diff --git a/talpid-wireguard/src/lib.rs b/talpid-wireguard/src/lib.rs index 7830c7a072..4897145f5d 100644 --- a/talpid-wireguard/src/lib.rs +++ b/talpid-wireguard/src/lib.rs @@ -8,7 +8,7 @@ use futures::future::{abortable, AbortHandle as FutureAbortHandle, BoxFuture, Fu #[cfg(windows)] use futures::{channel::mpsc, StreamExt}; #[cfg(target_os = "linux")] -use lazy_static::lazy_static; +use once_cell::sync::Lazy; #[cfg(target_os = "linux")] use std::env; #[cfg(windows)] @@ -160,16 +160,12 @@ impl Drop for ObfuscatorHandle { } #[cfg(target_os = "linux")] -lazy_static! { - /// Overrides the preference for the kernel module for WireGuard. - static ref FORCE_USERSPACE_WIREGUARD: bool = env::var("TALPID_FORCE_USERSPACE_WIREGUARD") +/// Overrides the preference for the kernel module for WireGuard. +static FORCE_USERSPACE_WIREGUARD: Lazy<bool> = Lazy::new(|| { + env::var("TALPID_FORCE_USERSPACE_WIREGUARD") .map(|v| v != "0") - .unwrap_or(false); - - static ref FORCE_NM_WIREGUARD: bool = env::var("TALPID_FORCE_NM_WIREGUARD") - .map(|v| v != "0") - .unwrap_or(false); -} + .unwrap_or(false) +}); async fn maybe_create_obfuscator( config: &mut Config, diff --git a/talpid-wireguard/src/logging.rs b/talpid-wireguard/src/logging.rs index d1c0a9c62d..bf91840644 100644 --- a/talpid-wireguard/src/logging.rs +++ b/talpid-wireguard/src/logging.rs @@ -1,9 +1,8 @@ +use once_cell::sync::Lazy; use parking_lot::Mutex; use std::{collections::HashMap, fmt, fs, io::Write, path::Path}; -lazy_static::lazy_static! { - static ref LOG_MUTEX: Mutex<HashMap<u32, fs::File>> = Mutex::new(HashMap::new()); -} +static LOG_MUTEX: Lazy<Mutex<HashMap<u32, fs::File>>> = Lazy::new(|| Mutex::new(HashMap::new())); static mut LOG_CONTEXT_NEXT_ORDINAL: u32 = 0; diff --git a/talpid-wireguard/src/wireguard_nt.rs b/talpid-wireguard/src/wireguard_nt.rs index 6fcc6ffd0b..8c6a7a0945 100644 --- a/talpid-wireguard/src/wireguard_nt.rs +++ b/talpid-wireguard/src/wireguard_nt.rs @@ -7,7 +7,7 @@ use super::{ use bitflags::bitflags; use futures::SinkExt; use ipnetwork::IpNetwork; -use lazy_static::lazy_static; +use once_cell::sync::Lazy; use std::{ ffi::CStr, fmt, @@ -38,11 +38,9 @@ use windows_sys::{ }, }; -lazy_static! { - static ref WG_NT_DLL: Mutex<Option<Arc<WgNtDll>>> = Mutex::new(None); - static ref ADAPTER_TYPE: U16CString = U16CString::from_str("Mullvad").unwrap(); - static ref ADAPTER_ALIAS: U16CString = U16CString::from_str("Mullvad").unwrap(); -} +static WG_NT_DLL: Lazy<Mutex<Option<Arc<WgNtDll>>>> = Lazy::new(|| Mutex::new(None)); +static ADAPTER_TYPE: Lazy<U16CString> = Lazy::new(|| U16CString::from_str("Mullvad").unwrap()); +static ADAPTER_ALIAS: Lazy<U16CString> = Lazy::new(|| U16CString::from_str("Mullvad").unwrap()); const ADAPTER_GUID: GUID = GUID { data1: 0x514a3988, @@ -506,9 +504,7 @@ impl Drop for WgNtTunnel { } } -lazy_static! { - static ref LOG_CONTEXT: Mutex<Option<u32>> = Mutex::new(None); -} +static LOG_CONTEXT: Lazy<Mutex<Option<u32>>> = Lazy::new(|| Mutex::new(None)); struct LoggerHandle { dll: Arc<WgNtDll>, @@ -1005,7 +1001,7 @@ pub fn as_uninit_byte_slice<T: Copy + Sized>(value: &T) -> &[mem::MaybeUninit<u8 #[cfg(test)] mod tests { use super::*; - use lazy_static::lazy_static; + use once_cell::sync::Lazy; use talpid_types::net::wireguard; #[derive(Debug, Eq, PartialEq, Clone, Copy)] @@ -1016,59 +1012,57 @@ mod tests { p0_allowed_ip_0: WgAllowedIp, } - lazy_static! { - static ref WG_PRIVATE_KEY: wireguard::PrivateKey = wireguard::PrivateKey::new_from_random(); - static ref WG_PUBLIC_KEY: wireguard::PublicKey = - wireguard::PrivateKey::new_from_random().public_key(); - static ref WG_CONFIG: Config = { - Config { - tunnel: wireguard::TunnelConfig { - private_key: WG_PRIVATE_KEY.clone(), - addresses: vec![], - }, - peers: vec![wireguard::PeerConfig { - public_key: WG_PUBLIC_KEY.clone(), - allowed_ips: vec!["1.3.3.0/24".parse().unwrap()], - endpoint: "1.2.3.4:1234".parse().unwrap(), - psk: None, - }], - ipv4_gateway: "0.0.0.0".parse().unwrap(), - ipv6_gateway: None, - mtu: 0, - use_wireguard_nt: true, - obfuscator_config: None, - } - }; - static ref WG_STRUCT_CONFIG: Interface = Interface { - interface: WgInterface { - flags: WgInterfaceFlag::HAS_PRIVATE_KEY | WgInterfaceFlag::REPLACE_PEERS, - listen_port: 0, - private_key: WG_PRIVATE_KEY.to_bytes(), - public_key: [0; WIREGUARD_KEY_LENGTH], - peers_count: 1, - }, - p0: WgPeer { - flags: WgPeerFlag::HAS_PUBLIC_KEY | WgPeerFlag::HAS_ENDPOINT, - reserved: 0, - public_key: *WG_PUBLIC_KEY.as_bytes(), - preshared_key: [0; WIREGUARD_KEY_LENGTH], - persistent_keepalive: 0, - endpoint: talpid_windows_net::inet_sockaddr_from_socketaddr( - "1.2.3.4:1234".parse().unwrap() - ) - .into(), - tx_bytes: 0, - rx_bytes: 0, - last_handshake: 0, - allowed_ips_count: 1, - }, - p0_allowed_ip_0: WgAllowedIp { - address: WgIpAddr::from("1.3.3.0".parse::<Ipv4Addr>().unwrap()), - address_family: AF_INET, - cidr: 24, - }, - }; - } + static WG_PRIVATE_KEY: Lazy<wireguard::PrivateKey> = + Lazy::new(|| wireguard::PrivateKey::new_from_random()); + static WG_PUBLIC_KEY: Lazy<wireguard::PublicKey> = + Lazy::new(|| wireguard::PrivateKey::new_from_random().public_key()); + static WG_CONFIG: Lazy<Config> = Lazy::new(|| Config { + tunnel: wireguard::TunnelConfig { + private_key: WG_PRIVATE_KEY.clone(), + addresses: vec![], + }, + peers: vec![wireguard::PeerConfig { + public_key: WG_PUBLIC_KEY.clone(), + allowed_ips: vec!["1.3.3.0/24".parse().unwrap()], + endpoint: "1.2.3.4:1234".parse().unwrap(), + psk: None, + }], + ipv4_gateway: "0.0.0.0".parse().unwrap(), + ipv6_gateway: None, + mtu: 0, + use_wireguard_nt: true, + obfuscator_config: None, + }); + + static WG_STRUCT_CONFIG: Lazy<Interface> = Lazy::new(|| Interface { + interface: WgInterface { + flags: WgInterfaceFlag::HAS_PRIVATE_KEY | WgInterfaceFlag::REPLACE_PEERS, + listen_port: 0, + private_key: WG_PRIVATE_KEY.to_bytes(), + public_key: [0; WIREGUARD_KEY_LENGTH], + peers_count: 1, + }, + p0: WgPeer { + flags: WgPeerFlag::HAS_PUBLIC_KEY | WgPeerFlag::HAS_ENDPOINT, + reserved: 0, + public_key: *WG_PUBLIC_KEY.as_bytes(), + preshared_key: [0; WIREGUARD_KEY_LENGTH], + persistent_keepalive: 0, + endpoint: talpid_windows_net::inet_sockaddr_from_socketaddr( + "1.2.3.4:1234".parse().unwrap(), + ) + .into(), + tx_bytes: 0, + rx_bytes: 0, + last_handshake: 0, + allowed_ips_count: 1, + }, + p0_allowed_ip_0: WgAllowedIp { + address: WgIpAddr::from("1.3.3.0".parse::<Ipv4Addr>().unwrap()), + address_family: AF_INET, + cidr: 24, + }, + }); fn get_proc_fn( _handle: HINSTANCE, |
