1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007
3 * 2008, 2009, 2013 Free Software Foundation, Inc.
4 * Written by Werner Koch.
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 * ALTERNATIVELY, this file may be distributed under the terms of the
22 * following license, in which case the provisions of this license are
23 * required INSTEAD OF the GNU General Public License. If you wish to
24 * allow use of your version of this file only under the terms of the
25 * GNU General Public License, and not to allow others to use your
26 * version of this file under the terms of the following license,
27 * indicate your decision by deleting this paragraph and the license
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, and the entire permission notice in its entirety,
35 * including the disclaimer of warranties.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
39 * 3. The name of the author may not be used to endorse or promote
40 * products derived from this software without specific prior
43 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
44 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53 * OF THE POSSIBILITY OF SUCH DAMAGE.
59 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
60 smartcard via a reader connected to the USB.
62 This is a limited driver allowing to use some CCID drivers directly
63 without any other specila drivers. This is a fallback driver to be
64 used when nothing else works or the system should be kept minimal
65 for security reasons. It makes use of the libusb library to gain
66 portable access to USB.
68 This driver has been tested with the SCM SCR335 and SPR532
69 smartcard readers and requires that a reader implements APDU or
70 TPDU level exchange and does fully automatic initialization.
77 #if defined(HAVE_LIBUSB) || defined(TEST)
84 #include <sys/types.h>
96 #include "ccid-driver.h"
98 #define DRVNAME "ccid-driver: "
101 /* Depending on how this source is used we either define our error
102 output to go to stderr or to the jnlib based logging functions. We
103 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
104 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
106 #if defined(GNUPG_MAJOR_VERSION) \
107 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
109 #if defined(GNUPG_SCD_MAIN_HEADER)
110 # include GNUPG_SCD_MAIN_HEADER
111 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
112 # include "options.h"
115 # include "cardglue.h"
116 # else /* This is the modularized GnuPG 1.9 or later. */
117 # include "scdaemon.h"
121 # define DEBUGOUT(t) do { if (debug_level) \
122 log_debug (DRVNAME t); } while (0)
123 # define DEBUGOUT_1(t,a) do { if (debug_level) \
124 log_debug (DRVNAME t,(a)); } while (0)
125 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
126 log_debug (DRVNAME t,(a),(b)); } while (0)
127 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
128 log_debug (DRVNAME t,(a),(b),(c));} while (0)
129 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
130 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
131 # define DEBUGOUT_CONT(t) do { if (debug_level) \
132 log_printf (t); } while (0)
133 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
134 log_printf (t,(a)); } while (0)
135 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
136 log_printf (t,(a),(b)); } while (0)
137 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
138 log_printf (t,(a),(b),(c)); } while (0)
139 # define DEBUGOUT_LF() do { if (debug_level) \
140 log_printf ("\n"); } while (0)
142 #else /* Other usage of this source - don't use gnupg specifics. */
144 # define DEBUGOUT(t) do { if (debug_level) \
145 fprintf (stderr, DRVNAME t); } while (0)
146 # define DEBUGOUT_1(t,a) do { if (debug_level) \
147 fprintf (stderr, DRVNAME t, (a)); } while (0)
148 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
149 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
150 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
151 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
152 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
153 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
154 # define DEBUGOUT_CONT(t) do { if (debug_level) \
155 fprintf (stderr, t); } while (0)
156 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
157 fprintf (stderr, t, (a)); } while (0)
158 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
159 fprintf (stderr, t, (a), (b)); } while (0)
160 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
161 fprintf (stderr, t, (a), (b), (c)); } while (0)
162 # define DEBUGOUT_LF() do { if (debug_level) \
163 putc ('\n', stderr); } while (0)
165 #endif /* This source not used by scdaemon. */
169 #define EAGAIN EWOULDBLOCK
175 RDR_to_PC_NotifySlotChange= 0x50,
176 RDR_to_PC_HardwareError = 0x51,
178 PC_to_RDR_SetParameters = 0x61,
179 PC_to_RDR_IccPowerOn = 0x62,
180 PC_to_RDR_IccPowerOff = 0x63,
181 PC_to_RDR_GetSlotStatus = 0x65,
182 PC_to_RDR_Secure = 0x69,
183 PC_to_RDR_T0APDU = 0x6a,
184 PC_to_RDR_Escape = 0x6b,
185 PC_to_RDR_GetParameters = 0x6c,
186 PC_to_RDR_ResetParameters = 0x6d,
187 PC_to_RDR_IccClock = 0x6e,
188 PC_to_RDR_XfrBlock = 0x6f,
189 PC_to_RDR_Mechanical = 0x71,
190 PC_to_RDR_Abort = 0x72,
191 PC_to_RDR_SetDataRate = 0x73,
193 RDR_to_PC_DataBlock = 0x80,
194 RDR_to_PC_SlotStatus = 0x81,
195 RDR_to_PC_Parameters = 0x82,
196 RDR_to_PC_Escape = 0x83,
197 RDR_to_PC_DataRate = 0x84
201 /* Two macro to detect whether a CCID command has failed and to get
202 the error code. These macros assume that we can access the
203 mandatory first 10 bytes of a CCID message in BUF. */
204 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
205 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
208 /* We need to know the vendor to do some hacks. */
210 VENDOR_CHERRY = 0x046a,
212 VENDOR_OMNIKEY= 0x076b,
213 VENDOR_GEMPC = 0x08e6,
214 VENDOR_VEGA = 0x0982,
215 VENDOR_REINER = 0x0c4b,
216 VENDOR_KAAN = 0x0d46,
217 VENDOR_VASCO = 0x1a44,
218 VENDOR_FSIJ = 0x234b,
221 /* Some product ids. */
222 #define SCM_SCR331 0xe001
223 #define SCM_SCR331DI 0x5111
224 #define SCM_SCR335 0x5115
225 #define SCM_SCR3320 0x5117
226 #define SCM_SPR532 0xe003
227 #define CHERRY_ST2000 0x003e
228 #define VASCO_920 0x0920
229 #define GEMPC_PINPAD 0x3478
230 #define GEMPC_CT30 0x3437
231 #define VEGA_ALPHA 0x0008
232 #define CYBERJACK_GO 0x0504
234 /* A list and a table with special transport descriptions. */
236 TRANSPORT_USB = 0, /* Standard USB transport. */
237 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
242 char *name; /* Device name. */
246 { "/dev/cmx0", TRANSPORT_CM4040 },
247 { "/dev/cmx1", TRANSPORT_CM4040 },
252 /* Store information on the driver's state. A pointer to such a
253 structure is used as handle for most functions. */
256 usb_dev_handle *idev;
258 int dev_fd; /* -1 for USB transport or file descriptor of the
260 unsigned short id_vendor;
261 unsigned short id_product;
262 unsigned short bcd_device;
270 unsigned char nonnull_nad;
274 unsigned char apdu_level:2; /* Reader supports short APDU level
275 exchange. With a value of 2 short
276 and extended level is supported.*/
277 unsigned int auto_voltage:1;
278 unsigned int auto_param:1;
279 unsigned int auto_pps:1;
280 unsigned int auto_ifsd:1;
281 unsigned int powered_off:1;
282 unsigned int has_pinpad:2;
283 unsigned int enodev_seen:1;
285 time_t last_progress; /* Last time we sent progress line. */
287 /* The progress callback and its first arg as supplied to
288 ccid_set_progress_cb. */
289 void (*progress_cb)(void *, const char *, int, int, int);
290 void *progress_cb_arg;
294 static int initialized_usb; /* Tracks whether USB has been initialized. */
295 static int debug_level; /* Flag to control the debug output.
298 2 = Level 1 + T=1 protocol tracing
299 3 = Level 2 + USB/I/O tracing of SlotStatus.
303 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
305 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
307 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
308 size_t *nread, int expected_type, int seqno, int timeout,
310 static int abort_cmd (ccid_driver_t handle, int seqno);
311 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
312 size_t datalen, unsigned char *result,
313 size_t resultmax, size_t *resultlen);
315 /* Convert a little endian stored 4 byte value into an unsigned
318 convert_le_u32 (const unsigned char *buf)
320 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
324 /* Convert a little endian stored 2 byte value into an unsigned
327 convert_le_u16 (const unsigned char *buf)
329 return buf[0] | (buf[1] << 8);
333 set_msg_len (unsigned char *msg, unsigned int length)
336 msg[2] = length >> 8;
337 msg[3] = length >> 16;
338 msg[4] = length >> 24;
343 my_sleep (int seconds)
346 /* With Pth we also call the standard sleep(0) so that the process
347 may give up its timeslot. */
350 # ifdef HAVE_W32_SYSTEM
358 # ifdef HAVE_W32_SYSTEM
359 Sleep (seconds*1000);
367 print_progress (ccid_driver_t handle)
369 time_t ct = time (NULL);
371 /* We don't want to print progress lines too often. */
372 if (ct == handle->last_progress)
375 if (handle->progress_cb)
376 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
378 handle->last_progress = ct;
383 /* Pint an error message for a failed CCID command including a textual
384 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
386 print_command_failed (const unsigned char *msg)
395 ec = CCID_ERROR_CODE (msg);
398 case 0x00: t = "Command not supported"; break;
400 case 0xE0: t = "Slot busy"; break;
401 case 0xEF: t = "PIN cancelled"; break;
402 case 0xF0: t = "PIN timeout"; break;
404 case 0xF2: t = "Automatic sequence ongoing"; break;
405 case 0xF3: t = "Deactivated Protocol"; break;
406 case 0xF4: t = "Procedure byte conflict"; break;
407 case 0xF5: t = "ICC class not supported"; break;
408 case 0xF6: t = "ICC protocol not supported"; break;
409 case 0xF7: t = "Bad checksum in ATR"; break;
410 case 0xF8: t = "Bad TS in ATR"; break;
412 case 0xFB: t = "An all inclusive hardware error occurred"; break;
413 case 0xFC: t = "Overrun error while talking to the ICC"; break;
414 case 0xFD: t = "Parity error while talking to the ICC"; break;
415 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
416 case 0xFF: t = "Host aborted the current activity"; break;
419 if (ec > 0 && ec < 128)
420 sprintf (buffer, "Parameter error at offset %d", ec);
422 sprintf (buffer, "Error code %02X", ec);
426 DEBUGOUT_1 ("CCID command failed: %s\n", t);
431 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
435 for (; off < datalen; off++)
437 if (!any || !(off % 16))
441 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
443 DEBUGOUT_CONT_1 (" %02X", data[off]);
446 if (any && (off % 16))
452 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
454 DEBUGOUT_1 ("%s:\n", name);
457 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
458 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
459 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
464 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
466 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
469 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
471 msg[7] == 1? "5.0 V":
472 msg[7] == 2? "3.0 V":
473 msg[7] == 3? "1.8 V":"");
474 print_pr_data (msg, msglen, 8);
479 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
481 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
482 print_pr_data (msg, msglen, 7);
487 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
489 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
490 print_pr_data (msg, msglen, 7);
495 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
499 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
502 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
503 val = convert_le_u16 (msg+8);
504 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
505 val == 1? " (continued)":
506 val == 2? " (continues+ends)":
507 val == 3? " (continues+continued)":
508 val == 16? " (DataBlock-expected)":"");
509 print_pr_data (msg, msglen, 10);
514 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
516 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
517 print_pr_data (msg, msglen, 7);
522 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
524 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
525 print_pr_data (msg, msglen, 7);
530 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
532 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
535 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
536 print_pr_data (msg, msglen, 8);
541 print_p2r_escape (const unsigned char *msg, size_t msglen)
543 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
544 print_pr_data (msg, msglen, 7);
549 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
551 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
554 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
555 print_pr_data (msg, msglen, 8);
560 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
562 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
565 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
566 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
567 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
568 print_pr_data (msg, msglen, 10);
573 print_p2r_secure (const unsigned char *msg, size_t msglen)
577 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
580 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
581 val = convert_le_u16 (msg+8);
582 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
583 val == 1? " (continued)":
584 val == 2? " (continues+ends)":
585 val == 3? " (continues+continued)":
586 val == 16? " (DataBlock-expected)":"");
587 print_pr_data (msg, msglen, 10);
592 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
594 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
597 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
598 print_pr_data (msg, msglen, 8);
603 print_p2r_abort (const unsigned char *msg, size_t msglen)
605 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
606 print_pr_data (msg, msglen, 7);
611 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
613 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
616 print_pr_data (msg, msglen, 7);
621 print_p2r_unknown (const unsigned char *msg, size_t msglen)
623 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
626 print_pr_data (msg, msglen, 0);
631 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
633 DEBUGOUT_1 ("%s:\n", name);
636 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
637 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
638 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
639 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
641 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
646 print_r2p_datablock (const unsigned char *msg, size_t msglen)
648 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
652 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
653 msg[9] == 1? " (continued)":
654 msg[9] == 2? " (continues+ends)":
655 msg[9] == 3? " (continues+continued)":
656 msg[9] == 16? " (XferBlock-expected)":"");
657 print_pr_data (msg, msglen, 10);
662 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
664 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
667 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
668 msg[9] == 0? " (running)":
669 msg[9] == 1? " (stopped-L)":
670 msg[9] == 2? " (stopped-H)":
671 msg[9] == 3? " (stopped)":"");
672 print_pr_data (msg, msglen, 10);
677 print_r2p_parameters (const unsigned char *msg, size_t msglen)
679 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
683 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
684 if (msglen == 17 && msg[9] == 1)
687 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
688 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
689 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
690 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
691 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
692 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
693 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
696 print_pr_data (msg, msglen, 10);
701 print_r2p_escape (const unsigned char *msg, size_t msglen)
703 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
706 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
707 print_pr_data (msg, msglen, 10);
712 print_r2p_datarate (const unsigned char *msg, size_t msglen)
714 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
719 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
720 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
721 print_pr_data (msg, msglen, 18);
724 print_pr_data (msg, msglen, 10);
729 print_r2p_unknown (const unsigned char *msg, size_t msglen)
731 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
734 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
735 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
736 print_pr_data (msg, msglen, 10);
740 /* Given a handle used for special transport prepare it for use. In
741 particular setup all information in way that resembles what
742 parse_cccid_descriptor does. */
744 prepare_special_transport (ccid_driver_t handle)
746 assert (!handle->id_vendor);
748 handle->nonnull_nad = 0;
749 handle->auto_ifsd = 0;
750 handle->max_ifsd = 32;
752 handle->has_pinpad = 0;
753 handle->apdu_level = 0;
754 switch (handle->id_product)
756 case TRANSPORT_CM4040:
757 DEBUGOUT ("setting up transport for CardMan 4040\n");
758 handle->apdu_level = 1;
761 default: assert (!"transport not defined");
765 /* Parse a CCID descriptor, optionally print all available features
766 and test whether this reader is usable by this driver. Returns 0
769 Note, that this code is based on the one in lsusb.c of the
770 usb-utils package, I wrote on 2003-09-01. -wk. */
772 parse_ccid_descriptor (ccid_driver_t handle,
773 const unsigned char *buf, size_t buflen)
777 int have_t1 = 0, have_tpdu=0;
780 handle->nonnull_nad = 0;
781 handle->auto_ifsd = 0;
782 handle->max_ifsd = 32;
784 handle->has_pinpad = 0;
785 handle->apdu_level = 0;
786 handle->auto_voltage = 0;
787 handle->auto_param = 0;
788 handle->auto_pps = 0;
789 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
790 handle->id_vendor, handle->id_product, handle->bcd_device);
791 if (buflen < 54 || buf[0] < 54)
793 DEBUGOUT ("CCID device descriptor is too short\n");
797 DEBUGOUT ("ChipCard Interface Descriptor:\n");
798 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
799 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
800 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
801 if (buf[3] != 1 || buf[2] != 0)
802 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
805 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
806 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
807 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
808 : buf[5] == 3? "1.8V":"?"));
810 us = convert_le_u32 (buf+6);
811 DEBUGOUT_1 (" dwProtocols %5u ", us);
813 DEBUGOUT_CONT (" T=0");
816 DEBUGOUT_CONT (" T=1");
820 DEBUGOUT_CONT (" (Invalid values detected)");
823 us = convert_le_u32(buf+10);
824 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
825 us = convert_le_u32(buf+14);
826 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
827 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
828 us = convert_le_u32(buf+19);
829 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
830 us = convert_le_u32(buf+23);
831 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
832 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
834 us = convert_le_u32(buf+28);
835 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
836 handle->max_ifsd = us;
838 us = convert_le_u32(buf+32);
839 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
841 DEBUGOUT_CONT ( " 2-wire");
843 DEBUGOUT_CONT ( " 3-wire");
845 DEBUGOUT_CONT ( " I2C");
848 us = convert_le_u32(buf+36);
849 DEBUGOUT_1 (" dwMechanical %08X ", us);
851 DEBUGOUT_CONT (" accept");
853 DEBUGOUT_CONT (" eject");
855 DEBUGOUT_CONT (" capture");
857 DEBUGOUT_CONT (" lock");
860 us = convert_le_u32(buf+40);
861 DEBUGOUT_1 (" dwFeatures %08X\n", us);
864 DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n");
865 handle->auto_voltage = 1;
868 DEBUGOUT (" Auto activation on insert\n");
871 DEBUGOUT (" Auto voltage selection\n");
872 handle->auto_voltage = 1;
875 DEBUGOUT (" Auto clock change\n");
877 DEBUGOUT (" Auto baud rate change\n");
880 DEBUGOUT (" Auto parameter negotiation made by CCID\n");
881 handle->auto_param = 1;
883 else if ((us & 0x0080))
885 DEBUGOUT (" Auto PPS made by CCID\n");
886 handle->auto_pps = 1;
888 if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
889 DEBUGOUT (" WARNING: conflicting negotiation features\n");
892 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
895 DEBUGOUT (" NAD value other than 0x00 accepted\n");
896 handle->nonnull_nad = 1;
900 DEBUGOUT (" Auto IFSD exchange\n");
901 handle->auto_ifsd = 1;
904 if ((us & 0x00010000))
906 DEBUGOUT (" TPDU level exchange\n");
909 else if ((us & 0x00020000))
911 DEBUGOUT (" Short APDU level exchange\n");
912 handle->apdu_level = 1;
914 else if ((us & 0x00040000))
916 DEBUGOUT (" Short and extended APDU level exchange\n");
917 handle->apdu_level = 2;
919 else if ((us & 0x00070000))
920 DEBUGOUT (" WARNING: conflicting exchange levels\n");
922 us = convert_le_u32(buf+44);
923 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
925 DEBUGOUT ( " bClassGetResponse ");
927 DEBUGOUT_CONT ("echo\n");
929 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
931 DEBUGOUT ( " bClassEnvelope ");
933 DEBUGOUT_CONT ("echo\n");
935 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
937 DEBUGOUT ( " wlcdLayout ");
938 if (!buf[50] && !buf[51])
939 DEBUGOUT_CONT ("none\n");
941 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
943 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
946 DEBUGOUT_CONT ( " verification");
947 handle->has_pinpad |= 1;
951 DEBUGOUT_CONT ( " modification");
952 handle->has_pinpad |= 2;
956 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
960 for (i=54; i < buf[0]-54; i++)
961 DEBUGOUT_CONT_1 (" %02X", buf[i]);
965 if (!have_t1 || !(have_tpdu || handle->apdu_level))
967 DEBUGOUT ("this drivers requires that the reader supports T=1, "
968 "TPDU or APDU level exchange - this is not available\n");
973 /* SCM drivers get stuck in their internal USB stack if they try to
974 send a frame of n*wMaxPacketSize back to us. Given that
975 wMaxPacketSize is 64 for these readers we set the IFSD to a value
977 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
984 0x5117 - SCR 3320 USB ID-000 reader
985 seems to be very slow but enabling this workaround boosts the
986 performance to a a more or less acceptable level (tested by David).
989 if (handle->id_vendor == VENDOR_SCM
990 && handle->max_ifsd > 48
991 && ( (handle->id_product == SCM_SCR331 && handle->bcd_device < 0x0516)
992 ||(handle->id_product == SCM_SCR331DI && handle->bcd_device < 0x0620)
993 ||(handle->id_product == SCM_SCR335 && handle->bcd_device < 0x0514)
994 ||(handle->id_product == SCM_SPR532 && handle->bcd_device < 0x0504)
995 ||(handle->id_product == SCM_SCR3320 && handle->bcd_device < 0x0522)
998 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
999 handle->max_ifsd = 48;
1002 if (handle->id_vendor == VENDOR_GEMPC && handle->id_product == GEMPC_CT30)
1004 DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
1005 handle->nonnull_nad = 0;
1013 get_escaped_usb_string (usb_dev_handle *idev, int idx,
1014 const char *prefix, const char *suffix)
1017 unsigned char buf[280];
1019 unsigned int langid;
1026 /* Fixme: The next line is for the current Valgrid without support
1028 memset (buf, 0, sizeof buf);
1030 /* First get the list of supported languages and use the first one.
1031 If we do don't find it we try to use English. Note that this is
1032 all in a 2 bute Unicode encoding using little endian. */
1033 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1034 (USB_DT_STRING << 8), 0,
1035 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1037 langid = 0x0409; /* English. */
1039 langid = (buf[3] << 8) | buf[2];
1041 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1042 (USB_DT_STRING << 8) + idx, langid,
1043 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1044 if (rc < 2 || buf[1] != USB_DT_STRING)
1045 return NULL; /* Error or not a string. */
1048 return NULL; /* Larger than our buffer. */
1050 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1053 n++; /* High byte set. */
1054 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1060 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1064 strcpy (result, prefix);
1065 n = strlen (prefix);
1066 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1069 result[n++] = '\xff'; /* High byte set. */
1070 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1072 sprintf (result+n, "%%%02X", *s);
1078 strcpy (result+n, suffix);
1083 /* This function creates an reader id to be used to find the same
1084 physical reader after a reset. It returns an allocated and possibly
1085 percent escaped string or NULL if not enough memory is available. */
1087 make_reader_id (usb_dev_handle *idev,
1088 unsigned int vendor, unsigned int product,
1089 unsigned char serialno_index)
1094 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1095 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1098 rid = malloc (strlen (prefix) + 3 + 1);
1101 strcpy (rid, prefix);
1102 strcat (rid, "X:0");
1108 /* Helper to find the endpoint from an interface descriptor. */
1110 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1113 int want_bulk_in = 0;
1116 want_bulk_in = 0x80;
1117 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1119 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1120 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1123 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1124 == USB_ENDPOINT_TYPE_INTERRUPT)
1125 && (ep->bEndpointAddress & 0x80))
1126 return (ep->bEndpointAddress & 0x0f);
1127 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1128 == USB_ENDPOINT_TYPE_BULK)
1129 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1130 return (ep->bEndpointAddress & 0x0f);
1132 /* Should never happen. */
1133 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1137 /* Helper for scan_or_find_devices. This function returns true if a
1138 requested device has been found or the caller should stop scanning
1139 for other reasons. */
1141 scan_or_find_usb_device (int scan_mode,
1142 int *readerno, int *count, char **rid_list,
1143 const char *readerid,
1144 struct usb_device *dev,
1146 struct usb_device **r_dev,
1147 usb_dev_handle **r_idev,
1148 unsigned char **ifcdesc_extra,
1149 size_t *ifcdesc_extra_len,
1150 int *interface_number,
1151 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1156 struct usb_config_descriptor *config;
1157 struct usb_interface *interface;
1158 struct usb_interface_descriptor *ifcdesc;
1160 usb_dev_handle *idev;
1164 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1166 config = dev->config + cfg_no;
1170 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1172 interface = config->interface + ifc_no;
1176 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1178 ifcdesc = (interface->altsetting + set_no);
1179 /* The second condition is for older SCM SPR 532 who did
1180 not know about the assigned CCID class. The third
1181 condition does the same for a Cherry SmartTerminal
1182 ST-2000. Instead of trying to interpret the strings
1183 we simply check the product ID. */
1184 if (ifcdesc && ifcdesc->extra
1185 && ((ifcdesc->bInterfaceClass == 11
1186 && ifcdesc->bInterfaceSubClass == 0
1187 && ifcdesc->bInterfaceProtocol == 0)
1188 || (ifcdesc->bInterfaceClass == 255
1189 && dev->descriptor.idVendor == VENDOR_SCM
1190 && dev->descriptor.idProduct == SCM_SPR532)
1191 || (ifcdesc->bInterfaceClass == 255
1192 && dev->descriptor.idVendor == VENDOR_CHERRY
1193 && dev->descriptor.idProduct == CHERRY_ST2000)))
1195 idev = usb_open (dev);
1198 DEBUGOUT_1 ("usb_open failed: %s\n",
1200 continue; /* with next setting. */
1203 rid = make_reader_id (idev,
1204 dev->descriptor.idVendor,
1205 dev->descriptor.idProduct,
1206 dev->descriptor.iSerialNumber);
1213 /* We are collecting infos about all
1214 available CCID readers. Store them and
1216 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1218 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1219 + strlen (rid) + 1);
1225 strcat (p, *rid_list);
1232 else /* Out of memory. */
1241 && !strcmp (readerid, rid)))
1243 /* We found the requested reader. */
1244 if (ifcdesc_extra && ifcdesc_extra_len)
1246 *ifcdesc_extra = malloc (ifcdesc
1248 if (!*ifcdesc_extra)
1252 return 1; /* Out of core. */
1254 memcpy (*ifcdesc_extra, ifcdesc->extra,
1256 *ifcdesc_extra_len = ifcdesc->extralen;
1259 if (interface_number)
1260 *interface_number = (ifcdesc->bInterfaceNumber);
1263 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1265 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1267 *ep_intr = find_endpoint (ifcdesc, 2);
1280 return 1; /* Found requested device. */
1284 /* This is not yet the reader we want.
1285 fixme: We should avoid the extra usb_open
1304 /* Combination function to either scan all CCID devices or to find and
1305 open one specific device.
1307 The function returns 0 if a reader has been found or when a scan
1308 returned without error.
1310 With READERNO = -1 and READERID is NULL, scan mode is used and
1311 R_RID should be the address where to store the list of reader_ids
1312 we found. If on return this list is empty, no CCID device has been
1313 found; otherwise it points to an allocated linked list of reader
1314 IDs. Note that in this mode the function always returns NULL.
1316 With READERNO >= 0 or READERID is not NULL find mode is used. This
1317 uses the same algorithm as the scan mode but stops and returns at
1318 the entry number READERNO and return the handle for the the opened
1319 USB device. If R_RID is not NULL it will receive the reader ID of
1320 that device. If R_DEV is not NULL it will the device pointer of
1321 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1322 malloced copy of the interfaces "extra: data filed;
1323 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1324 no reader with number READERNO or that reader is not usable by our
1325 implementation NULL will be returned. The caller must close a
1326 returned USB device handle and free (if not passed as NULL) the
1327 returned reader ID info as well as the IFCDESC_EXTRA. On error
1328 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1329 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1330 the READERID was found.
1332 If R_FD is not -1 on return the device is not using USB for
1333 transport but the device associated with that file descriptor. In
1334 this case INTERFACE will receive the transport type and the other
1335 USB specific return values are not used; the return value is
1338 Note that the first entry of the returned reader ID list in scan mode
1339 corresponds with a READERNO of 0 in find mode.
1342 scan_or_find_devices (int readerno, const char *readerid,
1344 struct usb_device **r_dev,
1345 unsigned char **ifcdesc_extra,
1346 size_t *ifcdesc_extra_len,
1347 int *interface_number,
1348 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1349 usb_dev_handle **r_idev,
1352 char *rid_list = NULL;
1354 struct usb_bus *busses, *bus;
1355 struct usb_device *dev = NULL;
1356 usb_dev_handle *idev = NULL;
1357 int scan_mode = (readerno == -1 && !readerid);
1360 /* Set return values to a default. */
1366 *ifcdesc_extra = NULL;
1367 if (ifcdesc_extra_len)
1368 *ifcdesc_extra_len = 0;
1369 if (interface_number)
1370 *interface_number = 0;
1376 /* See whether we want scan or find mode. */
1385 #ifdef HAVE_USB_GET_BUSSES
1386 busses = usb_get_busses();
1388 busses = usb_busses;
1391 for (bus = busses; bus; bus = bus->next)
1393 for (dev = bus->devices; dev; dev = dev->next)
1395 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1404 ep_bulk_out, ep_bulk_in, ep_intr))
1406 /* Found requested device or out of core. */
1410 return -1; /* error */
1418 /* Now check whether there are any devices with special transport types. */
1419 for (i=0; transports[i].name; i++)
1424 fd = open (transports[i].name, O_RDWR);
1425 if (fd == -1 && scan_mode && errno == EBUSY)
1427 /* Ignore this error in scan mode because it indicates that
1428 the device exists but is already open (most likely by us)
1429 and thus in general suitable as a reader. */
1433 DEBUGOUT_2 ("failed to open `%s': %s\n",
1434 transports[i].name, strerror (errno));
1438 rid = malloc (strlen (transports[i].name) + 30 + 10);
1444 return -1; /* Error. */
1446 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1449 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1450 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1457 return -1; /* Error. */
1462 strcat (p, rid_list);
1470 else if (!readerno ||
1471 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1473 /* Found requested device. */
1474 if (interface_number)
1475 *interface_number = transports[i].type;
1482 return 0; /* Okay, found device */
1484 else /* This is not yet the reader we want. */
1504 /* Set the level of debugging to LEVEL and return the old level. -1
1505 just returns the old level. A level of 0 disables debugging, 1
1506 enables debugging, 2 enables additional tracing of the T=1
1507 protocol, 3 additionally enables debugging for GetSlotStatus, other
1508 values are not yet defined.
1510 Note that libusb may provide its own debugging feature which is
1511 enabled by setting the envvar USB_DEBUG. */
1513 ccid_set_debug_level (int level)
1515 int old = debug_level;
1517 debug_level = level;
1523 ccid_get_reader_list (void)
1527 if (!initialized_usb)
1530 initialized_usb = 1;
1533 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1534 NULL, NULL, NULL, NULL, NULL))
1535 return NULL; /* Error. */
1540 /* Vendor specific custom initialization. */
1542 ccid_vendor_specific_init (ccid_driver_t handle)
1544 if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1548 * Vega alpha has a feature to show retry counter on the pinpad
1549 * display. But it assumes that the card returns the value of
1550 * retry counter by VERIFY with empty data (return code of
1551 * 63Cx). Unfortunately, existing OpenPGP cards don't support
1552 * VERIFY command with empty data. This vendor specific command
1553 * sequence is to disable the feature.
1555 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1557 r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1558 if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1559 && r != CCID_DRIVER_ERR_NO_CARD)
1567 /* Open the reader with the internal number READERNO and return a
1568 pointer to be used as handle in HANDLE. Returns 0 on success. */
1570 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1573 struct usb_device *dev = NULL;
1574 usb_dev_handle *idev = NULL;
1577 unsigned char *ifcdesc_extra = NULL;
1578 size_t ifcdesc_extra_len;
1580 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1584 if (!initialized_usb)
1587 initialized_usb = 1;
1590 /* See whether we want to use the reader ID string or a reader
1591 number. A readerno of -1 indicates that the reader ID string is
1593 if (readerid && strchr (readerid, ':'))
1594 readerno = -1; /* We want to use the readerid. */
1597 readerno = atoi (readerid);
1600 DEBUGOUT ("no CCID readers found\n");
1601 rc = CCID_DRIVER_ERR_NO_READER;
1606 readerno = 0; /* Default. */
1608 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1609 &ifcdesc_extra, &ifcdesc_extra_len,
1610 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1614 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1616 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1617 rc = CCID_DRIVER_ERR_NO_READER;
1621 /* Okay, this is a CCID reader. */
1622 *handle = calloc (1, sizeof **handle);
1625 DEBUGOUT ("out of memory\n");
1626 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1629 (*handle)->rid = rid;
1630 if (idev) /* Regular USB transport. */
1632 (*handle)->idev = idev;
1633 (*handle)->dev_fd = -1;
1634 (*handle)->id_vendor = dev->descriptor.idVendor;
1635 (*handle)->id_product = dev->descriptor.idProduct;
1636 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1637 (*handle)->ifc_no = ifc_no;
1638 (*handle)->ep_bulk_out = ep_bulk_out;
1639 (*handle)->ep_bulk_in = ep_bulk_in;
1640 (*handle)->ep_intr = ep_intr;
1642 else if (dev_fd != -1) /* Device transport. */
1644 (*handle)->idev = NULL;
1645 (*handle)->dev_fd = dev_fd;
1646 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1647 (*handle)->id_product = ifc_no; /* Transport type */
1648 prepare_special_transport (*handle);
1652 assert (!"no transport"); /* Bug. */
1655 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1659 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1661 DEBUGOUT ("device not supported\n");
1662 rc = CCID_DRIVER_ERR_NO_READER;
1666 rc = usb_claim_interface (idev, ifc_no);
1669 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1670 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1675 rc = ccid_vendor_specific_init (*handle);
1678 free (ifcdesc_extra);
1695 do_close_reader (ccid_driver_t handle)
1698 unsigned char msg[100];
1700 unsigned char seqno;
1702 if (!handle->powered_off)
1704 msg[0] = PC_to_RDR_IccPowerOff;
1705 msg[5] = 0; /* slot */
1706 msg[6] = seqno = handle->seqno++;
1707 msg[7] = 0; /* RFU */
1708 msg[8] = 0; /* RFU */
1709 msg[9] = 0; /* RFU */
1710 set_msg_len (msg, 0);
1713 rc = bulk_out (handle, msg, msglen, 0);
1715 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1717 handle->powered_off = 1;
1721 usb_release_interface (handle->idev, handle->ifc_no);
1722 usb_close (handle->idev);
1723 handle->idev = NULL;
1725 if (handle->dev_fd != -1)
1727 close (handle->dev_fd);
1728 handle->dev_fd = -1;
1733 /* Reset a reader on HANDLE. This is useful in case a reader has been
1734 plugged of and inserted at a different port. By resetting the
1735 handle, the same reader will be get used. Note, that on error the
1736 handle won't get released.
1738 This does not return an ATR, so ccid_get_atr should be called right
1742 ccid_shutdown_reader (ccid_driver_t handle)
1745 struct usb_device *dev = NULL;
1746 usb_dev_handle *idev = NULL;
1747 unsigned char *ifcdesc_extra = NULL;
1748 size_t ifcdesc_extra_len;
1749 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1751 if (!handle || !handle->rid)
1752 return CCID_DRIVER_ERR_INV_VALUE;
1754 do_close_reader (handle);
1756 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1757 &ifcdesc_extra, &ifcdesc_extra_len,
1758 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1759 &idev, NULL) || !idev)
1761 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1762 return CCID_DRIVER_ERR_NO_READER;
1767 handle->idev = idev;
1768 handle->ifc_no = ifc_no;
1769 handle->ep_bulk_out = ep_bulk_out;
1770 handle->ep_bulk_in = ep_bulk_in;
1771 handle->ep_intr = ep_intr;
1773 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1775 DEBUGOUT ("device not supported\n");
1776 rc = CCID_DRIVER_ERR_NO_READER;
1780 rc = usb_claim_interface (idev, ifc_no);
1783 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1784 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1790 free (ifcdesc_extra);
1794 usb_close (handle->idev);
1795 handle->idev = NULL;
1796 if (handle->dev_fd != -1)
1797 close (handle->dev_fd);
1798 handle->dev_fd = -1;
1807 ccid_set_progress_cb (ccid_driver_t handle,
1808 void (*cb)(void *, const char *, int, int, int),
1811 if (!handle || !handle->rid)
1812 return CCID_DRIVER_ERR_INV_VALUE;
1814 handle->progress_cb = cb;
1815 handle->progress_cb_arg = cb_arg;
1820 /* Close the reader HANDLE. */
1822 ccid_close_reader (ccid_driver_t handle)
1824 if (!handle || (!handle->idev && handle->dev_fd == -1))
1827 do_close_reader (handle);
1834 /* Return False if a card is present and powered. */
1836 ccid_check_card_presence (ccid_driver_t handle)
1838 (void)handle; /* Not yet implemented. */
1843 /* Write NBYTES of BUF to file descriptor FD. */
1845 writen (int fd, const void *buf, size_t nbytes)
1847 size_t nleft = nbytes;
1852 nwritten = write (fd, buf, nleft);
1861 buf = (const char*)buf + nwritten;
1868 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1869 Returns 0 on success. */
1871 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1876 /* No need to continue and clutter the log with USB write error
1877 messages after we got the first ENODEV. */
1878 if (handle->enodev_seen)
1879 return CCID_DRIVER_ERR_NO_READER;
1881 if (debug_level && (!no_debug || debug_level >= 3))
1883 switch (msglen? msg[0]:0)
1885 case PC_to_RDR_IccPowerOn:
1886 print_p2r_iccpoweron (msg, msglen);
1888 case PC_to_RDR_IccPowerOff:
1889 print_p2r_iccpoweroff (msg, msglen);
1891 case PC_to_RDR_GetSlotStatus:
1892 print_p2r_getslotstatus (msg, msglen);
1894 case PC_to_RDR_XfrBlock:
1895 print_p2r_xfrblock (msg, msglen);
1897 case PC_to_RDR_GetParameters:
1898 print_p2r_getparameters (msg, msglen);
1900 case PC_to_RDR_ResetParameters:
1901 print_p2r_resetparameters (msg, msglen);
1903 case PC_to_RDR_SetParameters:
1904 print_p2r_setparameters (msg, msglen);
1906 case PC_to_RDR_Escape:
1907 print_p2r_escape (msg, msglen);
1909 case PC_to_RDR_IccClock:
1910 print_p2r_iccclock (msg, msglen);
1912 case PC_to_RDR_T0APDU:
1913 print_p2r_to0apdu (msg, msglen);
1915 case PC_to_RDR_Secure:
1916 print_p2r_secure (msg, msglen);
1918 case PC_to_RDR_Mechanical:
1919 print_p2r_mechanical (msg, msglen);
1921 case PC_to_RDR_Abort:
1922 print_p2r_abort (msg, msglen);
1924 case PC_to_RDR_SetDataRate:
1925 print_p2r_setdatarate (msg, msglen);
1928 print_p2r_unknown (msg, msglen);
1935 rc = usb_bulk_write (handle->idev,
1936 handle->ep_bulk_out,
1938 5000 /* ms timeout */);
1942 if (rc == -(ENODEV))
1944 /* The Linux libusb returns a negative error value. Catch
1945 the most important one. */
1953 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1955 if (errno == ENODEV)
1957 handle->enodev_seen = 1;
1958 return CCID_DRIVER_ERR_NO_READER;
1963 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1967 rc = writen (handle->dev_fd, msg, msglen);
1970 DEBUGOUT_2 ("writen to %d failed: %s\n",
1971 handle->dev_fd, strerror (errno));
1974 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1978 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1979 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1980 is the sequence number used to send the request and EXPECTED_TYPE
1981 the type of message we expect. Does checks on the ccid
1982 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1983 avoid debug messages in case of no error; this can be overriden
1984 with a glibal debug level of at least 3. Returns 0 on success. */
1986 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1987 size_t *nread, int expected_type, int seqno, int timeout,
1992 int eagain_retries = 0;
1994 /* Fixme: The next line for the current Valgrind without support
1996 memset (buffer, 0, length);
2000 rc = usb_bulk_read (handle->idev,
2002 (char*)buffer, length,
2007 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
2008 if (rc == EAGAIN && eagain_retries++ < 3)
2013 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2015 *nread = msglen = rc;
2019 rc = read (handle->dev_fd, buffer, length);
2023 DEBUGOUT_2 ("read from %d failed: %s\n",
2024 handle->dev_fd, strerror (rc));
2025 if (rc == EAGAIN && eagain_retries++ < 5)
2030 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2032 *nread = msglen = rc;
2038 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2039 abort_cmd (handle, seqno);
2040 return CCID_DRIVER_ERR_INV_VALUE;
2044 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2045 return CCID_DRIVER_ERR_INV_VALUE;
2047 if (buffer[6] != seqno)
2049 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2051 /* Retry until we are synced again. */
2055 /* We need to handle the time extension request before we check that
2056 we got the expected message type. This is in particular required
2057 for the Cherry keyboard which sends a time extension request for
2059 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2061 /* Card present and active, time extension requested. */
2062 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2063 buffer[7], buffer[8]);
2067 if (buffer[0] != expected_type)
2069 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2070 abort_cmd (handle, seqno);
2071 return CCID_DRIVER_ERR_INV_VALUE;
2074 if (debug_level && (!no_debug || debug_level >= 3))
2078 case RDR_to_PC_DataBlock:
2079 print_r2p_datablock (buffer, msglen);
2081 case RDR_to_PC_SlotStatus:
2082 print_r2p_slotstatus (buffer, msglen);
2084 case RDR_to_PC_Parameters:
2085 print_r2p_parameters (buffer, msglen);
2087 case RDR_to_PC_Escape:
2088 print_r2p_escape (buffer, msglen);
2090 case RDR_to_PC_DataRate:
2091 print_r2p_datarate (buffer, msglen);
2094 print_r2p_unknown (buffer, msglen);
2098 if (CCID_COMMAND_FAILED (buffer))
2099 print_command_failed (buffer);
2101 /* Check whether a card is at all available. Note: If you add new
2102 error codes here, check whether they need to be ignored in
2104 switch ((buffer[7] & 0x03))
2106 case 0: /* no error */ break;
2107 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2108 case 2: return CCID_DRIVER_ERR_NO_CARD;
2109 case 3: /* RFU */ break;
2116 /* Send an abort sequence and wait until everything settled. */
2118 abort_cmd (ccid_driver_t handle, int seqno)
2122 unsigned char msg[100];
2127 /* I don't know how to send an abort to non-USB devices. */
2128 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2132 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2133 /* Send the abort command to the control pipe. Note that we don't
2134 need to keep track of sent abort commands because there should
2135 never be another thread using the same slot concurrently. */
2136 rc = usb_control_msg (handle->idev,
2137 0x21,/* bmRequestType: host-to-device,
2138 class specific, to interface. */
2140 (seqno << 8 | 0 /* slot */),
2143 1000 /* ms timeout */);
2146 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
2147 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2150 /* Now send the abort command to the bulk out pipe using the same
2151 SEQNO and SLOT. Do this in a loop to so that all seqno are
2153 seqno--; /* Adjust for next increment. */
2157 msg[0] = PC_to_RDR_Abort;
2158 msg[5] = 0; /* slot */
2160 msg[7] = 0; /* RFU */
2161 msg[8] = 0; /* RFU */
2162 msg[9] = 0; /* RFU */
2164 set_msg_len (msg, 0);
2166 rc = usb_bulk_write (handle->idev,
2167 handle->ep_bulk_out,
2169 5000 /* ms timeout */);
2173 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2176 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2181 rc = usb_bulk_read (handle->idev,
2183 (char*)msg, sizeof msg,
2184 5000 /*ms timeout*/);
2187 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2189 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2195 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2196 (unsigned int)msglen);
2197 return CCID_DRIVER_ERR_INV_VALUE;
2201 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2202 return CCID_DRIVER_ERR_INV_VALUE;
2205 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2206 msg[7], msg[8], msg[9]);
2207 if (CCID_COMMAND_FAILED (msg))
2208 print_command_failed (msg);
2210 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2212 handle->seqno = ((seqno + 1) & 0xff);
2213 DEBUGOUT ("sending abort sequence succeeded\n");
2219 /* Note that this function won't return the error codes NO_CARD or
2220 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2221 operation will get returned in RESULT and its length in RESULTLEN.
2222 If the response is larger than RESULTMAX, an error is returned and
2223 the required buffer length returned in RESULTLEN. */
2225 send_escape_cmd (ccid_driver_t handle,
2226 const unsigned char *data, size_t datalen,
2227 unsigned char *result, size_t resultmax, size_t *resultlen)
2230 unsigned char msg[100];
2232 unsigned char seqno;
2237 if (datalen > sizeof msg - 10)
2238 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2240 msg[0] = PC_to_RDR_Escape;
2241 msg[5] = 0; /* slot */
2242 msg[6] = seqno = handle->seqno++;
2243 msg[7] = 0; /* RFU */
2244 msg[8] = 0; /* RFU */
2245 msg[9] = 0; /* RFU */
2246 memcpy (msg+10, data, datalen);
2247 msglen = 10 + datalen;
2248 set_msg_len (msg, datalen);
2250 rc = bulk_out (handle, msg, msglen, 0);
2253 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2258 /* We need to ignore certain errorcode here. */
2260 case CCID_DRIVER_ERR_CARD_INACTIVE:
2261 case CCID_DRIVER_ERR_NO_CARD:
2263 if (msglen > resultmax)
2264 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2267 memcpy (result, msg, msglen);
2268 *resultlen = msglen;
2282 ccid_transceive_escape (ccid_driver_t handle,
2283 const unsigned char *data, size_t datalen,
2284 unsigned char *resp, size_t maxresplen, size_t *nresp)
2286 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2293 ccid_poll (ccid_driver_t handle)
2296 unsigned char msg[10];
2302 rc = usb_bulk_read (handle->idev,
2304 (char*)msg, sizeof msg,
2305 0 /* ms timeout */ );
2306 if (rc < 0 && errno == ETIMEDOUT)
2314 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2315 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2323 DEBUGOUT ("intr-in msg too short\n");
2324 return CCID_DRIVER_ERR_INV_VALUE;
2327 if (msg[0] == RDR_to_PC_NotifySlotChange)
2329 DEBUGOUT ("notify slot change:");
2330 for (i=1; i < msglen; i++)
2331 for (j=0; j < 4; j++)
2332 DEBUGOUT_CONT_3 (" %d:%c%c",
2334 (msg[i] & (1<<(j*2)))? 'p':'-',
2335 (msg[i] & (2<<(j*2)))? '*':' ');
2338 else if (msg[0] == RDR_to_PC_HardwareError)
2340 DEBUGOUT ("hardware error occured\n");
2344 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2351 /* Note that this function won't return the error codes NO_CARD or
2354 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2357 unsigned char msg[100];
2359 unsigned char seqno;
2363 msg[0] = PC_to_RDR_GetSlotStatus;
2364 msg[5] = 0; /* slot */
2365 msg[6] = seqno = handle->seqno++;
2366 msg[7] = 0; /* RFU */
2367 msg[8] = 0; /* RFU */
2368 msg[9] = 0; /* RFU */
2369 set_msg_len (msg, 0);
2371 rc = bulk_out (handle, msg, 10, 1);
2374 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2375 get cluttered up by a ticker function checking for the slot
2376 status and debugging enabled. */
2377 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2378 seqno, retries? 1000 : 200, 1);
2379 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2383 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2384 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2385 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2388 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2392 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2393 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2395 *statusbits = (msg[7] & 3);
2401 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2402 Calling this routine, it should prepare default values at PARAM
2403 beforehand. This routine assumes that card is accessed by T=1
2404 protocol. It doesn't analyze historical bytes at all.
2406 Returns < 0 value on error:
2407 -1 for parse error or integrity check error
2408 -2 for card doesn't support T=1 protocol
2409 -3 for parameters are nod explicitly defined by ATR
2410 -4 for this driver doesn't support CRC
2412 Returns >= 0 on success:
2413 0 for card is negotiable mode
2414 1 for card is specific mode (and not negotiable)
2417 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2421 int historical_bytes_num, negotiable = 1;
2423 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2428 param[1] |= 0x02; /* Convention is inverse. */
2432 historical_bytes_num = atr[i] & 0x0f;
2437 param[0] = atr[i]; /* TA1 - Fi & Di */
2442 NEXTBYTE (); /* TB1 - ignore */
2446 param[2] = atr[i]; /* TC1 - Guard Time */
2452 y = (atr[i] >> 4); /* TD1 */
2457 { /* TA2 - PPS mode */
2458 if ((atr[i] & 0x0f) != 1)
2459 return -2; /* Wrong card protocol (!= 1). */
2461 if ((atr[i] & 0x10) != 0x10)
2462 return -3; /* Transmission parameters are implicitly defined. */
2464 negotiable = 0; /* TA2 means specific mode. */
2469 NEXTBYTE (); /* TB2 - ignore */
2472 NEXTBYTE (); /* TC2 - ignore */
2476 y = (atr[i] >> 4); /* TD2 */
2488 param[5] = atr[i]; /* IFSC */
2490 /* XXX: check voltage? */
2491 param[4] = (atr[i] >> 6); /* ClockStop */
2499 param[3] = atr[i]; /* TBx - BWI & CWI */
2506 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2509 if (param[1] & 0x01)
2510 return -4; /* CRC not supported yet. */
2515 y = (atr[i] >> 4); /* TDx */
2524 i += historical_bytes_num - 1;
2546 /* Return the ATR of the card. This is not a cached value and thus an
2547 actual reset is done. */
2549 ccid_get_atr (ccid_driver_t handle,
2550 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2554 unsigned char msg[100];
2555 unsigned char *tpdu;
2556 size_t msglen, tpdulen;
2557 unsigned char seqno;
2562 unsigned char param[7] = { /* For Protocol T=1 */
2563 0x11, /* bmFindexDindex */
2564 0x10, /* bmTCCKST1 */
2565 0x00, /* bGuardTimeT1 */
2566 0x4d, /* bmWaitingIntegersT1 */
2567 0x00, /* bClockStop */
2569 0x00 /* bNadValue */
2572 /* First check whether a card is available. */
2573 rc = ccid_slot_status (handle, &statusbits);
2576 if (statusbits == 2)
2577 return CCID_DRIVER_ERR_NO_CARD;
2579 /* For an inactive and also for an active card, issue the PowerOn
2580 command to get the ATR. */
2582 msg[0] = PC_to_RDR_IccPowerOn;
2583 msg[5] = 0; /* slot */
2584 msg[6] = seqno = handle->seqno++;
2585 /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2586 msg[7] = handle->auto_voltage ? 0 : 1;
2587 msg[8] = 0; /* RFU */
2588 msg[9] = 0; /* RFU */
2589 set_msg_len (msg, 0);
2592 rc = bulk_out (handle, msg, msglen, 0);
2595 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2599 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2600 && ((handle->id_vendor == VENDOR_CHERRY
2601 && handle->id_product == 0x0005)
2602 || (handle->id_vendor == VENDOR_GEMPC
2603 && handle->id_product == 0x4433)
2607 /* Try switching to ISO mode. */
2608 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2612 else if (CCID_COMMAND_FAILED (msg))
2613 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2616 handle->powered_off = 0;
2620 size_t n = msglen - 10;
2624 memcpy (atr, msg+10, n);
2628 param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2629 rc = update_param_by_atr (param, msg+10, msglen - 10);
2632 DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2633 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2638 if (handle->auto_param)
2640 msg[0] = PC_to_RDR_GetParameters;
2641 msg[5] = 0; /* slot */
2642 msg[6] = seqno = handle->seqno++;
2643 msg[7] = 0; /* RFU */
2644 msg[8] = 0; /* RFU */
2645 msg[9] = 0; /* RFU */
2646 set_msg_len (msg, 0);
2648 rc = bulk_out (handle, msg, msglen, 0);
2650 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2653 DEBUGOUT ("GetParameters failed\n");
2654 else if (msglen == 17 && msg[9] == 1)
2657 else if (handle->auto_pps)
2659 else if (rc == 1) /* It's negotiable, send PPS. */
2661 msg[0] = PC_to_RDR_XfrBlock;
2662 msg[5] = 0; /* slot */
2663 msg[6] = seqno = handle->seqno++;
2667 msg[10] = 0xff; /* PPSS */
2668 msg[11] = 0x11; /* PPS0: PPS1, Protocol T=1 */
2669 msg[12] = param[0]; /* PPS1: Fi / Di */
2670 msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2671 set_msg_len (msg, 4);
2674 rc = bulk_out (handle, msg, msglen, 0);
2678 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2683 if (msglen != 10 + 4)
2685 DEBUGOUT_1 ("Setting PPS failed: %d\n", (int)msglen);
2686 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2689 if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2691 DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2692 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2696 /* Setup parameters to select T=1. */
2697 msg[0] = PC_to_RDR_SetParameters;
2698 msg[5] = 0; /* slot */
2699 msg[6] = seqno = handle->seqno++;
2700 msg[7] = 1; /* Select T=1. */
2701 msg[8] = 0; /* RFU */
2702 msg[9] = 0; /* RFU */
2705 memcpy (&msg[10], param, 7);
2706 set_msg_len (msg, 7);
2709 rc = bulk_out (handle, msg, msglen, 0);
2712 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2715 DEBUGOUT ("SetParameters failed (ignored)\n");
2717 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2718 handle->ifsc = msg[15];
2720 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2722 if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2724 DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2725 handle->nonnull_nad = 0;
2731 /* Send an S-Block with our maximum IFSD to the CCID. */
2732 if (!handle->apdu_level && !handle->auto_ifsd)
2735 /* NAD: DAD=1, SAD=0 */
2736 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2737 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2739 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2741 edc = compute_edc (tpdu, tpdulen, use_crc);
2743 tpdu[tpdulen++] = (edc >> 8);
2744 tpdu[tpdulen++] = edc;
2746 msg[0] = PC_to_RDR_XfrBlock;
2747 msg[5] = 0; /* slot */
2748 msg[6] = seqno = handle->seqno++;
2750 msg[8] = 0; /* RFU */
2751 msg[9] = 0; /* RFU */
2752 set_msg_len (msg, tpdulen);
2753 msglen = 10 + tpdulen;
2755 if (debug_level > 1)
2756 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2757 ((msg[11] & 0xc0) == 0x80)? 'R' :
2758 (msg[11] & 0x80)? 'S' : 'I',
2759 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2760 : !!(msg[11] & 0x40)),
2761 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2763 rc = bulk_out (handle, msg, msglen, 0);
2768 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2769 RDR_to_PC_DataBlock, seqno, 5000, 0);
2774 tpdulen = msglen - 10;
2777 return CCID_DRIVER_ERR_ABORTED;
2779 if (debug_level > 1)
2780 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2781 ((msg[11] & 0xc0) == 0x80)? 'R' :
2782 (msg[11] & 0x80)? 'S' : 'I',
2783 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2784 : !!(msg[11] & 0x40)),
2785 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2786 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2788 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2790 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2793 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2803 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2807 return 0x42; /* Not yet implemented. */
2811 unsigned char crc = 0;
2813 for (; datalen; datalen--)
2820 /* Return true if APDU is an extended length one. */
2822 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2824 if (apdulen < 7 || apdu[4])
2825 return 0; /* Too short or no Z byte. */
2830 /* Helper for ccid_transceive used for APDU level exchanges. */
2832 ccid_transceive_apdu_level (ccid_driver_t handle,
2833 const unsigned char *apdu_buf, size_t apdu_buflen,
2834 unsigned char *resp, size_t maxresplen,
2838 unsigned char send_buffer[10+261+300], recv_buffer[10+261+300];
2839 const unsigned char *apdu;
2843 unsigned char seqno;
2849 apdulen = apdu_buflen;
2852 /* The maximum length for a short APDU T=1 block is 261. For an
2853 extended APDU T=1 block the maximum length 65544; however
2854 extended APDU exchange level is not fully supported yet. */
2855 if (apdulen > sizeof (send_buffer) - 10)
2856 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2858 msg[0] = PC_to_RDR_XfrBlock;
2859 msg[5] = 0; /* slot */
2860 msg[6] = seqno = handle->seqno++;
2861 msg[7] = bwi; /* bBWI */
2862 msg[8] = 0; /* RFU */
2863 msg[9] = 0; /* RFU */
2864 memcpy (msg+10, apdu, apdulen);
2865 set_msg_len (msg, apdulen);
2866 msglen = 10 + apdulen;
2868 rc = bulk_out (handle, msg, msglen, 0);
2873 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2874 RDR_to_PC_DataBlock, seqno, 5000, 0);
2880 size_t total_msglen = msglen;
2884 unsigned char status;
2886 msg = recv_buffer + total_msglen;
2888 msg[0] = PC_to_RDR_XfrBlock;
2889 msg[5] = 0; /* slot */
2890 msg[6] = seqno = handle->seqno++;
2891 msg[7] = bwi; /* bBWI */
2892 msg[8] = 0x10; /* Request next data block */
2894 set_msg_len (msg, 0);
2897 rc = bulk_out (handle, msg, msglen, 0);
2901 rc = bulk_in (handle, msg, sizeof recv_buffer - total_msglen, &msglen,
2902 RDR_to_PC_DataBlock, seqno, 5000, 0);
2906 memmove (msg, msg+10, msglen - 10);
2907 total_msglen += msglen - 10;
2908 if (total_msglen >= sizeof recv_buffer)
2909 return CCID_DRIVER_ERR_OUT_OF_CORE;
2915 apdu = recv_buffer + 10;
2916 apdulen = total_msglen - 10;
2921 apdulen = msglen - 10;
2926 if (apdulen > maxresplen)
2928 DEBUGOUT_2 ("provided buffer too short for received data "
2930 (unsigned int)apdulen, (unsigned int)maxresplen);
2931 return CCID_DRIVER_ERR_INV_VALUE;
2934 memcpy (resp, apdu, apdulen);
2944 Protocol T=1 overview
2948 1 byte Node Address (NAD)
2949 1 byte Protocol Control Byte (PCB)
2952 0-254 byte APDU or Control Information (INF)
2954 1 byte Error Detection Code (EDC)
2958 bit 4..6 Destination Node Address (DAD)
2960 bit 2..0 Source Node Address (SAD)
2962 If node adresses are not used, SAD and DAD should be set to 0 on
2963 the first block sent to the card. If they are used they should
2964 have different values (0 for one is okay); that first block sets up
2965 the addresses of the nodes.
2968 Information Block (I-Block):
2970 bit 6 Sequence number (yep, that is modulo 2)
2973 Received-Ready Block (R-Block):
2977 bit 4 Sequence number
2978 bit 3..0 0 = no error
2979 1 = EDC or parity error
2981 other values are reserved
2982 Supervisory Block (S-Block):
2985 bit 5 clear=request,set=response
2986 bit 4..0 0 = resyncronisation request
2987 1 = information field size request
2989 3 = extension of BWT request
2991 other values are reserved
2996 ccid_transceive (ccid_driver_t handle,
2997 const unsigned char *apdu_buf, size_t apdu_buflen,
2998 unsigned char *resp, size_t maxresplen, size_t *nresp)
3001 /* The size of the buffer used to be 10+259. For the via_escape
3002 hack we need one extra byte, thus 11+259. */
3003 unsigned char send_buffer[11+259], recv_buffer[11+259];
3004 const unsigned char *apdu;
3006 unsigned char *msg, *tpdu, *p;
3007 size_t msglen, tpdulen, last_tpdulen, n;
3008 unsigned char seqno;
3021 nresp = &dummy_nresp;
3024 /* Smarter readers allow to send APDUs directly; divert here. */
3025 if (handle->apdu_level)
3027 /* We employ a hack for Omnikey readers which are able to send
3028 TPDUs using an escape sequence. There is no documentation
3029 but the Windows driver does it this way. Tested using a
3030 CM6121. This method works also for the Cherry XX44
3031 keyboards; however there are problems with the
3032 ccid_tranceive_secure which leads to a loss of sync on the
3033 CCID level. If Cherry wants to make their keyboard work
3034 again, they should hand over some docs. */
3035 if ((handle->id_vendor == VENDOR_OMNIKEY
3036 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
3037 && handle->apdu_level < 2
3038 && is_exlen_apdu (apdu_buf, apdu_buflen))
3041 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3042 resp, maxresplen, nresp);
3045 /* The other readers we support require sending TPDUs. */
3047 tpdulen = 0; /* Avoid compiler warning about no initialization. */
3049 hdrlen = via_escape? 11 : 10;
3051 /* NAD: DAD=1, SAD=0 */
3052 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3056 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
3064 apdulen = apdu_buflen;
3067 /* Construct an I-Block. */
3068 tpdu = msg + hdrlen;
3070 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3071 if (apdulen > handle->ifsc )
3073 apdulen = handle->ifsc;
3074 apdu_buf += handle->ifsc;
3075 apdu_buflen -= handle->ifsc;
3076 tpdu[1] |= (1 << 5); /* Set more bit. */
3079 memcpy (tpdu+3, apdu, apdulen);
3080 tpdulen = 3 + apdulen;
3081 edc = compute_edc (tpdu, tpdulen, use_crc);
3083 tpdu[tpdulen++] = (edc >> 8);
3084 tpdu[tpdulen++] = edc;
3089 msg[0] = PC_to_RDR_Escape;
3090 msg[5] = 0; /* slot */
3091 msg[6] = seqno = handle->seqno++;
3092 msg[7] = 0; /* RFU */
3093 msg[8] = 0; /* RFU */
3094 msg[9] = 0; /* RFU */
3095 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
3096 set_msg_len (msg, 1 + tpdulen);
3100 msg[0] = PC_to_RDR_XfrBlock;
3101 msg[5] = 0; /* slot */
3102 msg[6] = seqno = handle->seqno++;
3103 msg[7] = 4; /* bBWI */
3104 msg[8] = 0; /* RFU */
3105 msg[9] = 0; /* RFU */
3106 set_msg_len (msg, tpdulen);
3108 msglen = hdrlen + tpdulen;
3110 last_tpdulen = tpdulen;
3113 if (debug_level > 1)
3114 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3115 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3116 (msg[pcboff] & 0x80)? 'S' : 'I',
3117 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3118 : !!(msg[pcboff] & 0x40)),
3119 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3122 rc = bulk_out (handle, msg, msglen, 0);
3127 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3128 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
3133 tpdu = msg + hdrlen;
3134 tpdulen = msglen - hdrlen;
3139 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3140 return CCID_DRIVER_ERR_ABORTED;
3143 if (debug_level > 1)
3144 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3145 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3146 (msg[pcboff] & 0x80)? 'S' : 'I',
3147 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3148 : !!(msg[pcboff] & 0x40)),
3149 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3150 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3153 if (!(tpdu[1] & 0x80))
3154 { /* This is an I-block. */
3157 { /* last block sent was successful. */
3162 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3163 { /* Reponse does not match our sequence number. */
3165 tpdu = msg + hdrlen;
3167 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3170 edc = compute_edc (tpdu, tpdulen, use_crc);
3172 tpdu[tpdulen++] = (edc >> 8);
3173 tpdu[tpdulen++] = edc;
3180 p = tpdu + 3; /* Skip the prologue field. */
3181 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3182 /* fixme: verify the checksum. */
3187 DEBUGOUT_2 ("provided buffer too short for received data "
3189 (unsigned int)n, (unsigned int)maxresplen);
3190 return CCID_DRIVER_ERR_INV_VALUE;
3193 memcpy (resp, p, n);
3199 if (!(tpdu[1] & 0x20))
3200 return 0; /* No chaining requested - ready. */
3203 tpdu = msg + hdrlen;
3205 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3208 edc = compute_edc (tpdu, tpdulen, use_crc);
3210 tpdu[tpdulen++] = (edc >> 8);
3211 tpdu[tpdulen++] = edc;
3213 else if ((tpdu[1] & 0xc0) == 0x80)
3214 { /* This is a R-block. */
3215 if ( (tpdu[1] & 0x0f))
3218 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3220 /* Error probably due to switching to TPDU. Send a
3221 resync request. We use the recv_buffer so that
3222 we don't corrupt the send_buffer. */
3224 tpdu = msg + hdrlen;
3226 tpdu[1] = 0xc0; /* S-block resync request. */
3229 edc = compute_edc (tpdu, tpdulen, use_crc);
3231 tpdu[tpdulen++] = (edc >> 8);
3232 tpdu[tpdulen++] = edc;
3234 DEBUGOUT ("T=1: requesting resync\n");
3236 else if (retries > 3)
3238 DEBUGOUT ("T=1: 3 failed retries\n");
3239 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3243 /* Error: repeat last block */
3245 tpdulen = last_tpdulen;
3248 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3249 { /* Response does not match our sequence number. */
3250 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3251 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3254 { /* Send next chunk. */
3262 DEBUGOUT ("unexpected ACK R-block received\n");
3263 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3267 { /* This is a S-block. */
3269 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3270 (tpdu[1] & 0x20)? "response": "request",
3272 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3274 /* Information field size request. */
3275 unsigned char ifsc = tpdu[3];
3277 if (ifsc < 16 || ifsc > 254)
3278 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3281 tpdu = msg + hdrlen;
3283 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3287 edc = compute_edc (tpdu, tpdulen, use_crc);
3289 tpdu[tpdulen++] = (edc >> 8);
3290 tpdu[tpdulen++] = edc;
3291 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3293 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3295 /* Wait time extension request. */
3296 unsigned char bwi = tpdu[3];
3298 tpdu = msg + hdrlen;
3300 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3304 edc = compute_edc (tpdu, tpdulen, use_crc);
3306 tpdu[tpdulen++] = (edc >> 8);
3307 tpdu[tpdulen++] = edc;
3308 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3309 print_progress (handle);
3311 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3313 DEBUGOUT ("T=1: resync ack from reader\n");
3314 /* Repeat previous block. */
3316 tpdulen = last_tpdulen;
3319 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3321 } /* end T=1 protocol loop. */
3327 /* Send the CCID Secure command to the reader. APDU_BUF should
3328 contain the APDU template. PIN_MODE defines how the pin gets
3331 1 := The PIN is ASCII encoded and of variable length. The
3332 length of the PIN entered will be put into Lc by the reader.
3333 The APDU should me made up of 4 bytes without Lc.
3335 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3336 may be used t enable reasonable defaults.
3338 When called with RESP and NRESP set to NULL, the function will
3339 merely check whether the reader supports the secure command for the
3340 given APDU and PIN_MODE. */
3342 ccid_transceive_secure (ccid_driver_t handle,
3343 const unsigned char *apdu_buf, size_t apdu_buflen,
3345 unsigned char *resp, size_t maxresplen, size_t *nresp)
3348 unsigned char send_buffer[10+259], recv_buffer[10+259];
3349 unsigned char *msg, *tpdu, *p;
3350 size_t msglen, tpdulen, n;
3351 unsigned char seqno;
3354 int cherry_mode = 0;
3355 int enable_varlen = 0;
3357 testmode = !resp && !nresp;
3360 nresp = &dummy_nresp;
3363 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3365 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3368 return CCID_DRIVER_ERR_NO_PINPAD;
3370 if (!pininfo->minlen)
3371 pininfo->minlen = 1;
3372 if (!pininfo->maxlen)
3373 pininfo->maxlen = 15;
3375 /* Note that the 25 is the maximum value the SPR532 allows. */
3376 if (pininfo->minlen < 1 || pininfo->minlen > 25
3377 || pininfo->maxlen < 1 || pininfo->maxlen > 25
3378 || pininfo->minlen > pininfo->maxlen)
3379 return CCID_DRIVER_ERR_INV_VALUE;
3381 /* We have only tested a few readers so better don't risk anything
3382 and do not allow the use with other readers. */
3383 switch (handle->id_vendor)
3385 case VENDOR_SCM: /* Tested with SPR 532. */
3386 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3387 case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3388 pininfo->maxlen = 25;
3391 case VENDOR_REINER: /* Tested with cyberJack go */
3392 case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3396 pininfo->maxlen = 25;
3398 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3399 character on the keyboard channel. We use a special variant
3400 of PC_to_RDR_Secure which directs these characters to the
3401 smart card's bulk-in channel. We also need to append a zero
3402 Lc byte to the APDU. It seems that it will be replaced with
3403 the actual length instead of being appended before the APDU
3404 is send to the card. */
3405 if (handle->id_product != CHERRY_ST2000)
3409 if ((handle->id_vendor == VENDOR_GEMPC &&
3410 handle->id_product == GEMPC_PINPAD)
3411 || (handle->id_vendor == VENDOR_VEGA &&
3412 handle->id_product == VEGA_ALPHA))
3415 pininfo->minlen = 4;
3416 pininfo->maxlen = 8;
3419 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3423 pininfo->fixedlen = 0;
3426 return 0; /* Success */
3428 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3429 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3432 if (handle->id_vendor == VENDOR_SCM)
3434 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3435 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3441 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3442 msg[5] = 0; /* slot */
3443 msg[6] = seqno = handle->seqno++;
3444 msg[7] = 0; /* bBWI */
3445 msg[8] = 0; /* RFU */
3446 msg[9] = 0; /* RFU */
3447 msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3448 /* Perform PIN verification or PIN modification. */
3449 msg[11] = 0; /* Timeout in seconds. */
3450 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3451 if (handle->id_vendor == VENDOR_SCM)
3453 /* For the SPR532 the next 2 bytes need to be zero. We do this
3454 for all SCM products. Kudos to Martin Paljak for this
3456 msg[13] = msg[14] = 0;
3460 msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3461 0 bits of pin length to insert.
3462 PIN block size by fixedlen. */
3463 msg[14] = 0x00; /* bmPINLengthFormat:
3464 Units are bytes, position is 0. */
3468 if (apdu_buf[1] == 0x24)
3470 msg[msglen++] = 0; /* bInsertionOffsetOld */
3471 msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */
3474 /* The following is a little endian word. */
3475 msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */
3476 msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */
3478 if (apdu_buf[1] == 0x24)
3479 msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3481 * 0x00: new PIN once
3482 * 0x01: new PIN twice (confirmation)
3483 * 0x02: old PIN and new PIN once
3484 * 0x03: old PIN and new PIN twice (confirmation)
3487 msg[msglen] = 0x02; /* bEntryValidationCondition:
3488 Validation key pressed */
3489 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3490 msg[msglen] |= 0x01; /* Max size reached. */
3493 if (apdu_buf[1] == 0x20)
3494 msg[msglen++] = 0x01; /* bNumberMessage. */
3496 msg[msglen++] = 0x03; /* bNumberMessage. */
3498 msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3499 msg[msglen++] = 0x04; /* wLangId-High. */
3501 if (apdu_buf[1] == 0x20)
3502 msg[msglen++] = 0; /* bMsgIndex. */
3505 msg[msglen++] = 0; /* bMsgIndex1. */
3506 msg[msglen++] = 1; /* bMsgIndex2. */
3507 msg[msglen++] = 2; /* bMsgIndex3. */
3511 n = pininfo->fixedlen;
3512 if (apdu_buf[1] == 0x24)
3513 n += pininfo->fixedlen;
3515 /* bTeoProlog follows: */
3516 msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3517 msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3519 msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */
3521 msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */
3523 msg[msglen++] = apdu_buf[0]; /* CLA */
3524 msg[msglen++] = apdu_buf[1]; /* INS */
3525 msg[msglen++] = apdu_buf[2]; /* P1 */
3526 msg[msglen++] = apdu_buf[3]; /* P2 */
3529 else if (pininfo->fixedlen != 0)
3532 memset (&msg[msglen], 0xff, n);
3535 /* An EDC is not required. */
3536 set_msg_len (msg, msglen - 10);
3538 rc = bulk_out (handle, msg, msglen, 0);
3543 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3544 RDR_to_PC_DataBlock, seqno, 30000, 0);
3549 tpdulen = msglen - 10;
3551 if (handle->apdu_level)
3555 if (tpdulen > maxresplen)
3557 DEBUGOUT_2 ("provided buffer too short for received data "
3559 (unsigned int)tpdulen, (unsigned int)maxresplen);
3560 return CCID_DRIVER_ERR_INV_VALUE;
3563 memcpy (resp, tpdu, tpdulen);
3571 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3572 return CCID_DRIVER_ERR_ABORTED;
3574 if (debug_level > 1)
3575 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3576 ((msg[11] & 0xc0) == 0x80)? 'R' :
3577 (msg[11] & 0x80)? 'S' : 'I',
3578 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3579 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3580 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3582 if (!(tpdu[1] & 0x80))
3583 { /* This is an I-block. */
3584 /* Last block sent was successful. */
3587 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3588 { /* Reponse does not match our sequence number. */
3589 DEBUGOUT ("I-block with wrong seqno received\n");
3590 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3595 p = tpdu + 3; /* Skip the prologue field. */
3596 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3597 /* fixme: verify the checksum. */
3602 DEBUGOUT_2 ("provided buffer too short for received data "
3604 (unsigned int)n, (unsigned int)maxresplen);
3605 return CCID_DRIVER_ERR_INV_VALUE;
3608 memcpy (resp, p, n);
3614 if (!(tpdu[1] & 0x20))
3615 return 0; /* No chaining requested - ready. */
3617 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3618 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3620 else if ((tpdu[1] & 0xc0) == 0x80)
3621 { /* This is a R-block. */
3622 if ( (tpdu[1] & 0x0f))
3623 { /* Error: repeat last block */
3624 DEBUGOUT ("No retries supported for Secure operation\n");
3625 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3627 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3628 { /* Reponse does not match our sequence number. */
3629 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3630 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3633 { /* Send next chunk. */
3634 DEBUGOUT ("chaining not supported on Secure operation\n");
3635 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3639 { /* This is a S-block. */
3640 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3641 (tpdu[1] & 0x20)? "response": "request",
3643 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3656 print_error (int err)
3663 case 0: p = "success";
3664 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3665 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3666 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3667 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3668 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3669 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3670 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3671 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3672 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3673 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3674 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3675 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3676 default: sprintf (buf, "0x%05x", err); p = buf; break;
3678 fprintf (stderr, "operation failed: %s\n", p);
3683 print_data (const unsigned char *data, size_t length)
3687 fprintf (stderr, "operation status: %02X%02X\n",
3688 data[length-2], data[length-1]);
3693 fputs (" returned data:", stderr);
3694 for (; length; length--, data++)
3695 fprintf (stderr, " %02X", *data);
3696 putc ('\n', stderr);
3701 print_result (int rc, const unsigned char *data, size_t length)
3706 print_data (data, length);
3710 main (int argc, char **argv)
3715 unsigned char result[512];
3718 int verify_123456 = 0;
3730 if ( !strcmp (*argv, "--list"))
3733 p = ccid_get_reader_list ();
3740 else if ( !strcmp (*argv, "--debug"))
3742 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3745 else if ( !strcmp (*argv, "--no-poll"))
3750 else if ( !strcmp (*argv, "--no-pinpad"))
3755 else if ( !strcmp (*argv, "--verify-123456"))
3764 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3770 fputs ("getting ATR ...\n", stderr);
3771 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3780 fputs ("getting slot status ...\n", stderr);
3781 rc = ccid_slot_status (ccid, &slotstat);
3791 fputs ("selecting application OpenPGP ....\n", stderr);
3793 static unsigned char apdu[] = {
3794 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3795 rc = ccid_transceive (ccid,
3797 result, sizeof result, &resultlen);
3798 print_result (rc, result, resultlen);
3805 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3807 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3808 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3809 result, sizeof result, &resultlen);
3810 print_result (rc, result, resultlen);
3819 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3822 if (ccid_transceive_secure (ccid,
3826 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3829 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3831 rc = ccid_transceive_secure (ccid,
3834 result, sizeof result, &resultlen);
3835 print_result (rc, result, resultlen);
3840 if (verify_123456 && !did_verify)
3842 fputs ("verifying that CHV1 is 123456....\n", stderr);
3844 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3845 6, '1','2','3','4','5','6'};
3846 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3847 result, sizeof result, &resultlen);
3848 print_result (rc, result, resultlen);
3854 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3856 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3857 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3858 result, sizeof result, &resultlen);
3859 print_result (rc, result, resultlen);
3863 ccid_close_reader (ccid);
3870 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3874 #endif /*HAVE_LIBUSB*/