Skip to content
This repository has been archived by the owner on Jan 6, 2020. It is now read-only.

Commit

Permalink
Merge pull request #56 from maqi/rust_fmt
Browse files Browse the repository at this point in the history
rustfmt corrections
  • Loading branch information
Fraser Hutchison committed Jan 20, 2016
2 parents 8eceb60 + 55034b5 commit e5c4eed
Show file tree
Hide file tree
Showing 37 changed files with 2,023 additions and 1,391 deletions.
12 changes: 7 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ pub const LAUNCHER_LOCAL_CONFIG_FILE_NAME: &'static str = ".launcher.config";
pub const LAUNCHER_GLOBAL_CONFIG_FILE_NAME: &'static str = "LauncherSpecificConfigurationFile";
pub const MAX_ALLOWED_READ_PAYLOAD_SIZE_BYTES: u64 = 300 * 1024 * 1024;

pub fn get_base64_config() -> ::rustc_serialize::base64::Config {
::rustc_serialize::base64::Config {
char_set : ::rustc_serialize::base64::CharacterSet::Standard,
newline : ::rustc_serialize::base64::Newline::LF,
pad : true,
use rustc_serialize::base64::{CharacterSet, Config, Newline};

pub fn get_base64_config() -> Config {
Config {
char_set: CharacterSet::Standard,
newline: Newline::LF,
pad: true,
line_length: None,
}
}
203 changes: 126 additions & 77 deletions src/errors.rs

Large diffs are not rendered by default.

37 changes: 22 additions & 15 deletions src/ffi/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,36 +15,43 @@
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.

const FFI_ERROR_START_RANGE: i32 = ::errors::LAUNCHER_ERROR_START_RANGE - 500;
use std::fmt;

use safe_core::errors::CoreError;
use errors::{LAUNCHER_ERROR_START_RANGE, LauncherError};

const FFI_ERROR_START_RANGE: i32 = LAUNCHER_ERROR_START_RANGE - 500;

/// Errors during FFI operations
pub enum FfiError {
/// Errors from Safe Core
CoreError(Box<::safe_core::errors::CoreError>),
CoreError(Box<CoreError>),
/// Errors from Launcher
LauncherError(Box<::errors::LauncherError>),
LauncherError(Box<LauncherError>),
/// Unexpected or some programming error
Unexpected(String),
}

impl ::std::fmt::Debug for FfiError {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
impl fmt::Debug for FfiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
FfiError::CoreError(ref error) => write!(f, "FfiError::CoreError -> {:?}", error),
FfiError::LauncherError(ref error) => write!(f, "FfiError::LauncherError -> {:?}", error),
FfiError::Unexpected(ref error) => write!(f, "FfiError::Unexpected::{{{:?}}}", error),
FfiError::CoreError(ref error) => write!(f, "FfiError::CoreError -> {:?}", error),
FfiError::LauncherError(ref error) => {
write!(f, "FfiError::LauncherError -> {:?}", error)
}
FfiError::Unexpected(ref error) => write!(f, "FfiError::Unexpected::{{{:?}}}", error),
}
}
}

impl From<::errors::LauncherError> for FfiError {
fn from(error: ::errors::LauncherError) -> FfiError {
impl From<LauncherError> for FfiError {
fn from(error: LauncherError) -> FfiError {
FfiError::LauncherError(Box::new(error))
}
}

impl From<::safe_core::errors::CoreError> for FfiError {
fn from(error: ::safe_core::errors::CoreError) -> FfiError {
impl From<CoreError> for FfiError {
fn from(error: CoreError) -> FfiError {
FfiError::CoreError(Box::new(error))
}
}
Expand All @@ -58,9 +65,9 @@ impl<'a> From<&'a str> for FfiError {
impl Into<i32> for FfiError {
fn into(self) -> i32 {
match self {
FfiError::CoreError(error) => (*error).into(),
FfiError::LauncherError(error) => (*error).into(),
FfiError::Unexpected(_) => FFI_ERROR_START_RANGE - 1,
FfiError::CoreError(error) => (*error).into(),
FfiError::LauncherError(error) => (*error).into(),
FfiError::Unexpected(_) => FFI_ERROR_START_RANGE - 1,
}
}
}
15 changes: 11 additions & 4 deletions src/ffi/implementation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,18 @@
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.

use libc::c_char;

use std::ffi::CStr;

use ffi::errors::FfiError;

/// Converts c character pointer into Rust String
#[allow(unsafe_code)]
pub fn c_char_ptr_to_string(c_char_ptr: *const ::libc::c_char) -> Result<String, ::ffi::errors::FfiError> {
use ::std::error::Error;
pub fn c_char_ptr_to_string(c_char_ptr: *const c_char) -> Result<String, FfiError> {
use std::error::Error;

let cstr = unsafe { ::std::ffi::CStr::from_ptr(c_char_ptr) };
Ok(try!(String::from_utf8(cstr.to_bytes().iter().map(|a| *a).collect()).map_err(|error| ::ffi::errors::FfiError::from(error.description()))))
let cstr = unsafe { CStr::from_ptr(c_char_ptr) };
Ok(try!(String::from_utf8(cstr.to_bytes().iter().map(|a| *a).collect())
.map_err(|error| FfiError::from(error.description()))))
}
114 changes: 67 additions & 47 deletions src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,80 +18,100 @@
mod errors;
mod implementation;

use std::mem;

use libc::{c_char, c_void, int32_t};

use safe_core::client::Client;

use launcher::Launcher;

/// Create an account with SafeNetwork. This or any one of the other companion functions to get a
/// launcher must be called before initiating any operation allowed by this crate. `launcher_handle` is
/// a pointer to a pointer and must point to a valid pointer not junk, else the consequences are
/// launcher must be called before initiating any operation allowed by this crate. `launcher_handle`
/// is a pointer to a pointer and must point to a valid pointer not junk, else the consequences are
/// undefined.
#[no_mangle]
#[allow(unsafe_code)]
pub extern fn create_account(c_keyword : *const ::libc::c_char,
c_pin : *const ::libc::c_char,
c_password : *const ::libc::c_char,
launcher_handle: *mut *const ::libc::c_void) -> ::libc::int32_t {
let client = ffi_try!(::safe_core::client::Client::create_account(ffi_try!(implementation::c_char_ptr_to_string(c_keyword)),
ffi_try!(implementation::c_char_ptr_to_string(c_pin)),
ffi_try!(implementation::c_char_ptr_to_string(c_password))));
let launcher = ffi_try!(::launcher::Launcher::new(client));
unsafe { *launcher_handle = cast_to_launcher_ffi_handle(launcher); }
pub extern "C" fn create_account(c_keyword: *const c_char,
c_pin: *const c_char,
c_password: *const c_char,
launcher_handle: *mut *const c_void)
-> int32_t {
let client = ffi_try!(Client::create_account(
ffi_try!(implementation::c_char_ptr_to_string(c_keyword)),
ffi_try!(implementation::c_char_ptr_to_string(c_pin)),
ffi_try!(implementation::c_char_ptr_to_string(c_password))));
let launcher = ffi_try!(Launcher::new(client));
unsafe {
*launcher_handle = cast_to_launcher_ffi_handle(launcher);
}

0
}

/// Log into Safenetwork with an already registered account. This or any one of the other companion functions to get a
/// launcher must be called before initiating any operation allowed by this crate. `launcher_handle` is
/// a pointer to a pointer and must point to a valid pointer not junk, else the consequences are
/// undefined.
/// Log into Safenetwork with an already registered account. This or any one of the other companion
/// functions to get a launcher must be called before initiating any operation allowed by this
/// crate. `launcher_handle` is a pointer to a pointer and must point to a valid pointer not junk,
/// else the consequences are undefined.
#[no_mangle]
#[allow(unsafe_code)]
pub extern fn log_in(c_keyword : *const ::libc::c_char,
c_pin : *const ::libc::c_char,
c_password : *const ::libc::c_char,
launcher_handle: *mut *const ::libc::c_void) -> ::libc::int32_t {
let client = ffi_try!(::safe_core::client::Client::log_in(ffi_try!(implementation::c_char_ptr_to_string(c_keyword)),
ffi_try!(implementation::c_char_ptr_to_string(c_pin)),
ffi_try!(implementation::c_char_ptr_to_string(c_password))));
let launcher = ffi_try!(::launcher::Launcher::new(client));
unsafe { *launcher_handle = cast_to_launcher_ffi_handle(launcher); }
pub extern "C" fn log_in(c_keyword: *const c_char,
c_pin: *const c_char,
c_password: *const c_char,
launcher_handle: *mut *const c_void)
-> int32_t {
let client = ffi_try!(Client::log_in(
ffi_try!(implementation::c_char_ptr_to_string(c_keyword)),
ffi_try!(implementation::c_char_ptr_to_string(c_pin)),
ffi_try!(implementation::c_char_ptr_to_string(c_password))));
let launcher = ffi_try!(Launcher::new(client));
unsafe {
*launcher_handle = cast_to_launcher_ffi_handle(launcher);
}

0
}

/// Discard and clean up the previously allocated launcher. Use this only if the launcher is obtained
/// from one of the client obtainment functions in this crate (`create_account`, `log_in`).
/// Using `launcher_handle` after a call to this functions is undefined behaviour.
/// Discard and clean up the previously allocated launcher. Use this only if the launcher is
/// obtained from one of the client obtainment functions in this crate (`create_account`,
/// `log_in`). Using `launcher_handle` after a call to this functions is undefined behaviour.
#[no_mangle]
#[allow(unsafe_code)]
pub extern fn drop_launcher(launcher_handle: *const ::libc::c_void) {
let _ = unsafe { ::std::mem::transmute::<_, Box<::launcher::Launcher>>(launcher_handle) };
pub extern "C" fn drop_launcher(launcher_handle: *const c_void) {
let _ = unsafe { mem::transmute::<_, Box<Launcher>>(launcher_handle) };
}

#[allow(unsafe_code)]
fn cast_to_launcher_ffi_handle(launcher: ::launcher::Launcher) -> *const ::libc::c_void {
fn cast_to_launcher_ffi_handle(launcher: Launcher) -> *const c_void {
let boxed_launcher = Box::new(launcher);
unsafe { ::std::mem::transmute(boxed_launcher) }
unsafe { mem::transmute(boxed_launcher) }
}

// TODO(Spandan) ***W A R N I N G*** This will be UB - make sure to modify after uncommenting
// #[allow(unsafe_code)]
// fn cast_from_launcher_ffi_handle(launcher_handle: *const ::libc::c_void) -> ::launcher::Launcher {
// fn cast_from_launcher_ffi_handle(launcher_handle: *const c_void) -> Launcher {
// let boxed_launcher: Box<::launcher::Launcher> = unsafe {
// ::std::mem::transmute(launcher_handle)
// mem::transmute(launcher_handle)
// };
//
//
// let launcher = *boxed_launcher;
// ::std::mem::forget(boxed_launcher);
//
// mem::forget(boxed_launcher);
//
// launcher
// }


#[cfg(test)]
mod test {
use super::*;
use ::std::error::Error;

fn generate_random_cstring(len: usize) -> Result<::std::ffi::CString, ::ffi::errors::FfiError> {
let mut cstring_vec = unwrap_result!(::safe_core::utility::generate_random_vector::<u8>(len));
use libc::c_void;
use std::error::Error;
use std::ffi::CString;
use ffi::errors::FfiError;
use safe_core::utility;

fn generate_random_cstring(len: usize) -> Result<CString, FfiError> {
let mut cstring_vec = unwrap_result!(utility::generate_random_vector::<u8>(len));
// Avoid internal nulls and ensure valid ASCII (thus valid utf8)
for it in cstring_vec.iter_mut() {
*it %= 128;
Expand All @@ -100,7 +120,7 @@ mod test {
}
}

::std::ffi::CString::new(cstring_vec).map_err(|error| ::ffi::errors::FfiError::from(error.description()))
CString::new(cstring_vec).map_err(|error| FfiError::from(error.description()))
}

#[test]
Expand All @@ -110,8 +130,8 @@ mod test {
let cstring_password = unwrap_result!(generate_random_cstring(10));

{
let mut launcher_handle = 0 as *const ::libc::c_void;
assert_eq!(launcher_handle, 0 as *const ::libc::c_void);
let mut launcher_handle = 0 as *const c_void;
assert_eq!(launcher_handle, 0 as *const c_void);

{
let ptr_to_launcher_handle = &mut launcher_handle;
Expand All @@ -123,13 +143,13 @@ mod test {
0);
}

assert!(launcher_handle != 0 as *const ::libc::c_void);
assert!(launcher_handle != 0 as *const c_void);
drop_launcher(launcher_handle);
}

{
let mut launcher_handle = 0 as *const ::libc::c_void;
assert_eq!(launcher_handle, 0 as *const ::libc::c_void);
let mut launcher_handle = 0 as *const c_void;
assert_eq!(launcher_handle, 0 as *const c_void);

{
let ptr_to_launcher_handle = &mut launcher_handle;
Expand All @@ -141,7 +161,7 @@ mod test {
0);
}

assert!(launcher_handle != 0 as *const ::libc::c_void);
assert!(launcher_handle != 0 as *const c_void);
drop_launcher(launcher_handle);
}
}
Expand Down
35 changes: 20 additions & 15 deletions src/launcher/app_handler/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.

use std::fmt;
use std::sync::mpsc;

use errors::LauncherError;
use observer::AppHandlerObserver;
use xor_name::XorName;

/// This is an event subset to be used by external codes to communicate with the App Handling
Expand All @@ -29,27 +34,27 @@ pub enum AppHandlerEvent {
/// Modify settings for an app
ModifyAppSettings(event_data::ModifyAppSettings),
/// Register an observer to receive notifications about status of adding of an app.
RegisterAppAddObserver(::observer::AppHandlerObserver),
RegisterAppAddObserver(AppHandlerObserver),
/// Register an observer to receive notifications about status of removal of an app.
RegisterAppRemoveObserver(::observer::AppHandlerObserver),
RegisterAppRemoveObserver(AppHandlerObserver),
/// Register an observer to receive notifications about an app being activated. Note however
/// that a successful activation does not necessarily translate into successfully managed
/// session. It just means that app has been started. It can still crash after start, fail
/// authentication etc. Register obeservers in IPC module to get a more fine grained
/// information.
RegisterAppActivateObserver(::observer::AppHandlerObserver),
RegisterAppActivateObserver(AppHandlerObserver),
/// Register an observer to receive notifications about status of modification of an app.
RegisterAppModifyObserver(::observer::AppHandlerObserver),
RegisterAppModifyObserver(AppHandlerObserver),
/// Obtain all apps currently being managed by Launcher.
GetAllManagedApps(::std::sync::mpsc::Sender<Result<Vec<event_data::ManagedApp>, ::errors::LauncherError>>),
GetAllManagedApps(mpsc::Sender<Result<Vec<event_data::ManagedApp>, LauncherError>>),
/// Gracefully exit the app handling module. After a call to this Launcher will no longer cater
/// to any requests handled by this module. This is essentially Launcher-close scenario and
/// Launcher must be restarted to be functional again.
Terminate,
}

impl ::std::fmt::Debug for AppHandlerEvent {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
impl fmt::Debug for AppHandlerEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self)
}
}
Expand All @@ -76,7 +81,7 @@ pub mod event_data {
#[derive(Debug, Clone)]
pub struct AppDetail {
/// Absolute path to the app binary on this machine.
pub absolute_path : String,
pub absolute_path: String,
/// If this app is allowed to have access to `SAFEDrive`.
pub safe_drive_access: bool,
}
Expand All @@ -85,16 +90,16 @@ pub mod event_data {
#[derive(Debug, Clone)]
pub struct ManagedApp {
/// Unique id given to the app. This will be consistent across all machines.
pub id : XorName,
pub id: XorName,
/// Name of this app. Unless specifically changed it will be the name of the binary added
/// to Launcher in the first machine for this app.
pub name : String,
pub name: String,
/// If the app was added to this machine, this will contain the absolute path to the
/// application binary. Otherwise it will be `None` indicating that app was added to
/// Launcher but not yet on this machine.
pub local_path : Option<String>,
pub local_path: Option<String>,
/// Number of machines this app is currently added to Launcher in.
pub reference_count : u32,
pub reference_count: u32,
/// If this app is allowed to have access to `SAFEDrive`.
pub safe_drive_access: bool,
}
Expand All @@ -104,11 +109,11 @@ pub mod event_data {
#[derive(Debug, Clone)]
pub struct ModifyAppSettings {
/// Unique id given to the app. This will be consistent across all machines.
pub id : XorName,
pub id: XorName,
/// App name for this app stored in Launcher.
pub name : Option<String>,
pub name: Option<String>,
/// Modify local binary absolute path.
pub local_path : Option<String>,
pub local_path: Option<String>,
/// If this app is allowed to have access to `SAFEDrive`.
pub safe_drive_access: Option<bool>,
}
Expand Down

0 comments on commit e5c4eed

Please sign in to comment.