|
| 1 | +use crate::ProxyHandle; |
| 2 | + |
| 3 | +use mullvad_encrypted_dns_proxy::{config::ProxyConfig, config_resolver, Forwarder}; |
| 4 | +use std::{ |
| 5 | + collections::HashSet, |
| 6 | + io, mem, |
| 7 | + net::{Ipv4Addr, SocketAddr}, |
| 8 | + ptr, |
| 9 | +}; |
| 10 | +use tokio::{net::TcpListener, task::JoinHandle}; |
| 11 | + |
| 12 | +pub struct EncryptedDnsProxyState { |
| 13 | + /// Note that we rely on the randomness of the ordering of the items in the hashset to pick a |
| 14 | + /// random configurations every time. |
| 15 | + configurations: HashSet<ProxyConfig>, |
| 16 | + tried_configurations: HashSet<ProxyConfig>, |
| 17 | +} |
| 18 | + |
| 19 | +#[derive(Debug)] |
| 20 | +pub enum Error { |
| 21 | + /// Failed to initialize tokio runtime. |
| 22 | + TokioRuntime, |
| 23 | + /// Failed to bind a local listening socket, the one that will be forwarded through the proxy. |
| 24 | + BindLocalSocket(io::Error), |
| 25 | + /// Failed to get local listening address of the local listening socket. |
| 26 | + GetBindAddr(io::Error), |
| 27 | + /// Failed to initialize forwarder. |
| 28 | + Forwarder(io::Error), |
| 29 | + /// Failed to fetch a proxy configuration over DNS. |
| 30 | + FetchConfig(config_resolver::Error), |
| 31 | + /// Failed to initialize with a valid configuration. |
| 32 | + NoConfigs, |
| 33 | +} |
| 34 | + |
| 35 | +impl From<Error> for i32 { |
| 36 | + fn from(err: Error) -> Self { |
| 37 | + match err { |
| 38 | + Error::TokioRuntime => -1, |
| 39 | + Error::BindLocalSocket(_) => -2, |
| 40 | + Error::GetBindAddr(_) => -3, |
| 41 | + Error::Forwarder(_) => -4, |
| 42 | + Error::FetchConfig(_) => -5, |
| 43 | + Error::NoConfigs => -6, |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl EncryptedDnsProxyState { |
| 49 | + async fn start(&mut self) -> Result<ProxyHandle, Error> { |
| 50 | + self.fetch_configs().await?; |
| 51 | + let proxy_configuration = self.next_configuration().ok_or(Error::NoConfigs)?; |
| 52 | + |
| 53 | + let local_socket = Self::bind_local_addr() |
| 54 | + .await |
| 55 | + .map_err(Error::BindLocalSocket)?; |
| 56 | + let bind_addr = local_socket.local_addr().map_err(Error::GetBindAddr)?; |
| 57 | + let forwarder = Forwarder::connect(&proxy_configuration) |
| 58 | + .await |
| 59 | + .map_err(Error::Forwarder)?; |
| 60 | + let join_handle = Box::new(tokio::spawn(async move { |
| 61 | + if let Ok((client_conn, _)) = local_socket.accept().await { |
| 62 | + let _ = forwarder.forward(client_conn).await; |
| 63 | + } |
| 64 | + })); |
| 65 | + |
| 66 | + Ok(ProxyHandle { |
| 67 | + context: Box::into_raw(join_handle).cast(), |
| 68 | + port: bind_addr.port(), |
| 69 | + }) |
| 70 | + } |
| 71 | + |
| 72 | + async fn bind_local_addr() -> io::Result<TcpListener> { |
| 73 | + let bind_addr = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0); |
| 74 | + TcpListener::bind(bind_addr).await |
| 75 | + } |
| 76 | + |
| 77 | + /// Select a config. |
| 78 | + /// Always select an obfuscated configuration, if there are any left untried. If no obfuscated |
| 79 | + /// configurations exist, try plain configurations. The order is randomized due to the hash set |
| 80 | + /// storing the configurations in a random order. |
| 81 | + fn next_configuration(&mut self) -> Option<ProxyConfig> { |
| 82 | + if self.should_reset() { |
| 83 | + self.reset(); |
| 84 | + } |
| 85 | + |
| 86 | + // First, try getting an obfuscated configuration, if there exist any. |
| 87 | + let config = if let Some(obfuscated_config) = self |
| 88 | + .configurations |
| 89 | + .difference(&self.tried_configurations) |
| 90 | + .find(|config| config.obfuscation.is_some()) |
| 91 | + .cloned() |
| 92 | + { |
| 93 | + obfuscated_config |
| 94 | + } else { |
| 95 | + // If no obfuscated configurations exist, try the next untried configuration. |
| 96 | + self.configurations |
| 97 | + .difference(&self.tried_configurations) |
| 98 | + .next() |
| 99 | + .cloned()? |
| 100 | + }; |
| 101 | + |
| 102 | + self.tried_configurations.insert(config.clone()); |
| 103 | + Some(config) |
| 104 | + } |
| 105 | + |
| 106 | + /// Fetch a config, but error out only when no existing configuration was there. |
| 107 | + async fn fetch_configs(&mut self) -> Result<(), Error> { |
| 108 | + match mullvad_encrypted_dns_proxy::config_resolver::resolve_default_config().await { |
| 109 | + Ok(new_configs) => { |
| 110 | + self.configurations = HashSet::from_iter(new_configs.into_iter()); |
| 111 | + } |
| 112 | + Err(err) => { |
| 113 | + log::error!("Failed to fetch a new proxy configuration: {err:?}"); |
| 114 | + if self.is_empty() { |
| 115 | + return Err(Error::FetchConfig(err)); |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + Ok(()) |
| 120 | + } |
| 121 | + |
| 122 | + fn is_empty(&self) -> bool { |
| 123 | + self.configurations.is_empty() |
| 124 | + } |
| 125 | + |
| 126 | + /// Checks if the `tried_configurations` set should be reset. |
| 127 | + /// It should only be reset if the difference between `configurations` and |
| 128 | + /// `tried_configurations` is an empty set - in this case all available configurations have |
| 129 | + /// been tried. |
| 130 | + fn should_reset(&self) -> bool { |
| 131 | + self.configurations |
| 132 | + .difference(&self.tried_configurations) |
| 133 | + .count() |
| 134 | + == 0 |
| 135 | + } |
| 136 | + |
| 137 | + /// Clears the `tried_configurations` set. |
| 138 | + fn reset(&mut self) { |
| 139 | + self.tried_configurations.clear(); |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +/// Initializes a valid pointer to an instance of `EncryptedDnsProxyState`. |
| 144 | +#[no_mangle] |
| 145 | +pub unsafe extern "C" fn encrypted_dns_proxy_init() -> *mut EncryptedDnsProxyState { |
| 146 | + let state = Box::new(EncryptedDnsProxyState { |
| 147 | + configurations: Default::default(), |
| 148 | + tried_configurations: Default::default(), |
| 149 | + }); |
| 150 | + Box::into_raw(state) |
| 151 | +} |
| 152 | + |
| 153 | +/// This must be called only once to deallocate `EncryptedDnsProxyState`. |
| 154 | +/// |
| 155 | +/// # Safety |
| 156 | +/// `ptr` must be a valid, exclusive pointer to `EncryptedDnsProxyState`, initialized |
| 157 | +/// by `encrypted_dns_proxy_init`. This function is not thread safe, and should only be called |
| 158 | +/// once. |
| 159 | +#[no_mangle] |
| 160 | +pub unsafe extern "C" fn encrypted_dns_proxy_free(ptr: *mut EncryptedDnsProxyState) { |
| 161 | + let _ = unsafe { Box::from_raw(ptr) }; |
| 162 | +} |
| 163 | + |
| 164 | +/// # Safety |
| 165 | +/// encrypted_dns_proxy must be a valid, exclusive pointer to `EncryptedDnsProxyState`, initialized |
| 166 | +/// by `encrypted_dns_proxy_init`. This function is not thread safe. |
| 167 | +/// `proxy_handle` must be pointing to a valid memory region for the size of a `ProxyHandle`. This |
| 168 | +/// function is not thread safe, but it can be called repeatedly. Each successful invocation should |
| 169 | +/// clean up the resulting proxy via `[encrypted_dns_proxy_stop]`. |
| 170 | +/// |
| 171 | +/// `proxy_handle` will only contain valid values if the return value is zero. It is still valid to |
| 172 | +/// deallocate the memory. |
| 173 | +#[no_mangle] |
| 174 | +pub unsafe extern "C" fn encrypted_dns_proxy_start( |
| 175 | + encrypted_dns_proxy: *mut EncryptedDnsProxyState, |
| 176 | + proxy_handle: *mut ProxyHandle, |
| 177 | +) -> i32 { |
| 178 | + let handle = match crate::mullvad_ios_runtime() { |
| 179 | + Ok(handle) => handle, |
| 180 | + Err(err) => { |
| 181 | + log::error!("Cannot instantiate a tokio runtime: {}", err); |
| 182 | + return Error::TokioRuntime.into(); |
| 183 | + } |
| 184 | + }; |
| 185 | + |
| 186 | + let mut encrypted_dns_proxy = unsafe { Box::from_raw(encrypted_dns_proxy) }; |
| 187 | + let proxy_result = handle.block_on(encrypted_dns_proxy.start()); |
| 188 | + mem::forget(encrypted_dns_proxy); |
| 189 | + |
| 190 | + match proxy_result { |
| 191 | + Ok(handle) => unsafe { ptr::write(proxy_handle, handle) }, |
| 192 | + Err(err) => { |
| 193 | + let empty_handle = ProxyHandle { |
| 194 | + context: ptr::null_mut(), |
| 195 | + port: 0, |
| 196 | + }; |
| 197 | + unsafe { ptr::write(proxy_handle, empty_handle) } |
| 198 | + log::error!("Failed to create a proxy connection: {err:?}"); |
| 199 | + return err.into(); |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + 0 |
| 204 | +} |
| 205 | + |
| 206 | +/// # Safety |
| 207 | +/// `proxy_config` must be a valid pointer to a `ProxyHandle` as initialized by |
| 208 | +/// [`encrypted_dns_proxy_start`]. It should only ever be called once. |
| 209 | +#[no_mangle] |
| 210 | +pub unsafe extern "C" fn encrypted_dns_proxy_stop(proxy_config: *mut ProxyHandle) -> i32 { |
| 211 | + let ptr = unsafe { (*proxy_config).context }; |
| 212 | + if !ptr.is_null() { |
| 213 | + let handle: Box<JoinHandle<()>> = unsafe { Box::from_raw(ptr.cast()) }; |
| 214 | + handle.abort(); |
| 215 | + } |
| 216 | + 0i32 |
| 217 | +} |
0 commit comments