diff options
| -rw-r--r-- | mullvad_daemon/src/frontend_ipc_router.rs | 39 | ||||
| -rw-r--r-- | openvpn_ffi/src/lib.rs | 2 | ||||
| -rw-r--r-- | openvpn_ffi/src/parse.rs | 16 | ||||
| -rw-r--r-- | talpid_cli/src/cli.rs | 66 | ||||
| -rw-r--r-- | talpid_cli/src/main.rs | 18 | ||||
| -rw-r--r-- | talpid_core/src/net.rs | 6 | ||||
| -rw-r--r-- | talpid_core/src/process/monitor.rs | 34 | ||||
| -rw-r--r-- | talpid_core/src/process/openvpn.rs | 23 | ||||
| -rw-r--r-- | talpid_ipc/src/http_ipc/connection_info.rs | 10 | ||||
| -rw-r--r-- | talpid_ipc/src/http_ipc/mod.rs | 25 | ||||
| -rw-r--r-- | talpid_ipc/src/nop_ipc.rs | 2 | ||||
| -rw-r--r-- | talpid_ipc/src/zmq_ipc.rs | 20 | ||||
| -rw-r--r-- | talpid_ipc/tests/zmq_integration_tests.rs | 8 | ||||
| -rw-r--r-- | talpid_openvpn_plugin/src/lib.rs | 26 |
14 files changed, 175 insertions, 120 deletions
diff --git a/mullvad_daemon/src/frontend_ipc_router.rs b/mullvad_daemon/src/frontend_ipc_router.rs index f203a2fe72..aad05cf778 100644 --- a/mullvad_daemon/src/frontend_ipc_router.rs +++ b/mullvad_daemon/src/frontend_ipc_router.rs @@ -28,15 +28,20 @@ fn add_route<T, U, F>(router: &mut jsonrpc_core::IoHandler, method: &str, handle println!("Got rpc request with params {:?}", params); let parsed_params: T = params.parse()?; - let response: U = handler(&parsed_params).map_err(|e| { - error!("Failed responding to RPC request: {}", e); - jsonrpc_core::Error::internal_error() - })?; + let response: U = handler(&parsed_params) + .map_err( + |e| { + error!("Failed responding to RPC request: {}", e); + jsonrpc_core::Error::internal_error() + }, + )?; - serde_json::to_value(response).map_err(|e| { - error!("Unable to serialize response to RPC request: {}", e); - jsonrpc_core::Error::internal_error() - }) + serde_json::to_value(response).map_err( + |e| { + error!("Unable to serialize response to RPC request: {}", e); + jsonrpc_core::Error::internal_error() + }, + ) }; router.add_method(method, c); } @@ -53,17 +58,23 @@ fn mock_login(request: &LoginRequest) -> Result<::std::collections::HashMap<Stri if account_number.starts_with("1111") { // accounts starting with 1111 expire in one month - reply.insert("paidUntil".to_owned(), - "2018-12-31T16:00:00.000Z".to_owned()); + reply.insert( + "paidUntil".to_owned(), + "2018-12-31T16:00:00.000Z".to_owned(), + ); // res.paidUntil = moment().startOf('day').add(15, 'days').toISOString(); } else if account_number.starts_with("2222") { // expired in 2013 - reply.insert("paidUntil".to_owned(), - "2012-12-31T16:00:00.000Z".to_owned()); + reply.insert( + "paidUntil".to_owned(), + "2012-12-31T16:00:00.000Z".to_owned(), + ); } else if account_number.starts_with("3333") { // expire in 2038 - reply.insert("paidUntil".to_owned(), - "2037-12-31T16:00:00.000Z".to_owned()); + reply.insert( + "paidUntil".to_owned(), + "2037-12-31T16:00:00.000Z".to_owned(), + ); } else { bail!("you are not welcome {}!", account_number) } diff --git a/openvpn_ffi/src/lib.rs b/openvpn_ffi/src/lib.rs index 702ea43315..00e0d58031 100644 --- a/openvpn_ffi/src/lib.rs +++ b/openvpn_ffi/src/lib.rs @@ -59,7 +59,7 @@ impl OpenVpnPluginEvent { /// Tries to parse an integer from C into a variant of `OpenVpnPluginEvent`. pub fn from_int(i: c_int) -> Result<OpenVpnPluginEvent> { if i >= OpenVpnPluginEvent::Up as c_int && i <= OpenVpnPluginEvent::N as c_int { - Ok(unsafe { ::std::mem::transmute_copy::<c_int, OpenVpnPluginEvent>(&i) }) + Ok(unsafe { ::std::mem::transmute_copy::<c_int, OpenVpnPluginEvent>(&i) },) } else { bail!(ErrorKind::InvalidEnumVariant(i)); } diff --git a/openvpn_ffi/src/parse.rs b/openvpn_ffi/src/parse.rs index 2da10e3ca2..787883fd70 100644 --- a/openvpn_ffi/src/parse.rs +++ b/openvpn_ffi/src/parse.rs @@ -95,9 +95,11 @@ mod tests { fn string_array_two_strings() { let test_str1 = "foobar\0"; let test_str2 = "barbaz\0"; - let ptr_arr = [test_str1 as *const _ as *const c_char, - test_str2 as *const _ as *const c_char, - ptr::null()]; + let ptr_arr = [ + test_str1 as *const _ as *const c_char, + test_str2 as *const _ as *const c_char, + ptr::null(), + ]; let result = unsafe { string_array(&ptr_arr as *const *const c_char).unwrap() }; assert_eq!(["foobar", "barbaz"], &result[..]); } @@ -132,9 +134,11 @@ mod tests { fn env_two_same_key() { let test_str1 = "foo=123\0"; let test_str2 = "foo=abc\0"; - let ptr_arr = [test_str1 as *const _ as *const c_char, - test_str2 as *const _ as *const c_char, - ptr::null()]; + let ptr_arr = [ + test_str1 as *const _ as *const c_char, + test_str2 as *const _ as *const c_char, + ptr::null(), + ]; let env = unsafe { env(&ptr_arr as *const *const c_char).unwrap() }; assert_eq!(1, env.len()); assert_eq!(Some("abc"), env.get("foo").map(|s| &s[..])); diff --git a/talpid_cli/src/cli.rs b/talpid_cli/src/cli.rs index 79a13d94c2..b61c4112b5 100644 --- a/talpid_cli/src/cli.rs +++ b/talpid_cli/src/cli.rs @@ -1,4 +1,4 @@ -use clap::{Arg, App, ArgMatches}; +use clap::{App, Arg, ArgMatches}; use std::path::PathBuf; use talpid_core::net::RemoteAddr; @@ -41,30 +41,42 @@ fn create_app() -> App<'static, 'static> { .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) - .arg(Arg::with_name("openvpn") - .long("openvpn") - .help("Specify what OpenVPN binary to run") - .default_value("/usr/sbin/openvpn")) - .arg(Arg::with_name("config") - .short("c") - .long("config") - .help("Specify what config file to start OpenVPN with") - .default_value("./openvpn.conf")) - .arg(Arg::with_name("remotes") - .short("r") - .long("remotes") - .help("Configure what remote(s) to connect to. Accepts anything OpenVPN can use. \ - Format: <address>:<port>") - .takes_value(true) - .multiple(true) - .required(true)) - .arg(Arg::with_name("plugin") - .long("plugin") - .help("Path to talpid plugin") - .default_value(DEFAULT_PLUGIN_PATH)) - .arg(Arg::with_name("verbose") - .short("v") - .long("verbose") - .multiple(true) - .help("Sets the level of verbosity")) + .arg( + Arg::with_name("openvpn") + .long("openvpn") + .help("Specify what OpenVPN binary to run") + .default_value("/usr/sbin/openvpn"), + ) + .arg( + Arg::with_name("config") + .short("c") + .long("config") + .help("Specify what config file to start OpenVPN with") + .default_value("./openvpn.conf"), + ) + .arg( + Arg::with_name("remotes") + .short("r") + .long("remotes") + .help( + "Configure what remote(s) to connect to. Accepts anything OpenVPN can use. \ + Format: <address>:<port>", + ) + .takes_value(true) + .multiple(true) + .required(true), + ) + .arg( + Arg::with_name("plugin") + .long("plugin") + .help("Path to talpid plugin") + .default_value(DEFAULT_PLUGIN_PATH), + ) + .arg( + Arg::with_name("verbose") + .short("v") + .long("verbose") + .multiple(true) + .help("Sets the level of verbosity"), + ) } diff --git a/talpid_cli/src/main.rs b/talpid_cli/src/main.rs index e07a8126a7..0a857e05d3 100644 --- a/talpid_cli/src/main.rs +++ b/talpid_cli/src/main.rs @@ -39,7 +39,8 @@ pub fn init_logger() -> Result<()> { fn create_openvpn_command(args: &Args) -> OpenVpnCommand { let mut command = OpenVpnCommand::new(&args.binary); - command.config(&args.config) + command + .config(&args.config) .remotes(&args.remotes[..]) .unwrap() .pipe_output(args.verbosity > 0); @@ -70,12 +71,15 @@ fn start_monitor(monitor: &mut OpenVpnMonitor) -> StdResult<Receiver<OpenVpnEvent>, openvpn::Error> { let (tx, rx) = mpsc::channel(); let callback = move |clean| tx.send(clean).unwrap(); - monitor.start(callback) - .map(|(stdout, stderr)| { - stdout.map(|stream| pass_io(stream, io::stdout())); - stderr.map(|stream| pass_io(stream, io::stderr())); - rx - }) + monitor + .start(callback) + .map( + |(stdout, stderr)| { + stdout.map(|stream| pass_io(stream, io::stdout())); + stderr.map(|stream| pass_io(stream, io::stderr())); + rx + }, + ) } fn pass_io<I, O>(mut input: I, mut output: O) diff --git a/talpid_core/src/net.rs b/talpid_core/src/net.rs index 3701ae641e..f5f40688a7 100644 --- a/talpid_core/src/net.rs +++ b/talpid_core/src/net.rs @@ -56,9 +56,9 @@ impl RemoteAddr { fn from_domain_str(s: &str) -> Result<Self> { let (address, port_str) = Self::split_at_last_colon(s)?; - let port = u16::from_str(port_str).chain_err(|| { - ErrorKind::AddrParse(format!("Invalid port: \"{}\"", port_str)) - })?; + let port = + u16::from_str(port_str) + .chain_err(|| ErrorKind::AddrParse(format!("Invalid port: \"{}\"", port_str)),)?; if address.is_empty() || address.contains(':') { let msg = format!("Invalid IP or domain: \"{}\"", address); bail!(ErrorKind::AddrParse(msg)); diff --git a/talpid_core/src/process/monitor.rs b/talpid_core/src/process/monitor.rs index 3a6f9fb65f..c4e8b402d4 100644 --- a/talpid_core/src/process/monitor.rs +++ b/talpid_core/src/process/monitor.rs @@ -1,5 +1,5 @@ use std::io; -use std::process::{ChildStdout, ChildStderr}; +use std::process::{ChildStderr, ChildStdout}; use std::sync::{Arc, Mutex}; use std::thread; @@ -85,10 +85,12 @@ impl<S: ChildSpawner> ChildMonitor<S> { let mut child = self.spawner.spawn().chain_err(|| ErrorKind::Spawn)?; let io = (child.stdout(), child.stderr()); let thread_handle = self.spawn_monitor(child.clone(), listener); - *state_lock = State::Running(RunningState { - child: child, - thread_handle: Some(thread_handle), - }); + *state_lock = State::Running( + RunningState { + child: child, + thread_handle: Some(thread_handle), + }, + ); Ok(io) } else { bail!(ErrorKind::InvalidState); @@ -99,14 +101,16 @@ impl<S: ChildSpawner> ChildMonitor<S> { where L: FnMut(bool) + Send + 'static { let state_mutex = self.state.clone(); - thread::spawn(move || { - let success = child.wait().unwrap_or(false); - { - let mut state_lock = state_mutex.lock().unwrap(); - *state_lock = State::Stopped; - } - listener(success); - }) + thread::spawn( + move || { + let success = child.wait().unwrap_or(false); + { + let mut state_lock = state_mutex.lock().unwrap(); + *state_lock = State::Stopped; + } + listener(success); + }, + ) } /// Sends a kill signal to the child process. @@ -143,7 +147,7 @@ impl<S: ChildSpawner> Drop for ChildMonitor<S> { mod child_monitor_tests { use super::*; use std::io; - use std::process::{ChildStdout, ChildStderr}; + use std::process::{ChildStderr, ChildStdout}; use std::sync::{Arc, Mutex}; use std::sync::mpsc; use std::thread; @@ -209,7 +213,7 @@ mod child_monitor_tests { fn spawn(&mut self) -> io::Result<MockChild> { self.spawn_result .clone() - .ok_or(io::Error::new(io::ErrorKind::Other, "Mocking a failed process spawn")) + .ok_or(io::Error::new(io::ErrorKind::Other, "Mocking a failed process spawn"),) } } diff --git a/talpid_core/src/process/openvpn.rs b/talpid_core/src/process/openvpn.rs index e002d2b9c3..231898c6f8 100644 --- a/talpid_core/src/process/openvpn.rs +++ b/talpid_core/src/process/openvpn.rs @@ -1,18 +1,18 @@ extern crate openvpn_ffi; -use super::monitor::{ChildSpawner, ChildMonitor}; +use super::monitor::{ChildMonitor, ChildSpawner}; -use clonablechild::{ClonableChild, ChildExt}; +use clonablechild::{ChildExt, ClonableChild}; use net::{RemoteAddr, ToRemoteAddrs}; use std::collections::HashMap; -use std::ffi::{OsString, OsStr}; +use std::ffi::{OsStr, OsString}; use std::fmt; use std::io; use std::ops::DerefMut; use std::path::{Path, PathBuf}; -use std::process::{Command, Child, Stdio, ChildStdout, ChildStderr}; +use std::process::{Child, ChildStderr, ChildStdout, Command, Stdio}; use std::sync::{Arc, Mutex}; use talpid_ipc; @@ -90,7 +90,8 @@ impl OpenVpnCommand { fn create_command(&self) -> Command { let mut command = Command::new(&self.openvpn_bin); - command.stdin(Stdio::null()) + command + .stdin(Stdio::null()) .stdout(self.get_output_pipe_policy()) .stderr(self.get_output_pipe_policy()); command @@ -197,11 +198,14 @@ impl OpenVpnMonitor { fn start_plugin_listener<L>(&mut self, shared_listener: Arc<Mutex<L>>) -> Result<()> where L: FnMut(OpenVpnEvent) + Send + 'static { - let server_id = talpid_ipc::start_new_server(move |msg| { + let server_id = talpid_ipc::start_new_server( + move |msg| { let chained_msg = msg.chain_err(|| ErrorKind::PluginCommunicationError); let mut listener = shared_listener.lock().unwrap(); (listener.deref_mut())(OpenVpnEvent::PluginEvent(chained_msg)); - }).chain_err(|| ErrorKind::PluginCommunicationError)?; + }, + ) + .chain_err(|| ErrorKind::PluginCommunicationError)?; self.command.plugin(&self.plugin_path, vec![server_id]); Ok(()) } @@ -251,7 +255,10 @@ mod openvpn_command_tests { #[test] fn passes_two_remotes() { - let remotes = vec![RemoteAddr::new("127.0.0.1", 998), RemoteAddr::new("fe80::1", 1337)]; + let remotes = vec![ + RemoteAddr::new("127.0.0.1", 998), + RemoteAddr::new("fe80::1", 1337), + ]; let testee_args = OpenVpnCommand::new("").remotes(&remotes[..]).unwrap().get_arguments(); diff --git a/talpid_ipc/src/http_ipc/connection_info.rs b/talpid_ipc/src/http_ipc/connection_info.rs index 99d87c0603..1c4b3fac32 100644 --- a/talpid_ipc/src/http_ipc/connection_info.rs +++ b/talpid_ipc/src/http_ipc/connection_info.rs @@ -22,11 +22,13 @@ pub fn write(connection_info: &str) -> Result<()> { let file_location = PathBuf::from(IPC_CONNECTION_INFO_FILE); let mut file = open_file(&file_location)?; let res = file.write_all(connection_info.as_bytes()) - .chain_err(|| ErrorKind::WriteConnectionInfoFailed(file_location.clone())); + .chain_err(|| ErrorKind::WriteConnectionInfoFailed(file_location.clone()),); - debug!("Wrote IPC connection info ({}) to {}", - connection_info, - file_location.to_string_lossy()); + debug!( + "Wrote IPC connection info ({}) to {}", + connection_info, + file_location.to_string_lossy() + ); res } diff --git a/talpid_ipc/src/http_ipc/mod.rs b/talpid_ipc/src/http_ipc/mod.rs index 74b4feadef..16195ee69f 100644 --- a/talpid_ipc/src/http_ipc/mod.rs +++ b/talpid_ipc/src/http_ipc/mod.rs @@ -1,8 +1,8 @@ extern crate jsonrpc_core; extern crate jsonrpc_http_server; -use self::jsonrpc_http_server::{ServerBuilder, Server}; -use std::net::{SocketAddr, IpAddr, Ipv4Addr}; +use self::jsonrpc_http_server::{Server, ServerBuilder}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::result::Result as StdResult; mod connection_info; @@ -36,8 +36,11 @@ impl ServerHandle { pub fn start(build_router: fn() -> jsonrpc_core::IoHandler) -> Result<ServerHandle> { let server = start_server(build_router).chain_err(|| ErrorKind::UnableToStartServer)?; - let write_result = connection_info::write(server.address()) - .chain_err(|| ErrorKind::FailedToWriteConnectionInfo); + let write_result = connection_info::write(server.address()).chain_err( + || { + ErrorKind::FailedToWriteConnectionInfo + }, + ); if let Err(e) = write_result { error!("Could not write the connection info, killing the IPC server"); server.stop(); @@ -68,10 +71,12 @@ fn start_server_on_port(port: u16, ServerBuilder::new(router) .allow_only_bind_host() .start_http(&listen_addr) - .map(|server| { - ServerHandle { - address: format!("http://{}", listen_addr), - server: server, - } - }) + .map( + |server| { + ServerHandle { + address: format!("http://{}", listen_addr), + server: server, + } + }, + ) } diff --git a/talpid_ipc/src/nop_ipc.rs b/talpid_ipc/src/nop_ipc.rs index 50d4fae791..f6ead2676b 100644 --- a/talpid_ipc/src/nop_ipc.rs +++ b/talpid_ipc/src/nop_ipc.rs @@ -1,4 +1,4 @@ -use super::{ErrorKind, Result, IpcServerId}; +use super::{ErrorKind, IpcServerId, Result}; use serde; diff --git a/talpid_ipc/src/zmq_ipc.rs b/talpid_ipc/src/zmq_ipc.rs index 24d8e2f5d1..49aad9f699 100644 --- a/talpid_ipc/src/zmq_ipc.rs +++ b/talpid_ipc/src/zmq_ipc.rs @@ -1,7 +1,7 @@ extern crate zmq; extern crate serde_json; -use super::{ErrorKind, Result, ResultExt, IpcServerId}; +use super::{ErrorKind, IpcServerId, Result, ResultExt}; use serde; @@ -43,12 +43,15 @@ fn start_receive_loop<T, F>(socket: zmq::Socket, mut on_message: F) -> thread::J where T: serde::Deserialize + 'static, F: FnMut(Result<T>) + Send + 'static { - thread::spawn(move || loop { - let read_res = socket.recv_bytes(0) - .chain_err(|| ErrorKind::ReadFailure) - .and_then(|a| parse_message(&a)); - on_message(read_res); - }) + thread::spawn( + move || loop { + let read_res = socket + .recv_bytes(0) + .chain_err(|| ErrorKind::ReadFailure) + .and_then(|a| parse_message(&a)); + on_message(read_res); + }, + ) } fn parse_message<T>(message: &[u8]) -> Result<T> @@ -100,7 +103,8 @@ impl<T> IpcClient<T> let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::PUSH) .chain_err(|| "Could not create ZeroMQ PUSH socket".to_owned())?; - socket.connect(&self.server_id) + socket + .connect(&self.server_id) .chain_err(|| format!("Could not connect to {:?}", self.server_id))?; self.socket = Some(socket); diff --git a/talpid_ipc/tests/zmq_integration_tests.rs b/talpid_ipc/tests/zmq_integration_tests.rs index ba22e28c40..4bd484cf0a 100644 --- a/talpid_ipc/tests/zmq_integration_tests.rs +++ b/talpid_ipc/tests/zmq_integration_tests.rs @@ -3,7 +3,7 @@ mod zmq_integration_tests { extern crate serde; extern crate talpid_ipc; - use self::talpid_ipc::{Result, IpcServerId, IpcClient}; + use self::talpid_ipc::{IpcClient, IpcServerId, Result}; use std::sync::mpsc::{self, Receiver}; use std::time::Duration; @@ -16,7 +16,8 @@ mod zmq_integration_tests { let msg = "Hello".to_owned(); ipc_client.send(&msg).expect("Could not send message"); - let message = new_messages_rx.recv_timeout(Duration::from_millis(1000)) + let message = new_messages_rx + .recv_timeout(Duration::from_millis(1000)) .expect("Did not receive a message"); assert_eq!(message.unwrap(), "Hello", "Got wrong message"); @@ -29,8 +30,7 @@ mod zmq_integration_tests { let callback = move |message: Result<T>| { let _ = tx.send(message); }; let connection_string = - talpid_ipc::start_new_server(callback) - .expect("Could not start the server"); + talpid_ipc::start_new_server(callback).expect("Could not start the server"); (connection_string, rx) } diff --git a/talpid_openvpn_plugin/src/lib.rs b/talpid_openvpn_plugin/src/lib.rs index 14a6816894..f97394ec32 100644 --- a/talpid_openvpn_plugin/src/lib.rs +++ b/talpid_openvpn_plugin/src/lib.rs @@ -12,9 +12,9 @@ use std::os::raw::{c_int, c_void}; mod processing; -use openvpn_ffi::{openvpn_plugin_args_open_in, openvpn_plugin_args_open_return, +use openvpn_ffi::{OPENVPN_PLUGIN_FUNC_ERROR, OPENVPN_PLUGIN_FUNC_SUCCESS, OpenVpnPluginEvent, openvpn_plugin_args_func_in, openvpn_plugin_args_func_return, - OPENVPN_PLUGIN_FUNC_SUCCESS, OPENVPN_PLUGIN_FUNC_ERROR, OpenVpnPluginEvent}; + openvpn_plugin_args_open_in, openvpn_plugin_args_open_return}; use processing::EventProcessor; @@ -41,8 +41,8 @@ error_chain!{ /// All the OpenVPN events this plugin will register for listening to. Edit this variable to change /// events. -pub static INTERESTING_EVENTS: &'static [OpenVpnPluginEvent] = &[OpenVpnPluginEvent::Up, - OpenVpnPluginEvent::RoutePredown]; +pub static INTERESTING_EVENTS: &'static [OpenVpnPluginEvent] = + &[OpenVpnPluginEvent::Up, OpenVpnPluginEvent::RoutePredown]; /// Called by OpenVPN when the plugin is first loaded. @@ -123,8 +123,8 @@ fn openvpn_plugin_func_v3_internal(args: *const openvpn_plugin_args_func_in) -> let event_type = unsafe { (*args).event_type }; let event = OpenVpnPluginEvent::from_int(event_type).chain_err(|| ErrorKind::InvalidEventType)?; debug!("Received event: {:?}", event); - let env = - unsafe { openvpn_ffi::parse::env((*args).envp) }.chain_err(|| ErrorKind::ParseEnvFailed)?; + let env = unsafe { openvpn_ffi::parse::env((*args).envp) } + .chain_err(|| ErrorKind::ParseEnvFailed)?; let mut handle = unsafe { Box::from_raw((*args).handle as *mut EventProcessor) }; handle.process_event(event, env).chain_err(|| ErrorKind::EventProcessingFailed)?; @@ -137,13 +137,15 @@ fn openvpn_plugin_func_v3_internal(args: *const openvpn_plugin_args_func_in) -> pub fn init_logger() -> ::std::result::Result<(), ()> { - env_logger::init().or_else(|e| { - use std::io::Write; - let mut stderr = ::std::io::stderr(); - writeln!(&mut stderr, "Unable to initialize logging: {}", e) + env_logger::init().or_else( + |e| { + use std::io::Write; + let mut stderr = ::std::io::stderr(); + writeln!(&mut stderr, "Unable to initialize logging: {}", e) .expect("Unable to write to stderr"); - Err(()) - }) + Err(()) + }, + ) } pub fn log_error(msg: &str, error: &Error) { |
