summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorLinus Färnstrand <linus@mullvad.net>2017-09-19 11:06:17 +0200
committerLinus Färnstrand <linus@mullvad.net>2017-09-19 11:06:17 +0200
commitc7199bd140f4769dde66dc6044ab0921d1330378 (patch)
treec9ab111dc803f6ba4d1a5d43fc18ba99351d1b10
parentb572d0634b78d3de05ce39e5a49ce893c8065d6b (diff)
parent036e10fe4846679f710cf5a3571a730ce42563d4 (diff)
downloadmullvadvpn-c7199bd140f4769dde66dc6044ab0921d1330378.tar.xz
mullvadvpn-c7199bd140f4769dde66dc6044ab0921d1330378.zip
Merge branch 'update-rustfmt-to-nightly'
-rw-r--r--.travis.yml13
-rwxr-xr-xformat.sh8
-rw-r--r--mullvad-cli/src/cmds/account.rs28
-rw-r--r--mullvad-cli/src/cmds/custom_relay.rs56
-rw-r--r--mullvad-cli/src/main.rs8
-rw-r--r--mullvad-cli/src/rpc.rs17
-rw-r--r--mullvad-daemon/src/main.rs202
-rw-r--r--mullvad-daemon/src/management_interface.rs110
-rw-r--r--mullvad-daemon/src/settings.rs12
-rw-r--r--mullvad-daemon/src/shutdown.rs27
-rw-r--r--mullvad-types/src/lib.rs2
-rw-r--r--mullvad-types/src/relay_endpoint.rs11
-rw-r--r--rustfmt.toml6
-rw-r--r--talpid-core/src/firewall/macos.rs23
-rw-r--r--talpid-core/src/firewall/mod.rs12
-rw-r--r--talpid-core/src/lib.rs2
-rw-r--r--talpid-core/src/mktemp.rs4
-rw-r--r--talpid-core/src/mpsc.rs10
-rw-r--r--talpid-core/src/process/openvpn.rs18
-rw-r--r--talpid-core/src/tunnel/mod.rs45
-rw-r--r--talpid-core/src/tunnel/openvpn.rs111
-rw-r--r--talpid-ipc/src/client.rs33
-rw-r--r--talpid-ipc/src/lib.rs21
-rw-r--r--talpid-ipc/tests/ipc-client-server.rs10
-rw-r--r--talpid-openvpn-plugin/src/lib.rs33
-rw-r--r--talpid-openvpn-plugin/src/processing.rs9
-rw-r--r--talpid-types/src/lib.rs2
27 files changed, 443 insertions, 390 deletions
diff --git a/.travis.yml b/.travis.yml
index 8762ae3a03..af5254cff2 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,12 +1,9 @@
language: rust
cache: cargo
rust:
+ - nightly
- stable
- beta
- - nightly
-matrix:
- allow_failures:
- - rust: nightly
os:
- linux
- osx
@@ -18,7 +15,13 @@ before_script:
script:
- cargo build --all --verbose
- cargo test --all --verbose
- - ./format.sh --write-mode=diff
+ # Format only on nightly, since that is where rustfmt-nightly compiles
+ - if [ "${TRAVIS_RUST_VERSION}" = "nightly" ] && [ "${TRAVIS_OS_NAME}" = "linux" ]; then
+ export LD_LIBRARY_PATH=$(rustc --print sysroot)/lib:$LD_LIBRARY_PATH
+ && ./format.sh --write-mode=diff;
+ else
+ echo "Not checking formatting on this build";
+ fi
notifications:
email:
diff --git a/format.sh b/format.sh
index 0a899a7f73..b14aa48458 100755
--- a/format.sh
+++ b/format.sh
@@ -5,16 +5,16 @@
set -u
-VERSION="0.8.3"
+VERSION="0.2.6"
CMD="rustfmt"
-INSTALL_CMD="cargo install --vers $VERSION --force $CMD"
+INSTALL_CMD="cargo install --vers $VERSION --force rustfmt-nightly"
function correct_rustfmt() {
if ! which $CMD; then
echo "$CMD is not installed" >&2
return 1
fi
- local installed_version=$($CMD --version | cut -d' ' -f1)
+ local installed_version=$($CMD --version | cut -d'-' -f1)
if [[ "$installed_version" != "$VERSION" ]]; then
echo "Wrong version of $CMD installed. Expected $VERSION, got $installed_version" >&2
return 1
@@ -31,4 +31,4 @@ else
shift
fi
-find . -iname "*.rs" -not -path "*/target/*" -print0 | xargs -0 -n1 rustfmt "$@"
+find . -iname "*.rs" -not -path "*/target/*" -print0 | xargs -0 -n1 rustfmt --skip-children "$@"
diff --git a/mullvad-cli/src/cmds/account.rs b/mullvad-cli/src/cmds/account.rs
index f7cb106fc3..0dda601fc9 100644
--- a/mullvad-cli/src/cmds/account.rs
+++ b/mullvad-cli/src/cmds/account.rs
@@ -15,13 +15,19 @@ impl Command for Account {
clap::SubCommand::with_name(self.name())
.about("Control and display information about your Mullvad account")
.setting(clap::AppSettings::SubcommandRequired)
- .subcommand(clap::SubCommand::with_name("set")
- .about("Change account")
- .arg(clap::Arg::with_name("token")
- .help("The Mullvad account token to configure the client with")
- .required(true)))
- .subcommand(clap::SubCommand::with_name("get")
- .about("Display information about the currently configured account"))
+ .subcommand(
+ clap::SubCommand::with_name("set")
+ .about("Change account")
+ .arg(
+ clap::Arg::with_name("token")
+ .help("The Mullvad account token to configure the client with")
+ .required(true),
+ ),
+ )
+ .subcommand(
+ clap::SubCommand::with_name("get")
+ .about("Display information about the currently configured account"),
+ )
}
fn run(&self, matches: &clap::ArgMatches) -> Result<()> {
@@ -38,11 +44,9 @@ impl Command for Account {
impl Account {
fn set(&self, token: &str) -> Result<()> {
- rpc::call("set_account", &[token]).map(
- |_: Option<()>| {
- println!("Mullvad account \"{}\" set", token);
- },
- )
+ rpc::call("set_account", &[token]).map(|_: Option<()>| {
+ println!("Mullvad account \"{}\" set", token);
+ })
}
fn get(&self) -> Result<()> {
diff --git a/mullvad-cli/src/cmds/custom_relay.rs b/mullvad-cli/src/cmds/custom_relay.rs
index ab9a148fb3..d37169d52a 100644
--- a/mullvad-cli/src/cmds/custom_relay.rs
+++ b/mullvad-cli/src/cmds/custom_relay.rs
@@ -17,21 +17,33 @@ impl Command for CustomRelay {
clap::SubCommand::with_name(self.name())
.about("Set or remove custom relay")
.setting(clap::AppSettings::SubcommandRequired)
- .subcommand(clap::SubCommand::with_name("set")
- .about("Set a custom relay")
- .arg(clap::Arg::with_name("host")
- .help("The host name or IP of the relay")
- .required(true))
- .arg(clap::Arg::with_name("port")
- .help("The port of the relay")
- .required(true))
- .arg(clap::Arg::with_name("protocol")
- .help("The transport protocol. UDP is recommended as it usually results in
- higher throughput than TCP")
- .possible_values(&["udp", "tcp"])
- .default_value("udp")))
- .subcommand(clap::SubCommand::with_name("remove")
- .about("Remove the custom relay and use the default relays instead"))
+ .subcommand(
+ clap::SubCommand::with_name("set")
+ .about("Set a custom relay")
+ .arg(
+ clap::Arg::with_name("host")
+ .help("The host name or IP of the relay")
+ .required(true),
+ )
+ .arg(
+ clap::Arg::with_name("port")
+ .help("The port of the relay")
+ .required(true),
+ )
+ .arg(
+ clap::Arg::with_name("protocol")
+ .help(
+ "The transport protocol. UDP is recommended as it usually results in
+ higher throughput than TCP",
+ )
+ .possible_values(&["udp", "tcp"])
+ .default_value("udp"),
+ ),
+ )
+ .subcommand(
+ clap::SubCommand::with_name("remove")
+ .about("Remove the custom relay and use the default relays instead"),
+ )
}
fn run(&self, matches: &clap::ArgMatches) -> Result<()> {
@@ -57,18 +69,12 @@ impl CustomRelay {
protocol,
};
- rpc::call(
- "set_custom_relay",
- &[relay_endpoint],
- )
- .map(|_: Option<()>| println!("Custom relay set"))
+ rpc::call("set_custom_relay", &[relay_endpoint])
+ .map(|_: Option<()>| println!("Custom relay set"))
}
fn remove(&self) -> Result<()> {
- rpc::call(
- "remove_custom_relay",
- &[] as &[u8; 0],
- )
- .map(|_: Option<()>| println!("Custom relay removed"))
+ rpc::call("remove_custom_relay", &[] as &[u8; 0])
+ .map(|_: Option<()>| println!("Custom relay removed"))
}
}
diff --git a/mullvad-cli/src/main.rs b/mullvad-cli/src/main.rs
index 8543f7eecb..edcfbe3553 100644
--- a/mullvad-cli/src/main.rs
+++ b/mullvad-cli/src/main.rs
@@ -9,20 +9,20 @@
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
-extern crate mullvad_types;
-extern crate talpid_types;
-extern crate talpid_ipc;
#[macro_use]
extern crate clap;
+extern crate env_logger;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
-extern crate env_logger;
+extern crate mullvad_types;
extern crate serde;
extern crate serde_json;
+extern crate talpid_ipc;
+extern crate talpid_types;
mod rpc;
mod cmds;
diff --git a/mullvad-cli/src/rpc.rs b/mullvad-cli/src/rpc.rs
index d6569878cd..bd1d6e571b 100644
--- a/mullvad-cli/src/rpc.rs
+++ b/mullvad-cli/src/rpc.rs
@@ -6,21 +6,24 @@ use std::path::{Path, PathBuf};
use talpid_ipc::WsIpcClient;
pub fn call<T, O>(method: &str, args: &T) -> Result<O>
- where T: serde::Serialize,
- O: for<'de> serde::Deserialize<'de>
+where
+ T: serde::Serialize,
+ O: for<'de> serde::Deserialize<'de>,
{
call_internal(method, args).chain_err(|| "Unable to call backend over RPC")
}
pub fn call_internal<T, O>(method: &str, args: &T) -> Result<O>
- where T: serde::Serialize,
- O: for<'de> serde::Deserialize<'de>
+where
+ T: serde::Serialize,
+ O: for<'de> serde::Deserialize<'de>,
{
let address = read_rpc_address().chain_err(|| "Unable to read RPC address")?;
info!("Using RPC address {}", address);
- let mut rpc_client = WsIpcClient::new(address)
- .chain_err(|| "Unable to create RPC client")?;
- rpc_client.call(method, args).chain_err(|| format!("Unable to call RPC method {}", method))
+ let mut rpc_client = WsIpcClient::new(address).chain_err(|| "Unable to create RPC client")?;
+ rpc_client
+ .call(method, args)
+ .chain_err(|| format!("Unable to call RPC method {}", method))
}
diff --git a/mullvad-daemon/src/main.rs b/mullvad-daemon/src/main.rs
index 54b1ac1747..f252d762d3 100644
--- a/mullvad-daemon/src/main.rs
+++ b/mullvad-daemon/src/main.rs
@@ -6,15 +6,15 @@
//! GNU General Public License as published by the Free Software Foundation, either version 3 of
//! the License, or (at your option) any later version.
-#[macro_use]
-extern crate clap;
extern crate chrono;
#[macro_use]
-extern crate log;
+extern crate clap;
#[macro_use]
extern crate error_chain;
extern crate fern;
extern crate futures;
+#[macro_use]
+extern crate log;
extern crate serde;
#[macro_use]
@@ -24,13 +24,13 @@ extern crate serde_derive;
extern crate jsonrpc_client_core;
extern crate jsonrpc_client_http;
extern crate jsonrpc_core;
-extern crate jsonrpc_pubsub;
#[macro_use]
extern crate jsonrpc_macros;
+extern crate jsonrpc_pubsub;
extern crate jsonrpc_ws_server;
-extern crate uuid;
#[macro_use]
extern crate lazy_static;
+extern crate uuid;
extern crate mullvad_types;
extern crate talpid_core;
@@ -58,7 +58,7 @@ use mullvad_types::states::{DaemonState, SecurityState, TargetState};
use std::io;
use std::net::Ipv4Addr;
use std::path::PathBuf;
-use std::sync::{Arc, Mutex, mpsc};
+use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use talpid_core::firewall::{Firewall, FirewallProxy, SecurityPolicy};
@@ -190,34 +190,33 @@ impl Daemon {
let management_interface_broadcaster = Self::start_management_interface(tx.clone())?;
let state = TunnelState::NotRunning;
let target_state = TargetState::Unsecured;
- Ok(
- Daemon {
- state,
- tunnel_close_handle: None,
+ Ok(Daemon {
+ state,
+ tunnel_close_handle: None,
+ target_state,
+ last_broadcasted_state: DaemonState {
+ state: state.as_security_state(),
target_state,
- last_broadcasted_state: DaemonState {
- state: state.as_security_state(),
- target_state,
- },
- shutdown: false,
- rx,
- tx,
- management_interface_broadcaster,
- settings: settings::Settings::load().chain_err(|| "Unable to read settings")?,
- accounts_proxy: master::create_account_proxy()
- .chain_err(|| "Unable to bootstrap RPC client")?,
- firewall: FirewallProxy::new().chain_err(|| ErrorKind::FirewallError)?,
- relay_endpoint: None,
- tunnel_interface: None,
- relay_iter: RELAYS.iter().cloned().cycle(),
},
- )
+ shutdown: false,
+ rx,
+ tx,
+ management_interface_broadcaster,
+ settings: settings::Settings::load().chain_err(|| "Unable to read settings")?,
+ accounts_proxy: master::create_account_proxy()
+ .chain_err(|| "Unable to bootstrap RPC client")?,
+ firewall: FirewallProxy::new().chain_err(|| ErrorKind::FirewallError)?,
+ relay_endpoint: None,
+ tunnel_interface: None,
+ relay_iter: RELAYS.iter().cloned().cycle(),
+ })
}
// Starts the management interface and spawns a thread that will process it.
// Returns a handle that allows notifying all subscribers on events.
- fn start_management_interface(event_tx: mpsc::Sender<DaemonEvent>)
- -> Result<management_interface::EventBroadcaster> {
+ fn start_management_interface(
+ event_tx: mpsc::Sender<DaemonEvent>,
+ ) -> Result<management_interface::EventBroadcaster> {
let multiplex_event_tx = IntoSender::from(event_tx.clone());
let server = Self::start_management_interface_server(multiplex_event_tx)?;
let event_broadcaster = server.event_broadcaster();
@@ -225,29 +224,31 @@ impl Daemon {
Ok(event_broadcaster)
}
- fn start_management_interface_server(event_tx: IntoSender<TunnelCommand, DaemonEvent>)
- -> Result<ManagementInterfaceServer> {
- let server =
- ManagementInterfaceServer::start(event_tx)
- .chain_err(|| ErrorKind::ManagementInterfaceError("Failed to start server"),)?;
+ fn start_management_interface_server(
+ event_tx: IntoSender<TunnelCommand, DaemonEvent>,
+ ) -> Result<ManagementInterfaceServer> {
+ let server = ManagementInterfaceServer::start(event_tx).chain_err(|| {
+ ErrorKind::ManagementInterfaceError("Failed to start server")
+ })?;
info!(
"Mullvad management interface listening on {}",
server.address()
);
- rpc_info::write(server.address()).chain_err(|| ErrorKind::ManagementInterfaceError(
- "Failed to write RPC address to file"))?;
+ rpc_info::write(server.address()).chain_err(|| {
+ ErrorKind::ManagementInterfaceError("Failed to write RPC address to file")
+ })?;
Ok(server)
}
- fn spawn_management_interface_wait_thread(server: ManagementInterfaceServer,
- exit_tx: mpsc::Sender<DaemonEvent>) {
- thread::spawn(
- move || {
- let result = server.wait();
- debug!("Mullvad management interface shut down");
- let _ = exit_tx.send(DaemonEvent::ManagementInterfaceExited(result));
- },
- );
+ fn spawn_management_interface_wait_thread(
+ server: ManagementInterfaceServer,
+ exit_tx: mpsc::Sender<DaemonEvent>,
+ ) {
+ thread::spawn(move || {
+ let result = server.wait();
+ debug!("Mullvad management interface shut down");
+ let _ = exit_tx.send(DaemonEvent::ManagementInterfaceExited(result));
+ });
}
/// Consume the `Daemon` and run the main event loop. Blocks until an error happens or a
@@ -331,9 +332,11 @@ impl Daemon {
Self::oneshot_send(tx, self.last_broadcasted_state, "current state");
}
- fn on_get_account_data(&mut self,
- tx: OneshotSender<BoxFuture<AccountData, jsonrpc_client_core::Error>>,
- account_token: AccountToken) {
+ fn on_get_account_data(
+ &mut self,
+ tx: OneshotSender<BoxFuture<AccountData, jsonrpc_client_core::Error>>,
+ account_token: AccountToken,
+ ) {
let rpc_call = self.accounts_proxy
.get_expiry(account_token)
.map(|expiry| AccountData { expiry });
@@ -341,18 +344,18 @@ impl Daemon {
}
- fn on_set_account(&mut self,
- tx: OneshotSender<()>,
- account_token: Option<String>)
- -> Result<()> {
-
+ fn on_set_account(
+ &mut self,
+ tx: OneshotSender<()>,
+ account_token: Option<String>,
+ ) -> Result<()> {
let save_result = self.settings.set_account_token(account_token);
match save_result.chain_err(|| "Unable to save settings") {
Ok(account_changed) => {
Self::oneshot_send(tx, (), "set_account response");
- let tunnel_needs_restart = self.state == TunnelState::Connecting ||
- self.state == TunnelState::Connected;
+ let tunnel_needs_restart =
+ self.state == TunnelState::Connecting || self.state == TunnelState::Connected;
if account_changed && tunnel_needs_restart {
info!("Initiating tunnel restart because the account token changed");
self.kill_tunnel()?;
@@ -367,19 +370,19 @@ impl Daemon {
Self::oneshot_send(tx, self.settings.get_account_token(), "current account")
}
- fn on_set_custom_relay(&mut self,
- tx: OneshotSender<()>,
- relay_endpoint: Option<RelayEndpoint>)
- -> Result<()> {
-
+ fn on_set_custom_relay(
+ &mut self,
+ tx: OneshotSender<()>,
+ relay_endpoint: Option<RelayEndpoint>,
+ ) -> Result<()> {
let save_result = self.settings.set_custom_relay(relay_endpoint);
match save_result.chain_err(|| "Unable to save settings") {
Ok(relays_changed) => {
Self::oneshot_send(tx, (), "set_custom_relay response");
- let tunnel_needs_restart = self.state == TunnelState::Connecting ||
- self.state == TunnelState::Connected;
+ let tunnel_needs_restart =
+ self.state == TunnelState::Connecting || self.state == TunnelState::Connected;
if relays_changed && tunnel_needs_restart {
info!("Initiating tunnel restart because a custom relay was selected");
@@ -434,7 +437,8 @@ impl Daemon {
};
if self.last_broadcasted_state != new_daemon_state {
self.last_broadcasted_state = new_daemon_state;
- self.management_interface_broadcaster.notify_new_state(new_daemon_state);
+ self.management_interface_broadcaster
+ .notify_new_state(new_daemon_state);
}
}
@@ -453,8 +457,8 @@ impl Daemon {
Ok(())
}
- /// Set the target state of the client. If it changed trigger the operations needed to progress
- /// towards that state.
+ /// Set the target state of the client. If it changed trigger the operations needed to
+ /// progress towards that state.
fn set_target_state(&mut self, new_state: TargetState) -> Result<()> {
if new_state != self.target_state {
debug!("Target state {:?} => {:?}", self.target_state, new_state);
@@ -491,8 +495,7 @@ impl Daemon {
ErrorKind::InvalidState
);
- let relay = self.get_relay()
- .chain_err(|| ErrorKind::NoRelay)?;
+ let relay = self.get_relay().chain_err(|| ErrorKind::NoRelay)?;
let account_token = self.settings
.get_account_token()
@@ -523,7 +526,10 @@ impl Daemon {
// Must wrap the channel in a Mutex because TunnelMonitor forces the closure to be Sync
let event_tx = Arc::new(Mutex::new(self.tx.clone()));
let on_tunnel_event = move |event| {
- let _ = event_tx.lock().unwrap().send(DaemonEvent::TunnelEvent(event));
+ let _ = event_tx
+ .lock()
+ .unwrap()
+ .send(DaemonEvent::TunnelEvent(event));
};
TunnelMonitor::new(relay, account_token, on_tunnel_event)
.chain_err(|| ErrorKind::TunnelError("Unable to start tunnel monitor"))
@@ -531,13 +537,11 @@ impl Daemon {
fn spawn_tunnel_monitor_wait_thread(&self, tunnel_monitor: TunnelMonitor) {
let error_tx = self.tx.clone();
- thread::spawn(
- move || {
- let result = tunnel_monitor.wait();
- let _ = error_tx.send(DaemonEvent::TunnelExited(result));
- trace!("Tunnel monitor thread exit");
- },
- );
+ thread::spawn(move || {
+ let result = tunnel_monitor.wait();
+ let _ = error_tx.send(DaemonEvent::TunnelExited(result));
+ trace!("Tunnel monitor thread exit");
+ });
}
fn kill_tunnel(&mut self) -> Result<()> {
@@ -548,18 +552,18 @@ impl Daemon {
let close_handle = self.tunnel_close_handle.take().unwrap();
self.set_state(TunnelState::Exiting)?;
let result_tx = self.tx.clone();
- thread::spawn(
- move || {
- let result = close_handle.close();
- let _ = result_tx.send(DaemonEvent::TunnelKillResult(result));
- trace!("Tunnel kill thread exit");
- },
- );
+ thread::spawn(move || {
+ let result = close_handle.close();
+ let _ = result_tx.send(DaemonEvent::TunnelKillResult(result));
+ trace!("Tunnel kill thread exit");
+ });
Ok(())
}
pub fn shutdown_handle(&self) -> DaemonShutdownHandle {
- DaemonShutdownHandle { tx: self.tx.clone() }
+ DaemonShutdownHandle {
+ tx: self.tx.clone(),
+ }
}
fn set_security_policy(&mut self) -> Result<()> {
@@ -569,12 +573,16 @@ impl Daemon {
_ => bail!(ErrorKind::InvalidState),
};
debug!("Set security policy: {:?}", policy);
- self.firewall.apply_policy(policy).chain_err(|| ErrorKind::FirewallError)
+ self.firewall
+ .apply_policy(policy)
+ .chain_err(|| ErrorKind::FirewallError)
}
fn reset_security_policy(&mut self) -> Result<()> {
debug!("Reset security policy");
- self.firewall.reset_policy().chain_err(|| ErrorKind::FirewallError)
+ self.firewall
+ .reset_policy()
+ .chain_err(|| ErrorKind::FirewallError)
}
}
@@ -626,19 +634,15 @@ fn init_logger(log_level: log::LogLevelFilter, log_file: Option<&PathBuf>) -> Re
"hyper",
];
let mut config = fern::Dispatch::new()
- .format(
- |out, message, record| {
- out.finish(
- format_args!(
- "{}[{}][{}] {}",
- chrono::Local::now().format("[%Y-%m-%d %H:%M:%S%.3f]"),
- record.target(),
- record.level(),
- message
- ),
- )
- },
- )
+ .format(|out, message, record| {
+ out.finish(format_args!(
+ "{}[{}][{}] {}",
+ chrono::Local::now().format("[%Y-%m-%d %H:%M:%S%.3f]"),
+ record.target(),
+ record.level(),
+ message
+ ))
+ })
.level(log_level)
.chain(std::io::stdout());
for silenced_crate in &silenced_crates {
@@ -648,5 +652,7 @@ fn init_logger(log_level: log::LogLevelFilter, log_file: Option<&PathBuf>) -> Re
let f = fern::log_file(log_file).chain_err(|| "Failed to open log file for writing")?;
config = config.chain(f);
}
- config.apply().chain_err(|| "Failed to bootstrap logging system")
+ config
+ .apply()
+ .chain_err(|| "Failed to bootstrap logging system")
}
diff --git a/mullvad-daemon/src/management_interface.rs b/mullvad-daemon/src/management_interface.rs
index ff63fcfde7..7b222b8504 100644
--- a/mullvad-daemon/src/management_interface.rs
+++ b/mullvad-daemon/src/management_interface.rs
@@ -3,7 +3,7 @@ use error_chain;
use error_chain::ChainedError;
use jsonrpc_client_core;
use jsonrpc_core::{Error, ErrorCode, Metadata};
-use jsonrpc_core::futures::{Future, future, sync};
+use jsonrpc_core::futures::{future, sync, Future};
use jsonrpc_core::futures::sync::oneshot::Sender as OneshotSender;
use jsonrpc_macros::pubsub;
use jsonrpc_pubsub::{PubSubHandler, PubSubMetadata, Session, SubscriptionId};
@@ -115,7 +115,10 @@ pub enum TunnelCommand {
/// Request the current state.
GetState(OneshotSender<DaemonState>),
/// Request the metadata for an account.
- GetAccountData(OneshotSender<BoxFuture<AccountData, jsonrpc_client_core::Error>>, AccountToken),
+ GetAccountData(
+ OneshotSender<BoxFuture<AccountData, jsonrpc_client_core::Error>>,
+ AccountToken,
+ ),
/// Set which account token to use for subsequent connection attempts.
SetAccount(OneshotSender<()>, Option<AccountToken>),
/// Request the current account token being used.
@@ -137,7 +140,8 @@ pub struct ManagementInterfaceServer {
impl ManagementInterfaceServer {
pub fn start<T>(tunnel_tx: IntoSender<TunnelCommand, T>) -> talpid_ipc::Result<Self>
- where T: From<TunnelCommand> + 'static + Send
+ where
+ T: From<TunnelCommand> + 'static + Send,
{
let rpc = ManagementInterface::new(tunnel_tx);
let subscriptions = rpc.subscriptions.clone();
@@ -145,12 +149,10 @@ impl ManagementInterfaceServer {
let mut io = PubSubHandler::default();
io.extend_with(rpc.to_delegate());
let server = talpid_ipc::IpcServer::start_with_metadata(io.into(), meta_extractor)?;
- Ok(
- ManagementInterfaceServer {
- server,
- subscriptions,
- },
- )
+ Ok(ManagementInterfaceServer {
+ server,
+ subscriptions,
+ })
}
pub fn address(&self) -> &str {
@@ -158,7 +160,9 @@ impl ManagementInterfaceServer {
}
pub fn event_broadcaster(&self) -> EventBroadcaster {
- EventBroadcaster { subscriptions: self.subscriptions.clone() }
+ EventBroadcaster {
+ subscriptions: self.subscriptions.clone(),
+ }
}
/// Consumes the server and waits for it to finish. Returns an error if the server exited
@@ -182,16 +186,19 @@ impl EventBroadcaster {
/// Sends an error to all `error` subscribers of the management interface.
pub fn notify_error<E>(&self, error: &E)
- where E: error_chain::ChainedError
+ where
+ E: error_chain::ChainedError,
{
let error_strings = error.iter().map(|e| e.to_string()).collect();
self.notify(&self.subscriptions.error_subscriptions, error_strings);
}
- fn notify<T>(&self,
- subscriptions_lock: &RwLock<HashMap<SubscriptionId, pubsub::Sink<T>>>,
- value: T)
- where T: serde::Serialize + Clone
+ fn notify<T>(
+ &self,
+ subscriptions_lock: &RwLock<HashMap<SubscriptionId, pubsub::Sink<T>>>,
+ value: T,
+ ) where
+ T: serde::Serialize + Clone,
{
let subscriptions = subscriptions_lock.read().unwrap();
for sink in subscriptions.values() {
@@ -213,8 +220,10 @@ impl<T: From<TunnelCommand> + 'static + Send> ManagementInterface<T> {
}
}
- fn subscribe<V>(subscriber: pubsub::Subscriber<V>,
- subscriptions_lock: &RwLock<HashMap<SubscriptionId, pubsub::Sink<V>>>) {
+ fn subscribe<V>(
+ subscriber: pubsub::Subscriber<V>,
+ subscriptions_lock: &RwLock<HashMap<SubscriptionId, pubsub::Sink<V>>>,
+ ) {
let mut subscriptions = subscriptions_lock.write().unwrap();
loop {
let id = SubscriptionId::String(uuid::Uuid::new_v4().to_string());
@@ -228,21 +237,20 @@ impl<T: From<TunnelCommand> + 'static + Send> ManagementInterface<T> {
}
}
- fn unsubscribe<V>(id: SubscriptionId,
- subscriptions_lock: &RwLock<HashMap<SubscriptionId, pubsub::Sink<V>>>)
- -> BoxFuture<(), Error> {
+ fn unsubscribe<V>(
+ id: SubscriptionId,
+ subscriptions_lock: &RwLock<HashMap<SubscriptionId, pubsub::Sink<V>>>,
+ ) -> BoxFuture<(), Error> {
let was_removed = subscriptions_lock.write().unwrap().remove(&id).is_some();
let result = if was_removed {
debug!("Unsubscribing id {:?}", id);
future::ok(())
} else {
- future::err(
- Error {
- code: ErrorCode::InvalidParams,
- message: "Invalid subscription".to_owned(),
- data: None,
- },
- )
+ future::err(Error {
+ code: ErrorCode::InvalidParams,
+ message: "Invalid subscription".to_owned(),
+ data: None,
+ })
};
Box::new(result)
}
@@ -251,7 +259,7 @@ impl<T: From<TunnelCommand> + 'static + Send> ManagementInterface<T> {
fn send_command_to_daemon(&self, command: TunnelCommand) -> BoxFuture<(), Error> {
Box::new(
future::result(self.tx.lock().unwrap().send(command))
- .map_err(|_| Error::internal_error())
+ .map_err(|_| Error::internal_error()),
)
}
@@ -282,19 +290,15 @@ impl<T: From<TunnelCommand> + 'static + Send> ManagementInterfaceApi for Managem
let (tx, rx) = sync::oneshot::channel();
let future = self.send_command_to_daemon(TunnelCommand::GetAccountData(tx, account_token))
.and_then(|_| rx.map_err(|_| Error::internal_error()))
- .and_then(
- |rpc_future| {
- rpc_future.map_err(
- |error: jsonrpc_client_core::Error| {
- error!(
- "Unable to get account data from master: {}",
- error.display_chain()
- );
- Self::map_rpc_error(error)
- },
- )
- },
- );
+ .and_then(|rpc_future| {
+ rpc_future.map_err(|error: jsonrpc_client_core::Error| {
+ error!(
+ "Unable to get account data from master: {}",
+ error.display_chain()
+ );
+ Self::map_rpc_error(error)
+ })
+ });
Box::new(future)
}
@@ -367,18 +371,18 @@ impl<T: From<TunnelCommand> + 'static + Send> ManagementInterfaceApi for Managem
fn get_location(&self) -> Result<Location, Error> {
trace!("get_location");
- Ok(
- Location {
- latlong: [1.0, 2.0],
- country: "narnia".to_owned(),
- city: "Le city".to_owned(),
- },
- )
+ Ok(Location {
+ latlong: [1.0, 2.0],
+ country: "narnia".to_owned(),
+ city: "Le city".to_owned(),
+ })
}
- fn new_state_subscribe(&self,
- _meta: Self::Metadata,
- subscriber: pubsub::Subscriber<DaemonState>) {
+ fn new_state_subscribe(
+ &self,
+ _meta: Self::Metadata,
+ subscriber: pubsub::Subscriber<DaemonState>,
+ ) {
trace!("new_state_subscribe");
Self::subscribe(subscriber, &self.subscriptions.new_state_subscriptions);
}
@@ -420,5 +424,7 @@ impl PubSubMetadata for Meta {
/// Metadata extractor function for `Meta`.
fn meta_extractor(context: &jsonrpc_ws_server::RequestContext) -> Meta {
- Meta { session: Some(Arc::new(Session::new(context.sender()))) }
+ Meta {
+ session: Some(Arc::new(Session::new(context.sender()))),
+ }
}
diff --git a/mullvad-daemon/src/settings.rs b/mullvad-daemon/src/settings.rs
index 63a4325d5e..230f7fcedf 100644
--- a/mullvad-daemon/src/settings.rs
+++ b/mullvad-daemon/src/settings.rs
@@ -74,7 +74,8 @@ impl Settings {
debug!("Writing settings to {}", settings_path.to_string_lossy());
let mut file = File::create(&settings_path)
.chain_err(|| ErrorKind::WriteError(settings_path.clone()))?;
- file.write_all(data.as_bytes()).chain_err(|| ErrorKind::WriteError(settings_path))?;
+ file.write_all(data.as_bytes())
+ .chain_err(|| ErrorKind::WriteError(settings_path))?;
Ok(())
}
@@ -86,7 +87,8 @@ impl Settings {
fn read_settings(file: &mut File, path: PathBuf) -> Result<Settings> {
let mut data = Vec::new();
- file.read_to_end(&mut data).chain_err(|| ErrorKind::ReadError(path))?;
+ file.read_to_end(&mut data)
+ .chain_err(|| ErrorKind::ReadError(path))?;
toml::from_slice(&data).chain_err(|| ErrorKind::ParseError)
}
@@ -104,8 +106,7 @@ impl Settings {
Self::format_account_token(&account_token),
);
self.account_token = account_token;
- self.save()
- .map(|_| true)
+ self.save().map(|_| true)
} else {
Ok(false)
}
@@ -131,8 +132,7 @@ impl Settings {
self.custom_relay = relay_endpoint;
- self.save()
- .map(|_| true)
+ self.save().map(|_| true)
} else {
Ok(false)
}
diff --git a/mullvad-daemon/src/shutdown.rs b/mullvad-daemon/src/shutdown.rs
index 4da73c4d05..ac41381e1e 100644
--- a/mullvad-daemon/src/shutdown.rs
+++ b/mullvad-daemon/src/shutdown.rs
@@ -8,14 +8,13 @@ mod platform {
use super::Result;
pub fn set_shutdown_signal_handler<F>(f: F) -> Result<()>
- where F: Fn() + 'static + Send
+ where
+ F: Fn() + 'static + Send,
{
- simple_signal::set_handler(
- &[Signal::Term, Signal::Int], move |s| {
- debug!("Process received signal: {:?}", s);
- f();
- }
- );
+ simple_signal::set_handler(&[Signal::Term, Signal::Int], move |s| {
+ debug!("Process received signal: {:?}", s);
+ f();
+ });
Ok(())
}
}
@@ -27,15 +26,13 @@ mod platform {
use super::{Result, ResultExt};
pub fn set_shutdown_signal_handler<F>(f: F) -> Result<()>
- where F: Fn() + 'static + Send
+ where
+ F: Fn() + 'static + Send,
{
- ctrlc::set_handler(
- move || {
- debug!("Process received Ctrl-c");
- f();
- },
- )
- .chain_err(|| "Unable to attach ctrl-c handler")
+ ctrlc::set_handler(move || {
+ debug!("Process received Ctrl-c");
+ f();
+ }).chain_err(|| "Unable to attach ctrl-c handler")
}
}
diff --git a/mullvad-types/src/lib.rs b/mullvad-types/src/lib.rs
index 608e3eee80..1ec57c010a 100644
--- a/mullvad-types/src/lib.rs
+++ b/mullvad-types/src/lib.rs
@@ -7,9 +7,9 @@
//! the License, or (at your option) any later version.
extern crate chrono;
+extern crate serde;
#[macro_use]
extern crate serde_derive;
-extern crate serde;
extern crate talpid_types;
diff --git a/mullvad-types/src/relay_endpoint.rs b/mullvad-types/src/relay_endpoint.rs
index 894fcab3b5..8a53d16393 100644
--- a/mullvad-types/src/relay_endpoint.rs
+++ b/mullvad-types/src/relay_endpoint.rs
@@ -20,7 +20,6 @@ pub struct RelayEndpoint {
impl RelayEndpoint {
pub fn to_endpoint(&self) -> Result<talpid_types::net::Endpoint> {
-
let socket_addrs = to_socket_addrs(self.host.as_str(), self.port)?;
ensure!(
socket_addrs.len() > 0,
@@ -37,7 +36,11 @@ impl RelayEndpoint {
)
}
- Ok(talpid_types::net::Endpoint::new(socket_addr.ip(), socket_addr.port(), self.protocol),)
+ Ok(talpid_types::net::Endpoint::new(
+ socket_addr.ip(),
+ socket_addr.port(),
+ self.protocol,
+ ))
}
}
@@ -56,9 +59,7 @@ fn choose_ip(socket_addrs: &Vec<SocketAddr>) -> Option<SocketAddr> {
// IPv4 ad IPv6s and take form the IPv4 pile if any.
let (mut ipv4, mut ipv6): (Vec<SocketAddr>, Vec<SocketAddr>) =
- socket_addrs
- .into_iter()
- .partition(|addr| addr.is_ipv4());
+ socket_addrs.into_iter().partition(|addr| addr.is_ipv4());
// If there are many IP:s, we simply ignore the rest
ipv4.pop().or(ipv6.pop())
diff --git a/rustfmt.toml b/rustfmt.toml
index d56f55c24d..25060d89d5 100644
--- a/rustfmt.toml
+++ b/rustfmt.toml
@@ -1,6 +1,7 @@
# Activation of features, almost objectively better ;)
reorder_imports = true
reorder_imported_names = true
+reorder_imports_in_group = true
use_try_shorthand = true
condense_wildcard_suffices = true
normalize_comments = true
@@ -8,9 +9,4 @@ wrap_comments = true
# Heavily subjective style choices
comment_width = 100
-chain_one_line_max = 100
-array_layout = "Block"
-fn_call_style = "Block"
take_source_hints = true
-
-write_mode = "Overwrite"
diff --git a/talpid-core/src/firewall/macos.rs b/talpid-core/src/firewall/macos.rs
index e3bfa9870f..14c9fb5033 100644
--- a/talpid-core/src/firewall/macos.rs
+++ b/talpid-core/src/firewall/macos.rs
@@ -16,12 +16,10 @@ pub struct PacketFilter {
impl Firewall<Error> for PacketFilter {
fn new() -> Result<Self> {
- Ok(
- PacketFilter {
- pf: pfctl::PfCtl::new()?,
- pf_was_enabled: None,
- },
- )
+ Ok(PacketFilter {
+ pf: pfctl::PfCtl::new()?,
+ pf_was_enabled: None,
+ })
}
fn apply_policy(&mut self, policy: SecurityPolicy) -> Result<()> {
@@ -35,10 +33,9 @@ impl Firewall<Error> for PacketFilter {
self.remove_rules(),
self.remove_anchor(),
self.restore_state(),
- ]
- .into_iter()
- .collect::<Result<Vec<_>>>()
- .map(|_| ())
+ ].into_iter()
+ .collect::<Result<Vec<_>>>()
+ .map(|_| ())
}
}
@@ -160,11 +157,13 @@ impl PacketFilter {
}
fn add_anchor(&mut self) -> Result<()> {
- self.pf.try_add_anchor(ANCHOR_NAME, pfctl::AnchorKind::Filter)
+ self.pf
+ .try_add_anchor(ANCHOR_NAME, pfctl::AnchorKind::Filter)
}
fn remove_anchor(&mut self) -> Result<()> {
- self.pf.try_remove_anchor(ANCHOR_NAME, pfctl::AnchorKind::Filter)
+ self.pf
+ .try_remove_anchor(ANCHOR_NAME, pfctl::AnchorKind::Filter)
}
}
diff --git a/talpid-core/src/firewall/mod.rs b/talpid-core/src/firewall/mod.rs
index acc0f21792..a1fa7edbc3 100644
--- a/talpid-core/src/firewall/mod.rs
+++ b/talpid-core/src/firewall/mod.rs
@@ -38,7 +38,9 @@ pub enum SecurityPolicy {
/// Abstract firewall interaction trait
pub trait Firewall<E: ::std::error::Error> {
/// Create new instance of Firewall
- fn new() -> ::std::result::Result<Self, E> where Self: Sized;
+ fn new() -> ::std::result::Result<Self, E>
+ where
+ Self: Sized;
/// Enable firewall and set firewall rules based on SecurityPolicy
fn apply_policy(&mut self, policy: SecurityPolicy) -> ::std::result::Result<(), E>;
@@ -58,10 +60,14 @@ impl Firewall<Error> for FirewallProxy {
}
fn apply_policy(&mut self, policy: SecurityPolicy) -> Result<()> {
- self.0.apply_policy(policy).chain_err(|| ErrorKind::FirewallConfigurationError)
+ self.0
+ .apply_policy(policy)
+ .chain_err(|| ErrorKind::FirewallConfigurationError)
}
fn reset_policy(&mut self) -> Result<()> {
- self.0.reset_policy().chain_err(|| ErrorKind::FirewallConfigurationError)
+ self.0
+ .reset_policy()
+ .chain_err(|| ErrorKind::FirewallConfigurationError)
}
}
diff --git a/talpid-core/src/lib.rs b/talpid-core/src/lib.rs
index c4cff6ebfc..c14377919e 100644
--- a/talpid-core/src/lib.rs
+++ b/talpid-core/src/lib.rs
@@ -29,9 +29,9 @@ extern crate jsonrpc_core;
extern crate jsonrpc_macros;
extern crate uuid;
+extern crate openvpn_plugin;
extern crate talpid_ipc;
extern crate talpid_types;
-extern crate openvpn_plugin;
#[cfg(target_os = "macos")]
extern crate pfctl;
diff --git a/talpid-core/src/mktemp.rs b/talpid-core/src/mktemp.rs
index e8ba33c3c5..fc39127069 100644
--- a/talpid-core/src/mktemp.rs
+++ b/talpid-core/src/mktemp.rs
@@ -13,7 +13,9 @@ pub struct TempFile {
impl TempFile {
/// Create a new unique `TempFile`. The file will not exist after this.
pub fn new() -> Self {
- TempFile { path: generate_path() }
+ TempFile {
+ path: generate_path(),
+ }
}
pub fn to_path_buf(&self) -> PathBuf {
diff --git a/talpid-core/src/mpsc.rs b/talpid-core/src/mpsc.rs
index d63956c452..533dd857c1 100644
--- a/talpid-core/src/mpsc.rs
+++ b/talpid-core/src/mpsc.rs
@@ -9,7 +9,8 @@ pub struct IntoSender<T, U> {
}
impl<T, U> IntoSender<T, U>
- where T: Into<U>
+where
+ T: Into<U>,
{
/// Converts the `T` into a `U` and sends it on the channel.
pub fn send(&self, t: T) -> Result<(), mpsc::SendError<U>> {
@@ -18,7 +19,8 @@ impl<T, U> IntoSender<T, U>
}
impl<T, U> From<mpsc::Sender<U>> for IntoSender<T, U>
- where T: Into<U>
+where
+ T: Into<U>,
{
fn from(sender: mpsc::Sender<U>) -> Self {
IntoSender {
@@ -69,7 +71,9 @@ mod tests {
let (tx, rx) = mpsc::channel::<Outer>();
let inner_tx: IntoSender<Inner, Outer> = tx.clone().into();
- thread::spawn(move || { inner_tx.send(Inner::One).unwrap(); });
+ thread::spawn(move || {
+ inner_tx.send(Inner::One).unwrap();
+ });
assert_eq!(Outer::Inner(Inner::One), rx.recv().unwrap());
}
diff --git a/talpid-core/src/process/openvpn.rs b/talpid-core/src/process/openvpn.rs
index c756757a75..046d70b569 100644
--- a/talpid-core/src/process/openvpn.rs
+++ b/talpid-core/src/process/openvpn.rs
@@ -64,8 +64,8 @@ impl OpenVpnCommand {
self
}
- /// Sets the path to the file where the username and password for user-pass authentication is
- /// stored. See the `--auth-user-pass` OpenVPN documentation for details.
+ /// Sets the path to the file where the username and password for user-pass authentication
+ /// is stored. See the `--auth-user-pass` OpenVPN documentation for details.
pub fn user_pass<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
self.user_pass_path = Some(path.as_ref().to_path_buf());
self
@@ -138,12 +138,10 @@ impl OpenVpnCommand {
let mut args: Vec<String> = vec![];
if let Some(ref endpoint) = self.remote {
args.push("--proto".to_owned());
- args.push(
- match endpoint.protocol {
- net::TransportProtocol::Udp => "udp".to_owned(),
- net::TransportProtocol::Tcp => "tcp-client".to_owned(),
- },
- );
+ args.push(match endpoint.protocol {
+ net::TransportProtocol::Udp => "udp".to_owned(),
+ net::TransportProtocol::Tcp => "tcp-client".to_owned(),
+ });
args.push("--remote".to_owned());
args.push(endpoint.address.ip().to_string());
args.push(endpoint.address.port().to_string());
@@ -162,8 +160,8 @@ impl OpenVpnCommand {
}
impl fmt::Display for OpenVpnCommand {
- /// Format the program and arguments of an `OpenVpnCommand` for display. Any non-utf8 data is
- /// lossily converted using the utf8 replacement character.
+ /// Format the program and arguments of an `OpenVpnCommand` for display. Any non-utf8 data
+ /// is lossily converted using the utf8 replacement character.
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(&self.openvpn_bin.to_string_lossy())?;
for arg in self.get_arguments().iter().map(|arg| arg.to_string_lossy()) {
diff --git a/talpid-core/src/tunnel/mod.rs b/talpid-core/src/tunnel/mod.rs
index 83212e6874..5f73e5be20 100644
--- a/talpid-core/src/tunnel/mod.rs
+++ b/talpid-core/src/tunnel/mod.rs
@@ -57,13 +57,15 @@ pub enum TunnelEvent {
impl TunnelEvent {
/// Converts an `OpenVpnPluginEvent` to a `TunnelEvent`.
/// Returns `None` if there is no corresponding `TunnelEvent`.
- fn from_openvpn_event(event: &OpenVpnPluginEvent,
- env: &HashMap<String, String>)
- -> Option<TunnelEvent> {
+ fn from_openvpn_event(
+ event: &OpenVpnPluginEvent,
+ env: &HashMap<String, String>,
+ ) -> Option<TunnelEvent> {
match *event {
OpenVpnPluginEvent::Up => {
- let tunnel_interface =
- env.get("dev").expect("No \"dev\" in tunnel up event").to_owned();
+ let tunnel_interface = env.get("dev")
+ .expect("No \"dev\" in tunnel up event")
+ .to_owned();
Some(TunnelEvent::Up { tunnel_interface })
}
OpenVpnPluginEvent::RoutePredown => Some(TunnelEvent::Down),
@@ -84,7 +86,8 @@ impl TunnelMonitor {
/// Creates a new `TunnelMonitor` that connects to the given remote and notifies `on_event`
/// on tunnel state changes.
pub fn new<L>(remote: net::Endpoint, account_token: &str, on_event: L) -> Result<Self>
- where L: Fn(TunnelEvent) + Send + Sync + 'static
+ where
+ L: Fn(TunnelEvent) + Send + Sync + 'static,
{
let user_pass_file = Self::create_user_pass_file(account_token)
.chain_err(|| ErrorKind::CredentialsWriteError)?;
@@ -104,12 +107,10 @@ impl TunnelMonitor {
let monitor = openvpn::OpenVpnMonitor::new(cmd, on_openvpn_event, Self::get_plugin_path()?)
.chain_err(|| ErrorKind::TunnelMonitoringError)?;
- Ok(
- TunnelMonitor {
- monitor,
- _user_pass_file: user_pass_file,
- },
- )
+ Ok(TunnelMonitor {
+ monitor,
+ _user_pass_file: user_pass_file,
+ })
}
fn create_openvpn_cmd(remote: net::Endpoint, user_pass_file: &Path) -> OpenVpnCommand {
@@ -117,7 +118,9 @@ impl TunnelMonitor {
if let Some(config) = Self::get_config_path() {
cmd.config(config);
}
- cmd.remote(remote).user_pass(user_pass_file).ca(Self::get_ca_path());
+ cmd.remote(remote)
+ .user_pass(user_pass_file)
+ .ca(Self::get_ca_path());
cmd
}
@@ -143,8 +146,7 @@ impl TunnelMonitor {
}
fn get_plugin_path() -> Result<PathBuf> {
- let lib_ext = Self::get_library_extension()
- .chain_err(|| ErrorKind::PluginNotFound)?;
+ let lib_ext = Self::get_library_extension().chain_err(|| ErrorKind::PluginNotFound)?;
let path = Self::get_install_dir()
.unwrap_or(PathBuf::from("."))
@@ -175,7 +177,11 @@ impl TunnelMonitor {
.unwrap_or(PathBuf::from("."))
.join("openvpn.conf");
- if path.exists() { Some(path) } else { None }
+ if path.exists() {
+ Some(path)
+ } else {
+ None
+ }
}
fn get_install_dir() -> Option<PathBuf> {
@@ -215,7 +221,8 @@ impl TunnelMonitor {
Ok(())
}
- /// Creates a handle to this monitor, allowing the tunnel to be closed while some other thread
+ /// Creates a handle to this monitor, allowing the tunnel to be closed while some other
+ /// thread
/// is blocked in `wait`.
pub fn close_handle(&self) -> CloseHandle {
CloseHandle(self.monitor.close_handle())
@@ -223,7 +230,9 @@ impl TunnelMonitor {
/// Consumes the monitor and block until the tunnel exits or there is an error.
pub fn wait(self) -> Result<()> {
- self.monitor.wait().chain_err(|| ErrorKind::TunnelMonitoringError)
+ self.monitor
+ .wait()
+ .chain_err(|| ErrorKind::TunnelMonitoringError)
}
}
diff --git a/talpid-core/src/tunnel/openvpn.rs b/talpid-core/src/tunnel/openvpn.rs
index 368fb20257..c9ca9b49ef 100644
--- a/talpid-core/src/tunnel/openvpn.rs
+++ b/talpid-core/src/tunnel/openvpn.rs
@@ -8,7 +8,7 @@ use std::io;
use std::path::Path;
use std::process::ExitStatus;
use std::result::Result as StdResult;
-use std::sync::{Arc, mpsc};
+use std::sync::{mpsc, Arc};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
@@ -50,8 +50,9 @@ impl OpenVpnMonitor<OpenVpnCommand> {
/// Creates a new `OpenVpnMonitor` with the given listener and using the plugin at the given
/// path.
pub fn new<L, P>(cmd: OpenVpnCommand, on_event: L, plugin_path: P) -> Result<Self>
- where L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
- P: AsRef<Path>
+ where
+ L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
+ P: AsRef<Path>,
{
Self::new_internal(cmd, on_event, plugin_path)
}
@@ -59,25 +60,26 @@ impl OpenVpnMonitor<OpenVpnCommand> {
impl<C: OpenVpnBuilder> OpenVpnMonitor<C> {
fn new_internal<L, P>(mut cmd: C, on_event: L, plugin_path: P) -> Result<OpenVpnMonitor<C>>
- where L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
- P: AsRef<Path>
+ where
+ L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
+ P: AsRef<Path>,
{
- let event_dispatcher = OpenVpnEventDispatcher::start(on_event)
- .chain_err(|| ErrorKind::EventDispatcherError)?;
+ let event_dispatcher =
+ OpenVpnEventDispatcher::start(on_event).chain_err(|| ErrorKind::EventDispatcherError)?;
cmd.plugin(plugin_path, vec![event_dispatcher.address().to_owned()]);
- let child = cmd.start().chain_err(|| ErrorKind::ChildProcessError("Failed to start"))?;
+ let child = cmd.start()
+ .chain_err(|| ErrorKind::ChildProcessError("Failed to start"))?;
- Ok(
- OpenVpnMonitor {
- child: Arc::new(child),
- event_dispatcher: Some(event_dispatcher),
- closed: Arc::new(AtomicBool::new(false)),
- },
- )
+ Ok(OpenVpnMonitor {
+ child: Arc::new(child),
+ event_dispatcher: Some(event_dispatcher),
+ closed: Arc::new(AtomicBool::new(false)),
+ })
}
- /// Creates a handle to this monitor, allowing the tunnel to be closed while some other thread
+ /// Creates a handle to this monitor, allowing the tunnel to be closed while some other
+ /// thread
/// is blocked in `wait`.
pub fn close_handle(&self) -> OpenVpnCloseHandle<C::ProcessHandle> {
OpenVpnCloseHandle {
@@ -86,22 +88,21 @@ impl<C: OpenVpnBuilder> OpenVpnMonitor<C> {
}
}
- /// Consumes the monitor and blocks until OpenVPN exits or there is an error in either waiting
+ /// Consumes the monitor and blocks until OpenVPN exits or there is an error in either
+ /// waiting
/// for the process or in the event dispatcher.
pub fn wait(mut self) -> Result<()> {
match self.wait_result() {
- WaitResult::Child(Ok(exit_status), closed) => {
- if exit_status.success() || closed {
- debug!(
- "OpenVPN exited, as expected, with exit status: {}",
- exit_status
- );
- Ok(())
- } else {
- error!("OpenVPN died unexpectedly with status: {}", exit_status);
- Err(ErrorKind::ChildProcessError("Died unexpectedly").into())
- }
- }
+ WaitResult::Child(Ok(exit_status), closed) => if exit_status.success() || closed {
+ debug!(
+ "OpenVPN exited, as expected, with exit status: {}",
+ exit_status
+ );
+ Ok(())
+ } else {
+ error!("OpenVPN died unexpectedly with status: {}", exit_status);
+ Err(ErrorKind::ChildProcessError("Died unexpectedly").into())
+ },
WaitResult::Child(Err(e), _) => {
error!("OpenVPN process wait error: {}", e);
Err(e).chain_err(|| ErrorKind::ChildProcessError("Error when waiting"))
@@ -128,21 +129,19 @@ impl<C: OpenVpnBuilder> OpenVpnMonitor<C> {
let (child_tx, rx) = mpsc::channel();
let dispatcher_tx = child_tx.clone();
- thread::spawn(
- move || {
- let result = child_wait_handle.wait();
- let closed = closed_handle.load(Ordering::SeqCst);
- child_tx.send(WaitResult::Child(result, closed)).unwrap();
- dispatcher_handle.close();
- },
- );
- thread::spawn(
- move || {
- let result = event_dispatcher.wait();
- dispatcher_tx.send(WaitResult::EventDispatcher(result)).unwrap();
- let _ = child_close_handle.close();
- },
- );
+ thread::spawn(move || {
+ let result = child_wait_handle.wait();
+ let closed = closed_handle.load(Ordering::SeqCst);
+ child_tx.send(WaitResult::Child(result, closed)).unwrap();
+ dispatcher_handle.close();
+ });
+ thread::spawn(move || {
+ let result = event_dispatcher.wait();
+ dispatcher_tx
+ .send(WaitResult::EventDispatcher(result))
+ .unwrap();
+ let _ = child_close_handle.close();
+ });
let result = rx.recv().unwrap();
let _ = rx.recv().unwrap();
@@ -235,7 +234,8 @@ pub struct OpenVpnEventDispatcher {
impl OpenVpnEventDispatcher {
/// Construct and start the IPC server with the given event listener callback.
pub fn start<L>(on_event: L) -> talpid_ipc::Result<Self>
- where L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static
+ where
+ L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
{
let rpc = OpenVpnEventApiImpl { on_event };
let mut io = IoHandler::new();
@@ -249,7 +249,8 @@ impl OpenVpnEventDispatcher {
self.server.address()
}
- /// Creates a handle to this event dispatcher, allowing the listening server to be closed while
+ /// Creates a handle to this event dispatcher, allowing the listening server to be closed
+ /// while
/// some other thread is blocked in `wait`.
pub fn close_handle(&self) -> talpid_ipc::CloseHandle {
self.server.close_handle()
@@ -278,18 +279,21 @@ mod api {
use self::api::*;
struct OpenVpnEventApiImpl<L>
- where L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static
+where
+ L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
{
on_event: L,
}
impl<L> OpenVpnEventApi for OpenVpnEventApiImpl<L>
- where L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static
+where
+ L: Fn(OpenVpnPluginEvent, HashMap<String, String>) + Send + Sync + 'static,
{
- fn openvpn_event(&self,
- event: OpenVpnPluginEvent,
- env: HashMap<String, String>)
- -> StdResult<(), Error> {
+ fn openvpn_event(
+ &self,
+ event: OpenVpnPluginEvent,
+ env: HashMap<String, String>,
+ ) -> StdResult<(), Error> {
debug!("OpenVPN event {:?}", event);
(self.on_event)(event, env);
Ok(())
@@ -319,7 +323,8 @@ mod tests {
}
fn start(&self) -> io::Result<Self::ProcessHandle> {
- self.process_handle.ok_or(io::Error::new(io::ErrorKind::Other, "failed to start"))
+ self.process_handle
+ .ok_or(io::Error::new(io::ErrorKind::Other, "failed to start"))
}
}
diff --git a/talpid-ipc/src/client.rs b/talpid-ipc/src/client.rs
index 5d63db24f9..f3765a52fe 100644
--- a/talpid-ipc/src/client.rs
+++ b/talpid-ipc/src/client.rs
@@ -20,8 +20,10 @@ impl<O: for<'de> serde::Deserialize<'de>> ws::Factory for Factory<O> {
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
debug!("Sending: {}", self.request);
- if let Err(e) =
- sender.send(&self.request[..]).chain_err(|| "Unable to send jsonrpc request") {
+ if let Err(e) = sender
+ .send(&self.request[..])
+ .chain_err(|| "Unable to send jsonrpc request")
+ {
self.result_tx.send(Err(e)).unwrap();
}
Handler {
@@ -41,19 +43,16 @@ impl<O: for<'de> serde::Deserialize<'de>> Handler<O> {
fn parse_reply(&self, msg: ws::Message) -> Result<O> {
let json: serde_json::Value =
match msg {
- ws::Message::Text(s) => serde_json::from_str(&s),
- ws::Message::Binary(b) => serde_json::from_slice(&b),
- }
- .chain_err(|| "Unable to deserialize ws message as JSON")?;
+ ws::Message::Text(s) => serde_json::from_str(&s),
+ ws::Message::Binary(b) => serde_json::from_slice(&b),
+ }.chain_err(|| "Unable to deserialize ws message as JSON")?;
let result: Option<serde_json::Value> = match json {
serde_json::Value::Object(mut map) => map.remove("result"),
_ => None,
};
match result {
- Some(result) => {
- serde_json::from_value(result)
- .chain_err(|| "Unable to deserialize result into derisred type")
- }
+ Some(result) => serde_json::from_value(result)
+ .chain_err(|| "Unable to deserialize result into derisred type"),
None => bail!("Invalid reply, no 'result' field"),
}
}
@@ -85,8 +84,9 @@ impl WsIpcClient {
}
pub fn call<T, O>(&mut self, method: &str, params: &T) -> Result<O>
- where T: serde::Serialize,
- O: for<'de> serde::Deserialize<'de>
+ where
+ T: serde::Serialize,
+ O: for<'de> serde::Deserialize<'de>,
{
let (result_tx, result_rx) = mpsc::channel();
let factory = Factory {
@@ -94,8 +94,10 @@ impl WsIpcClient {
result_tx: result_tx,
};
let mut ws = ws::WebSocket::new(factory).chain_err(|| "Unable to create WebSocket")?;
- ws.connect(self.url.clone()).chain_err(|| "Unable to connect WebSocket to url")?;
- ws.run().chain_err(|| "Error while running WebSocket event loop")?;
+ ws.connect(self.url.clone())
+ .chain_err(|| "Unable to connect WebSocket to url")?;
+ ws.run()
+ .chain_err(|| "Error while running WebSocket event loop")?;
match result_rx.try_recv() {
Ok(result) => result,
@@ -104,7 +106,8 @@ impl WsIpcClient {
}
fn get_json<T>(&mut self, method: &str, params: &T) -> String
- where T: serde::Serialize
+ where
+ T: serde::Serialize,
{
let request_json = json!({
"jsonrpc": "2.0",
diff --git a/talpid-ipc/src/lib.rs b/talpid-ipc/src/lib.rs
index 287497b0be..668c54aef3 100644
--- a/talpid-ipc/src/lib.rs
+++ b/talpid-ipc/src/lib.rs
@@ -17,8 +17,8 @@ extern crate serde_json;
extern crate jsonrpc_core;
extern crate jsonrpc_ws_server;
-extern crate ws;
extern crate url;
+extern crate ws;
use jsonrpc_core::{MetaIoHandler, Metadata};
use jsonrpc_ws_server::{MetaExtractor, NoopExtractor, Server, ServerBuilder};
@@ -53,21 +53,20 @@ impl IpcServer {
}
pub fn start_with_metadata<M, E>(handler: MetaIoHandler<M>, meta_extractor: E) -> Result<Self>
- where M: Metadata,
- E: MetaExtractor<M>
+ where
+ M: Metadata,
+ E: MetaExtractor<M>,
{
let listen_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0);
ServerBuilder::new(handler)
.session_meta_extractor(meta_extractor)
.start(&listen_addr)
- .map(
- |server| {
- IpcServer {
- address: format!("ws://{}", server.addr()),
- server: server,
- }
- },
- )
+ .map(|server| {
+ IpcServer {
+ address: format!("ws://{}", server.addr()),
+ server: server,
+ }
+ })
.chain_err(|| ErrorKind::IpcServerError)
}
diff --git a/talpid-ipc/tests/ipc-client-server.rs b/talpid-ipc/tests/ipc-client-server.rs
index 654eff4dcc..ee4343caed 100644
--- a/talpid-ipc/tests/ipc-client-server.rs
+++ b/talpid-ipc/tests/ipc-client-server.rs
@@ -1,13 +1,13 @@
-extern crate talpid_ipc;
-extern crate jsonrpc_core;
#[macro_use]
-extern crate jsonrpc_macros;
+extern crate assert_matches;
extern crate env_logger;
+extern crate jsonrpc_core;
#[macro_use]
-extern crate assert_matches;
+extern crate jsonrpc_macros;
+extern crate talpid_ipc;
use jsonrpc_core::{Error, IoHandler};
-use std::sync::{Mutex, mpsc};
+use std::sync::{mpsc, Mutex};
use std::time::Duration;
build_rpc_trait! {
diff --git a/talpid-openvpn-plugin/src/lib.rs b/talpid-openvpn-plugin/src/lib.rs
index 9e01b285d3..5212c83161 100644
--- a/talpid-openvpn-plugin/src/lib.rs
+++ b/talpid-openvpn-plugin/src/lib.rs
@@ -6,11 +6,11 @@
//! GNU General Public License as published by the Free Software Foundation, either version 3 of
//! the License, or (at your option) any later version.
+extern crate env_logger;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
-extern crate env_logger;
#[macro_use]
extern crate openvpn_plugin;
@@ -57,9 +57,10 @@ openvpn_plugin!(
::EventProcessor
);
-fn openvpn_open(args: &[CString],
- _env: &HashMap<CString, CString>)
- -> Result<(Vec<OpenVpnPluginEvent>, EventProcessor)> {
+fn openvpn_open(
+ args: &[CString],
+ _env: &HashMap<CString, CString>,
+) -> Result<(Vec<OpenVpnPluginEvent>, EventProcessor)> {
env_logger::init().chain_err(|| "Failed to bootstrap logging system")?;
debug!("Initializing plugin");
@@ -75,8 +76,9 @@ fn parse_args(args: &[CString]) -> Result<talpid_ipc::IpcServerId> {
.chain_err(|| ErrorKind::ParseArgsFailed)?
.into_iter();
let _plugin_path = args_iter.next();
- let core_server_id: talpid_ipc::IpcServerId = args_iter.next()
- .ok_or_else(|| ErrorKind::Msg("No core server id given as first argument".to_owned()))?;
+ let core_server_id: talpid_ipc::IpcServerId = args_iter.next().ok_or_else(|| {
+ ErrorKind::Msg("No core server id given as first argument".to_owned())
+ })?;
Ok(core_server_id)
}
@@ -85,16 +87,19 @@ fn openvpn_close(_handle: EventProcessor) {
debug!("Unloading plugin");
}
-fn openvpn_event(event: OpenVpnPluginEvent,
- _args: &[CString],
- env: &HashMap<CString, CString>,
- handle: &mut EventProcessor)
- -> Result<EventResult> {
+fn openvpn_event(
+ event: OpenVpnPluginEvent,
+ _args: &[CString],
+ env: &HashMap<CString, CString>,
+ handle: &mut EventProcessor,
+) -> Result<EventResult> {
debug!("Received event: {:?}", event);
- let parsed_env = openvpn_plugin::ffi::parse::env_utf8(env)
- .chain_err(|| ErrorKind::ParseEnvFailed)?;
+ let parsed_env =
+ openvpn_plugin::ffi::parse::env_utf8(env).chain_err(|| ErrorKind::ParseEnvFailed)?;
- handle.process_event(event, parsed_env).chain_err(|| ErrorKind::EventProcessingFailed)?;
+ handle
+ .process_event(event, parsed_env)
+ .chain_err(|| ErrorKind::EventProcessingFailed)?;
Ok(EventResult::Success)
}
diff --git a/talpid-openvpn-plugin/src/processing.rs b/talpid-openvpn-plugin/src/processing.rs
index 5f3c8e4afd..b76e92e409 100644
--- a/talpid-openvpn-plugin/src/processing.rs
+++ b/talpid-openvpn-plugin/src/processing.rs
@@ -23,10 +23,11 @@ impl EventProcessor {
Ok(EventProcessor { ipc_client })
}
- pub fn process_event(&mut self,
- event: openvpn_plugin::types::OpenVpnPluginEvent,
- env: HashMap<String, String>)
- -> Result<()> {
+ pub fn process_event(
+ &mut self,
+ event: openvpn_plugin::types::OpenVpnPluginEvent,
+ env: HashMap<String, String>,
+ ) -> Result<()> {
trace!("Processing \"{:?}\" event", event);
self.ipc_client
.call("openvpn_event", &(event, env))
diff --git a/talpid-types/src/lib.rs b/talpid-types/src/lib.rs
index c32daa26d3..e6571c6238 100644
--- a/talpid-types/src/lib.rs
+++ b/talpid-types/src/lib.rs
@@ -6,8 +6,8 @@
//! GNU General Public License as published by the Free Software Foundation, either version 3 of
//! the License, or (at your option) any later version.
+extern crate serde;
#[macro_use]
extern crate serde_derive;
-extern crate serde;
pub mod net;