diff --git a/services/usb-cramium/Cargo.toml b/services/usb-cramium/Cargo.toml index ccbec2334..e2494565c 100644 --- a/services/usb-cramium/Cargo.toml +++ b/services/usb-cramium/Cargo.toml @@ -8,6 +8,7 @@ utralib = { version = "0.1.25", optional = true, default-features = false } xous-names = { package = "xous-api-names", version = "0.9.63" } ticktimer = { package = "xous-api-ticktimer", version = "0.9.61" } xous = "0.9.64" +xous-ipc = "0.10.2" log-server = { package = "xous-api-log", version = "0.1.61" } log = "0.4.14" num-derive = { version = "0.3.3", default-features = false } @@ -15,10 +16,25 @@ num-traits = { version = "0.2.14", default-features = false } cramium-hal = { path = "../../libs/cramium-hal", features = ["std"] } cram-hal-service = { path = "../cram-hal-service" } xous-usb-hid = { git = "https://github.com/betrusted-io/xous-usb-hid.git", branch = "main" } -ghostfat = "0.5.0" +rkyv = { version = "0.8.8", default-features = false, features = [ + "std", + "alloc", +] } +packed_struct = { version = "0.10", default-features = false } # used by the xous-usb-hid crate + +[dependencies.usb-device] +# see top level Cargo.toml for patch.crates-io directive to help with dev work +version = "0.2.8" +features = ["log"] locales = { path = "../../locales" } [features] -cramium-soc = ["utralib/cramium-soc"] -default = [] +cramium-soc = ["utralib/cramium-soc", "utralib/std"] +# none of these other modes are actually supported, but are listed here +# to allow direct re-use of API code +precursor = ["utralib/precursor", "utralib/std"] +hosted = ["utralib/hosted", "utralib/std"] +renode = ["utralib/renode", "utralib/std"] +mass-storage = [] +default = ["mass-storage"] diff --git a/services/usb-cramium/src/api.rs b/services/usb-cramium/src/api.rs new file mode 100644 index 000000000..10cbc4e0b --- /dev/null +++ b/services/usb-cramium/src/api.rs @@ -0,0 +1,212 @@ +// Note: the log server relies on this name not changing in order to hook the serial port for logging output. +// changing this name shouldn't lead to a crash, but it will lead to the USB driver being undiscoverable by +// the log crate. +pub(crate) const SERVER_NAME_USB_DEVICE: &'static str = "_Xous USB device driver_"; + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + /// Returns the link status + LinkStatus = 0, + /// Send a keyboard code + SendKeyCode = 1, + /// "Type" a string to the keyboard. This API is relied upon by the log crate. + SendString = 2, + /// Get the current LED state + GetLedState = 3, + /// Switch to a specified device core + SwitchCores = 4, + /// Makes sure a given core is selected + EnsureCore = 5, + /// Check which core is connected + WhichCore = 6, + /// Restrict the debug core + RestrictDebugAccess = 7, + /// Retrieve restriction state + IsRestricted = 8, + /// Set-and-check of USB debug restriction + DebugUsbOp = 9, + /// Set autotype rate + SetAutotypeRate = 10, + /// Register a USB event observer + RegisterUsbObserver = 11, + /// Modify log level + SetLogLevel = 12, + + /// Send a U2F message + U2fTx = 128, + /// Blocks the caller, waiting for a U2F message + U2fRxDeferred = 129, + /// A bump from the timeout process to check if U2fRx has timed out + U2fRxTimeout = 130, + + /// Query if the HID driver was able to start + IsSocCompatible = 256, + + /// Hook serial ASCII listener + SerialHookAscii = 512, + /// Hook serial binary listener + SerialHookBinary = 513, + /// Flush any serial buffers + SerialFlush = 514, + /// Hook eager serial sender for TRNG output. This will not succeed if hooked for console mode already. + SerialHookTrngSender = 515, + /// Hook serial to the console input + SerialHookConsole = 516, + /// Clear any hooks + SerialClearHooks = 517, + /// TRNG send poll + SerialTrngPoll = 518, + + #[cfg(feature = "mass-storage")] + SetBlockDevice = 1024, + #[cfg(feature = "mass-storage")] + SetBlockDeviceSID = 1025, + #[cfg(feature = "mass-storage")] + ResetBlockDevice = 1026, + + // HIDv2 + /// Read a HID report + HIDReadReport = 1027, + + /// Write a HID report + HIDWriteReport = 1028, + + /// Set the HID descriptor to be pushed to the USB host + HIDSetDescriptor = 1029, + + /// Unset HID descriptor and reset HIDv2 state + HIDUnsetDescriptor = 1030, + + /// Handle the USB interrupt + UsbIrqHandler = 2048, + /// Suspend/resume callback + #[cfg(any(feature = "renode", feature = "precursor", feature = "hosted"))] + SuspendResume = 2049, + /// Exits the server + Quit = 4096, + + /// API used by the logging crate. The number is hard-coded; don't change it. + LogString = 8192, +} + +// The log crate depends on this API not changing. +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Clone)] +pub struct UsbString { + pub s: String, + pub sent: Option, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct U2fMsgIpc { + /// All U2F protocol messages are 64 bytes + pub data: [u8; 64], + /// Encodes the state of the message + pub code: U2fCode, + /// Specifies an optional timeout + pub timeout_ms: Option, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone, Eq, PartialEq)] +pub enum U2fCode { + Tx, + TxAck, + RxWait, + RxAck, + RxTimeout, + Hangup, + Denied, +} + +#[derive(Eq, PartialEq, Copy, Clone)] +#[repr(usize)] +pub enum UsbDeviceType { + Debug = 0, + FidoKbd = 1, + Fido = 2, + MassStorage = 3, + Serial = 4, + HIDv2 = 5, +} +use std::convert::TryFrom; + +impl TryFrom for UsbDeviceType { + type Error = &'static str; + + fn try_from(value: usize) -> Result { + match value { + 0 => Ok(UsbDeviceType::Debug), + 1 => Ok(UsbDeviceType::FidoKbd), + 2 => Ok(UsbDeviceType::Fido), + 3 => Ok(UsbDeviceType::MassStorage), + 4 => Ok(UsbDeviceType::Serial), + 5 => Ok(UsbDeviceType::HIDv2), + _ => Err("Invalid UsbDeviceType specifier"), + } + } +} + +pub const SERIAL_BINARY_BUFLEN: usize = 128; +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Clone)] +pub struct UsbSerialAscii { + pub s: String, + pub delimiter: Option, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct UsbSerialBinary { + pub d: [u8; SERIAL_BINARY_BUFLEN], + pub len: usize, +} + +pub const MAX_HID_REPORT_DESCRIPTOR_LEN: usize = 1024; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct HIDReportDescriptorMessage { + pub descriptor: [u8; MAX_HID_REPORT_DESCRIPTOR_LEN], + pub len: usize, +} + +#[derive(Copy, Clone, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +#[repr(C, align(8))] +pub struct HIDReport(pub [u8; 64]); + +impl Default for HIDReport { + fn default() -> Self { return Self([0u8; 64]) } +} + +#[derive(Debug, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct HIDReportMessage { + pub data: Option, +} + +/// this structure is used to register a USB listener. +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Clone)] +pub(crate) struct UsbListenerRegistration { + pub server_name: String, + pub listener_op_id: usize, +} + +#[derive(Debug, Eq, PartialEq, Copy, Clone)] +#[repr(usize)] +pub enum LogLevel { + Trace = 0, + Debug = 1, + Info = 2, + Warn = 3, + Err = 4, +} + +impl TryFrom for LogLevel { + type Error = &'static str; + + fn try_from(value: usize) -> Result { + match value { + 0 => Ok(LogLevel::Trace), + 1 => Ok(LogLevel::Debug), + 2 => Ok(LogLevel::Info), + 3 => Ok(LogLevel::Warn), + 4 => Ok(LogLevel::Err), + _ => Err("Invalid LogLevel"), + } + } +} diff --git a/services/usb-cramium/src/lib.rs b/services/usb-cramium/src/lib.rs new file mode 100644 index 000000000..87a1bafe9 --- /dev/null +++ b/services/usb-cramium/src/lib.rs @@ -0,0 +1,377 @@ +#![cfg_attr(target_os = "none", no_std)] + +use cram_hal_service::trng; + +pub mod api; +pub use api::*; +use num_traits::*; +use packed_struct::PackedStruct; +use rkyv::option::ArchivedOption; +use trng::api::TrngTestMode; +pub use usb_device::device::UsbDeviceState; +use xous::{CID, Message, send_message}; +use xous_ipc::Buffer; +pub use xous_usb_hid::device::fido::RawFidoReport; +pub use xous_usb_hid::device::keyboard::KeyboardLedsReport; +pub use xous_usb_hid::page::Keyboard as UsbKeyCode; + +#[derive(Debug)] +pub struct UsbHid { + conn: CID, +} +impl UsbHid { + pub fn new() -> Self { + let xns = xous_names::XousNames::new().expect("couldn't connect to XousNames"); + REFCOUNT.fetch_add(1, Ordering::Relaxed); + let conn = xns + .request_connection_blocking(api::SERVER_NAME_USB_DEVICE) + .expect("Can't connect to USB device server"); + UsbHid { conn } + } + + pub fn set_block_device(&self, read_id: usize, write_id: usize, max_lba_id: usize) { + send_message( + self.conn, + Message::new_blocking_scalar( + Opcode::SetBlockDevice.to_usize().unwrap(), + read_id, + write_id, + max_lba_id, + 0, + ), + ) + .unwrap(); + } + + pub fn set_block_device_sid(&self, app_sid: xous::SID) { + let sid = app_sid.to_u32(); + send_message( + self.conn, + Message::new_blocking_scalar( + Opcode::SetBlockDeviceSID.to_usize().unwrap(), + sid.0 as usize, + sid.1 as usize, + sid.2 as usize, + sid.3 as usize, + ), + ) + .unwrap(); + } + + pub fn reset_block_device(&self) { + send_message( + self.conn, + Message::new_blocking_scalar(Opcode::ResetBlockDevice.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); + } + + /// used to query if the HID core was able to start. Mainly to handle edge cases between updates. + pub fn is_soc_compatible(&self) -> bool { true } + + /// this will always trigger a reset, even if it's the same core we're switching to + pub fn switch_to_core(&self, _core: UsbDeviceType) -> Result<(), xous::Error> { Ok(()) } + + /// this will not trigger a reset if we're already on the requested core + pub fn ensure_core(&self, _core: UsbDeviceType) -> Result<(), xous::Error> { Ok(()) } + + pub fn get_current_core(&self) -> Result { Ok(UsbDeviceType::FidoKbd) } + + pub fn restrict_debug_access(&self, _restrict: bool) -> Result<(), xous::Error> { Ok(()) } + + pub fn is_debug_restricted(&self) -> Result { Ok(true) } + + // if do_lock is Some(), set the debug USB lock status to locked if true, unlocked if false + // returns a tuple of (bool, bool) -> (is_locked, force_update) + // needs_update is so that the polling function knows to redraw the UX after a resume-from-suspend + pub fn debug_usb(&self, _do_lock: Option) -> Result<(bool, bool), xous::Error> { Ok((true, false)) } + + pub fn status(&self) -> UsbDeviceState { + match send_message( + self.conn, + Message::new_blocking_scalar(Opcode::LinkStatus.to_usize().unwrap(), 0, 0, 0, 0), + ) { + Ok(xous::Result::Scalar1(code)) => match code { + 0 => UsbDeviceState::Default, + 1 => UsbDeviceState::Addressed, + 2 => UsbDeviceState::Configured, + 3 => UsbDeviceState::Suspend, + _ => panic!("Internal error: illegal status code"), + }, + _ => panic!("Internal error: illegal return type"), + } + } + + /// Sends up to three keyboard codes at once as defined by USB HID usage tables; + /// see See [Universal Serial Bus (USB) HID Usage Tables Version 1.12](): + /// If the vector is empty, you get an all-key-up situation + pub fn send_keycode(&self, code: Vec, auto_keyup: bool) -> Result<(), xous::Error> { + if code.len() > 3 { + log::warn!("Excess keycodes ignored"); + } + match send_message( + self.conn, + Message::new_blocking_scalar( + Opcode::SendKeyCode.to_usize().unwrap(), + if code.len() >= 1 { code[0] as usize } else { 0 }, + if code.len() >= 2 { code[1] as usize } else { 0 }, + if code.len() >= 3 { code[2] as usize } else { 0 }, + if auto_keyup { 1 } else { 0 }, + ), + ) { + Ok(xous::Result::Scalar1(code)) => { + match code { + 0 => Ok(()), + // indicates that we aren't connected to a host to send characters + _ => Err(xous::Error::UseBeforeInit), + } + } + _ => Err(xous::Error::UseBeforeInit), + } + } + + /// This will attempt to send a string using an API based on the currently connected device + /// If it's a Keyboard, it will "type" it; if it's a UART, it will just blast it out the Tx. + pub fn send_str(&self, s: &str) -> Result { + let serializer = UsbString { s: String::from(s), sent: None }; + let mut buf = Buffer::into_buf(serializer).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::SendString.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + let returned = buf.to_original::().or(Err(xous::Error::InternalError))?; + match returned.sent { + Some(sent) => Ok(sent as usize), + // indicate that probably the USB was not connected + None => Err(xous::Error::UseBeforeInit), + } + } + + /// Sets the autotype delay. Defaults to 30ms on boot, must be reset every time on reboot. + pub fn set_autotype_delay_ms(&self, rate: usize) { + send_message( + self.conn, + Message::new_scalar(Opcode::SetAutotypeRate.to_usize().unwrap(), rate, 0, 0, 0), + ) + .unwrap(); // just unwrap it. If the send fails, we want to see the panic at this spot! + } + + pub fn get_led_state(&self) -> Result { + match send_message( + self.conn, + Message::new_blocking_scalar(Opcode::GetLedState.to_usize().unwrap(), 0, 0, 0, 0), + ) { + Ok(xous::Result::Scalar1(code)) => match KeyboardLedsReport::unpack(&[code as u8]) { + Ok(r) => Ok(r), + Err(_) => Err(xous::Error::InternalError), + }, + _ => panic!("Internal error: illegal return type"), + } + } + + pub fn u2f_wait_incoming(&self) -> Result { + let req = U2fMsgIpc { data: [0; 64], code: U2fCode::RxWait, timeout_ms: None }; + let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + let ack = buf.to_original::().unwrap(); + match ack.code { + U2fCode::RxAck => { + let mut u2fmsg = RawFidoReport::default(); + u2fmsg.packet.copy_from_slice(&ack.data); + Ok(u2fmsg) + } + U2fCode::Hangup => Err(xous::Error::ProcessTerminated), + U2fCode::RxTimeout => Err(xous::Error::Timeout), + _ => Err(xous::Error::InternalError), + } + } + + /// Note: this variant is not tested. + pub fn u2f_wait_incoming_timeout(&self, timeout_ms: u64) -> Result { + let req = U2fMsgIpc { data: [0; 64], code: U2fCode::RxWait, timeout_ms: Some(timeout_ms) }; + let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + let ack = buf.to_original::().unwrap(); + match ack.code { + U2fCode::RxAck => { + let mut u2fmsg = RawFidoReport::default(); + u2fmsg.packet.copy_from_slice(&ack.data); + Ok(u2fmsg) + } + U2fCode::Hangup => Err(xous::Error::ProcessTerminated), + U2fCode::RxTimeout => Err(xous::Error::Timeout), + _ => Err(xous::Error::InternalError), + } + } + + pub fn u2f_send(&self, msg: RawFidoReport) -> Result<(), xous::Error> { + let mut req = U2fMsgIpc { data: [0; 64], code: U2fCode::Tx, timeout_ms: None }; + req.data.copy_from_slice(&msg.packet); + let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::U2fTx.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + let ack = buf.to_original::().unwrap(); + match ack.code { + U2fCode::TxAck => Ok(()), + U2fCode::Denied => Err(xous::Error::AccessDenied), + _ => Err(xous::Error::InternalError), + } + } + + /// Blocks until an ASCII string terminated by `delimiter` is received on serial; if `None`, it + /// will return as soon as a character (or series of characters) have been received (thus the return + /// `String` will be piecemeal) + pub fn serial_wait_ascii(&self, delimiter: Option) -> String { + let req = UsbSerialAscii { s: String::new(), delimiter }; + let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); + buf.lend_mut(self.conn, Opcode::SerialHookAscii.to_u32().unwrap()) + .or(Err(xous::Error::InternalError)) + .expect("Internal error"); + let resp = buf.to_original::().unwrap(); + resp.s + } + + /// Blocks until enough binary data has been received to fill the buffer + /// Another thread can be used to call serial_flush() if we don't want to + /// block forever and we're receiving small amounts of binary data. + pub fn serial_wait_binary(&self) -> Vec { + let req = UsbSerialBinary { d: [0u8; SERIAL_BINARY_BUFLEN], len: 0 }; + let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); + buf.lend_mut(self.conn, Opcode::SerialHookBinary.to_u32().unwrap()) + .or(Err(xous::Error::InternalError)) + .expect("Internal error"); + let resp = buf.to_original::().unwrap(); + resp.d[..resp.len].to_vec() + } + + /// Non-blocking call that issues a serial flush command to the USB stack + pub fn serial_flush(&self) -> Result<(), xous::Error> { + send_message(self.conn, Message::new_scalar(Opcode::SerialFlush.to_usize().unwrap(), 0, 0, 0, 0)) + .map(|_| ()) + } + + /// Inject serial input over USB to the debug console. Dangerous! + /// This will also override/discard any existing hooked listeners. + pub fn serial_console_input_injection(&self) { + send_message( + self.conn, + Message::new_scalar(Opcode::SerialHookConsole.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); + } + + pub fn serial_clear_input_hooks(&self) { + send_message( + self.conn, + Message::new_scalar(Opcode::SerialClearHooks.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); + } + + /// Tries to set the serial port in TRNG mode. Will silently fail if already in console mode. + pub fn serial_set_trng_mode(&self, mode: TrngTestMode) { + send_message( + self.conn, + Message::new_scalar( + Opcode::SerialHookTrngSender.to_usize().unwrap(), + mode.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) + .unwrap(); + } + + pub fn register_u2f_observer(&self, server_name: &str, action_opcode: usize) { + let kr = + UsbListenerRegistration { server_name: String::from(server_name), listener_op_id: action_opcode }; + let buf = Buffer::into_buf(kr).unwrap(); + buf.lend(self.conn, Opcode::RegisterUsbObserver.to_u32().unwrap()) + .expect("couldn't register listener"); + } + + /// Sets the userland application HID device descriptor. + /// It cannot be longer than 1024 bytes. + pub fn connect_hid_app(&self, descriptor: Vec) -> Result<(), xous::Error> { + if descriptor.len() > MAX_HID_REPORT_DESCRIPTOR_LEN { + return Err(xous::Error::OutOfMemory); + } + + let mut container = HIDReportDescriptorMessage { + descriptor: [0u8; MAX_HID_REPORT_DESCRIPTOR_LEN], + len: descriptor.len(), + }; + + for (place, element) in container.descriptor.iter_mut().zip(descriptor.iter()) { + *place = *element; + } + + let mut buf = Buffer::into_buf(container).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::HIDSetDescriptor.to_u32().unwrap()).map(|_| ())?; + + Ok(()) + } + + /// Unset the userland application HID device descriptor and discards the cached + /// reports. + pub fn disconnect_hid_app(&self) -> Result<(), xous::Error> { + match send_message( + self.conn, + Message::new_blocking_scalar(Opcode::HIDUnsetDescriptor.to_usize().unwrap(), 0, 0, 0, 0), + ) { + Ok(_) => Ok(()), + Err(err) => Err(err), + } + } + + /// Reads a HID report off the USB bus. + pub fn read_report(&self) -> Result { + let report = HIDReportMessage::default(); + + let mut buf = Buffer::into_buf(report).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::HIDReadReport.to_u32().unwrap()).map(|_| ())?; + + let report = buf.as_flat::().unwrap(); + + match &report.data { + ArchivedOption::Some(data) => { + let mut ret = HIDReport::default(); + + for (&s, d) in data.0[..data.0.len() as usize].iter().zip(ret.0.iter_mut()) { + *d = s; + } + + Ok(ret) + } + ArchivedOption::None => Err(xous::Error::UnknownError), + } + } + + /// Writes a HID report on the USB bus. + pub fn write_report(&self, report: HIDReport) -> Result<(), xous::Error> { + let buf = Buffer::into_buf(report).or(Err(xous::Error::InternalError))?; + buf.lend(self.conn, Opcode::HIDWriteReport.to_u32().unwrap()).map(|_| ())?; + + Ok(()) + } + + /// Attempts to set the logging level of the USB server + pub fn set_log_level(&self, level: LogLevel) { + send_message( + self.conn, + Message::new_scalar(Opcode::SetLogLevel.to_usize().unwrap(), level as usize, 0, 0, 0), + ) + .unwrap(); + } +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for UsbHid { + fn drop(&mut self) { + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { + unsafe { + xous::disconnect(self.conn).unwrap(); + } + } + } +}