From 9df0f3bd565dfbf8c97d02969a17504c688bf381 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Mon, 18 Feb 2019 21:36:31 +0000 Subject: Refactor command execution into commands module This patch refactors the command execution. A command is represented by a struct implementing the Command trait. The enum_cmd macro is used to generate a mapping from the CommandId enum to a Command instance and to execute the command. The request and response data is manually converted from and to raw byte slices. As we do not have a standard library, we cannot create a Box from a CommandId. Instead, we directly delegate the execute method to the corresponding Command. --- src/device.rs | 49 ++----------------------------------------------- 1 file changed, 2 insertions(+), 47 deletions(-) (limited to 'src/device.rs') diff --git a/src/device.rs b/src/device.rs index a6bf9bf..300ce56 100644 --- a/src/device.rs +++ b/src/device.rs @@ -4,13 +4,13 @@ use usb_device::bus::{UsbBus, UsbBusAllocator}; use usb_device::device::{UsbDevice, UsbDeviceBuilder, UsbVidPid}; +use crate::commands::{CommandId, COMMAND_LEN}; use crate::hid::{HidDevice, Protocol, ReportType, Subclass}; use crate::util::TryFrom; const VID_CLAY_LOGIC: u16 = 0x20a0; const PID_NITROKEY_PRO: u16 = 0x4108; -const COMMAND_LEN: usize = 53; const REPORT_LEN: usize = 64; const REPORT_DESCRIPTOR: &[u8] = &[ 0x05, 0x01, 0x09, 0x06, 0xA1, 0x01, 0x05, 0x07, 0x19, 0xE0, 0x29, 0xE7, 0x15, 0x00, 0x25, 0x01, @@ -47,14 +47,6 @@ enum_u8! { } } -enum_u8! { - #[derive(Clone, Copy, Debug, PartialEq)] - pub enum CommandId { - GetStatus = 0, - ReadSlotName = 2, - } -} - pub struct Nitrokey { buf: [u8; REPORT_LEN], } @@ -65,43 +57,6 @@ impl Nitrokey { buf: [0; REPORT_LEN], } } - - fn execute_command(&self, command_id: CommandId, data: &[u8], buf: &mut [u8]) -> CommandStatus { - let data: &[u8] = match command_id { - CommandId::GetStatus => { - &[ - 1, // firmware_version_st.minor - 0, // firmware_version_st.major - 0, // card_serial[0] - 0, // card_serial[1] - 0, // card_serial[2] - 0, // card_serial[3] - 0, // numlock - 0, // capslock - 0, // enable_user_password - 0, // delete_user_password - ] - } - CommandId::ReadSlotName => { - assert!(data.len() > 1); - let slot_number = data[0]; - if slot_number != 0x20 { - return CommandStatus::SlotNotProgrammed; - } - - &[ - 0x74, // t - 0x65, // e - 0x73, // s - 0x74, // t - 0x00, // NULL - ] - } - }; - assert!(buf.len() >= data.len()); - buf[..data.len()].copy_from_slice(data); - CommandStatus::Ok - } } impl HidDevice for Nitrokey { @@ -131,7 +86,7 @@ impl HidDevice for Nitrokey { let device_status = DeviceStatus::Ok; let command_id = self.buf[0]; let command_status = if let Ok(command_id) = CommandId::try_from(command_id) { - self.execute_command(command_id, &self.buf[1..60], &mut buf) + command_id.execute(&self.buf[1..60], &mut buf) } else { CommandStatus::UnknownCommand }; -- cgit v1.2.1