Spawn socks5 runtime in thread

This commit is contained in:
Jon Häggblad
2022-05-25 10:06:50 +02:00
parent db09870352
commit 5a374fe8ff
8 changed files with 60 additions and 29 deletions
+5 -5
View File
@@ -38,11 +38,11 @@ use crate::socks::{
pub mod config;
pub type ClientControlMessageSender = mpsc::UnboundedSender<ClientControlMessage>;
pub type ClientControlMessageReceiver = mpsc::UnboundedReceiver<ClientControlMessage>;
pub type Socks5ControlMessageSender = mpsc::UnboundedSender<Socks5ControlMessage>;
pub type Socks5ControlMessageReceiver = mpsc::UnboundedReceiver<Socks5ControlMessage>;
#[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");
}
+3 -2
View File
@@ -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"
+1
View File
@@ -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"
+26 -8
View File
@@ -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<String> = Lazy::new(|| {
let mut rng = rand::thread_rng();
format!("{}{:08}", "nym-connect-", rng.gen::<u64>())
});
// 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);
}
+5 -4
View File
@@ -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())))
@@ -14,6 +14,7 @@ pub async fn start_connecting(
guard.start_connecting(&window).await;
Ok(ConnectResult {
// WIP(JON): fixme
address: "Test".to_string(),
})
}
@@ -14,6 +14,7 @@ pub async fn start_disconnecting(
guard.start_disconnecting(&window).await;
Ok(ConnectResult {
// WIP(JON): fixme
address: "Test".to_string(),
})
}
+18 -10
View File
@@ -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<RwLock<Option<Socks5NymClient>>>,
socks5_client_sender: Option<ClientControlMessageSender>,
socks5_client_sender: Option<Socks5ControlMessageSender>,
}
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