diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..ab9510e --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,41 @@ + +build: &build + docker: + - image: majorz/rust-$CIRCLE_JOB:rust-1.23.0 + steps: + - checkout + - run: cargo build + +version: 2 + +jobs: + aarch64: + <<: *build + rpi: + <<: *build + armv7hf: + <<: *build + i386: + <<: *build + amd64: + <<: *build + test: + docker: + - image: majorz/rust-test-deploy:rust-nightly-2018-01-08 + steps: + - checkout + - run: cargo fmt -- --write-mode=diff + - run: cargo clippy -- -D warnings + +workflows: + version: 2 + test: + jobs: + - test + build: + jobs: + - aarch64 + - rpi + - armv7hf + - i386 + - amd64 diff --git a/.editorconfig b/.editorconfig index e8c0272..fa995eb 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,3 +8,6 @@ indent_size = 4 [*.md] trim_trailing_whitespace = false + +[*.yml] +indent_size = 2 diff --git a/.travis.yml b/.travis.yml index 1a2286c..c362685 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,24 +1,4 @@ -dist: trusty -sudo: required -language: rust -cache: cargo -rust: - - nightly - - beta - - stable -before_install: - - sudo apt-get -qq update - - sudo apt-get install -yq --no-install-recommends libdbus-1-dev -install: - - type -p cargo-install-update || cargo install cargo-update - - cargo install-update -i cargo-update - - cargo install-update -i rustfmt - - if [ $TRAVIS_RUST_VERSION == nightly ]; then - cargo install-update -i clippy; - fi -script: - - cargo fmt -- --write-mode=diff - - if [ $TRAVIS_RUST_VERSION == nightly ]; then - cargo clippy -- -D warnings; - fi - - cargo build +language: generic +script: printf 'empty' +notifications: + email: false diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bd2d9d..fd8ed5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file automatically by Versionist. DO NOT EDIT THIS FILE MANUALLY! This project adheres to [Semantic Versioning](http://semver.org/). +## v0.8.3 - 2018-01-10 + +* Transitioning to CircleCI and running latest clippy and rustfmt #107 [majorz] + ## v0.8.2 - 2017-10-20 * Do not include clippy as an optional dependency #100 [majorz] diff --git a/Cargo.toml b/Cargo.toml index 3dc27a3..5fe3b98 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "network-manager" -version = "0.8.2" +version = "0.8.3" authors = ["Joseph Roberts ", "Zahari Petkov "] description = "Rust NetworkManager bindings" homepage = "https://github.com/resin-io-modules/network-manager" diff --git a/README.md b/README.md index 96c755a..50d162d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,28 @@ network-manager -============== +=============== -[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/resin-io-modules/NetworkManager/blob/master/LICENSE) -[![Build Status](https://travis-ci.org/resin-io-modules/network-manager.svg?branch=master)](https://travis-ci.org/resin-io-modules/network-manager) > Rust NetworkManager bindings + +[![Current Release](https://img.shields.io/github/release/resin-io-modules/network-manager.svg?style=flat-square)](https://github.com/resin-io-modules/network-manager/releases/latest) +[![CircleCI status](https://img.shields.io/circleci/project/github/resin-io-modules/network-manager.svg?style=flat-square)](https://circleci.com/gh/resin-io-modules/network-manager) +[![License](https://img.shields.io/github/license/resin-io-modules/network-manager.svg?style=flat-square)](https://github.com/resin-io-modules/network-manager/blob/master/LICENSE) +[![Issues](https://img.shields.io/github/issues/resin-io-modules/network-manager.svg?style=flat-square)](https://github.com/resin-io-modules/network-manager/issues) + +
+ an open source :satellite: project by resin.io +
+ +*** + +Support +------- + +If you're having any problem, please [raise an issue](https://github.com/resin-io-modules/network-manager/issues/new) on GitHub or [contact us](https://resin.io/community/), and the resin.io team will be happy to help. + +*** + +License +------- + +network-manager is free software, and may be redistributed under the terms specified in +the [license](https://github.com/resin-io-modules/network-manager/blob/master/LICENSE). diff --git a/examples/create.rs b/examples/create.rs index 79c4674..691aff0 100644 --- a/examples/create.rs +++ b/examples/create.rs @@ -3,8 +3,7 @@ extern crate network_manager; use std::env; use std::process; -use network_manager::{NetworkManager, DeviceType}; - +use network_manager::{DeviceType, NetworkManager}; fn main() { let args: Vec = env::args().collect(); diff --git a/examples/hotspot.rs b/examples/hotspot.rs index c355cd1..558a985 100644 --- a/examples/hotspot.rs +++ b/examples/hotspot.rs @@ -3,8 +3,7 @@ extern crate network_manager; use std::env; use std::process; -use network_manager::{NetworkManager, Device, DeviceType}; - +use network_manager::{Device, DeviceType, NetworkManager}; struct Options { interface: Option, @@ -12,13 +11,11 @@ struct Options { password: Option, } - fn print_usage_and_exit() { println!("USAGE: hotspot [-i INTERFACE] SSID [PASSWORD]"); process::exit(1); } - fn parse_options() -> Options { let args: Vec = env::args().collect(); @@ -51,7 +48,6 @@ fn parse_options() -> Options { } } - fn find_device(manager: &NetworkManager, interface: Option) -> Option { if let Some(interface) = interface { let device = manager.get_device_by_interface(&interface).unwrap(); @@ -64,9 +60,9 @@ fn find_device(manager: &NetworkManager, interface: Option) -> Option) -> Option Ok(ConnectionState::Activated), - ConnectionState::Activating => { - wait(self, &ConnectionState::Activated, self.dbus_manager.method_timeout()) - }, + ConnectionState::Activating => wait( + self, + &ConnectionState::Activated, + self.dbus_manager.method_timeout(), + ), ConnectionState::Unknown => Err("Unable to get connection state".to_string()), _ => { self.dbus_manager.activate_connection(&self.path)?; - wait(self, &ConnectionState::Activated, self.dbus_manager.method_timeout()) + wait( + self, + &ConnectionState::Activated, + self.dbus_manager.method_timeout(), + ) }, } } @@ -91,9 +96,11 @@ impl Connection { match state { ConnectionState::Deactivated => Ok(ConnectionState::Deactivated), - ConnectionState::Deactivating => { - wait(self, &ConnectionState::Deactivated, self.dbus_manager.method_timeout()) - }, + ConnectionState::Deactivating => wait( + self, + &ConnectionState::Deactivated, + self.dbus_manager.method_timeout(), + ), ConnectionState::Unknown => Err("Unable to get connection state".to_string()), _ => { let active_path_option = @@ -102,7 +109,11 @@ impl Connection { if let Some(active_path) = active_path_option { self.dbus_manager.deactivate_connection(&active_path)?; - wait(self, &ConnectionState::Deactivated, self.dbus_manager.method_timeout()) + wait( + self, + &ConnectionState::Deactivated, + self.dbus_manager.method_timeout(), + ) } else { Ok(ConnectionState::Deactivated) } @@ -143,7 +154,11 @@ impl Eq for Connection {} impl fmt::Debug for Connection { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Connection {{ path: {:?}, settings: {:?} }}", self.path, self.settings) + write!( + f, + "Connection {{ path: {:?}, settings: {:?} }}", + self.path, self.settings + ) } } @@ -159,7 +174,6 @@ impl<'a> From<&'a Connection> for i32 { } } - #[derive(Default, Debug, Clone, Eq, PartialEq)] pub struct ConnectionSettings { pub kind: String, // `type` is a reserved word, so we are using `kind` instead @@ -194,7 +208,6 @@ impl From for ConnectionState { } } - pub fn get_connections(dbus_manager: &Rc) -> Result, String> { let paths = dbus_manager.list_connections()?; @@ -209,7 +222,6 @@ pub fn get_connections(dbus_manager: &Rc) -> Result, ) -> Result, String> { @@ -228,7 +240,6 @@ pub fn get_active_connections( Ok(connections) } - pub fn connect_to_access_point

( dbus_manager: &Rc, device_path: &str, @@ -250,7 +261,11 @@ where let connection = Connection::init(dbus_manager, &path)?; - let state = wait(&connection, &ConnectionState::Activated, dbus_manager.method_timeout())?; + let state = wait( + &connection, + &ConnectionState::Activated, + dbus_manager.method_timeout(), + )?; Ok((connection, state)) } @@ -267,17 +282,15 @@ where S: AsSsidSlice + ?Sized, P: AsAsciiStr + ?Sized, { - let (path, _) = dbus_manager.create_hotspot( - device_path, - interface, - ssid, - password, - address, - )?; + let (path, _) = dbus_manager.create_hotspot(device_path, interface, ssid, password, address)?; let connection = Connection::init(dbus_manager, &path)?; - let state = wait(&connection, &ConnectionState::Activated, dbus_manager.method_timeout())?; + let state = wait( + &connection, + &ConnectionState::Activated, + dbus_manager.method_timeout(), + )?; Ok((connection, state)) } @@ -320,15 +333,16 @@ fn wait( total_time += 1; if state == *target_state { - debug!("Connection target state reached: {:?} / {}s elapsed", state, total_time); + debug!( + "Connection target state reached: {:?} / {}s elapsed", + state, total_time + ); return Ok(state); } else if total_time >= timeout { debug!( "Timeout reached in waiting for connection state ({:?}): {:?} / {}s elapsed", - target_state, - state, - total_time + target_state, state, total_time ); return Ok(state); @@ -336,9 +350,7 @@ fn wait( debug!( "Still waiting for connection state ({:?}): {:?} / {}s elapsed", - target_state, - state, - total_time + target_state, state, total_time ); } } @@ -358,15 +370,16 @@ mod tests { // e.g. export TEST_WIFI_SSID="Resin.io Wifi" let wifi_env_var = "TEST_WIFI_SSID"; let connection = match ::std::env::var(wifi_env_var) { - Ok(ssid) => { - connections - .iter() - .filter(|c| c.settings().ssid.as_str().unwrap() == ssid) - .nth(0) - .unwrap() - .clone() - }, - Err(e) => panic!("couldn't retrieve environment variable {}: {}", wifi_env_var, e), + Ok(ssid) => connections + .iter() + .filter(|c| c.settings().ssid.as_str().unwrap() == ssid) + .nth(0) + .unwrap() + .clone(), + Err(e) => panic!( + "couldn't retrieve environment variable {}: {}", + wifi_env_var, e + ), }; let state = connection.get_state().unwrap(); diff --git a/src/dbus_api.rs b/src/dbus_api.rs index bd48dc7..ffa8e8f 100644 --- a/src/dbus_api.rs +++ b/src/dbus_api.rs @@ -1,14 +1,12 @@ use dbus::Connection as DBusConnection; -use dbus::{BusType, Path, ConnPath, Message}; -use dbus::arg::{Variant, Iter, Array, Get, RefArg}; +use dbus::{BusType, ConnPath, Message, Path}; +use dbus::arg::{Array, Get, Iter, RefArg, Variant}; use dbus::stdintf::OrgFreedesktopDBusProperties; use dbus::Error; - const DEFAULT_TIMEOUT: u64 = 15; const RETRIES_ALLOWED: usize = 10; - pub struct DBusApi { connection: DBusConnection, method_timeout: u64, @@ -53,10 +51,7 @@ impl DBusApi { .map_err(|error| { let message = format!( "D-Bus '{}'::'{}' method call failed on '{}': {}", - interface, - method, - path, - error + interface, method, path, error ); error!("{}", message); message @@ -80,14 +75,15 @@ impl DBusApi { retries += 1; if retries == RETRIES_ALLOWED { - return Err(format!("method call failed after {} retries", RETRIES_ALLOWED)); + return Err(format!( + "method call failed after {} retries", + RETRIES_ALLOWED + )); } debug!( "Retrying '{}'::'{}' method call: retry #{}", - interface, - method, - retries, + interface, method, retries, ); ::std::thread::sleep(::std::time::Duration::from_secs(1)); @@ -114,10 +110,9 @@ impl DBusApi { } fn send_message_checked(&self, message: Message) -> Option> { - match self.connection.send_with_reply_and_block( - message, - self.method_timeout as i32 * 1000, - ) { + match self.connection + .send_with_reply_and_block(message, self.method_timeout as i32 * 1000) + { Ok(response) => Some(Ok(response)), Err(err) => { let message = get_error_message(&err).to_string(); @@ -143,10 +138,7 @@ impl DBusApi { let property_error = |details: &str, err: bool| { let message = format!( "D-Bus get '{}'::'{}' property failed on '{}': {}", - interface, - name, - path, - details + interface, name, path, details ); if err { error!("{}", message); @@ -159,17 +151,13 @@ impl DBusApi { let path = self.with_path(path); match path.get(interface, name) { - Ok(variant) => { - match DBusApi::variant_to(&variant) { - Some(data) => Ok(data), - None => property_error("wrong property type", true), - } + Ok(variant) => match DBusApi::variant_to(&variant) { + Some(data) => Ok(data), + None => property_error("wrong property type", true), }, - Err(err) => { - match err.message() { - Some(details) => property_error(details, false), - None => property_error("no details", false), - } + Err(err) => match err.message() { + Some(details) => property_error(details, false), + None => property_error("no details", false), }, } } @@ -178,9 +166,9 @@ impl DBusApi { where T: Get<'a>, { - response.get1().ok_or_else( - || "D-Bus wrong response type".to_string(), - ) + response + .get1() + .ok_or_else(|| "D-Bus wrong response type".to_string()) } pub fn extract_two<'a, T1, T2>(&self, response: &'a Message) -> Result<(T1, T2), String> @@ -200,48 +188,39 @@ impl DBusApi { } fn with_path<'a, P: Into>>(&'a self, path: P) -> ConnPath<&'a DBusConnection> { - self.connection.with_path( - self.base, - path, - self.method_timeout as i32 * 1000, - ) + self.connection + .with_path(self.base, path, self.method_timeout as i32 * 1000) } } - pub trait VariantTo { fn variant_to(value: &Variant>) -> Option; } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { value.0.as_str().and_then(|v| Some(v.to_string())) } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { value.0.as_i64() } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { value.0.as_i64().and_then(|v| Some(v as u32)) } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { value.0.as_i64().and_then(|v| Some(v == 0)) } } - impl VariantTo> for DBusApi { fn variant_to(value: &Variant>) -> Option> { let mut result = Vec::new(); @@ -262,7 +241,6 @@ impl VariantTo> for DBusApi { } } - impl VariantTo> for DBusApi { fn variant_to(value: &Variant>) -> Option> { let mut result = Vec::new(); @@ -283,14 +261,13 @@ impl VariantTo> for DBusApi { } } - pub fn extract<'a, T>(var: &mut Variant>) -> Result where T: Get<'a>, { - var.0.get::().ok_or_else(|| { - format!("D-Bus variant type does not match: {:?}", var) - }) + var.0 + .get::() + .ok_or_else(|| format!("D-Bus variant type does not match: {:?}", var)) } pub fn variant_iter_to_vec_u8(var: &mut Variant) -> Result, String> { diff --git a/src/dbus_nm.rs b/src/dbus_nm.rs index 627c871..9e2d265 100644 --- a/src/dbus_nm.rs +++ b/src/dbus_nm.rs @@ -4,37 +4,35 @@ use std::net::Ipv4Addr; use ascii::AsAsciiStr; use dbus::Path; -use dbus::arg::{Dict, Variant, Iter, Array, RefArg}; +use dbus::arg::{Array, Dict, Iter, RefArg, Variant}; -use dbus_api::{DBusApi, extract, path_to_string, VariantTo, variant_iter_to_vec_u8}; +use dbus_api::{extract, path_to_string, DBusApi, VariantTo, variant_iter_to_vec_u8}; use manager::{Connectivity, NetworkManagerState}; use connection::{ConnectionSettings, ConnectionState}; -use ssid::{Ssid, SsidSlice, AsSsidSlice}; -use device::{DeviceType, DeviceState}; -use wifi::{NM80211ApSecurityFlags, NM80211ApFlags, Security, WEP, NONE}; - +use ssid::{AsSsidSlice, Ssid, SsidSlice}; +use device::{DeviceState, DeviceType}; +use wifi::{NM80211ApFlags, NM80211ApSecurityFlags, Security, NONE, WEP}; type VariantMap = HashMap>>; -const NM_SERVICE_MANAGER: &'static str = "org.freedesktop.NetworkManager"; +const NM_SERVICE_MANAGER: &str = "org.freedesktop.NetworkManager"; -const NM_SERVICE_PATH: &'static str = "/org/freedesktop/NetworkManager"; -const NM_SETTINGS_PATH: &'static str = "/org/freedesktop/NetworkManager/Settings"; +const NM_SERVICE_PATH: &str = "/org/freedesktop/NetworkManager"; +const NM_SETTINGS_PATH: &str = "/org/freedesktop/NetworkManager/Settings"; -const NM_SERVICE_INTERFACE: &'static str = "org.freedesktop.NetworkManager"; -const NM_SETTINGS_INTERFACE: &'static str = "org.freedesktop.NetworkManager.Settings"; -const NM_CONNECTION_INTERFACE: &'static str = "org.freedesktop.NetworkManager.Settings.\ - Connection"; -const NM_ACTIVE_INTERFACE: &'static str = "org.freedesktop.NetworkManager.Connection.Active"; -const NM_DEVICE_INTERFACE: &'static str = "org.freedesktop.NetworkManager.Device"; -const NM_WIRELESS_INTERFACE: &'static str = "org.freedesktop.NetworkManager.Device.Wireless"; -const NM_ACCESS_POINT_INTERFACE: &'static str = "org.freedesktop.NetworkManager.AccessPoint"; +const NM_SERVICE_INTERFACE: &str = "org.freedesktop.NetworkManager"; +const NM_SETTINGS_INTERFACE: &str = "org.freedesktop.NetworkManager.Settings"; +const NM_CONNECTION_INTERFACE: &str = "org.freedesktop.NetworkManager.Settings.\ + Connection"; +const NM_ACTIVE_INTERFACE: &str = "org.freedesktop.NetworkManager.Connection.Active"; +const NM_DEVICE_INTERFACE: &str = "org.freedesktop.NetworkManager.Device"; +const NM_WIRELESS_INTERFACE: &str = "org.freedesktop.NetworkManager.Device.Wireless"; +const NM_ACCESS_POINT_INTERFACE: &str = "org.freedesktop.NetworkManager.AccessPoint"; const NM_WEP_KEY_TYPE_PASSPHRASE: u32 = 2; -const UNKNOWN_CONNECTION: &'static str = "org.freedesktop.NetworkManager.UnknownConnection"; -const METHOD_RETRY_ERROR_NAMES: &'static [&'static str; 1] = &[UNKNOWN_CONNECTION]; - +const UNKNOWN_CONNECTION: &str = "org.freedesktop.NetworkManager.UnknownConnection"; +const METHOD_RETRY_ERROR_NAMES: &[&str; 1] = &[UNKNOWN_CONNECTION]; pub struct DBusNetworkManager { dbus: DBusApi, @@ -52,11 +50,8 @@ impl DBusNetworkManager { } pub fn get_state(&self) -> Result { - let response = self.dbus.call( - NM_SERVICE_PATH, - NM_SERVICE_INTERFACE, - "state", - )?; + let response = self.dbus + .call(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "state")?; let state: i64 = self.dbus.extract(&response)?; @@ -64,11 +59,8 @@ impl DBusNetworkManager { } pub fn check_connectivity(&self) -> Result { - let response = self.dbus.call( - NM_SERVICE_PATH, - NM_SERVICE_INTERFACE, - "CheckConnectivity", - )?; + let response = self.dbus + .call(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "CheckConnectivity")?; let connectivity: u32 = self.dbus.extract(&response)?; @@ -76,27 +68,18 @@ impl DBusNetworkManager { } pub fn is_wireless_enabled(&self) -> Result { - self.dbus.property( - NM_SERVICE_PATH, - NM_SERVICE_INTERFACE, - "WirelessEnabled", - ) + self.dbus + .property(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "WirelessEnabled") } pub fn is_networking_enabled(&self) -> Result { - self.dbus.property( - NM_SERVICE_PATH, - NM_SERVICE_INTERFACE, - "NetworkingEnabled", - ) + self.dbus + .property(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "NetworkingEnabled") } pub fn list_connections(&self) -> Result, String> { - let response = self.dbus.call( - NM_SETTINGS_PATH, - NM_SETTINGS_INTERFACE, - "ListConnections", - )?; + let response = self.dbus + .call(NM_SETTINGS_PATH, NM_SETTINGS_INTERFACE, "ListConnections")?; let array: Array = self.dbus.extract(&response)?; @@ -104,11 +87,8 @@ impl DBusNetworkManager { } pub fn get_active_connections(&self) -> Result, String> { - self.dbus.property( - NM_SERVICE_PATH, - NM_SERVICE_INTERFACE, - "ActiveConnections", - ) + self.dbus + .property(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "ActiveConnections") } pub fn get_active_connection_path(&self, path: &str) -> Option { @@ -127,7 +107,8 @@ impl DBusNetworkManager { } pub fn get_connection_settings(&self, path: &str) -> Result { - let response = self.dbus.call(path, NM_CONNECTION_INTERFACE, "GetSettings")?; + let response = self.dbus + .call(path, NM_CONNECTION_INTERFACE, "GetSettings")?; let dict: Dict<&str, Dict<&str, Variant, _>, _> = self.dbus.extract(&response)?; @@ -226,8 +207,16 @@ impl DBusNetworkManager { let mut security_settings: VariantMap = HashMap::new(); if security.contains(WEP) { - add_val(&mut security_settings, "wep-key-type", NM_WEP_KEY_TYPE_PASSPHRASE); - add_str(&mut security_settings, "wep-key0", verify_password(password)?); + add_val( + &mut security_settings, + "wep-key-type", + NM_WEP_KEY_TYPE_PASSPHRASE, + ); + add_str( + &mut security_settings, + "wep-key0", + verify_password(password)?, + ); } else { add_str(&mut security_settings, "key-mgmt", "wpa-psk"); add_str(&mut security_settings, "psk", verify_password(password)?); @@ -247,10 +236,12 @@ impl DBusNetworkManager { ], )?; - let (conn_path, active_connection): (Path, Path) = self.dbus.extract_two(&response)?; - Ok((path_to_string(&conn_path)?, path_to_string(&active_connection)?)) + Ok(( + path_to_string(&conn_path)?, + path_to_string(&active_connection)?, + )) } pub fn create_hotspot( @@ -322,18 +313,17 @@ impl DBusNetworkManager { ], )?; - let (conn_path, active_connection): (Path, Path) = self.dbus.extract_two(&response)?; - Ok((path_to_string(&conn_path)?, path_to_string(&active_connection)?)) + Ok(( + path_to_string(&conn_path)?, + path_to_string(&active_connection)?, + )) } pub fn get_devices(&self) -> Result, String> { - self.dbus.property( - NM_SERVICE_PATH, - NM_SERVICE_INTERFACE, - "Devices", - ) + self.dbus + .property(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "Devices") } pub fn get_device_by_interface(&self, interface: &str) -> Result { @@ -383,19 +373,13 @@ impl DBusNetworkManager { } pub fn get_device_access_points(&self, path: &str) -> Result, String> { - self.dbus.property( - path, - NM_WIRELESS_INTERFACE, - "AccessPoints", - ) + self.dbus + .property(path, NM_WIRELESS_INTERFACE, "AccessPoints") } pub fn get_access_point_ssid(&self, path: &str) -> Option { - if let Ok(ssid_vec) = self.dbus.property::>( - path, - NM_ACCESS_POINT_INTERFACE, - "Ssid", - ) + if let Ok(ssid_vec) = self.dbus + .property::>(path, NM_ACCESS_POINT_INTERFACE, "Ssid") { Ssid::from_bytes(ssid_vec).ok() } else { @@ -404,11 +388,8 @@ impl DBusNetworkManager { } pub fn get_access_point_strength(&self, path: &str) -> Result { - self.dbus.property( - path, - NM_ACCESS_POINT_INTERFACE, - "Strength", - ) + self.dbus + .property(path, NM_ACCESS_POINT_INTERFACE, "Strength") } pub fn get_access_point_flags(&self, path: &str) -> Result { @@ -416,55 +397,46 @@ impl DBusNetworkManager { } pub fn get_access_point_wpa_flags(&self, path: &str) -> Result { - self.dbus.property( - path, - NM_ACCESS_POINT_INTERFACE, - "WpaFlags", - ) + self.dbus + .property(path, NM_ACCESS_POINT_INTERFACE, "WpaFlags") } pub fn get_access_point_rsn_flags(&self, path: &str) -> Result { - self.dbus.property( - path, - NM_ACCESS_POINT_INTERFACE, - "RsnFlags", - ) + self.dbus + .property(path, NM_ACCESS_POINT_INTERFACE, "RsnFlags") } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { value.0.as_i64().map(DeviceType::from) } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { value.0.as_i64().map(DeviceState::from) } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { - value.0.as_i64().and_then( - |v| NM80211ApFlags::from_bits(v as u32), - ) + value + .0 + .as_i64() + .and_then(|v| NM80211ApFlags::from_bits(v as u32)) } } - impl VariantTo for DBusApi { fn variant_to(value: &Variant>) -> Option { - value.0.as_i64().and_then(|v| { - NM80211ApSecurityFlags::from_bits(v as u32) - }) + value + .0 + .as_i64() + .and_then(|v| NM80211ApSecurityFlags::from_bits(v as u32)) } } - pub fn add_val(map: &mut VariantMap, key: K, value: V) where K: Into, @@ -486,7 +458,10 @@ fn verify_password(password: &T) -> Result<&str, String> Err(_) => Err("Not an ASCII password".to_string()), Ok(p) => { if p.len() > 64 { - Err(format!("Password length should not exceed 64: {} len", p.len())) + Err(format!( + "Password length should not exceed 64: {} len", + p.len() + )) } else { Ok(p.as_str()) } diff --git a/src/device.rs b/src/device.rs index a38baa5..48e6ffb 100644 --- a/src/device.rs +++ b/src/device.rs @@ -3,8 +3,7 @@ use std::fmt; use dbus_nm::DBusNetworkManager; -use wifi::{WiFiDevice, new_wifi_device}; - +use wifi::{new_wifi_device, WiFiDevice}; #[derive(Clone)] pub struct Device { @@ -67,7 +66,11 @@ impl Device { _ => { self.dbus_manager.connect_device(&self.path)?; - wait(self, &DeviceState::Activated, self.dbus_manager.method_timeout()) + wait( + self, + &DeviceState::Activated, + self.dbus_manager.method_timeout(), + ) }, } } @@ -91,7 +94,11 @@ impl Device { _ => { self.dbus_manager.disconnect_device(&self.path)?; - wait(self, &DeviceState::Disconnected, self.dbus_manager.method_timeout()) + wait( + self, + &DeviceState::Disconnected, + self.dbus_manager.method_timeout(), + ) }, } } @@ -102,9 +109,7 @@ impl fmt::Debug for Device { write!( f, "Device {{ path: {:?}, interface: {:?}, device_type: {:?} }}", - self.path, - self.interface, - self.device_type + self.path, self.interface, self.device_type ) } } @@ -180,7 +185,6 @@ impl From for DeviceType { } } - #[derive(Clone, Debug, PartialEq)] pub enum DeviceState { Unknown, @@ -222,7 +226,6 @@ impl From for DeviceState { } } - pub fn get_devices(dbus_manager: &Rc) -> Result, String> { let device_paths = dbus_manager.get_devices()?; @@ -280,15 +283,16 @@ fn wait(device: &Device, target_state: &DeviceState, timeout: u64) -> Result= timeout { debug!( "Timeout reached in waiting for device state ({:?}): {:?} / {}s elapsed", - target_state, - state, - total_time + target_state, state, total_time ); return Ok(state); @@ -296,9 +300,7 @@ fn wait(device: &Device, target_state: &DeviceState, timeout: u64) -> Result, @@ -149,12 +148,10 @@ impl From for NetworkManagerState { warn!("Undefined Network Manager state: {}", state); NetworkManagerState::Unknown }, - } } } - #[derive(Clone, Debug, PartialEq)] pub enum Connectivity { Unknown, @@ -176,12 +173,10 @@ impl From for Connectivity { warn!("Undefined connectivity state: {}", state); Connectivity::Unknown }, - } } } - #[cfg(test)] mod tests { use super::*; @@ -216,17 +211,29 @@ mod tests { match s { ServiceState::Active => { NetworkManager::stop_service(10).unwrap(); - assert_eq!(ServiceState::Inactive, NetworkManager::get_service_state().unwrap()); + assert_eq!( + ServiceState::Inactive, + NetworkManager::get_service_state().unwrap() + ); NetworkManager::start_service(10).unwrap(); - assert_eq!(ServiceState::Active, NetworkManager::get_service_state().unwrap()); + assert_eq!( + ServiceState::Active, + NetworkManager::get_service_state().unwrap() + ); }, ServiceState::Inactive => { NetworkManager::start_service(10).unwrap(); - assert_eq!(ServiceState::Active, NetworkManager::get_service_state().unwrap()); + assert_eq!( + ServiceState::Active, + NetworkManager::get_service_state().unwrap() + ); NetworkManager::stop_service(10).unwrap(); - assert_eq!(ServiceState::Inactive, NetworkManager::get_service_state().unwrap()); + assert_eq!( + ServiceState::Inactive, + NetworkManager::get_service_state().unwrap() + ); }, _ => (), } diff --git a/src/service.rs b/src/service.rs index e5ae205..8d15283 100644 --- a/src/service.rs +++ b/src/service.rs @@ -5,16 +5,16 @@ extern crate tokio_timer; use std::str::FromStr; use std::time::Duration; -use self::dbus::{Connection, ConnectionItem, Message, Props, BusType, Path, Interface, Member}; +use self::dbus::{BusType, Connection, ConnectionItem, Interface, Member, Message, Path, Props}; use self::dbus::arg::{Dict, Iter, Variant}; use self::futures::Future; use self::futures_cpupool::CpuPool; use self::tokio_timer::Timer; -pub const SD_SERVICE_MANAGER: &'static str = "org.freedesktop.systemd1"; -pub const SD_SERVICE_PATH: &'static str = "/org/freedesktop/systemd1"; -pub const SD_MANAGER_INTERFACE: &'static str = "org.freedesktop.systemd1.Manager"; -pub const SD_UNIT_INTERFACE: &'static str = "org.freedesktop.systemd1.Unit"; +pub const SD_SERVICE_MANAGER: &str = "org.freedesktop.systemd1"; +pub const SD_SERVICE_PATH: &str = "/org/freedesktop/systemd1"; +pub const SD_MANAGER_INTERFACE: &str = "org.freedesktop.systemd1.Manager"; +pub const SD_UNIT_INTERFACE: &str = "org.freedesktop.systemd1.Unit"; pub fn start_service(timeout: u64) -> Result { let state = get_service_state()?; @@ -31,9 +31,7 @@ pub fn start_service(timeout: u64) -> Result { ).map_err(Error::Message)? .append2("NetworkManager.service", "fail"); - let connection = Connection::get_private(BusType::System).map_err( - Error::Connection, - )?; + let connection = Connection::get_private(BusType::System).map_err(Error::Connection)?; connection .send_with_reply_and_block(message, 2000) @@ -59,9 +57,7 @@ pub fn stop_service(timeout: u64) -> Result { ).map_err(Error::Message)? .append2("NetworkManager.service", "fail"); - let connection = Connection::get_private(BusType::System).map_err( - Error::Connection, - )?; + let connection = Connection::get_private(BusType::System).map_err(Error::Connection)?; connection .send_with_reply_and_block(message, 2000) @@ -81,9 +77,7 @@ pub fn get_service_state() -> Result { ).map_err(Error::Message)? .append1("NetworkManager.service"); - let connection = Connection::get_private(BusType::System).map_err( - Error::Connection, - )?; + let connection = Connection::get_private(BusType::System).map_err(Error::Connection)?; let response = connection .send_with_reply_and_block(message, 2000) @@ -91,8 +85,13 @@ pub fn get_service_state() -> Result { let path = response.get1::().ok_or(Error::NotFound)?; - let response = Props::new(&connection, SD_SERVICE_MANAGER, path, SD_UNIT_INTERFACE, 2000) - .get("ActiveState") + let response = Props::new( + &connection, + SD_SERVICE_MANAGER, + path, + SD_UNIT_INTERFACE, + 2000, + ).get("ActiveState") .map_err(Error::Props)?; response @@ -107,22 +106,18 @@ fn handler(timeout: u64, target_state: ServiceState) -> Result Result, @@ -13,9 +12,7 @@ pub struct Ssid { impl Ssid { pub fn new() -> Self { - Ssid { - vec: Vec::new(), - } + Ssid { vec: Vec::new() } } pub fn from_bytes(bytes: B) -> Result @@ -32,9 +29,7 @@ impl Ssid { where B: Into>, { - Ssid { - vec: bytes.into(), - } + Ssid { vec: bytes.into() } } } @@ -91,7 +86,10 @@ impl fmt::Debug for SsidSlice { impl AsSsidSlice for [u8] { fn as_ssid_slice(&self) -> Result<&SsidSlice, String> { if self.len() > 32 { - Err(format!("SSID length should not exceed 32: {} len", self.len())) + Err(format!( + "SSID length should not exceed 32: {} len", + self.len() + )) } else { Ok(unsafe { mem::transmute(self) }) } diff --git a/src/wifi.rs b/src/wifi.rs index 948513f..ed47c16 100644 --- a/src/wifi.rs +++ b/src/wifi.rs @@ -5,11 +5,10 @@ use ascii::AsAsciiStr; use dbus_nm::DBusNetworkManager; -use connection::{Connection, ConnectionState, connect_to_access_point, create_hotspot}; +use connection::{connect_to_access_point, create_hotspot, Connection, ConnectionState}; use device::{Device, PathGetter}; use ssid::{AsSsidSlice, Ssid, SsidSlice}; - pub struct WiFiDevice<'a> { dbus_manager: Rc, device: &'a Device, @@ -32,9 +31,8 @@ impl<'a> WiFiDevice<'a> { pub fn get_access_points(&self) -> Result, String> { let mut access_points = Vec::new(); - let paths = self.dbus_manager.get_device_access_points( - self.device.path(), - )?; + let paths = self.dbus_manager + .get_device_access_points(self.device.path())?; for path in paths { if let Some(access_point) = get_access_point(&self.dbus_manager, &path)? { @@ -87,7 +85,6 @@ impl<'a> WiFiDevice<'a> { } } - #[derive(Debug)] pub struct AccessPoint { path: String, @@ -102,7 +99,6 @@ impl AccessPoint { } } - bitflags! { pub struct Security: u32 { const NONE = 0b0000_0000; @@ -113,7 +109,6 @@ bitflags! { } } - bitflags! { pub struct NM80211ApFlags: u32 { // access point has no special capabilities @@ -123,7 +118,6 @@ bitflags! { } } - bitflags! { pub struct NM80211ApSecurityFlags: u32 { // the access point has no special security requirements @@ -151,7 +145,6 @@ bitflags! { } } - pub fn new_wifi_device<'a>( dbus_manager: &Rc, device: &'a Device, @@ -162,7 +155,6 @@ pub fn new_wifi_device<'a>( } } - fn get_access_point( manager: &DBusNetworkManager, path: &str, @@ -185,7 +177,6 @@ fn get_access_point( } } - fn get_access_point_security(manager: &DBusNetworkManager, path: &str) -> Result { let flags = manager.get_access_point_flags(path)?;