summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlon Levy <alevy@redhat.com>2010-07-05 21:07:51 +0300
committerAlon Levy <alevy@redhat.com>2010-07-25 13:30:17 +0300
commit26beef0cfab874a0be275f021a645190f769c56a (patch)
treec34de50cbbbbb11cf92bb337c761091fa62c5bfb
parent19ee79090a331fe6c4ea6e01038990c4db2d901d (diff)
usb-ccid: initial commit. device doesn't crash under fedora 64. openct sees it.
-rw-r--r--hw/usb-ccid.c759
-rwxr-xr-xtests/test_ccid.py51
2 files changed, 810 insertions, 0 deletions
diff --git a/hw/usb-ccid.c b/hw/usb-ccid.c
new file mode 100644
index 000000000..a59049d80
--- /dev/null
+++ b/hw/usb-ccid.c
@@ -0,0 +1,759 @@
+/*
+ * CCID Device emulation
+ *
+ * Copyright (c) 2006 CodeSourcery.
+ * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
+ * Copyright (c) 2010 Red Hat.
+ * Written by Paul Brook, reused for FTDI by Samuel Thibault,
+ * reused for CCID by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include "qemu-common.h"
+#include "qemu-error.h"
+#include "usb.h"
+#include "qemu-char.h"
+
+#include "scard_common.h"
+
+#define DEBUG_CCID
+
+#ifdef DEBUG_CCID
+#define DPRINTF(fmt, ...) \
+do { printf("usb-ccid: " fmt , ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...) do {} while(0)
+#endif
+
+#define RECV_BUF 384
+
+#define DeviceOutVendor ((USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_DEVICE)<<8)
+#define DeviceInVendor ((USB_DIR_IN |USB_TYPE_VENDOR|USB_RECIP_DEVICE)<<8)
+
+#define CCID_CONTROL_ABORT 0x1
+#define CCID_CONTROL_GET_CLOCK_FREQUENCIES 0x2
+#define CCID_CONTROL_GET_DATA_RATES 0x3
+
+#define IMPERSONATE_ATHENA
+#ifdef IMPERSONATE_ATHENA
+#define CCID_PRODUCT_DESCRIPTION "ASEDrive CCID"
+#define CCID_VENDOR_DESCRIPTION "QEMU " QEMU_VERSION
+#define CCID_INTERFACE_NAME "CCID Interface"
+#define CCID_SERIAL_NUMBER_STRING "ASE016"
+#else
+#define CCID_PRODUCT_DESCRIPTION "QEMU USB CCID"
+#define CCID_VENDOR_DESCRIPTION "QEMU " QEMU_VERSION
+#define CCID_INTERFACE_NAME "CCID Interface"
+#define CCID_SERIAL_NUMBER_STRING "1"
+#endif
+
+// BULK_OUT messages from PC to Reader
+// Defined in CCID Rev 1.1 6.1 (page 26)
+#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn 0x62
+#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff 0x63
+#define CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus 0x65
+#define CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock 0x6f
+#define CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters 0x6c
+#define CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters 0x6d
+#define CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters 0x61
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Escape 0x6b
+#define CCID_MESSAGE_TYPE_PC_to_RDR_IccClock 0x6e
+#define CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU 0x6a
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Secure 0x69
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical 0x71
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Abort 0x72
+#define CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency 0x73
+
+// BULK_IN messages from Reader to PC
+// Defined in CCID Rev 1.1 6.2 (page 48)
+#define CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock 0x80
+#define CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus 0x81
+#define CCID_MESSAGE_TYPE_RDR_to_PC_Parameters 0x82
+#define CCID_MESSAGE_TYPE_RDR_to_PC_Escape 0x83
+#define CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency 0x84
+
+// INTERRUPT_IN messages from Reader to PC
+// Defined in CCID Rev 1.1 6.3 (page 56)
+#define CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange 0x50
+#define CCID_MESSAGE_TYPE_RDR_to_PC_HardwareError 0x51
+
+// Endpoints for CCID - addresses are up to us to decide.
+// To support slot insertion and removal we must have an interrupt in ep
+// in addition we need a bulk in and bulk out ep
+// 5.2, page 20
+#define CCID_INT_IN_EP 1
+#define CCID_BULK_IN_EP 2
+#define CCID_BULK_OUT_EP 3
+
+// bmSlotICCState masks
+#define SLOT_0_STATE_MASK 1
+#define SLOT_0_CHANGED_MASK 2
+
+typedef struct __attribute__ ((__packed__)) {
+ uint8_t bMessageType;
+ uint32_t dwLength;
+ uint8_t bSlot;
+ uint8_t bSeq;
+} CCID_Header;
+
+typedef struct __attribute__ ((__packed__)) {
+ CCID_Header hdr;
+ uint8_t bStatus; // Only used in BULK_IN
+ uint8_t bError; // Only used in BULK_IN
+} CCID_BULK_IN;
+
+typedef struct __attribute__ ((__packed__)) {
+ CCID_BULK_IN b;
+ uint8_t bClockStatus;
+} CCID_SlotStatus;
+
+typedef struct __attribute__ ((__packed__)) {
+ CCID_BULK_IN b;
+ uint8_t bChainParameter;
+ // here starts the data part
+} CCID_DataBlock;
+
+// 6.1.4 PC_to_RDR_XfrBlock
+typedef struct __attribute__ ((__packed__)) {
+ CCID_Header hdr;
+ uint8_t bBWI; // Block Waiting Timeout
+ uint16_t wLevelParameter;
+ // here starts the data part
+} CCID_XferBlock;
+
+typedef struct __attribute__ ((__packed__)) {
+ CCID_Header hdr;
+ uint8_t bPowerSelect;
+ uint16_t abRFU;
+} CCID_IccPowerOn;
+
+typedef struct {
+ uint8_t bMessageType; // CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange
+ uint8_t bmSlotICCState;
+} CCID_Notify_Slot_Change;
+
+typedef struct {
+ USBDevice dev;
+ uint8_t recv_buf[RECV_BUF];
+ uint16_t recv_ptr;
+ uint16_t recv_used;
+ CharDriverState *cs;
+ uint8_t bmSlotICCState;
+ bool notify_slot_change;
+ uint8_t answer_slot; // used for DataBlock response to XferBlock
+ uint8_t answer_seq; // ditto
+} USBCCIDState;
+
+/* Slot specific variables. We emulate a single slot card reader.
+ */
+
+uint8_t DEFAULT_ATR[] = {
+// From some example somewhere
+// 0x3B, 0xB0, 0x18, 0x00, 0xD1, 0x81, 0x05, 0xB1, 0x40, 0x38, 0x1F, 0x03, 0x28
+
+// From an Athena smart card
+ 0x3B, 0xD5, 0x18, 0xFF, 0x80, 0x91, 0xFE, 0x1F, 0xC3, 0x80, 0x73, 0xC8, 0x21, 0x13, 0x08
+
+}; // maximum size of ATR - from 7816-3
+
+#define MAX_ATR_SIZE 40
+uint8_t atr[MAX_ATR_SIZE];
+uint8_t atr_length;
+
+/* CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
+ * "USB Device Framework", section 9.6.1, in the Universal Serial Bus Specification.
+ *
+ * This device implemented based on the spec and with an Athena Smart Card Reader
+ * as reference:
+ * 0dc3:1004 Athena Smartcard Solutions, Inc.
+ */
+
+static const uint8_t qemu_ccid_dev_descriptor[] = {
+ 0x12, /* u8 bLength; */
+ USB_DT_DEVICE, /* u8 bDescriptorType; Device */
+ 0x10, 0x01, /* u16 bcdUSB; v1.1 */
+
+ 0x00, /* u8 bDeviceClass; */
+ 0x00, /* u8 bDeviceSubClass; */
+ 0x00, /* u8 bDeviceProtocol; [ low/full speeds only ] */
+ 0x40, /* u8 bMaxPacketSize0; 8 Bytes (valid: 8,16,32,64) */
+
+ /* Vendor and product id are arbitrary. */
+ 0xc3, 0x0d, /* u16 idVendor; Taken from usb-serial,
+ * using Athena - 0dc3 */
+ 0x04, 0x10, /* u16 idProduct; using Athena Smartcard Reader II 1004 */
+ 0x01, 0x00, /* u16 bcdDevice; version.
+ * update whenever a change is done. */
+ 0x01, /* u8 iManufacturer; */
+ 0x02, /* u8 iProduct; */
+ 0x03, /* u8 iSerialNumber; */
+ 0x01, /* u8 bNumConfigurations; */
+};
+
+static const uint8_t qemu_ccid_config_descriptor[] = {
+
+ /* one configuration */
+ 0x09, /* u8 bLength; */
+ USB_DT_CONFIG, /* u8 bDescriptorType; Configuration */
+ 0x5d, 0x00, /* u16 wTotalLength; 9+9+54+7+7+7 */
+ 0x01, /* u8 bNumInterfaces; (1) */
+ 0x01, /* u8 bConfigurationValue; */
+ 0x00, /* u8 iConfiguration; */
+ 0x80, /* u8 bmAttributes;
+ Bit 7: must be set,
+ 6: Self-powered,
+ 5: Remote wakeup,
+ 4..0: resvd */
+ 100/2, /* u8 MaxPower; 50 == 100mA */
+
+ /* one interface */
+ 0x09, /* u8 if_bLength; */
+ USB_DT_INTERFACE, /* u8 if_bDescriptorType; Interface */
+ 0x00, /* u8 if_bInterfaceNumber; */
+ 0x00, /* u8 if_bAlternateSetting; */
+ 0x03, /* u8 if_bNumEndpoints; */
+ 0x0b, /* u8 if_bInterfaceClass; Smart Card Device Class */
+ 0x00, /* u8 if_bInterfaceSubClass; Subclass code */
+ 0x00, /* u8 if_bInterfaceProtocol; Protocol code */
+ 0x04, /* u8 if_iInterface; Index of string descriptor */
+
+ /* Smart Card Device Class Descriptor */
+ 0x36, /* u8 bLength; */
+ 0x21, /* u8 bDescriptorType; Functional */
+ 0x10, 0x01, /* u16 bcdCCID; CCID Specification Release Number. */
+ 0x00, /* u8 bMaxSlotIndex; The index of the highest available
+ slot on this device. All slots are consecutive starting
+ at 00h. */
+ 0x07, /* u8 bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
+
+ 0x03, 0x00, /* u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
+ 0x00, 0x00, /* PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
+ /* u32 dwDefaultClock; in kHZ (0x1000 is 4 MHz) */
+ 0x00, 0x10, 0x00, 0x00,
+ /* u32 dwMaximumClock; */
+ 0x00, 0x10, 0x00, 0x00,
+ 0x00, /* u8 bNumClockSupported; 0 means just the default and max. */
+ /* u32 dwDataRate ;bps. 9600 == 00002580h, 115200 = 0001C200 */
+ 0x00, 0xC2, 0x01, 0x00,
+ /* u32 dwMaxDataRate ; 9600 bps == 00002580h */
+ 0x00, 0xC2, 0x01, 0x00,
+ 0x00, /* u8 bNumDataRatesSupported; 00 means all rates between
+ * default and max */
+ /* u32 dwMaxIFSD; maximum IFSD supported by CCID for protocol
+ * T=1 TODO (copied from Athena) */
+ 0xfc, 0x00, 0x00, 0x00,
+ /* u32 dwSyncProtocols; 1 - 2-wire, 2 - 3-wire, 4 - I2C */
+ 0x00, 0x00, 0x00, 0x00,
+ /* u32 dwMechanical; 0 - no special characteristics. */
+ 0x00, 0x00, 0x00, 0x00,
+ /* u32 dwFeatures;
+ * 0 - No special characteristics
+ * + 2 Automatic parameter configuration based on ATR data
+ * 4 Automatic activation of ICC on insertinc
+ * 8 Automatic ICC voltage selection
+ * + 10 Automatic ICC clock frequency change
+ * + 20 Automatic baud rate change
+ * 40 Automatic parameters negotiation made by the CCID
+ * 80 automatic PPS made by the CCID
+ * 100 CCID can set ICC in clock stop mode
+ * 200 NAD value other then 00 accepted (T=1 protocol)
+ * 400 Automatic IFSD exchange as first exchange (T=1)
+ * One of the following only:
+ * 10000 TPDU level exchanges with CCID
+ * 20000 Short APDU level exchange with CCID
+ * + 40000 Short and Extended APDU level exchange with CCID
+ *
+ * 100000 USB Wake up signaling supported on card insertion
+ * and removal. Must set bit 5 in bmAttributes in Configuration
+ * descriptor if 100000 is set.*/
+ 0x32, 0x00, 0x04, 0x00,
+ /* u32 dwMaxCCIDMessageLength; For extended APDU in [261 + 10
+ * , 65544 + 10]. Otherwise the minimum is wMaxPacketSize of
+ * the Bulk-OUT endpoint */
+ 0x12, 0x00, 0x01, 0x00,
+ 0xFF, /* u8 bClassGetResponse; Significant only for CCID that
+ * offers an APDU level for exchanges. Indicates the default
+ * class value used by the CCID when it sends a Get Response
+ * command to perform the transportation of an APDU by T=0
+ * protocol
+ * FFh indicates that the CCID echos the class of the APDU.
+ */
+ 0xFF, /* u8 bClassEnvelope; EAPDU only. Envelope command for T=0 */
+ 0x00, 0x00, /* u16 wLcdLayout; XXYY Number of lines (XX) and chars per
+ * line for LCD display used for PIN entry. 0000 - no LCD */
+ 0x01, /* u8 bPINSupport; 01h PIN Verification,
+ * 02h PIN Modification */
+ 0x01, /* u8 bMaxCCIDBusySlots; */
+
+ /* Interrupt-IN endpoint */
+ 0x07, /* u8 ep_bLength; */
+ USB_DT_ENDPOINT, /* u8 ep_bDescriptorType; Endpoint */
+ 0x80 | CCID_INT_IN_EP, /* u8 ep_bEndpointAddress; IN Endpoint 1 */
+ 0x03, /* u8 ep_bmAttributes; Interrupt */
+ 0x40, 0x00, /* u16 ep_wMaxPacketSize; */
+ 0xff, /* u8 ep_bInterval; */
+
+ /* Bulk-In endpoint */
+ 0x07, /* u8 ep_bLength; */
+ USB_DT_ENDPOINT, /* u8 ep_bDescriptorType; Endpoint */
+ 0x80 | CCID_BULK_IN_EP, /* u8 ep_bEndpointAddress; IN Endpoint 2 */
+ 0x02, /* u8 ep_bmAttributes; Bulk */
+ 0x40, 0x00, /* u16 ep_wMaxPacketSize; */
+ 0x00, /* u8 ep_bInterval; */
+
+ /* Bulk-Out endpoint */
+ 0x07, /* u8 ep_bLength; */
+ USB_DT_ENDPOINT, /* u8 ep_bDescriptorType; Endpoint */
+ CCID_BULK_OUT_EP, /* u8 ep_bEndpointAddress; OUT Endpoint 3 */
+ 0x02, /* u8 ep_bmAttributes; Bulk */
+ 0x40, 0x00, /* u16 ep_wMaxPacketSize; */
+ 0x00, /* u8 ep_bInterval; */
+
+};
+
+static void usb_ccid_reset(USBCCIDState *s)
+{
+ /* TODO: Set flow control to none */
+ s->recv_ptr = 0;
+ s->recv_used = 0;
+ /* TODO: purge in char driver */
+}
+
+static void usb_ccid_handle_reset(USBDevice *dev)
+{
+ USBCCIDState *s = (USBCCIDState *)dev;
+
+ DPRINTF("Reset\n");
+
+ usb_ccid_reset(s);
+ /* TODO: Reset char device, send BREAK? */
+}
+
+static int usb_ccid_handle_control(USBDevice *dev, int request, int value,
+ int index, int length, uint8_t *data)
+{
+ //USBCCIDState *s = (USBCCIDState *)dev;
+ int ret = 0;
+
+ //DPRINTF("got control %x, value %x\n",request, value);
+ switch (request) {
+ case DeviceRequest | USB_REQ_GET_STATUS:
+ data[0] = (0 << USB_DEVICE_SELF_POWERED) |
+ (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
+ data[1] = 0x00;
+ ret = 2;
+ break;
+ case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
+ if (value == USB_DEVICE_REMOTE_WAKEUP) {
+ dev->remote_wakeup = 0;
+ } else {
+ goto fail;
+ }
+ ret = 0;
+ break;
+ case DeviceOutRequest | USB_REQ_SET_FEATURE:
+ if (value == USB_DEVICE_REMOTE_WAKEUP) {
+ dev->remote_wakeup = 1;
+ } else {
+ goto fail;
+ }
+ ret = 0;
+ break;
+ case DeviceOutRequest | USB_REQ_SET_ADDRESS:
+ dev->addr = value;
+ ret = 0;
+ break;
+ case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
+ switch(value >> 8) {
+ case USB_DT_DEVICE:
+ memcpy(data, qemu_ccid_dev_descriptor,
+ sizeof(qemu_ccid_dev_descriptor));
+ ret = sizeof(qemu_ccid_dev_descriptor);
+ break;
+ case USB_DT_CONFIG:
+ memcpy(data, qemu_ccid_config_descriptor,
+ sizeof(qemu_ccid_config_descriptor));
+ ret = sizeof(qemu_ccid_config_descriptor);
+ /* I got a request with size 8 - even though the
+ * basic descriptor is size 9. So handle it correctly.
+ * byte zero is the length*/
+ /* BROKEN - TODO?
+ if (length < data[0]) {
+ DPRINTF("Adjusting length of descriptor to requested length\n");
+ data[0] = length;
+ ret = length;
+ }
+ */
+ break;
+ case USB_DT_STRING:
+ switch(value & 0xff) {
+ case 0:
+ /* language ids */
+ data[0] = 4;
+ data[1] = 3;
+ data[2] = 0x09;
+ data[3] = 0x04;
+ ret = 4;
+ break;
+ case 1:
+ /* vendor description */
+ ret = set_usb_string(data, CCID_VENDOR_DESCRIPTION);
+ break;
+ case 2:
+ /* product description */
+ ret = set_usb_string(data, CCID_PRODUCT_DESCRIPTION);
+ break;
+ case 3:
+ /* serial number */
+ ret = set_usb_string(data, CCID_SERIAL_NUMBER_STRING);
+ break;
+ case 4:
+ /* interface name */
+ ret = set_usb_string(data, CCID_INTERFACE_NAME);
+ break;
+ default:
+ goto fail;
+ }
+ break;
+ default:
+ goto fail;
+ }
+ break;
+ case DeviceRequest | USB_REQ_GET_CONFIGURATION:
+ data[0] = 1;
+ ret = 1;
+ break;
+ case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
+ /* Only one configuration - we just ignore the request */
+ ret = 0;
+ break;
+ case DeviceRequest | USB_REQ_GET_INTERFACE:
+ data[0] = 0;
+ ret = 1;
+ break;
+ case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
+ ret = 0;
+ break;
+ case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
+ ret = 0;
+ break;
+
+ /* Class specific requests. */
+ case DeviceOutVendor | CCID_CONTROL_ABORT:
+ DPRINTF("ccid_control abort\n");
+ ret = USB_RET_STALL;
+ break;
+ case DeviceOutVendor | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
+ DPRINTF("ccid_control get clock frequencies\n");
+ ret = USB_RET_STALL;
+ break;
+ case DeviceOutVendor | CCID_CONTROL_GET_DATA_RATES:
+ DPRINTF("ccid_control get data rates\n");
+ ret = USB_RET_STALL;
+ break;
+ default:
+ fail:
+ DPRINTF("got unsupported/bogus control %x, value %x\n", request, value);
+ ret = USB_RET_STALL;
+ break;
+ }
+ return ret;
+}
+
+static uint8_t* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
+{
+ if (len + s->recv_used > RECV_BUF) {
+ printf("usb-ccid.c: %s: overflow of receive buf. bailing out.\n", __func__);
+ exit(-1);
+ }
+ if (s->recv_used == 0) {
+ s->recv_ptr = 0;
+ }
+ s->recv_used += len;
+ return s->recv_buf + s->recv_ptr;
+}
+
+/*
+static void ccid_fill_header(CCID_Header* h, CCID_Header* recv,
+ uint8_t type, uint32_t length, uint8_t status, uint8_t error)
+{
+}
+*/
+
+static void ccid_write_slot_status(USBCCIDState* s, CCID_Header* recv)
+{
+ CCID_SlotStatus *h = (CCID_SlotStatus*)ccid_reserve_recv_buf(s, 10);
+ h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus;
+ h->b.hdr.dwLength = 0;
+ h->b.hdr.bSlot = recv->bSlot;
+ h->b.hdr.bSeq = recv->bSeq;
+ h->b.bStatus = 0;
+ h->b.bError = 0;
+ h->bClockStatus = 0; // 0 - Clock Running, 1 - Clock stopped in State L, 2 - H, 3 - unkonwn state. rest are RFU
+}
+
+static void ccid_write_data_block(USBCCIDState* s, uint8_t slot, uint8_t seq,
+ const uint8_t* data, uint32_t len)
+{
+ CCID_DataBlock *p;
+
+ if (sizeof(s->recv_buf) < sizeof(*p) + len) {
+ abort();
+ }
+ p = (CCID_DataBlock*)ccid_reserve_recv_buf(s, sizeof(*p) + len);
+ p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
+ p->b.hdr.dwLength = len;
+ p->b.hdr.bSlot = slot;
+ p->b.hdr.bSeq = seq;
+ p->b.bStatus = 0;
+ p->b.bError = 0;
+ memcpy((char*)p+sizeof(*p), data, len);
+}
+
+static void ccid_write_data_block_answer(USBCCIDState* s, const uint8_t* data, uint32_t len)
+{
+ ccid_write_data_block(s, s->answer_slot, s->answer_seq, data, len);
+}
+
+static void ccid_write_data_block_atr(USBCCIDState* s, CCID_Header* recv)
+{
+ ccid_write_data_block(s, recv->bSlot, recv->bSeq, atr, atr_length);
+}
+
+static void usb_ccid_on_slot_change(USBCCIDState* s, bool full)
+{
+ // RDR_to_PC_NotifySlotChange, 6.3.1 page 56
+ uint8_t current = s->bmSlotICCState;
+ if (full) {
+ s->bmSlotICCState |= SLOT_0_STATE_MASK; // Slot 0 status full
+ } else {
+ s->bmSlotICCState &= ~SLOT_0_STATE_MASK; // Slot 0 status empty
+ }
+ if (current != s->bmSlotICCState) {
+ s->bmSlotICCState |= SLOT_0_CHANGED_MASK; // Slot 0 changed
+ }
+ s->notify_slot_change = true;
+}
+
+static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock* recv)
+{
+ static SCRMsgHeader scr_msg_header;
+ if (!s->cs) {
+ printf("usb-ccid: discarding apdu length %d\n", recv->hdr.dwLength);
+ return;
+ // XXX - dummy mode for testing, or just have the whole virtual card here.
+ }
+ s->answer_slot = recv->hdr.bSlot;
+ s->answer_seq = recv->hdr.bSeq;
+ scr_msg_header.type = SCard_APDU;
+ scr_msg_header.nLength = recv->hdr.dwLength;
+ qemu_chr_write(s->cs, (uint8_t*)&scr_msg_header, sizeof(SCRMsgHeader));
+ qemu_chr_write(s->cs, (uint8_t*)recv + sizeof(*recv), recv->hdr.dwLength);
+}
+
+static int usb_ccid_handle_data(USBDevice *dev, USBPacket *p)
+{
+ USBCCIDState *s = (USBCCIDState *)dev;
+ int ret = 0;
+ uint8_t *data = p->data;
+ int len = p->len;
+ int first_len;
+ CCID_Header* ccid_header;
+#ifdef DEBUG_CCID
+ //int i;
+#endif
+
+ /*
+ DPRINTF("handle_data: %d: got %d bytes\n", p->pid, len);
+ #ifdef DEBUG_CCID
+ if (len < 30) {
+ DPRINTF("handle_data: ");
+ for (i = 0 ; i < len ; ++i) {
+ printf("%X ", data[i]);
+ }
+ printf("\n");
+ }
+ #endif
+ */
+
+ switch (p->pid) {
+ case USB_TOKEN_OUT:
+ // translate CCID to a APDU request, or handle here.
+ // right now all is handled here. (development only)
+ if (len < 10) {
+ DPRINTF("handle_data: bad USB_TOKEN_OUT length, should be at least 10 bytes\n");
+ } else {
+ ccid_header = (CCID_Header*)data;
+ switch (ccid_header->bMessageType) {
+ case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
+ ccid_write_slot_status(s, ccid_header);
+ break;
+ case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
+ // We need to send an ATR back
+ ccid_write_data_block_atr(s, ccid_header);
+ break;
+ case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
+ ccid_on_apdu_from_guest(s, (CCID_XferBlock*)data);
+ break;
+ default:
+ DPRINTF("handle_data: unhandled message type %d\n",
+ ccid_header->bMessageType);
+ }
+ }
+ break;
+
+ case USB_TOKEN_IN:
+ switch (p->devep & 0xf) {
+ case CCID_BULK_IN_EP:
+ first_len = RECV_BUF - s->recv_ptr;
+ if (len > s->recv_used)
+ len = s->recv_used;
+ if (!len) {
+ ret = USB_RET_NAK;
+ break;
+ }
+ if (first_len > len)
+ first_len = len;
+ memcpy(data, s->recv_buf + s->recv_ptr, first_len);
+ if (len > first_len)
+ memcpy(data + first_len, s->recv_buf, len - first_len);
+ s->recv_used -= len;
+ s->recv_ptr = (s->recv_ptr + len) % RECV_BUF;
+ ret = len;
+ DPRINTF("handle_data: bulk_in: sending %d bytes\n", ret);
+ break;
+ case CCID_INT_IN_EP:
+ if (s->notify_slot_change) {
+ // page 56, RDR_to_PC_NotifySlotChange
+ data[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
+ data[1] = s->bmSlotICCState;
+ ret = 2;
+ s->notify_slot_change = false;
+ s->bmSlotICCState &= ~ SLOT_0_CHANGED_MASK; // next notify won't say "this changed"
+ DPRINTF("handle_data: int_in: notify_slot_change %X\n", s->bmSlotICCState);
+ }
+ break;
+ default:
+ DPRINTF("Bad endpoint\n");
+ break;
+ }
+ break;
+ default:
+ DPRINTF("Bad token\n");
+ //fail:
+ ret = USB_RET_STALL;
+ break;
+ }
+
+ return ret;
+}
+
+static void usb_ccid_handle_destroy(USBDevice *dev)
+{
+ USBCCIDState *s = (USBCCIDState *)dev;
+
+ if (s->cs) {
+ qemu_chr_close(s->cs);
+ }
+}
+
+/* APDU chardev */
+
+static int usb_ccid_can_read(void *opaque)
+{
+ //USBCCIDState *s = opaque;
+ return 70000; // XXX number has meaning, or just positive for yes?
+}
+
+static void usb_ccid_read(void *opaque, const uint8_t *buf, int size)
+{
+ static uint8_t readbuf[10000];
+ static uint32_t readpos = 0;
+ USBCCIDState *s = opaque;
+ const SCRMsgHeader* scr_msg_header = (const SCRMsgHeader*)readbuf;
+ const uint8_t* data = readbuf + sizeof(SCRMsgHeader);
+ uint32_t available = size + readpos;
+
+ printf("usb-ccid: chardev read %d\n", size);
+ memcpy(readbuf + readpos, buf, size);
+ readpos += size;
+
+ if (available - sizeof(SCRMsgHeader) < scr_msg_header->nLength) {
+ printf("usb-ccid: chardev read short, missing %ld\n",
+ scr_msg_header->nLength + sizeof(SCRMsgHeader) - available);
+ return;
+ }
+
+ readpos = 0; // ready for next message
+
+ switch (scr_msg_header->type) {
+ case SCard_ATR:
+ DPRINTF("SCard_ATR %d\n", scr_msg_header->nLength);
+ assert(scr_msg_header->nLength <= MAX_ATR_SIZE);
+ memcpy(atr, data, scr_msg_header->nLength);
+ atr_length = scr_msg_header->nLength;
+ usb_ccid_on_slot_change(s, true);
+ break;
+ case SCard_APDU:
+ DPRINTF("SCard_APDU %d (answer seq %d, slot %d)\n", scr_msg_header->nLength,
+ s->answer_seq, s->answer_slot);
+ ccid_write_data_block_answer(s, data, scr_msg_header->nLength);
+ break;
+ case SCard_Remove:
+ DPRINTF("SCard_Remove\n");
+ usb_ccid_on_slot_change(s, false);
+ break;
+ default:
+ printf("usb-ccid: chardev: unexpected message of type %X\n", scr_msg_header->type);
+ };
+}
+
+static void usb_ccid_event(void *opaque, int event)
+{
+ //USBCCIDState *s = opaque;
+}
+
+/* Control chardev */
+
+static int usb_ccid_initfn(USBDevice *dev)
+{
+ USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
+ s->dev.speed = USB_SPEED_FULL;
+ s->notify_slot_change = false;
+ s->answer_slot = -1; // should be an invalid number
+ s->answer_seq = -1; // should be an invalid number
+ assert(sizeof(DEFAULT_ATR) <= MAX_ATR_SIZE);
+ memcpy(atr, DEFAULT_ATR, sizeof(DEFAULT_ATR));
+ atr_length = sizeof(DEFAULT_ATR);
+ if (s->cs) {
+ DPRINTF("initing chardev\n");
+ qemu_chr_add_handlers(s->cs, usb_ccid_can_read, usb_ccid_read,
+ usb_ccid_event, s);
+ }
+ usb_ccid_handle_reset(dev);
+ return 0;
+}
+
+static struct USBDeviceInfo ccid_info = {
+ .product_desc = "QEMU USB CCID",
+ .qdev.name = "usb-ccid",
+ .qdev.size = sizeof(USBCCIDState),
+ .init = usb_ccid_initfn,
+ .handle_packet = usb_generic_handle_packet,
+ .handle_reset = usb_ccid_handle_reset,
+ .handle_control = usb_ccid_handle_control,
+ .handle_data = usb_ccid_handle_data,
+ .handle_destroy = usb_ccid_handle_destroy,
+ .usbdevice_name = "ccid",
+ .qdev.props = (Property[]) {
+ DEFINE_PROP_CHR("chardev", USBCCIDState, cs),
+ DEFINE_PROP_END_OF_LIST(),
+ },
+};
+
+static void usb_ccid_register_devices(void)
+{
+ usb_qdev_register(&ccid_info);
+}
+device_init(usb_ccid_register_devices)
diff --git a/tests/test_ccid.py b/tests/test_ccid.py
new file mode 100755
index 000000000..5f2cb0ecf
--- /dev/null
+++ b/tests/test_ccid.py
@@ -0,0 +1,51 @@
+#!/usr/bin/python
+
+# testing usb-ccid:
+# run qemu with a usb-ccid device and a chardev connected to a socket
+# on port 2001 (just to work with this script):
+# qemu ... -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -device usb-ccid,chardev=ccid
+
+import socket
+import struct
+
+SCard_ATR, SCard_APDU, SCard_Remove = range(3)
+
+default_atr=''.join([chr(x) for x in [0x3B, 0xB0, 0x18, 0x00, 0xD1, 0x81, 0x05, 0xB1, 0x40, 0x38, 0x1F, 0x03, 0x28]])
+
+def insert_card(s, atr=default_atr):
+ send_msg(s, SCard_ATR, atr)
+
+def send_msg(s, the_type, data):
+ s.send(struct.pack('ii', the_type, len(data)) + data)
+
+def echoback(s):
+ while True:
+ msg = s.recv(10000)
+ the_type, the_len = struct.unpack('ii', msg[:8])
+ if the_len != len(msg) - 8:
+ print "length in header doesn't match message: header said %s, message minus 8 is %s" % (the_len, len(msg) - 8)
+ if the_type == SCard_ATR:
+ print "got ATR?? ignoring"
+ continue
+ if the_type == SCard_APDU:
+ print "got APDU of length %s" % the_len
+ send_msg(s, SCard_APDU, msg[8:])
+ continue
+ if the_type == SCard_Remove:
+ print "got removal??"
+ continue
+ print "got unexpected message type %s (length = %s)" % (the_type, the_len)
+
+if __name__ == '__main__':
+ s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect(('localhost', 2001))
+ import sys
+ if len(sys.argv) > 1:
+ if sys.argv[1] == 'loop':
+ print "entering echo loop"
+ echoback(s)
+ elif sys.argv[1] == 'atr':
+ atr = default_atr if len(sys.argv) == 2 else sys.argv[2]
+ print "sending atr %r" % atr
+ insert_card(s, atr)
+