From 5a374fe8ff21266ce3e093f2d4093728be84fb3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20H=C3=A4ggblad?= Date: Wed, 25 May 2022 10:06:50 +0200 Subject: [PATCH] Spawn socks5 runtime in thread --- clients/socks5/src/client/mod.rs | 10 +++--- hrycyszynvpn/Cargo.lock | 5 +-- hrycyszynvpn/src-tauri/Cargo.toml | 1 + hrycyszynvpn/src-tauri/src/config/mod.rs | 34 ++++++++++++++----- hrycyszynvpn/src-tauri/src/main.rs | 9 ++--- .../src/operations/connection/connect.rs | 1 + .../src/operations/connection/disconnect.rs | 1 + hrycyszynvpn/src-tauri/src/state.rs | 28 +++++++++------ 8 files changed, 60 insertions(+), 29 deletions(-) diff --git a/clients/socks5/src/client/mod.rs b/clients/socks5/src/client/mod.rs index 51645476d8..43e13d22e1 100644 --- a/clients/socks5/src/client/mod.rs +++ b/clients/socks5/src/client/mod.rs @@ -38,11 +38,11 @@ use crate::socks::{ pub mod config; -pub type ClientControlMessageSender = mpsc::UnboundedSender; -pub type ClientControlMessageReceiver = mpsc::UnboundedReceiver; +pub type Socks5ControlMessageSender = mpsc::UnboundedSender; +pub type Socks5ControlMessageReceiver = mpsc::UnboundedReceiver; #[derive(Debug)] -pub enum ClientControlMessage { +pub enum Socks5ControlMessage { Stop, } @@ -282,11 +282,11 @@ impl NymClient { } // Variant of `run_forever` that listends for message to shutdown - pub async fn run_and_listen(&mut self, mut receiver: ClientControlMessageReceiver) { + pub async fn run_and_listen(&mut self, mut receiver: Socks5ControlMessageReceiver) { self.start().await; tokio::select! { message = receiver.next() => match message { - Some(ClientControlMessage::Stop) => { + Some(Socks5ControlMessage::Stop) => { info!("Received: {:?}", message); info!("Shutting down"); } diff --git a/hrycyszynvpn/Cargo.lock b/hrycyszynvpn/Cargo.lock index 47d3df3c8f..bd4c0becd6 100644 --- a/hrycyszynvpn/Cargo.lock +++ b/hrycyszynvpn/Cargo.lock @@ -2537,6 +2537,7 @@ dependencies = [ "futures", "log", "nym-socks5-client", + "once_cell", "pretty_env_logger", "rand 0.7.3", "serde", @@ -3674,9 +3675,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.10.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" +checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" [[package]] name = "opaque-debug" diff --git a/hrycyszynvpn/src-tauri/Cargo.toml b/hrycyszynvpn/src-tauri/Cargo.toml index 7655820b93..d24b247c25 100644 --- a/hrycyszynvpn/src-tauri/Cargo.toml +++ b/hrycyszynvpn/src-tauri/Cargo.toml @@ -25,6 +25,7 @@ bip39 = "1.0" dirs = "4.0" eyre = "0.6.5" futures = "0.3" +once_cell = "1.12" rand = "0.7" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/hrycyszynvpn/src-tauri/src/config/mod.rs b/hrycyszynvpn/src-tauri/src/config/mod.rs index 4bbbdc44c9..53bbe34036 100644 --- a/hrycyszynvpn/src-tauri/src/config/mod.rs +++ b/hrycyszynvpn/src-tauri/src/config/mod.rs @@ -1,32 +1,40 @@ use log::info; +use once_cell::sync::Lazy; use rand::rngs::OsRng; +use rand::Rng; use client_core::client::key_manager::KeyManager; use client_core::config::persistence::key_pathfinder::ClientKeyPathfinder; use config::NymConfig; -pub static SOCKS5_CONFIG_ID: &str = "hrycyszynvpn"; +// Generate a random id used for the config, since we need to init a new configuration each time +// due to not being able to reuse gateway registration. This is probably something we should +// improve. +pub static SOCKS5_CONFIG_ID: Lazy = Lazy::new(|| { + let mut rng = rand::thread_rng(); + format!("{}{:08}", "nym-connect-", rng.gen::()) +}); -// TODO -pub static PROVIDER_ADDRESS: &str = "HL2ufyQ875JNkro17ubKQB4gJyy2ozG8SMrUvHbYXYca.E7iz8hixuWE763h6MdaSnXAXobDqEHuq3Bzvi9XLQhW@BNjYZPxzcJwczXHHgBxCAyVJKxN6LPteDRrKapxWmexv"; +// TODO: make this configurable from the UI +pub static PROVIDER_ADDRESS: &str = "EWa8DgePKfuWSjqPo6NEdavBK6gpnK4TKb2npi2HWuC2.6PGVT9y83UMGbFrPKDnCvTP2jJjpXYpD87ZpiRsLo1YR@CgQrYP8etksSBf4nALNqp93SHPpgFwEUyTsjBNNLj5WM"; -// TODO: move to config file -//static GATEWAY_ID: &str = "83x9YyNkQ5QEY84ZU6Wmq8XHqfwf9SUtR7g5PAYB1FRY"; // sandbox +const DEFAULT_ETH_ENDPOINT: &str = "https://rinkeby.infura.io/v3/00000000000000000000000000000000"; +const DEFAULT_ETH_PRIVATE_KEY: &str = + "0000000000000000000000000000000000000000000000000000000000000001"; pub struct Config {} impl Config { pub async fn init() { info!("Initialising..."); - init_socks5(PROVIDER_ADDRESS, None).await; - info!("Configuration saved 🚀"); } } pub async fn init_socks5(provider_address: &str, chosen_gateway_id: Option<&str>) { - let id = SOCKS5_CONFIG_ID; + let id: &str = &SOCKS5_CONFIG_ID; + log::trace!("Creating config for id: {}", id); let mut config = nym_socks5::client::config::Config::new(id, provider_address); // create identity, encryption and ack keys. @@ -64,6 +72,15 @@ pub async fn init_socks5(provider_address: &str, chosen_gateway_id: Option<&str> .expect("Failed to generated keys"); info!("Saved all generated keys"); + // As far as I'm aware, these two are not used, they are only set because the socks5 init code + // requires them for initialising the bandwidth controller. + config + .get_base_mut() + .with_eth_endpoint(DEFAULT_ETH_ENDPOINT); + config + .get_base_mut() + .with_eth_private_key(DEFAULT_ETH_PRIVATE_KEY); + let config_save_location = config.get_config_file_save_location(); config .save_to_file(None) @@ -72,5 +89,6 @@ pub async fn init_socks5(provider_address: &str, chosen_gateway_id: Option<&str> info!("Using gateway: {}", config.get_base().get_gateway_id(),); info!("Client configuration completed.\n\n\n"); + dbg!(&config); nym_socks5::commands::init::show_address(&config); } diff --git a/hrycyszynvpn/src-tauri/src/main.rs b/hrycyszynvpn/src-tauri/src/main.rs index 8c023cfc5a..2e41bd001a 100644 --- a/hrycyszynvpn/src-tauri/src/main.rs +++ b/hrycyszynvpn/src-tauri/src/main.rs @@ -25,13 +25,14 @@ mod state; mod window; fn main() { - //console_subscriber::init(); - //tracing_subscriber::fmt::init(); setup_logging(); println!("Starting up..."); - // as per breaking change description here: https://github.com/tauri-apps/tauri/blob/feac1d193c6d618e49916ad0707201f43d5cdd36/tooling/bundler/CHANGELOG.md - fix_path_env::fix(); + // As per breaking change description here + // https://github.com/tauri-apps/tauri/blob/feac1d193c6d618e49916ad0707201f43d5cdd36/tooling/bundler/CHANGELOG.md + if let Err(error) = fix_path_env::fix() { + log::warn!("Failed to fix PATH: {error}"); + } tauri::Builder::default() .manage(Arc::new(RwLock::new(State::new()))) diff --git a/hrycyszynvpn/src-tauri/src/operations/connection/connect.rs b/hrycyszynvpn/src-tauri/src/operations/connection/connect.rs index 0eb2e87607..42a43fcb51 100644 --- a/hrycyszynvpn/src-tauri/src/operations/connection/connect.rs +++ b/hrycyszynvpn/src-tauri/src/operations/connection/connect.rs @@ -14,6 +14,7 @@ pub async fn start_connecting( guard.start_connecting(&window).await; Ok(ConnectResult { + // WIP(JON): fixme address: "Test".to_string(), }) } diff --git a/hrycyszynvpn/src-tauri/src/operations/connection/disconnect.rs b/hrycyszynvpn/src-tauri/src/operations/connection/disconnect.rs index 04a2c680d6..c04ac7ea80 100644 --- a/hrycyszynvpn/src-tauri/src/operations/connection/disconnect.rs +++ b/hrycyszynvpn/src-tauri/src/operations/connection/disconnect.rs @@ -14,6 +14,7 @@ pub async fn start_disconnecting( guard.start_disconnecting(&window).await; Ok(ConnectResult { + // WIP(JON): fixme address: "Test".to_string(), }) } diff --git a/hrycyszynvpn/src-tauri/src/state.rs b/hrycyszynvpn/src-tauri/src/state.rs index 48cf63a261..db0c7266e4 100644 --- a/hrycyszynvpn/src-tauri/src/state.rs +++ b/hrycyszynvpn/src-tauri/src/state.rs @@ -8,7 +8,9 @@ use futures::channel::mpsc; use config::NymConfig; #[cfg(not(feature = "coconut"))] use nym_socks5::client::NymClient as Socks5NymClient; -use nym_socks5::client::{ClientControlMessageReceiver, ClientControlMessageSender, ClientControlMessage}; +use nym_socks5::client::{ + Socks5ControlMessage, Socks5ControlMessageReceiver, Socks5ControlMessageSender, +}; use tokio::time::sleep; use crate::config::SOCKS5_CONFIG_ID; @@ -19,15 +21,13 @@ use tauri::Manager; pub struct State { status: ConnectionStatusKind, - //socks5_client: Arc>>, - socks5_client_sender: Option, + socks5_client_sender: Option, } impl State { pub fn new() -> Self { State { status: ConnectionStatusKind::Disconnected, - //socks5_client: Arc::new(RwLock::new(None)), socks5_client_sender: None, } } @@ -56,7 +56,10 @@ impl State { self.set_state(ConnectionStatusKind::Connecting, window); self.status = ConnectionStatusKind::Connecting; - //Self::init_config().await; + // Setup configuration by writing to file + Self::init_config().await; + + // Kick of the main task and get the channel for controlling it let sender = start_nym_socks5_client(); self.socks5_client_sender = Some(sender); @@ -71,7 +74,7 @@ impl State { // Send shutdown message if let Some(ref mut sender) = self.socks5_client_sender { - sender.send(ClientControlMessage::Stop).await.unwrap(); + sender.send(Socks5ControlMessage::Stop).await.unwrap(); } self.status = ConnectionStatusKind::Disconnected; @@ -79,8 +82,8 @@ impl State { } } -fn start_nym_socks5_client() -> ClientControlMessageSender { - let id = SOCKS5_CONFIG_ID; +fn start_nym_socks5_client() -> Socks5ControlMessageSender { + let id: &str = &SOCKS5_CONFIG_ID; info!("Loading config from file"); let config = nym_socks5::client::config::Config::load_from_file(Some(id)).unwrap(); @@ -90,8 +93,13 @@ fn start_nym_socks5_client() -> ClientControlMessageSender { let (sender, receiver) = mpsc::unbounded(); - tokio::spawn(async move { - socks5_client.run_and_listen(receiver).await; + // Spawn a separate runtime for the socks5 client so we can forcefully terminate. + // Once we can gracefully shutdown the socks5 client we can get rid of this. + std::thread::spawn(|| { + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async move { + socks5_client.run_and_listen(receiver).await; + }); }); sender