diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/auth.rs | 44 | ||||
| -rw-r--r-- | src/device.rs | 72 | ||||
| -rw-r--r-- | src/lib.rs | 8 | ||||
| -rw-r--r-- | src/otp.rs | 38 | ||||
| -rw-r--r-- | src/pws.rs | 33 | ||||
| -rw-r--r-- | src/tests/device.rs | 89 | ||||
| -rw-r--r-- | src/tests/otp.rs | 55 | ||||
| -rw-r--r-- | src/tests/pws.rs | 69 | ||||
| -rw-r--r-- | src/util.rs | 37 | 
9 files changed, 195 insertions, 250 deletions
| diff --git a/src/auth.rs b/src/auth.rs index 6a0a71f..62b851f 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -5,7 +5,7 @@ use otp::{ConfigureOtp, GenerateOtp, OtpMode, OtpSlotData, RawOtpSlotData};  use std::ffi::CString;  use std::ops::Deref;  use std::os::raw::c_int; -use util::{generate_password, result_from_string, CommandError, CommandStatus}; +use util::{generate_password, get_command_result, result_from_string, CommandError};  static TEMPORARY_PASSWORD_LENGTH: usize = 25; @@ -287,41 +287,33 @@ impl<T: Device> Admin<T> {      /// ```      ///      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot -    pub fn write_config(&self, config: Config) -> CommandStatus { -        let raw_config = match RawConfig::try_from(config) { -            Ok(raw_config) => raw_config, -            Err(err) => return CommandStatus::Error(err), -        }; +    pub fn write_config(&self, config: Config) -> Result<(), CommandError> { +        let raw_config = RawConfig::try_from(config)?;          unsafe { -            let rv = nitrokey_sys::NK_write_config( +            get_command_result(nitrokey_sys::NK_write_config(                  raw_config.numlock,                  raw_config.capslock,                  raw_config.scrollock,                  raw_config.user_password,                  false,                  self.temp_password.as_ptr() as *const i8, -            ); -            return CommandStatus::from(rv); +            ))          }      } -    fn write_otp_slot<C>(&self, data: OtpSlotData, callback: C) -> CommandStatus +    fn write_otp_slot<C>(&self, data: OtpSlotData, callback: C) -> Result<(), CommandError>      where          C: Fn(RawOtpSlotData, *const i8) -> c_int,      { -        let raw_data = match RawOtpSlotData::new(data) { -            Ok(raw_data) => raw_data, -            Err(err) => return CommandStatus::Error(err), -        }; +        let raw_data = RawOtpSlotData::new(data)?;          let temp_password_ptr = self.temp_password.as_ptr() as *const i8; -        let rv = callback(raw_data, temp_password_ptr); -        return CommandStatus::from(rv); +        get_command_result(callback(raw_data, temp_password_ptr))      }  }  impl<T: Device> ConfigureOtp for Admin<T> { -    fn write_hotp_slot(&self, data: OtpSlotData, counter: u64) -> CommandStatus { -        return self.write_otp_slot(data, |raw_data: RawOtpSlotData, temp_password_ptr| unsafe { +    fn write_hotp_slot(&self, data: OtpSlotData, counter: u64) -> Result<(), CommandError> { +        self.write_otp_slot(data, |raw_data: RawOtpSlotData, temp_password_ptr| unsafe {              nitrokey_sys::NK_write_hotp_slot(                  raw_data.number,                  raw_data.name.as_ptr(), @@ -333,11 +325,11 @@ impl<T: Device> ConfigureOtp for Admin<T> {                  raw_data.token_id.as_ptr(),                  temp_password_ptr,              ) -        }); +        })      } -    fn write_totp_slot(&self, data: OtpSlotData, time_window: u16) -> CommandStatus { -        return self.write_otp_slot(data, |raw_data: RawOtpSlotData, temp_password_ptr| unsafe { +    fn write_totp_slot(&self, data: OtpSlotData, time_window: u16) -> Result<(), CommandError> { +        self.write_otp_slot(data, |raw_data: RawOtpSlotData, temp_password_ptr| unsafe {              nitrokey_sys::NK_write_totp_slot(                  raw_data.number,                  raw_data.name.as_ptr(), @@ -349,17 +341,17 @@ impl<T: Device> ConfigureOtp for Admin<T> {                  raw_data.token_id.as_ptr(),                  temp_password_ptr,              ) -        }); +        })      } -    fn erase_hotp_slot(&self, slot: u8) -> CommandStatus { +    fn erase_hotp_slot(&self, slot: u8) -> Result<(), CommandError> {          let temp_password_ptr = self.temp_password.as_ptr() as *const i8; -        unsafe { CommandStatus::from(nitrokey_sys::NK_erase_hotp_slot(slot, temp_password_ptr)) } +        unsafe { get_command_result(nitrokey_sys::NK_erase_hotp_slot(slot, temp_password_ptr)) }      } -    fn erase_totp_slot(&self, slot: u8) -> CommandStatus { +    fn erase_totp_slot(&self, slot: u8) -> Result<(), CommandError> {          let temp_password_ptr = self.temp_password.as_ptr() as *const i8; -        unsafe { CommandStatus::from(nitrokey_sys::NK_erase_totp_slot(slot, temp_password_ptr)) } +        unsafe { get_command_result(nitrokey_sys::NK_erase_totp_slot(slot, temp_password_ptr)) }      }  } diff --git a/src/device.rs b/src/device.rs index f901306..c4e83a9 100644 --- a/src/device.rs +++ b/src/device.rs @@ -5,7 +5,7 @@ use nitrokey_sys;  use otp::GenerateOtp;  use pws::GetPasswordSafe;  use std::ffi::CString; -use util::{get_last_error, result_from_string, CommandError, CommandStatus}; +use util::{get_command_result, get_last_error, result_from_string, CommandError};  /// Available Nitrokey models.  #[derive(Debug, PartialEq)] @@ -296,14 +296,14 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus, Device}; +    /// use nitrokey::Device;      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::connect()?;      /// match device.change_admin_pin("12345678", "12345679") { -    ///     CommandStatus::Success => println!("Updated admin PIN."), -    ///     CommandStatus::Error(err) => println!("Failed to update admin PIN: {:?}", err), +    ///     Ok(()) => println!("Updated admin PIN."), +    ///     Err(err) => println!("Failed to update admin PIN: {:?}", err),      /// };      /// #     Ok(())      /// # } @@ -311,16 +311,16 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      ///      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword -    fn change_admin_pin(&self, current: &str, new: &str) -> CommandStatus { +    fn change_admin_pin(&self, current: &str, new: &str) -> Result<(), CommandError> {          let current_string = CString::new(current);          let new_string = CString::new(new);          if current_string.is_err() || new_string.is_err() { -            return CommandStatus::Error(CommandError::InvalidString); +            return Err(CommandError::InvalidString);          }          let current_string = current_string.unwrap();          let new_string = new_string.unwrap();          unsafe { -            CommandStatus::from(nitrokey_sys::NK_change_admin_PIN( +            get_command_result(nitrokey_sys::NK_change_admin_PIN(                  current_string.as_ptr(),                  new_string.as_ptr(),              )) @@ -337,14 +337,14 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus, Device}; +    /// use nitrokey::Device;      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::connect()?;      /// match device.change_user_pin("123456", "123457") { -    ///     CommandStatus::Success => println!("Updated admin PIN."), -    ///     CommandStatus::Error(err) => println!("Failed to update admin PIN: {:?}", err), +    ///     Ok(()) => println!("Updated admin PIN."), +    ///     Err(err) => println!("Failed to update admin PIN: {:?}", err),      /// };      /// #     Ok(())      /// # } @@ -352,16 +352,16 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      ///      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword -    fn change_user_pin(&self, current: &str, new: &str) -> CommandStatus { +    fn change_user_pin(&self, current: &str, new: &str) -> Result<(), CommandError> {          let current_string = CString::new(current);          let new_string = CString::new(new);          if current_string.is_err() || new_string.is_err() { -            return CommandStatus::Error(CommandError::InvalidString); +            return Err(CommandError::InvalidString);          }          let current_string = current_string.unwrap();          let new_string = new_string.unwrap();          unsafe { -            CommandStatus::from(nitrokey_sys::NK_change_user_PIN( +            get_command_result(nitrokey_sys::NK_change_user_PIN(                  current_string.as_ptr(),                  new_string.as_ptr(),              )) @@ -378,14 +378,14 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus, Device}; +    /// use nitrokey::Device;      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::connect()?;      /// match device.unlock_user_pin("12345678", "123456") { -    ///     CommandStatus::Success => println!("Unlocked user PIN."), -    ///     CommandStatus::Error(err) => println!("Failed to unlock user PIN: {:?}", err), +    ///     Ok(()) => println!("Unlocked user PIN."), +    ///     Err(err) => println!("Failed to unlock user PIN: {:?}", err),      /// };      /// #     Ok(())      /// # } @@ -393,16 +393,16 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      ///      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword -    fn unlock_user_pin(&self, admin_pin: &str, user_pin: &str) -> CommandStatus { +    fn unlock_user_pin(&self, admin_pin: &str, user_pin: &str) -> Result<(), CommandError> {          let admin_pin_string = CString::new(admin_pin);          let user_pin_string = CString::new(user_pin);          if admin_pin_string.is_err() || user_pin_string.is_err() { -            return CommandStatus::Error(CommandError::InvalidString); +            return Err(CommandError::InvalidString);          }          let admin_pin_string = admin_pin_string.unwrap();          let user_pin_string = user_pin_string.unwrap();          unsafe { -            CommandStatus::from(nitrokey_sys::NK_unlock_user_password( +            get_command_result(nitrokey_sys::NK_unlock_user_password(                  admin_pin_string.as_ptr(),                  user_pin_string.as_ptr(),              )) @@ -417,20 +417,20 @@ pub trait Device: Authenticate + GetPasswordSafe + GenerateOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus, Device}; +    /// use nitrokey::Device;      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::connect()?;      /// match device.lock() { -    ///     CommandStatus::Success => println!("Locked the Nitrokey device."), -    ///     CommandStatus::Error(err) => println!("Could not lock the Nitrokey device: {:?}", err), +    ///     Ok(()) => println!("Locked the Nitrokey device."), +    ///     Err(err) => println!("Could not lock the Nitrokey device: {:?}", err),      /// };      /// #     Ok(())      /// # }      /// ``` -    fn lock(&self) -> CommandStatus { -        unsafe { CommandStatus::from(nitrokey_sys::NK_lock_device()) } +    fn lock(&self) -> Result<(), CommandError> { +        unsafe { get_command_result(nitrokey_sys::NK_lock_device()) }      }  } @@ -547,14 +547,13 @@ impl Storage {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus};      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::Storage::connect()?;      /// match device.enable_encrypted_volume("123456") { -    ///     CommandStatus::Success => println!("Enabled the encrypted volume."), -    ///     CommandStatus::Error(err) => println!("Could not enable the encrypted volume: {:?}", err), +    ///     Ok(()) => println!("Enabled the encrypted volume."), +    ///     Err(err) => println!("Could not enable the encrypted volume: {:?}", err),      /// };      /// #     Ok(())      /// # } @@ -562,13 +561,13 @@ impl Storage {      ///      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword -    pub fn enable_encrypted_volume(&self, user_pin: &str) -> CommandStatus { +    pub fn enable_encrypted_volume(&self, user_pin: &str) -> Result<(), CommandError> {          let user_pin = CString::new(user_pin);          if user_pin.is_err() { -            return CommandStatus::Error(CommandError::InvalidString); +            return Err(CommandError::InvalidString);          }          let user_pin = user_pin.unwrap(); -        unsafe { CommandStatus::from(nitrokey_sys::NK_unlock_encrypted_volume(user_pin.as_ptr())) } +        unsafe { get_command_result(nitrokey_sys::NK_unlock_encrypted_volume(user_pin.as_ptr())) }      }      /// Disables the encrypted storage volume. @@ -579,7 +578,6 @@ impl Storage {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus};      /// # use nitrokey::CommandError;      ///      /// fn use_volume() {} @@ -587,17 +585,17 @@ impl Storage {      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::Storage::connect()?;      /// match device.enable_encrypted_volume("123456") { -    ///     CommandStatus::Success => { +    ///     Ok(()) => {      ///         println!("Enabled the encrypted volume.");      ///         use_volume();      ///         match device.disable_encrypted_volume() { -    ///             CommandStatus::Success => println!("Disabled the encrypted volume."), -    ///             CommandStatus::Err(err) => { +    ///             Ok(()) => println!("Disabled the encrypted volume."), +    ///             Err(err) => {      ///                 println!("Could not disable the encrypted volume: {:?}", err);      ///             },      ///         };      ///     }, -    ///     CommandStatus::Error(err) => println!("Could not enable the encrypted volume: {:?}", err), +    ///     Err(err) => println!("Could not enable the encrypted volume: {:?}", err),      /// };      /// #     Ok(())      /// # } @@ -605,8 +603,8 @@ impl Storage {      ///      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`WrongPassword`]: enum.CommandError.html#variant.WrongPassword -    pub fn disable_encrypted_volume(&self) -> CommandStatus { -        unsafe { CommandStatus::from(nitrokey_sys::NK_lock_encrypted_volume()) } +    pub fn disable_encrypted_volume(&self) -> Result<(), CommandError> { +        unsafe { get_command_result(nitrokey_sys::NK_lock_encrypted_volume()) }      }  } @@ -37,7 +37,7 @@  //! Configure an HOTP slot:  //!  //! ```no_run -//! use nitrokey::{Authenticate, CommandStatus, ConfigureOtp, OtpMode, OtpSlotData}; +//! use nitrokey::{Authenticate, ConfigureOtp, OtpMode, OtpSlotData};  //! # use nitrokey::CommandError;  //!  //! # fn try_main() -> Result<(), (CommandError)> { @@ -46,8 +46,8 @@  //! match device.authenticate_admin("12345678") {  //!     Ok(admin) => {  //!         match admin.write_hotp_slot(slot_data, 0) { -//!             CommandStatus::Success => println!("Successfully wrote slot."), -//!             CommandStatus::Error(err) => println!("Could not write slot: {:?}", err), +//!             Ok(()) => println!("Successfully wrote slot."), +//!             Err(err) => println!("Could not write slot: {:?}", err),  //!         }  //!     },  //!     Err((_, err)) => println!("Could not authenticate as admin: {:?}", err), @@ -102,7 +102,7 @@ pub use config::Config;  pub use device::{connect, Device, DeviceWrapper, Pro, Storage};  pub use otp::{ConfigureOtp, GenerateOtp, OtpMode, OtpSlotData};  pub use pws::{GetPasswordSafe, PasswordSafe, SLOT_COUNT}; -pub use util::{CommandError, CommandStatus, LogLevel}; +pub use util::{CommandError, LogLevel};  /// Enables or disables debug output.  Calling this method with `true` is equivalent to setting the  /// log level to `Debug`; calling it with `false` is equivalent to the log level `Error` (see @@ -1,6 +1,6 @@  use nitrokey_sys;  use std::ffi::CString; -use util::{result_from_string, CommandError, CommandStatus}; +use util::{get_command_result, result_from_string, CommandError};  /// Modes for one-time password generation.  #[derive(Debug, PartialEq)] @@ -25,7 +25,7 @@ pub trait ConfigureOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{Authenticate, CommandStatus, ConfigureOtp, OtpMode, OtpSlotData}; +    /// use nitrokey::{Authenticate, ConfigureOtp, OtpMode, OtpSlotData};      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), (CommandError)> { @@ -34,8 +34,8 @@ pub trait ConfigureOtp {      /// match device.authenticate_admin("12345678") {      ///     Ok(admin) => {      ///         match admin.write_hotp_slot(slot_data, 0) { -    ///             CommandStatus::Success => println!("Successfully wrote slot."), -    ///             CommandStatus::Error(err) => println!("Could not write slot: {:?}", err), +    ///             Ok(()) => println!("Successfully wrote slot."), +    ///             Err(err) => println!("Could not write slot: {:?}", err),      ///         }      ///     },      ///     Err((_, err)) => println!("Could not authenticate as admin: {:?}", err), @@ -47,7 +47,7 @@ pub trait ConfigureOtp {      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`NoName`]: enum.CommandError.html#variant.NoName -    fn write_hotp_slot(&self, data: OtpSlotData, counter: u64) -> CommandStatus; +    fn write_hotp_slot(&self, data: OtpSlotData, counter: u64) -> Result<(), CommandError>;      /// Configure a TOTP slot with the given data and set the TOTP time window to the given value      /// (default 30). @@ -61,7 +61,7 @@ pub trait ConfigureOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{Authenticate, CommandStatus, ConfigureOtp, OtpMode, OtpSlotData}; +    /// use nitrokey::{Authenticate, ConfigureOtp, OtpMode, OtpSlotData};      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), (CommandError)> { @@ -70,8 +70,8 @@ pub trait ConfigureOtp {      /// match device.authenticate_admin("12345678") {      ///     Ok(admin) => {      ///         match admin.write_totp_slot(slot_data, 30) { -    ///             CommandStatus::Success => println!("Successfully wrote slot."), -    ///             CommandStatus::Error(err) => println!("Could not write slot: {:?}", err), +    ///             Ok(()) => println!("Successfully wrote slot."), +    ///             Err(err) => println!("Could not write slot: {:?}", err),      ///         }      ///     },      ///     Err((_, err)) => println!("Could not authenticate as admin: {:?}", err), @@ -83,7 +83,7 @@ pub trait ConfigureOtp {      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString      /// [`NoName`]: enum.CommandError.html#variant.NoName -    fn write_totp_slot(&self, data: OtpSlotData, time_window: u16) -> CommandStatus; +    fn write_totp_slot(&self, data: OtpSlotData, time_window: u16) -> Result<(), CommandError>;      /// Erases an HOTP slot.      /// @@ -94,7 +94,7 @@ pub trait ConfigureOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{Authenticate, CommandStatus, ConfigureOtp}; +    /// use nitrokey::{Authenticate, ConfigureOtp};      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), (CommandError)> { @@ -102,8 +102,8 @@ pub trait ConfigureOtp {      /// match device.authenticate_admin("12345678") {      ///     Ok(admin) => {      ///         match admin.erase_hotp_slot(1) { -    ///             CommandStatus::Success => println!("Successfully erased slot."), -    ///             CommandStatus::Error(err) => println!("Could not erase slot: {:?}", err), +    ///             Ok(()) => println!("Successfully erased slot."), +    ///             Err(err) => println!("Could not erase slot: {:?}", err),      ///         }      ///     },      ///     Err((_, err)) => println!("Could not authenticate as admin: {:?}", err), @@ -113,7 +113,7 @@ pub trait ConfigureOtp {      /// ```      ///      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot -    fn erase_hotp_slot(&self, slot: u8) -> CommandStatus; +    fn erase_hotp_slot(&self, slot: u8) -> Result<(), CommandError>;      /// Erases a TOTP slot.      /// @@ -124,7 +124,7 @@ pub trait ConfigureOtp {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{Authenticate, CommandStatus, ConfigureOtp}; +    /// use nitrokey::{Authenticate, ConfigureOtp};      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), (CommandError)> { @@ -132,8 +132,8 @@ pub trait ConfigureOtp {      /// match device.authenticate_admin("12345678") {      ///     Ok(admin) => {      ///         match admin.erase_totp_slot(1) { -    ///             CommandStatus::Success => println!("Successfully erased slot."), -    ///             CommandStatus::Error(err) => println!("Could not erase slot: {:?}", err), +    ///             Ok(()) => println!("Successfully erased slot."), +    ///             Err(err) => println!("Could not erase slot: {:?}", err),      ///         }      ///     },      ///     Err((_, err)) => println!("Could not authenticate as admin: {:?}", err), @@ -143,7 +143,7 @@ pub trait ConfigureOtp {      /// ```      ///      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot -    fn erase_totp_slot(&self, slot: u8) -> CommandStatus; +    fn erase_totp_slot(&self, slot: u8) -> Result<(), CommandError>;  }  /// Provides methods to generate OTP codes and to query OTP slots on a Nitrokey @@ -181,8 +181,8 @@ pub trait GenerateOtp {      ///      /// [`get_totp_code`]: #method.get_totp_code      /// [`Timestamp`]: enum.CommandError.html#variant.Timestamp -    fn set_time(&self, time: u64) -> CommandStatus { -        unsafe { CommandStatus::from(nitrokey_sys::NK_totp_set_time(time)) } +    fn set_time(&self, time: u64) -> Result<(), CommandError> { +        unsafe { get_command_result(nitrokey_sys::NK_totp_set_time(time)) }      }      /// Returns the name of the given HOTP slot. @@ -2,7 +2,7 @@ use device::{Device, DeviceWrapper, Pro, Storage};  use libc;  use nitrokey_sys;  use std::ffi::CString; -use util::{get_last_error, result_from_string, CommandError, CommandStatus}; +use util::{get_command_result, get_last_error, result_from_string, CommandError};  /// The number of slots in a [`PasswordSafe`][].  /// @@ -111,15 +111,12 @@ fn get_password_safe<'a>(          return Err(CommandError::InvalidString);      }      let user_pin_string = user_pin_string.unwrap(); -    let status = unsafe { -        CommandStatus::from(nitrokey_sys::NK_enable_password_safe( +    let result = unsafe { +        get_command_result(nitrokey_sys::NK_enable_password_safe(              user_pin_string.as_ptr(),          ))      }; -    match status { -        CommandStatus::Success => Ok(PasswordSafe { _device: device }), -        CommandStatus::Error(err) => Err(err), -    } +    result.map(|()| PasswordSafe { _device: device })  }  impl<'a> PasswordSafe<'a> { @@ -283,19 +280,25 @@ impl<'a> PasswordSafe<'a> {      ///      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot      /// [`InvalidString`]: enum.CommandError.html#variant.InvalidString -    pub fn write_slot(&self, slot: u8, name: &str, login: &str, password: &str) -> CommandStatus { +    pub fn write_slot( +        &self, +        slot: u8, +        name: &str, +        login: &str, +        password: &str, +    ) -> Result<(), CommandError> {          let name_string = CString::new(name);          let login_string = CString::new(login);          let password_string = CString::new(password);          if name_string.is_err() || login_string.is_err() || password_string.is_err() { -            return CommandStatus::Error(CommandError::InvalidString); +            return Err(CommandError::InvalidString);          }          let name_string = name_string.unwrap();          let login_string = login_string.unwrap();          let password_string = password_string.unwrap();          unsafe { -            CommandStatus::from(nitrokey_sys::NK_write_password_safe_slot( +            get_command_result(nitrokey_sys::NK_write_password_safe_slot(                  slot,                  name_string.as_ptr(),                  login_string.as_ptr(), @@ -314,23 +317,23 @@ impl<'a> PasswordSafe<'a> {      /// # Example      ///      /// ```no_run -    /// use nitrokey::{CommandStatus, GetPasswordSafe}; +    /// use nitrokey::GetPasswordSafe;      /// # use nitrokey::CommandError;      ///      /// # fn try_main() -> Result<(), CommandError> {      /// let device = nitrokey::connect()?;      /// let pws = device.get_password_safe("123456")?;      /// match pws.erase_slot(0) { -    ///     CommandStatus::Success => println!("Erased slot 0."), -    ///     CommandStatus::Error(err) => println!("Could not erase slot 0: {:?}", err), +    ///     Ok(()) => println!("Erased slot 0."), +    ///     Err(err) => println!("Could not erase slot 0: {:?}", err),      /// };      /// #     Ok(())      /// # }      /// ```      ///      /// [`InvalidSlot`]: enum.CommandError.html#variant.InvalidSlot -    pub fn erase_slot(&self, slot: u8) -> CommandStatus { -        unsafe { CommandStatus::from(nitrokey_sys::NK_erase_password_safe_slot(slot)) } +    pub fn erase_slot(&self, slot: u8) -> Result<(), CommandError> { +        unsafe { get_command_result(nitrokey_sys::NK_erase_password_safe_slot(slot)) }      }  } diff --git a/src/tests/device.rs b/src/tests/device.rs index 22423fa..60ca33a 100644 --- a/src/tests/device.rs +++ b/src/tests/device.rs @@ -2,7 +2,7 @@ use std::ffi::CStr;  use std::process::Command;  use std::{thread, time};  use tests::util::{Target, ADMIN_PASSWORD, USER_PASSWORD}; -use {Authenticate, CommandError, CommandStatus, Config, Device}; +use {Authenticate, CommandError, Config, Device, Storage};  static ADMIN_NEW_PASSWORD: &str = "1234567890";  static USER_NEW_PASSWORD: &str = "abcdefghij"; @@ -130,23 +130,20 @@ fn config() {      let device = Target::connect().unwrap();      let admin = device.authenticate_admin(ADMIN_PASSWORD).unwrap();      let config = Config::new(None, None, None, true); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      let get_config = admin.get_config().unwrap();      assert_eq!(config, get_config);      let config = Config::new(None, Some(9), None, true); -    assert_eq!( -        CommandStatus::Error(CommandError::InvalidSlot), -        admin.write_config(config) -    ); +    assert_eq!(Err(CommandError::InvalidSlot), admin.write_config(config));      let config = Config::new(Some(1), None, Some(0), false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      let get_config = admin.get_config().unwrap();      assert_eq!(config, get_config);      let config = Config::new(None, None, None, false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      let get_config = admin.get_config().unwrap();      assert_eq!(config, get_config);  } @@ -158,8 +155,11 @@ fn change_user_pin() {      let device = device.authenticate_user(USER_PASSWORD).unwrap().device();      let device = device.authenticate_user(USER_NEW_PASSWORD).unwrap_err().0; -    let result = device.change_user_pin(USER_PASSWORD, USER_NEW_PASSWORD); -    assert_eq!(CommandStatus::Success, result); +    assert!( +        device +            .change_user_pin(USER_PASSWORD, USER_NEW_PASSWORD) +            .is_ok() +    );      let device = device.authenticate_user(USER_PASSWORD).unwrap_err().0;      let device = device @@ -168,13 +168,16 @@ fn change_user_pin() {          .device();      let result = device.change_user_pin(USER_PASSWORD, USER_PASSWORD); -    assert_eq!(CommandStatus::Error(CommandError::WrongPassword), result); +    assert_eq!(Err(CommandError::WrongPassword), result); -    let result = device.change_user_pin(USER_NEW_PASSWORD, USER_PASSWORD); -    assert_eq!(CommandStatus::Success, result); +    assert!( +        device +            .change_user_pin(USER_NEW_PASSWORD, USER_PASSWORD) +            .is_ok() +    );      let device = device.authenticate_user(USER_PASSWORD).unwrap().device(); -    device.authenticate_user(USER_NEW_PASSWORD).unwrap_err(); +    assert!(device.authenticate_user(USER_NEW_PASSWORD).is_err());  }  #[test] @@ -184,8 +187,11 @@ fn change_admin_pin() {      let device = device.authenticate_admin(ADMIN_PASSWORD).unwrap().device();      let device = device.authenticate_admin(ADMIN_NEW_PASSWORD).unwrap_err().0; -    let result = device.change_admin_pin(ADMIN_PASSWORD, ADMIN_NEW_PASSWORD); -    assert_eq!(CommandStatus::Success, result); +    assert!( +        device +            .change_admin_pin(ADMIN_PASSWORD, ADMIN_NEW_PASSWORD) +            .is_ok() +    );      let device = device.authenticate_admin(ADMIN_PASSWORD).unwrap_err().0;      let device = device @@ -193,11 +199,16 @@ fn change_admin_pin() {          .unwrap()          .device(); -    let result = device.change_admin_pin(ADMIN_PASSWORD, ADMIN_PASSWORD); -    assert_eq!(CommandStatus::Error(CommandError::WrongPassword), result); +    assert_eq!( +        Err(CommandError::WrongPassword), +        device.change_admin_pin(ADMIN_PASSWORD, ADMIN_PASSWORD) +    ); -    let result = device.change_admin_pin(ADMIN_NEW_PASSWORD, ADMIN_PASSWORD); -    assert_eq!(CommandStatus::Success, result); +    assert!( +        device +            .change_admin_pin(ADMIN_NEW_PASSWORD, ADMIN_PASSWORD) +            .is_ok() +    );      let device = device.authenticate_admin(ADMIN_PASSWORD).unwrap().device();      device.authenticate_admin(ADMIN_NEW_PASSWORD).unwrap_err(); @@ -216,12 +227,13 @@ fn require_failed_user_login(device: Target, password: &str, error: CommandError  fn unlock_user_pin() {      let device = Target::connect().unwrap();      let device = device.authenticate_user(USER_PASSWORD).unwrap().device(); -    assert_eq!( -        CommandStatus::Success, -        device.unlock_user_pin(ADMIN_PASSWORD, USER_PASSWORD) +    assert!( +        device +            .unlock_user_pin(ADMIN_PASSWORD, USER_PASSWORD) +            .is_ok()      );      assert_eq!( -        CommandStatus::Error(CommandError::WrongPassword), +        Err(CommandError::WrongPassword),          device.unlock_user_pin(USER_PASSWORD, USER_PASSWORD)      ); @@ -232,12 +244,13 @@ fn unlock_user_pin() {      let device = require_failed_user_login(device, USER_PASSWORD, CommandError::WrongPassword);      assert_eq!( -        CommandStatus::Error(CommandError::WrongPassword), +        Err(CommandError::WrongPassword),          device.unlock_user_pin(USER_PASSWORD, USER_PASSWORD)      ); -    assert_eq!( -        CommandStatus::Success, -        device.unlock_user_pin(ADMIN_PASSWORD, USER_PASSWORD) +    assert!( +        device +            .unlock_user_pin(ADMIN_PASSWORD, USER_PASSWORD) +            .is_ok()      );      device.authenticate_user(USER_PASSWORD).unwrap();  } @@ -246,22 +259,19 @@ fn unlock_user_pin() {  #[cfg_attr(not(feature = "test-storage"), ignore)]  fn encrypted_volume() {      let device = Storage::connect().unwrap(); -    assert_eq!(CommandStatus::Success, device.lock()); +    assert!(device.lock().is_ok());      assert_eq!(1, count_nitrokey_block_devices()); -    assert_eq!(CommandStatus::Success, device.disable_encrypted_volume()); +    assert!(device.disable_encrypted_volume().is_ok());      assert_eq!(1, count_nitrokey_block_devices());      assert_eq!( -        CommandStatus::Error(CommandError::WrongPassword), +        Err(CommandError::WrongPassword),          device.enable_encrypted_volume("123")      );      assert_eq!(1, count_nitrokey_block_devices()); -    assert_eq!( -        CommandStatus::Success, -        device.enable_encrypted_volume(USER_PASSWORD) -    ); +    assert!(device.enable_encrypted_volume(USER_PASSWORD).is_ok());      assert_eq!(2, count_nitrokey_block_devices()); -    assert_eq!(CommandStatus::Success, device.disable_encrypted_volume()); +    assert!(device.disable_encrypted_volume().is_ok());      assert_eq!(1, count_nitrokey_block_devices());  } @@ -270,10 +280,7 @@ fn encrypted_volume() {  fn lock() {      let device = Storage::connect().unwrap(); -    assert_eq!( -        CommandStatus::Success, -        device.enable_encrypted_volume(USER_PASSWORD) -    ); -    assert_eq!(CommandStatus::Success, device.lock()); +    assert!(device.enable_encrypted_volume(USER_PASSWORD).is_ok()); +    assert!(device.lock().is_ok());      assert_eq!(1, count_nitrokey_block_devices());  } diff --git a/src/tests/otp.rs b/src/tests/otp.rs index 91f9f1b..cf71d9d 100644 --- a/src/tests/otp.rs +++ b/src/tests/otp.rs @@ -1,7 +1,6 @@  use std::ops::Deref;  use tests::util::{Target, ADMIN_PASSWORD, USER_PASSWORD}; -use {Admin, Authenticate, CommandError, CommandStatus, Config, ConfigureOtp, GenerateOtp, OtpMode, -     OtpSlotData}; +use {Admin, Authenticate, CommandError, Config, ConfigureOtp, GenerateOtp, OtpMode, OtpSlotData};  // test suite according to RFC 4226, Appendix D  static HOTP_SECRET: &str = "3132333435363738393031323334353637383930"; @@ -36,10 +35,7 @@ fn get_admin_test_device() -> Admin<Target> {  fn configure_hotp(admin: &ConfigureOtp, counter: u8) {      let slot_data = OtpSlotData::new(1, "test-hotp", HOTP_SECRET, OtpMode::SixDigits); -    assert_eq!( -        CommandStatus::Success, -        admin.write_hotp_slot(slot_data, counter.into()) -    ); +    assert!(admin.write_hotp_slot(slot_data, counter.into()).is_ok());  }  fn check_hotp_codes(device: &GenerateOtp, offset: u8) { @@ -56,7 +52,7 @@ fn check_hotp_codes(device: &GenerateOtp, offset: u8) {  fn hotp_no_pin() {      let admin = get_admin_test_device();      let config = Config::new(None, None, None, false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      configure_hotp(&admin, 0);      check_hotp_codes(admin.deref(), 0); @@ -73,7 +69,7 @@ fn hotp_no_pin() {  fn hotp_pin() {      let admin = get_admin_test_device();      let config = Config::new(None, None, None, true); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      configure_hotp(&admin, 0);      let user = admin.device().authenticate_user(USER_PASSWORD).unwrap(); @@ -87,7 +83,7 @@ fn hotp_pin() {  fn hotp_slot_name() {      let admin = get_admin_test_device();      let slot_data = OtpSlotData::new(1, "test-hotp", HOTP_SECRET, OtpMode::SixDigits); -    assert_eq!(CommandStatus::Success, admin.write_hotp_slot(slot_data, 0)); +    assert!(admin.write_hotp_slot(slot_data, 0).is_ok());      let device = admin.device();      let result = device.get_hotp_slot_name(1); @@ -102,12 +98,12 @@ fn hotp_error() {      let admin = get_admin_test_device();      let slot_data = OtpSlotData::new(1, "", HOTP_SECRET, OtpMode::SixDigits);      assert_eq!( -        CommandStatus::Error(CommandError::NoName), +        Err(CommandError::NoName),          admin.write_hotp_slot(slot_data, 0)      );      let slot_data = OtpSlotData::new(4, "test", HOTP_SECRET, OtpMode::SixDigits);      assert_eq!( -        CommandStatus::Error(CommandError::InvalidSlot), +        Err(CommandError::InvalidSlot),          admin.write_hotp_slot(slot_data, 0)      );      let code = admin.get_hotp_code(4); @@ -119,13 +115,13 @@ fn hotp_error() {  fn hotp_erase() {      let admin = get_admin_test_device();      let config = Config::new(None, None, None, false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      let slot_data = OtpSlotData::new(1, "test1", HOTP_SECRET, OtpMode::SixDigits); -    assert_eq!(CommandStatus::Success, admin.write_hotp_slot(slot_data, 0)); +    assert!(admin.write_hotp_slot(slot_data, 0).is_ok());      let slot_data = OtpSlotData::new(2, "test2", HOTP_SECRET, OtpMode::SixDigits); -    assert_eq!(CommandStatus::Success, admin.write_hotp_slot(slot_data, 0)); +    assert!(admin.write_hotp_slot(slot_data, 0).is_ok()); -    assert_eq!(CommandStatus::Success, admin.erase_hotp_slot(1)); +    assert!(admin.erase_hotp_slot(1).is_ok());      let device = admin.device();      let result = device.get_hotp_slot_name(1); @@ -139,10 +135,7 @@ fn hotp_erase() {  fn configure_totp(admin: &ConfigureOtp, factor: u64) {      let slot_data = OtpSlotData::new(1, "test-totp", TOTP_SECRET, OtpMode::EightDigits);      let time_window = 30u64.checked_mul(factor).unwrap(); -    assert_eq!( -        CommandStatus::Success, -        admin.write_totp_slot(slot_data, time_window as u16) -    ); +    assert!(admin.write_totp_slot(slot_data, time_window as u16).is_ok());  }  fn check_totp_codes(device: &GenerateOtp, factor: u64, timestamp_size: TotpTimestampSize) { @@ -153,7 +146,7 @@ fn check_totp_codes(device: &GenerateOtp, factor: u64, timestamp_size: TotpTimes              continue;          } -        assert_eq!(CommandStatus::Success, device.set_time(time)); +        assert!(device.set_time(time).is_ok());          let result = device.get_totp_code(1);          assert!(result.is_ok());          let result_code = result.unwrap(); @@ -171,7 +164,7 @@ fn totp_no_pin() {      // TODO: this test may fail due to bad timing --> find solution      let admin = get_admin_test_device();      let config = Config::new(None, None, None, false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      configure_totp(&admin, 1);      check_totp_codes(admin.deref(), 1, TotpTimestampSize::U32); @@ -191,7 +184,7 @@ fn totp_no_pin() {  fn totp_no_pin_64() {      let admin = get_admin_test_device();      let config = Config::new(None, None, None, false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      configure_totp(&admin, 1);      check_totp_codes(admin.deref(), 1, TotpTimestampSize::U64); @@ -209,7 +202,7 @@ fn totp_pin() {      // TODO: this test may fail due to bad timing --> find solution      let admin = get_admin_test_device();      let config = Config::new(None, None, None, true); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      configure_totp(&admin, 1);      let user = admin.device().authenticate_user(USER_PASSWORD).unwrap(); @@ -225,7 +218,7 @@ fn totp_pin() {  fn totp_pin_64() {      let admin = get_admin_test_device();      let config = Config::new(None, None, None, true); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      configure_totp(&admin, 1);      let user = admin.device().authenticate_user(USER_PASSWORD).unwrap(); @@ -239,7 +232,7 @@ fn totp_pin_64() {  fn totp_slot_name() {      let admin = get_admin_test_device();      let slot_data = OtpSlotData::new(1, "test-totp", TOTP_SECRET, OtpMode::EightDigits); -    assert_eq!(CommandStatus::Success, admin.write_totp_slot(slot_data, 0)); +    assert!(admin.write_totp_slot(slot_data, 0).is_ok());      let device = admin.device();      let result = device.get_totp_slot_name(1); @@ -255,12 +248,12 @@ fn totp_error() {      let admin = get_admin_test_device();      let slot_data = OtpSlotData::new(1, "", HOTP_SECRET, OtpMode::SixDigits);      assert_eq!( -        CommandStatus::Error(CommandError::NoName), +        Err(CommandError::NoName),          admin.write_hotp_slot(slot_data, 0)      );      let slot_data = OtpSlotData::new(4, "test", HOTP_SECRET, OtpMode::SixDigits);      assert_eq!( -        CommandStatus::Error(CommandError::InvalidSlot), +        Err(CommandError::InvalidSlot),          admin.write_hotp_slot(slot_data, 0)      );      let code = admin.get_hotp_code(4); @@ -272,13 +265,13 @@ fn totp_error() {  fn totp_erase() {      let admin = get_admin_test_device();      let config = Config::new(None, None, None, false); -    assert_eq!(CommandStatus::Success, admin.write_config(config)); +    assert!(admin.write_config(config).is_ok());      let slot_data = OtpSlotData::new(1, "test1", TOTP_SECRET, OtpMode::SixDigits); -    assert_eq!(CommandStatus::Success, admin.write_totp_slot(slot_data, 0)); +    assert!(admin.write_totp_slot(slot_data, 0).is_ok());      let slot_data = OtpSlotData::new(2, "test2", TOTP_SECRET, OtpMode::SixDigits); -    assert_eq!(CommandStatus::Success, admin.write_totp_slot(slot_data, 0)); +    assert!(admin.write_totp_slot(slot_data, 0).is_ok()); -    assert_eq!(CommandStatus::Success, admin.erase_totp_slot(1)); +    assert!(admin.erase_totp_slot(1).is_ok());      let device = admin.device();      let result = device.get_totp_slot_name(1); diff --git a/src/tests/pws.rs b/src/tests/pws.rs index 02e33cd..f581515 100644 --- a/src/tests/pws.rs +++ b/src/tests/pws.rs @@ -2,7 +2,7 @@ use device::Device;  use nitrokey_sys;  use pws::{GetPasswordSafe, PasswordSafe, SLOT_COUNT};  use tests::util::{Target, ADMIN_PASSWORD, USER_PASSWORD}; -use util::{result_from_string, CommandError, CommandStatus}; +use util::{result_from_string, CommandError};  fn get_pws(device: &Target) -> PasswordSafe {      device.get_password_safe(USER_PASSWORD).unwrap() @@ -28,17 +28,14 @@ fn drop() {      let device = Target::connect().unwrap();      {          let pws = get_pws(&device); -        assert_eq!( -            CommandStatus::Success, -            pws.write_slot(1, "name", "login", "password") -        ); +        assert!(pws.write_slot(1, "name", "login", "password").is_ok());          assert_eq!("name", pws.get_slot_name(1).unwrap());          let result = result_from_string(unsafe { nitrokey_sys::NK_get_password_safe_slot_name(1) });          assert_eq!(Ok(String::from("name")), result);      }      let result = result_from_string(unsafe { nitrokey_sys::NK_get_password_safe_slot_name(1) });      assert_eq!(Ok(String::from("name")), result); -    device.lock(); +    assert!(device.lock().is_ok());      let result = result_from_string(unsafe { nitrokey_sys::NK_get_password_safe_slot_name(1) });      assert_eq!(Err(CommandError::NotAuthorized), result);  } @@ -49,30 +46,19 @@ fn get_status() {      let device = Target::connect().unwrap();      let pws = get_pws(&device);      for i in 0..SLOT_COUNT { -        assert_eq!( -            CommandStatus::Success, -            pws.erase_slot(i), -            "Could not erase slot {}", -            i -        ); +        assert!(pws.erase_slot(i).is_ok(), "Could not erase slot {}", i);      }      let status = pws.get_slot_status().unwrap();      assert_eq!(status, [false; SLOT_COUNT as usize]); -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(1, "name", "login", "password") -    ); +    assert!(pws.write_slot(1, "name", "login", "password").is_ok());      let status = pws.get_slot_status().unwrap();      for i in 0..SLOT_COUNT {          assert_eq!(i == 1, status[i as usize]);      }      for i in 0..SLOT_COUNT { -        assert_eq!( -            CommandStatus::Success, -            pws.write_slot(i, "name", "login", "password") -        ); +        assert!(pws.write_slot(i, "name", "login", "password").is_ok());      }      let status = pws.get_slot_status().unwrap();      assert_eq!(status, [true; SLOT_COUNT as usize]); @@ -83,15 +69,12 @@ fn get_status() {  fn get_data() {      let device = Target::connect().unwrap();      let pws = get_pws(&device); -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(1, "name", "login", "password") -    ); +    assert!(pws.write_slot(1, "name", "login", "password").is_ok());      assert_eq!("name", pws.get_slot_name(1).unwrap());      assert_eq!("login", pws.get_slot_login(1).unwrap());      assert_eq!("password", pws.get_slot_password(1).unwrap()); -    assert_eq!(CommandStatus::Success, pws.erase_slot(1)); +    assert!(pws.erase_slot(1).is_ok());      // TODO: check error codes      assert_eq!(Err(CommandError::Unknown), pws.get_slot_name(1));      assert_eq!(Err(CommandError::Unknown), pws.get_slot_login(1)); @@ -100,10 +83,7 @@ fn get_data() {      let name = "with å";      let login = "pär@test.com";      let password = "'i3lJc[09?I:,[u7dWz9"; -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(1, name, login, password) -    ); +    assert!(pws.write_slot(1, name, login, password).is_ok());      assert_eq!(name, pws.get_slot_name(1).unwrap());      assert_eq!(login, pws.get_slot_login(1).unwrap());      assert_eq!(password, pws.get_slot_password(1).unwrap()); @@ -129,30 +109,21 @@ fn write() {      let pws = get_pws(&device);      assert_eq!( -        CommandStatus::Error(CommandError::InvalidSlot), +        Err(CommandError::InvalidSlot),          pws.write_slot(SLOT_COUNT, "name", "login", "password")      ); -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(0, "", "login", "password") -    ); +    assert!(pws.write_slot(0, "", "login", "password").is_ok());      assert_eq!(Err(CommandError::Unknown), pws.get_slot_name(0));      assert_eq!(Ok(String::from("login")), pws.get_slot_login(0));      assert_eq!(Ok(String::from("password")), pws.get_slot_password(0)); -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(0, "name", "", "password") -    ); +    assert!(pws.write_slot(0, "name", "", "password").is_ok());      assert_eq!(Ok(String::from("name")), pws.get_slot_name(0));      assert_eq!(Err(CommandError::Unknown), pws.get_slot_login(0));      assert_eq!(Ok(String::from("password")), pws.get_slot_password(0)); -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(0, "name", "login", "") -    ); +    assert!(pws.write_slot(0, "name", "login", "").is_ok());      assert_eq!(Ok(String::from("name")), pws.get_slot_name(0));      assert_eq!(Ok(String::from("login")), pws.get_slot_login(0));      assert_eq!(Err(CommandError::Unknown), pws.get_slot_password(0)); @@ -163,16 +134,10 @@ fn write() {  fn erase() {      let device = Target::connect().unwrap();      let pws = get_pws(&device); -    assert_eq!( -        CommandStatus::Error(CommandError::InvalidSlot), -        pws.erase_slot(SLOT_COUNT) -    ); +    assert_eq!(Err(CommandError::InvalidSlot), pws.erase_slot(SLOT_COUNT)); -    assert_eq!( -        CommandStatus::Success, -        pws.write_slot(0, "name", "login", "password") -    ); -    assert_eq!(CommandStatus::Success, pws.erase_slot(0)); -    assert_eq!(CommandStatus::Success, pws.erase_slot(0)); +    assert!(pws.write_slot(0, "name", "login", "password").is_ok()); +    assert!(pws.erase_slot(0).is_ok()); +    assert!(pws.erase_slot(0).is_ok());      assert_eq!(Err(CommandError::Unknown), pws.get_slot_name(0));  } diff --git a/src/util.rs b/src/util.rs index 364b0de..1608952 100644 --- a/src/util.rs +++ b/src/util.rs @@ -39,15 +39,6 @@ pub enum CommandError {      RngError,  } -/// Command execution status. -#[derive(Debug, PartialEq)] -pub enum CommandStatus { -    /// The command was successful. -    Success, -    /// An error occured during command execution. -    Error(CommandError), -} -  /// Log level for libnitrokey.  ///  /// Setting the log level to a lower level enables all output from higher levels too.  Currently, @@ -90,17 +81,22 @@ pub fn result_from_string(ptr: *const c_char) -> Result<String, CommandError> {      }  } -pub fn get_last_status() -> CommandStatus { -    unsafe { -        let status = nitrokey_sys::NK_get_last_command_status(); -        return CommandStatus::from(status as c_int); +pub fn get_command_result(value: c_int) -> Result<(), CommandError> { +    match value { +        0 => Ok(()), +        other => Err(CommandError::from(other)),      }  } +pub fn get_last_result() -> Result<(), CommandError> { +    let value = unsafe { nitrokey_sys::NK_get_last_command_status() } as c_int; +    get_command_result(value) +} +  pub fn get_last_error() -> CommandError { -    return match get_last_status() { -        CommandStatus::Success => CommandError::Unknown, -        CommandStatus::Error(err) => err, +    return match get_last_result() { +        Ok(()) => CommandError::Unknown, +        Err(err) => err,      };  } @@ -133,15 +129,6 @@ impl From<c_int> for CommandError {      }  } -impl From<c_int> for CommandStatus { -    fn from(value: c_int) -> Self { -        match value { -            0 => CommandStatus::Success, -            other => CommandStatus::Error(CommandError::from(other)), -        } -    } -} -  impl Into<i32> for LogLevel {      fn into(self) -> i32 {          match self { | 
