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"
97 #include "../include/host2net.h"
99 #define DRVNAME "ccid-driver: "
101 /* Max length of buffer with out CCID message header of 10-byte
102 Sending: 547 for RSA-4096 key import
103 APDU size = 540 (24+4+256+256)
104 commnd + lc + le = 4 + 3 + 0
105 Sending: write data object of cardholder certificate
107 commnd + lc + le = 4 + 3 + 0
108 Receiving: 2048 for cardholder certificate
110 #define CCID_MAX_BUF (2048+7+10)
112 /* CCID command timeout. OpenPGPcard v2.1 requires timeout of 13 seconds. */
113 #define CCID_CMD_TIMEOUT (13*1000)
115 /* Depending on how this source is used we either define our error
116 output to go to stderr or to the jnlib based logging functions. We
117 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
118 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
120 #if defined(GNUPG_MAJOR_VERSION) \
121 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
123 #if defined(GNUPG_SCD_MAIN_HEADER)
124 # include GNUPG_SCD_MAIN_HEADER
125 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
126 # include "options.h"
129 # include "cardglue.h"
130 # else /* This is the modularized GnuPG 1.9 or later. */
131 # include "scdaemon.h"
135 # define DEBUGOUT(t) do { if (debug_level) \
136 log_debug (DRVNAME t); } while (0)
137 # define DEBUGOUT_1(t,a) do { if (debug_level) \
138 log_debug (DRVNAME t,(a)); } while (0)
139 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
140 log_debug (DRVNAME t,(a),(b)); } while (0)
141 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
142 log_debug (DRVNAME t,(a),(b),(c));} while (0)
143 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
144 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
145 # define DEBUGOUT_CONT(t) do { if (debug_level) \
146 log_printf (t); } while (0)
147 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
148 log_printf (t,(a)); } while (0)
149 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
150 log_printf (t,(a),(b)); } while (0)
151 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
152 log_printf (t,(a),(b),(c)); } while (0)
153 # define DEBUGOUT_LF() do { if (debug_level) \
154 log_printf ("\n"); } while (0)
156 #else /* Other usage of this source - don't use gnupg specifics. */
158 # define DEBUGOUT(t) do { if (debug_level) \
159 fprintf (stderr, DRVNAME t); } while (0)
160 # define DEBUGOUT_1(t,a) do { if (debug_level) \
161 fprintf (stderr, DRVNAME t, (a)); } while (0)
162 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
163 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
164 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
165 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
166 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
167 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
168 # define DEBUGOUT_CONT(t) do { if (debug_level) \
169 fprintf (stderr, t); } while (0)
170 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
171 fprintf (stderr, t, (a)); } while (0)
172 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
173 fprintf (stderr, t, (a), (b)); } while (0)
174 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
175 fprintf (stderr, t, (a), (b), (c)); } while (0)
176 # define DEBUGOUT_LF() do { if (debug_level) \
177 putc ('\n', stderr); } while (0)
179 #endif /* This source not used by scdaemon. */
183 #define EAGAIN EWOULDBLOCK
189 RDR_to_PC_NotifySlotChange= 0x50,
190 RDR_to_PC_HardwareError = 0x51,
192 PC_to_RDR_SetParameters = 0x61,
193 PC_to_RDR_IccPowerOn = 0x62,
194 PC_to_RDR_IccPowerOff = 0x63,
195 PC_to_RDR_GetSlotStatus = 0x65,
196 PC_to_RDR_Secure = 0x69,
197 PC_to_RDR_T0APDU = 0x6a,
198 PC_to_RDR_Escape = 0x6b,
199 PC_to_RDR_GetParameters = 0x6c,
200 PC_to_RDR_ResetParameters = 0x6d,
201 PC_to_RDR_IccClock = 0x6e,
202 PC_to_RDR_XfrBlock = 0x6f,
203 PC_to_RDR_Mechanical = 0x71,
204 PC_to_RDR_Abort = 0x72,
205 PC_to_RDR_SetDataRate = 0x73,
207 RDR_to_PC_DataBlock = 0x80,
208 RDR_to_PC_SlotStatus = 0x81,
209 RDR_to_PC_Parameters = 0x82,
210 RDR_to_PC_Escape = 0x83,
211 RDR_to_PC_DataRate = 0x84
215 /* Two macro to detect whether a CCID command has failed and to get
216 the error code. These macros assume that we can access the
217 mandatory first 10 bytes of a CCID message in BUF. */
218 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
219 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
222 /* We need to know the vendor to do some hacks. */
224 VENDOR_CHERRY = 0x046a,
226 VENDOR_OMNIKEY= 0x076b,
227 VENDOR_GEMPC = 0x08e6,
228 VENDOR_VEGA = 0x0982,
229 VENDOR_REINER = 0x0c4b,
230 VENDOR_KAAN = 0x0d46,
231 VENDOR_VASCO = 0x1a44,
232 VENDOR_FSIJ = 0x234b,
235 /* Some product ids. */
236 #define SCM_SCR331 0xe001
237 #define SCM_SCR331DI 0x5111
238 #define SCM_SCR335 0x5115
239 #define SCM_SCR3320 0x5117
240 #define SCM_SPR532 0xe003
241 #define CHERRY_ST2000 0x003e
242 #define VASCO_920 0x0920
243 #define GEMPC_PINPAD 0x3478
244 #define GEMPC_CT30 0x3437
245 #define VEGA_ALPHA 0x0008
246 #define CYBERJACK_GO 0x0504
248 /* A list and a table with special transport descriptions. */
250 TRANSPORT_USB = 0, /* Standard USB transport. */
251 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
256 char *name; /* Device name. */
260 { "/dev/cmx0", TRANSPORT_CM4040 },
261 { "/dev/cmx1", TRANSPORT_CM4040 },
266 /* Store information on the driver's state. A pointer to such a
267 structure is used as handle for most functions. */
270 usb_dev_handle *idev;
272 int dev_fd; /* -1 for USB transport or file descriptor of the
274 unsigned short id_vendor;
275 unsigned short id_product;
276 unsigned short bcd_device;
284 unsigned char nonnull_nad;
288 unsigned char apdu_level:2; /* Reader supports short APDU level
289 exchange. With a value of 2 short
290 and extended level is supported.*/
291 unsigned int auto_voltage:1;
292 unsigned int auto_param:1;
293 unsigned int auto_pps:1;
294 unsigned int auto_ifsd:1;
295 unsigned int powered_off:1;
296 unsigned int has_pinpad:2;
297 unsigned int enodev_seen:1;
299 time_t last_progress; /* Last time we sent progress line. */
301 /* The progress callback and its first arg as supplied to
302 ccid_set_progress_cb. */
303 void (*progress_cb)(void *, const char *, int, int, int);
304 void *progress_cb_arg;
308 static int initialized_usb; /* Tracks whether USB has been initialized. */
309 static int debug_level; /* Flag to control the debug output.
312 2 = Level 1 + T=1 protocol tracing
313 3 = Level 2 + USB/I/O tracing of SlotStatus.
317 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
319 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
321 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
322 size_t *nread, int expected_type, int seqno, int timeout,
324 static int abort_cmd (ccid_driver_t handle, int seqno);
325 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
326 size_t datalen, unsigned char *result,
327 size_t resultmax, size_t *resultlen);
329 /* Convert a little endian stored 4 byte value into an unsigned
332 convert_le_u32 (const unsigned char *buf)
334 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | ((unsigned int)buf[3] << 24);
338 /* Convert a little endian stored 2 byte value into an unsigned
341 convert_le_u16 (const unsigned char *buf)
343 return buf[0] | (buf[1] << 8);
347 set_msg_len (unsigned char *msg, unsigned int length)
350 msg[2] = length >> 8;
351 msg[3] = length >> 16;
352 msg[4] = length >> 24;
357 my_sleep (int seconds)
360 /* With Pth we also call the standard sleep(0) so that the process
361 may give up its timeslot. */
364 # ifdef HAVE_W32_SYSTEM
372 # ifdef HAVE_W32_SYSTEM
373 Sleep (seconds*1000);
381 print_progress (ccid_driver_t handle)
383 time_t ct = time (NULL);
385 /* We don't want to print progress lines too often. */
386 if (ct == handle->last_progress)
389 if (handle->progress_cb)
390 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
392 handle->last_progress = ct;
397 /* Pint an error message for a failed CCID command including a textual
398 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
400 print_command_failed (const unsigned char *msg)
409 ec = CCID_ERROR_CODE (msg);
412 case 0x00: t = "Command not supported"; break;
414 case 0xE0: t = "Slot busy"; break;
415 case 0xEF: t = "PIN cancelled"; break;
416 case 0xF0: t = "PIN timeout"; break;
418 case 0xF2: t = "Automatic sequence ongoing"; break;
419 case 0xF3: t = "Deactivated Protocol"; break;
420 case 0xF4: t = "Procedure byte conflict"; break;
421 case 0xF5: t = "ICC class not supported"; break;
422 case 0xF6: t = "ICC protocol not supported"; break;
423 case 0xF7: t = "Bad checksum in ATR"; break;
424 case 0xF8: t = "Bad TS in ATR"; break;
426 case 0xFB: t = "An all inclusive hardware error occurred"; break;
427 case 0xFC: t = "Overrun error while talking to the ICC"; break;
428 case 0xFD: t = "Parity error while talking to the ICC"; break;
429 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
430 case 0xFF: t = "Host aborted the current activity"; break;
433 if (ec > 0 && ec < 128)
434 sprintf (buffer, "Parameter error at offset %d", ec);
436 sprintf (buffer, "Error code %02X", ec);
440 DEBUGOUT_1 ("CCID command failed: %s\n", t);
445 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
449 for (; off < datalen; off++)
451 if (!any || !(off % 16))
455 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
457 DEBUGOUT_CONT_1 (" %02X", data[off]);
460 if (any && (off % 16))
466 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
468 DEBUGOUT_1 ("%s:\n", name);
471 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
472 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
473 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
478 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
480 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
483 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
485 msg[7] == 1? "5.0 V":
486 msg[7] == 2? "3.0 V":
487 msg[7] == 3? "1.8 V":"");
488 print_pr_data (msg, msglen, 8);
493 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
495 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
496 print_pr_data (msg, msglen, 7);
501 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
503 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
504 print_pr_data (msg, msglen, 7);
509 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
513 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
516 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
517 val = convert_le_u16 (msg+8);
518 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
519 val == 1? " (continued)":
520 val == 2? " (continues+ends)":
521 val == 3? " (continues+continued)":
522 val == 16? " (DataBlock-expected)":"");
523 print_pr_data (msg, msglen, 10);
528 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
530 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
531 print_pr_data (msg, msglen, 7);
536 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
538 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
539 print_pr_data (msg, msglen, 7);
544 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
546 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
549 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
550 print_pr_data (msg, msglen, 8);
555 print_p2r_escape (const unsigned char *msg, size_t msglen)
557 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
558 print_pr_data (msg, msglen, 7);
563 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
565 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
568 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
569 print_pr_data (msg, msglen, 8);
574 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
576 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
579 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
580 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
581 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
582 print_pr_data (msg, msglen, 10);
587 print_p2r_secure (const unsigned char *msg, size_t msglen)
591 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
594 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
595 val = convert_le_u16 (msg+8);
596 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
597 val == 1? " (continued)":
598 val == 2? " (continues+ends)":
599 val == 3? " (continues+continued)":
600 val == 16? " (DataBlock-expected)":"");
601 print_pr_data (msg, msglen, 10);
606 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
608 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
611 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
612 print_pr_data (msg, msglen, 8);
617 print_p2r_abort (const unsigned char *msg, size_t msglen)
619 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
620 print_pr_data (msg, msglen, 7);
625 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
627 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
630 print_pr_data (msg, msglen, 7);
635 print_p2r_unknown (const unsigned char *msg, size_t msglen)
637 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
640 print_pr_data (msg, msglen, 0);
645 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
647 DEBUGOUT_1 ("%s:\n", name);
650 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
651 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
652 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
653 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
655 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
660 print_r2p_datablock (const unsigned char *msg, size_t msglen)
662 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
666 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
667 msg[9] == 1? " (continued)":
668 msg[9] == 2? " (continues+ends)":
669 msg[9] == 3? " (continues+continued)":
670 msg[9] == 16? " (XferBlock-expected)":"");
671 print_pr_data (msg, msglen, 10);
676 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
678 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
681 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
682 msg[9] == 0? " (running)":
683 msg[9] == 1? " (stopped-L)":
684 msg[9] == 2? " (stopped-H)":
685 msg[9] == 3? " (stopped)":"");
686 print_pr_data (msg, msglen, 10);
691 print_r2p_parameters (const unsigned char *msg, size_t msglen)
693 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
697 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
698 if (msglen == 17 && msg[9] == 1)
701 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
702 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
703 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
704 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
705 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
706 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
707 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
710 print_pr_data (msg, msglen, 10);
715 print_r2p_escape (const unsigned char *msg, size_t msglen)
717 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
720 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
721 print_pr_data (msg, msglen, 10);
726 print_r2p_datarate (const unsigned char *msg, size_t msglen)
728 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
733 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
734 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
735 print_pr_data (msg, msglen, 18);
738 print_pr_data (msg, msglen, 10);
743 print_r2p_unknown (const unsigned char *msg, size_t msglen)
745 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
748 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
749 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
750 print_pr_data (msg, msglen, 10);
754 /* Given a handle used for special transport prepare it for use. In
755 particular setup all information in way that resembles what
756 parse_cccid_descriptor does. */
758 prepare_special_transport (ccid_driver_t handle)
760 assert (!handle->id_vendor);
762 handle->nonnull_nad = 0;
763 handle->auto_ifsd = 0;
764 handle->max_ifsd = 32;
765 handle->max_ccid_msglen = CCID_MAX_BUF;
766 handle->has_pinpad = 0;
767 handle->apdu_level = 0;
768 switch (handle->id_product)
770 case TRANSPORT_CM4040:
771 DEBUGOUT ("setting up transport for CardMan 4040\n");
772 handle->apdu_level = 1;
775 default: assert (!"transport not defined");
779 /* Parse a CCID descriptor, optionally print all available features
780 and test whether this reader is usable by this driver. Returns 0
783 Note, that this code is based on the one in lsusb.c of the
784 usb-utils package, I wrote on 2003-09-01. -wk. */
786 parse_ccid_descriptor (ccid_driver_t handle,
787 const unsigned char *buf, size_t buflen)
791 int have_t1 = 0, have_tpdu=0;
794 handle->nonnull_nad = 0;
795 handle->auto_ifsd = 0;
796 handle->max_ifsd = 32;
797 handle->has_pinpad = 0;
798 handle->apdu_level = 0;
799 handle->auto_voltage = 0;
800 handle->auto_param = 0;
801 handle->auto_pps = 0;
802 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
803 handle->id_vendor, handle->id_product, handle->bcd_device);
804 if (buflen < 54 || buf[0] < 54)
806 DEBUGOUT ("CCID device descriptor is too short\n");
810 DEBUGOUT ("ChipCard Interface Descriptor:\n");
811 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
812 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
813 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
814 if (buf[3] != 1 || buf[2] != 0)
815 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
818 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
819 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
820 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
821 : buf[5] == 3? "1.8V":"?"));
823 us = convert_le_u32 (buf+6);
824 DEBUGOUT_1 (" dwProtocols %5u ", us);
826 DEBUGOUT_CONT (" T=0");
829 DEBUGOUT_CONT (" T=1");
833 DEBUGOUT_CONT (" (Invalid values detected)");
836 us = convert_le_u32(buf+10);
837 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
838 us = convert_le_u32(buf+14);
839 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
840 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
841 us = convert_le_u32(buf+19);
842 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
843 us = convert_le_u32(buf+23);
844 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
845 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
847 us = convert_le_u32(buf+28);
848 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
849 handle->max_ifsd = us;
851 us = convert_le_u32(buf+32);
852 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
854 DEBUGOUT_CONT ( " 2-wire");
856 DEBUGOUT_CONT ( " 3-wire");
858 DEBUGOUT_CONT ( " I2C");
861 us = convert_le_u32(buf+36);
862 DEBUGOUT_1 (" dwMechanical %08X ", us);
864 DEBUGOUT_CONT (" accept");
866 DEBUGOUT_CONT (" eject");
868 DEBUGOUT_CONT (" capture");
870 DEBUGOUT_CONT (" lock");
873 us = convert_le_u32(buf+40);
874 DEBUGOUT_1 (" dwFeatures %08X\n", us);
877 DEBUGOUT (" Auto configuration based on ATR (assumes auto voltage)\n");
878 handle->auto_voltage = 1;
881 DEBUGOUT (" Auto activation on insert\n");
884 DEBUGOUT (" Auto voltage selection\n");
885 handle->auto_voltage = 1;
888 DEBUGOUT (" Auto clock change\n");
890 DEBUGOUT (" Auto baud rate change\n");
893 DEBUGOUT (" Auto parameter negotiation made by CCID\n");
894 handle->auto_param = 1;
896 else if ((us & 0x0080))
898 DEBUGOUT (" Auto PPS made by CCID\n");
899 handle->auto_pps = 1;
901 if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
902 DEBUGOUT (" WARNING: conflicting negotiation features\n");
905 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
908 DEBUGOUT (" NAD value other than 0x00 accepted\n");
909 handle->nonnull_nad = 1;
913 DEBUGOUT (" Auto IFSD exchange\n");
914 handle->auto_ifsd = 1;
917 if ((us & 0x00010000))
919 DEBUGOUT (" TPDU level exchange\n");
922 else if ((us & 0x00020000))
924 DEBUGOUT (" Short APDU level exchange\n");
925 handle->apdu_level = 1;
927 else if ((us & 0x00040000))
929 DEBUGOUT (" Short and extended APDU level exchange\n");
930 handle->apdu_level = 2;
932 else if ((us & 0x00070000))
933 DEBUGOUT (" WARNING: conflicting exchange levels\n");
935 us = convert_le_u32(buf+44);
936 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
937 handle->max_ccid_msglen = us;
939 DEBUGOUT ( " bClassGetResponse ");
941 DEBUGOUT_CONT ("echo\n");
943 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
945 DEBUGOUT ( " bClassEnvelope ");
947 DEBUGOUT_CONT ("echo\n");
949 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
951 DEBUGOUT ( " wlcdLayout ");
952 if (!buf[50] && !buf[51])
953 DEBUGOUT_CONT ("none\n");
955 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
957 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
960 DEBUGOUT_CONT ( " verification");
961 handle->has_pinpad |= 1;
965 DEBUGOUT_CONT ( " modification");
966 handle->has_pinpad |= 2;
970 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
974 for (i=54; i < buf[0]-54; i++)
975 DEBUGOUT_CONT_1 (" %02X", buf[i]);
979 if (!have_t1 || !(have_tpdu || handle->apdu_level))
981 DEBUGOUT ("this drivers requires that the reader supports T=1, "
982 "TPDU or APDU level exchange - this is not available\n");
987 /* SCM drivers get stuck in their internal USB stack if they try to
988 send a frame of n*wMaxPacketSize back to us. Given that
989 wMaxPacketSize is 64 for these readers we set the IFSD to a value
991 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
998 0x5117 - SCR 3320 USB ID-000 reader
999 seems to be very slow but enabling this workaround boosts the
1000 performance to a a more or less acceptable level (tested by David).
1003 if (handle->id_vendor == VENDOR_SCM
1004 && handle->max_ifsd > 48
1005 && ( (handle->id_product == SCM_SCR331 && handle->bcd_device < 0x0516)
1006 ||(handle->id_product == SCM_SCR331DI && handle->bcd_device < 0x0620)
1007 ||(handle->id_product == SCM_SCR335 && handle->bcd_device < 0x0514)
1008 ||(handle->id_product == SCM_SPR532 && handle->bcd_device < 0x0504)
1009 ||(handle->id_product == SCM_SCR3320 && handle->bcd_device < 0x0522)
1012 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
1013 handle->max_ifsd = 48;
1016 if (handle->id_vendor == VENDOR_GEMPC && handle->id_product == GEMPC_CT30)
1018 DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
1019 handle->nonnull_nad = 0;
1027 get_escaped_usb_string (usb_dev_handle *idev, int idx,
1028 const char *prefix, const char *suffix)
1031 unsigned char buf[280];
1033 unsigned int langid;
1040 /* Fixme: The next line is for the current Valgrid without support
1042 memset (buf, 0, sizeof buf);
1044 /* First get the list of supported languages and use the first one.
1045 If we do don't find it we try to use English. Note that this is
1046 all in a 2 bute Unicode encoding using little endian. */
1047 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1048 (USB_DT_STRING << 8), 0,
1049 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1051 langid = 0x0409; /* English. */
1053 langid = (buf[3] << 8) | buf[2];
1055 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1056 (USB_DT_STRING << 8) + idx, langid,
1057 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1058 if (rc < 2 || buf[1] != USB_DT_STRING)
1059 return NULL; /* Error or not a string. */
1062 return NULL; /* Larger than our buffer. */
1064 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1067 n++; /* High byte set. */
1068 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1074 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1078 strcpy (result, prefix);
1079 n = strlen (prefix);
1080 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1083 result[n++] = '\xff'; /* High byte set. */
1084 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1086 sprintf (result+n, "%%%02X", *s);
1092 strcpy (result+n, suffix);
1097 /* This function creates an reader id to be used to find the same
1098 physical reader after a reset. It returns an allocated and possibly
1099 percent escaped string or NULL if not enough memory is available. */
1101 make_reader_id (usb_dev_handle *idev,
1102 unsigned int vendor, unsigned int product,
1103 unsigned char serialno_index)
1108 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1109 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1112 rid = malloc (strlen (prefix) + 3 + 1);
1115 strcpy (rid, prefix);
1116 strcat (rid, "X:0");
1122 /* Helper to find the endpoint from an interface descriptor. */
1124 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1127 int want_bulk_in = 0;
1130 want_bulk_in = 0x80;
1131 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1133 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1134 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1137 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1138 == USB_ENDPOINT_TYPE_INTERRUPT)
1139 && (ep->bEndpointAddress & 0x80))
1140 return (ep->bEndpointAddress & 0x0f);
1141 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1142 == USB_ENDPOINT_TYPE_BULK)
1143 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1144 return (ep->bEndpointAddress & 0x0f);
1146 /* Should never happen. */
1147 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1151 /* Helper for scan_or_find_devices. This function returns true if a
1152 requested device has been found or the caller should stop scanning
1153 for other reasons. */
1155 scan_or_find_usb_device (int scan_mode,
1156 int *readerno, int *count, char **rid_list,
1157 const char *readerid,
1158 struct usb_device *dev,
1160 struct usb_device **r_dev,
1161 usb_dev_handle **r_idev,
1162 unsigned char **ifcdesc_extra,
1163 size_t *ifcdesc_extra_len,
1164 int *interface_number,
1165 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1170 struct usb_config_descriptor *config;
1171 struct usb_interface *interface;
1172 struct usb_interface_descriptor *ifcdesc;
1174 usb_dev_handle *idev;
1178 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1180 config = dev->config + cfg_no;
1184 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1186 interface = config->interface + ifc_no;
1190 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1192 ifcdesc = (interface->altsetting + set_no);
1193 /* The second condition is for older SCM SPR 532 who did
1194 not know about the assigned CCID class. The third
1195 condition does the same for a Cherry SmartTerminal
1196 ST-2000. Instead of trying to interpret the strings
1197 we simply check the product ID. */
1198 if (ifcdesc && ifcdesc->extra
1199 && ((ifcdesc->bInterfaceClass == 11
1200 && ifcdesc->bInterfaceSubClass == 0
1201 && ifcdesc->bInterfaceProtocol == 0)
1202 || (ifcdesc->bInterfaceClass == 255
1203 && dev->descriptor.idVendor == VENDOR_SCM
1204 && dev->descriptor.idProduct == SCM_SPR532)
1205 || (ifcdesc->bInterfaceClass == 255
1206 && dev->descriptor.idVendor == VENDOR_CHERRY
1207 && dev->descriptor.idProduct == CHERRY_ST2000)))
1209 idev = usb_open (dev);
1212 DEBUGOUT_1 ("usb_open failed: %s\n",
1214 continue; /* with next setting. */
1217 rid = make_reader_id (idev,
1218 dev->descriptor.idVendor,
1219 dev->descriptor.idProduct,
1220 dev->descriptor.iSerialNumber);
1227 /* We are collecting infos about all
1228 available CCID readers. Store them and
1230 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1232 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1233 + strlen (rid) + 1);
1239 strcat (p, *rid_list);
1246 else /* Out of memory. */
1255 && !strcmp (readerid, rid)))
1257 /* We found the requested reader. */
1258 if (ifcdesc_extra && ifcdesc_extra_len)
1260 *ifcdesc_extra = malloc (ifcdesc
1262 if (!*ifcdesc_extra)
1266 return 1; /* Out of core. */
1268 memcpy (*ifcdesc_extra, ifcdesc->extra,
1270 *ifcdesc_extra_len = ifcdesc->extralen;
1273 if (interface_number)
1274 *interface_number = (ifcdesc->bInterfaceNumber);
1277 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1279 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1281 *ep_intr = find_endpoint (ifcdesc, 2);
1294 return 1; /* Found requested device. */
1298 /* This is not yet the reader we want.
1299 fixme: We should avoid the extra usb_open
1318 /* Combination function to either scan all CCID devices or to find and
1319 open one specific device.
1321 The function returns 0 if a reader has been found or when a scan
1322 returned without error.
1324 With READERNO = -1 and READERID is NULL, scan mode is used and
1325 R_RID should be the address where to store the list of reader_ids
1326 we found. If on return this list is empty, no CCID device has been
1327 found; otherwise it points to an allocated linked list of reader
1328 IDs. Note that in this mode the function always returns NULL.
1330 With READERNO >= 0 or READERID is not NULL find mode is used. This
1331 uses the same algorithm as the scan mode but stops and returns at
1332 the entry number READERNO and return the handle for the the opened
1333 USB device. If R_RID is not NULL it will receive the reader ID of
1334 that device. If R_DEV is not NULL it will the device pointer of
1335 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1336 malloced copy of the interfaces "extra: data filed;
1337 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1338 no reader with number READERNO or that reader is not usable by our
1339 implementation NULL will be returned. The caller must close a
1340 returned USB device handle and free (if not passed as NULL) the
1341 returned reader ID info as well as the IFCDESC_EXTRA. On error
1342 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1343 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1344 the READERID was found.
1346 If R_FD is not -1 on return the device is not using USB for
1347 transport but the device associated with that file descriptor. In
1348 this case INTERFACE will receive the transport type and the other
1349 USB specific return values are not used; the return value is
1352 Note that the first entry of the returned reader ID list in scan mode
1353 corresponds with a READERNO of 0 in find mode.
1356 scan_or_find_devices (int readerno, const char *readerid,
1358 struct usb_device **r_dev,
1359 unsigned char **ifcdesc_extra,
1360 size_t *ifcdesc_extra_len,
1361 int *interface_number,
1362 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1363 usb_dev_handle **r_idev,
1366 char *rid_list = NULL;
1368 struct usb_bus *busses, *bus;
1369 struct usb_device *dev = NULL;
1370 usb_dev_handle *idev = NULL;
1371 int scan_mode = (readerno == -1 && !readerid);
1374 /* Set return values to a default. */
1380 *ifcdesc_extra = NULL;
1381 if (ifcdesc_extra_len)
1382 *ifcdesc_extra_len = 0;
1383 if (interface_number)
1384 *interface_number = 0;
1390 /* See whether we want scan or find mode. */
1399 #ifdef HAVE_USB_GET_BUSSES
1400 busses = usb_get_busses();
1402 busses = usb_busses;
1405 for (bus = busses; bus; bus = bus->next)
1407 for (dev = bus->devices; dev; dev = dev->next)
1409 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1418 ep_bulk_out, ep_bulk_in, ep_intr))
1420 /* Found requested device or out of core. */
1424 return -1; /* error */
1432 /* Now check whether there are any devices with special transport types. */
1433 for (i=0; transports[i].name; i++)
1438 fd = open (transports[i].name, O_RDWR);
1439 if (fd == -1 && scan_mode && errno == EBUSY)
1441 /* Ignore this error in scan mode because it indicates that
1442 the device exists but is already open (most likely by us)
1443 and thus in general suitable as a reader. */
1447 DEBUGOUT_2 ("failed to open `%s': %s\n",
1448 transports[i].name, strerror (errno));
1452 rid = malloc (strlen (transports[i].name) + 30 + 10);
1458 return -1; /* Error. */
1460 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1463 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1464 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1471 return -1; /* Error. */
1476 strcat (p, rid_list);
1484 else if (!readerno ||
1485 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1487 /* Found requested device. */
1488 if (interface_number)
1489 *interface_number = transports[i].type;
1496 return 0; /* Okay, found device */
1498 else /* This is not yet the reader we want. */
1518 /* Set the level of debugging to LEVEL and return the old level. -1
1519 just returns the old level. A level of 0 disables debugging, 1
1520 enables debugging, 2 enables additional tracing of the T=1
1521 protocol, 3 additionally enables debugging for GetSlotStatus, other
1522 values are not yet defined.
1524 Note that libusb may provide its own debugging feature which is
1525 enabled by setting the envvar USB_DEBUG. */
1527 ccid_set_debug_level (int level)
1529 int old = debug_level;
1531 debug_level = level;
1537 ccid_get_reader_list (void)
1541 if (!initialized_usb)
1544 initialized_usb = 1;
1547 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1548 NULL, NULL, NULL, NULL, NULL))
1549 return NULL; /* Error. */
1554 /* Vendor specific custom initialization. */
1556 ccid_vendor_specific_init (ccid_driver_t handle)
1558 if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1562 * Vega alpha has a feature to show retry counter on the pinpad
1563 * display. But it assumes that the card returns the value of
1564 * retry counter by VERIFY with empty data (return code of
1565 * 63Cx). Unfortunately, existing OpenPGP cards don't support
1566 * VERIFY command with empty data. This vendor specific command
1567 * sequence is to disable the feature.
1569 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1571 r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1572 if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1573 && r != CCID_DRIVER_ERR_NO_CARD)
1581 /* Open the reader with the internal number READERNO and return a
1582 pointer to be used as handle in HANDLE. Returns 0 on success. */
1584 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1587 struct usb_device *dev = NULL;
1588 usb_dev_handle *idev = NULL;
1591 unsigned char *ifcdesc_extra = NULL;
1592 size_t ifcdesc_extra_len;
1594 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1598 if (!initialized_usb)
1601 initialized_usb = 1;
1604 /* See whether we want to use the reader ID string or a reader
1605 number. A readerno of -1 indicates that the reader ID string is
1607 if (readerid && strchr (readerid, ':'))
1608 readerno = -1; /* We want to use the readerid. */
1611 readerno = atoi (readerid);
1614 DEBUGOUT ("no CCID readers found\n");
1615 rc = CCID_DRIVER_ERR_NO_READER;
1620 readerno = 0; /* Default. */
1622 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1623 &ifcdesc_extra, &ifcdesc_extra_len,
1624 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1628 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1630 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1631 rc = CCID_DRIVER_ERR_NO_READER;
1635 /* Okay, this is a CCID reader. */
1636 *handle = calloc (1, sizeof **handle);
1639 DEBUGOUT ("out of memory\n");
1640 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1643 (*handle)->rid = rid;
1644 if (idev) /* Regular USB transport. */
1646 (*handle)->idev = idev;
1647 (*handle)->dev_fd = -1;
1648 (*handle)->id_vendor = dev->descriptor.idVendor;
1649 (*handle)->id_product = dev->descriptor.idProduct;
1650 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1651 (*handle)->ifc_no = ifc_no;
1652 (*handle)->ep_bulk_out = ep_bulk_out;
1653 (*handle)->ep_bulk_in = ep_bulk_in;
1654 (*handle)->ep_intr = ep_intr;
1656 else if (dev_fd != -1) /* Device transport. */
1658 (*handle)->idev = NULL;
1659 (*handle)->dev_fd = dev_fd;
1660 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1661 (*handle)->id_product = ifc_no; /* Transport type */
1662 prepare_special_transport (*handle);
1666 assert (!"no transport"); /* Bug. */
1669 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1673 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1675 DEBUGOUT ("device not supported\n");
1676 rc = CCID_DRIVER_ERR_NO_READER;
1680 rc = usb_claim_interface (idev, ifc_no);
1683 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1684 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1689 rc = ccid_vendor_specific_init (*handle);
1692 free (ifcdesc_extra);
1709 do_close_reader (ccid_driver_t handle)
1712 unsigned char msg[100];
1714 unsigned char seqno;
1716 if (!handle->powered_off)
1718 msg[0] = PC_to_RDR_IccPowerOff;
1719 msg[5] = 0; /* slot */
1720 msg[6] = seqno = handle->seqno++;
1721 msg[7] = 0; /* RFU */
1722 msg[8] = 0; /* RFU */
1723 msg[9] = 0; /* RFU */
1724 set_msg_len (msg, 0);
1727 rc = bulk_out (handle, msg, msglen, 0);
1729 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1731 handle->powered_off = 1;
1735 usb_release_interface (handle->idev, handle->ifc_no);
1736 usb_close (handle->idev);
1737 handle->idev = NULL;
1739 if (handle->dev_fd != -1)
1741 close (handle->dev_fd);
1742 handle->dev_fd = -1;
1747 /* Reset a reader on HANDLE. This is useful in case a reader has been
1748 plugged of and inserted at a different port. By resetting the
1749 handle, the same reader will be get used. Note, that on error the
1750 handle won't get released.
1752 This does not return an ATR, so ccid_get_atr should be called right
1756 ccid_shutdown_reader (ccid_driver_t handle)
1759 struct usb_device *dev = NULL;
1760 usb_dev_handle *idev = NULL;
1761 unsigned char *ifcdesc_extra = NULL;
1762 size_t ifcdesc_extra_len;
1763 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1765 if (!handle || !handle->rid)
1766 return CCID_DRIVER_ERR_INV_VALUE;
1768 do_close_reader (handle);
1770 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1771 &ifcdesc_extra, &ifcdesc_extra_len,
1772 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1773 &idev, NULL) || !idev)
1775 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1776 return CCID_DRIVER_ERR_NO_READER;
1781 handle->idev = idev;
1782 handle->ifc_no = ifc_no;
1783 handle->ep_bulk_out = ep_bulk_out;
1784 handle->ep_bulk_in = ep_bulk_in;
1785 handle->ep_intr = ep_intr;
1787 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1789 DEBUGOUT ("device not supported\n");
1790 rc = CCID_DRIVER_ERR_NO_READER;
1794 rc = usb_claim_interface (idev, ifc_no);
1797 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1798 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1804 free (ifcdesc_extra);
1808 usb_close (handle->idev);
1809 handle->idev = NULL;
1810 if (handle->dev_fd != -1)
1811 close (handle->dev_fd);
1812 handle->dev_fd = -1;
1821 ccid_set_progress_cb (ccid_driver_t handle,
1822 void (*cb)(void *, const char *, int, int, int),
1825 if (!handle || !handle->rid)
1826 return CCID_DRIVER_ERR_INV_VALUE;
1828 handle->progress_cb = cb;
1829 handle->progress_cb_arg = cb_arg;
1834 /* Close the reader HANDLE. */
1836 ccid_close_reader (ccid_driver_t handle)
1838 if (!handle || (!handle->idev && handle->dev_fd == -1))
1841 do_close_reader (handle);
1848 /* Return False if a card is present and powered. */
1850 ccid_check_card_presence (ccid_driver_t handle)
1852 (void)handle; /* Not yet implemented. */
1857 /* Write NBYTES of BUF to file descriptor FD. */
1859 writen (int fd, const void *buf, size_t nbytes)
1861 size_t nleft = nbytes;
1866 nwritten = write (fd, buf, nleft);
1875 buf = (const char*)buf + nwritten;
1882 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1883 Returns 0 on success. */
1885 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1890 /* No need to continue and clutter the log with USB write error
1891 messages after we got the first ENODEV. */
1892 if (handle->enodev_seen)
1893 return CCID_DRIVER_ERR_NO_READER;
1895 if (debug_level && (!no_debug || debug_level >= 3))
1897 switch (msglen? msg[0]:0)
1899 case PC_to_RDR_IccPowerOn:
1900 print_p2r_iccpoweron (msg, msglen);
1902 case PC_to_RDR_IccPowerOff:
1903 print_p2r_iccpoweroff (msg, msglen);
1905 case PC_to_RDR_GetSlotStatus:
1906 print_p2r_getslotstatus (msg, msglen);
1908 case PC_to_RDR_XfrBlock:
1909 print_p2r_xfrblock (msg, msglen);
1911 case PC_to_RDR_GetParameters:
1912 print_p2r_getparameters (msg, msglen);
1914 case PC_to_RDR_ResetParameters:
1915 print_p2r_resetparameters (msg, msglen);
1917 case PC_to_RDR_SetParameters:
1918 print_p2r_setparameters (msg, msglen);
1920 case PC_to_RDR_Escape:
1921 print_p2r_escape (msg, msglen);
1923 case PC_to_RDR_IccClock:
1924 print_p2r_iccclock (msg, msglen);
1926 case PC_to_RDR_T0APDU:
1927 print_p2r_to0apdu (msg, msglen);
1929 case PC_to_RDR_Secure:
1930 print_p2r_secure (msg, msglen);
1932 case PC_to_RDR_Mechanical:
1933 print_p2r_mechanical (msg, msglen);
1935 case PC_to_RDR_Abort:
1936 print_p2r_abort (msg, msglen);
1938 case PC_to_RDR_SetDataRate:
1939 print_p2r_setdatarate (msg, msglen);
1942 print_p2r_unknown (msg, msglen);
1949 rc = usb_bulk_write (handle->idev,
1950 handle->ep_bulk_out,
1952 5000 /* ms timeout */);
1956 if (rc == -(ENODEV))
1958 /* The Linux libusb returns a negative error value. Catch
1959 the most important one. */
1967 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1969 if (errno == ENODEV)
1971 handle->enodev_seen = 1;
1972 return CCID_DRIVER_ERR_NO_READER;
1977 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1981 rc = writen (handle->dev_fd, msg, msglen);
1984 DEBUGOUT_2 ("writen to %d failed: %s\n",
1985 handle->dev_fd, strerror (errno));
1988 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1992 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1993 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1994 is the sequence number used to send the request and EXPECTED_TYPE
1995 the type of message we expect. Does checks on the ccid
1996 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1997 avoid debug messages in case of no error; this can be overriden
1998 with a glibal debug level of at least 3. Returns 0 on success. */
2000 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
2001 size_t *nread, int expected_type, int seqno, int timeout,
2006 int eagain_retries = 0;
2008 /* Fixme: The next line for the current Valgrind without support
2010 memset (buffer, 0, length);
2014 rc = usb_bulk_read (handle->idev,
2016 (char*)buffer, length,
2021 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
2022 if (rc == EAGAIN && eagain_retries++ < 3)
2027 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2029 *nread = msglen = rc;
2033 rc = read (handle->dev_fd, buffer, length);
2037 DEBUGOUT_2 ("read from %d failed: %s\n",
2038 handle->dev_fd, strerror (rc));
2039 if (rc == EAGAIN && eagain_retries++ < 5)
2044 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2046 *nread = msglen = rc;
2052 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2053 abort_cmd (handle, seqno);
2054 return CCID_DRIVER_ERR_INV_VALUE;
2058 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2059 return CCID_DRIVER_ERR_INV_VALUE;
2061 if (buffer[6] != seqno)
2063 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2065 /* Retry until we are synced again. */
2069 /* We need to handle the time extension request before we check that
2070 we got the expected message type. This is in particular required
2071 for the Cherry keyboard which sends a time extension request for
2073 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2075 /* Card present and active, time extension requested. */
2076 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2077 buffer[7], buffer[8]);
2081 if (buffer[0] != expected_type)
2083 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2084 abort_cmd (handle, seqno);
2085 return CCID_DRIVER_ERR_INV_VALUE;
2088 if (debug_level && (!no_debug || debug_level >= 3))
2092 case RDR_to_PC_DataBlock:
2093 print_r2p_datablock (buffer, msglen);
2095 case RDR_to_PC_SlotStatus:
2096 print_r2p_slotstatus (buffer, msglen);
2098 case RDR_to_PC_Parameters:
2099 print_r2p_parameters (buffer, msglen);
2101 case RDR_to_PC_Escape:
2102 print_r2p_escape (buffer, msglen);
2104 case RDR_to_PC_DataRate:
2105 print_r2p_datarate (buffer, msglen);
2108 print_r2p_unknown (buffer, msglen);
2112 if (CCID_COMMAND_FAILED (buffer))
2113 print_command_failed (buffer);
2115 /* Check whether a card is at all available. Note: If you add new
2116 error codes here, check whether they need to be ignored in
2118 switch ((buffer[7] & 0x03))
2120 case 0: /* no error */ break;
2121 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2122 case 2: return CCID_DRIVER_ERR_NO_CARD;
2123 case 3: /* RFU */ break;
2130 /* Send an abort sequence and wait until everything settled. */
2132 abort_cmd (ccid_driver_t handle, int seqno)
2136 unsigned char msg[100];
2141 /* I don't know how to send an abort to non-USB devices. */
2142 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2146 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2147 /* Send the abort command to the control pipe. Note that we don't
2148 need to keep track of sent abort commands because there should
2149 never be another thread using the same slot concurrently. */
2150 rc = usb_control_msg (handle->idev,
2151 0x21,/* bmRequestType: host-to-device,
2152 class specific, to interface. */
2154 (seqno << 8 | 0 /* slot */),
2157 1000 /* ms timeout */);
2160 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
2161 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2164 /* Now send the abort command to the bulk out pipe using the same
2165 SEQNO and SLOT. Do this in a loop to so that all seqno are
2167 seqno--; /* Adjust for next increment. */
2171 msg[0] = PC_to_RDR_Abort;
2172 msg[5] = 0; /* slot */
2174 msg[7] = 0; /* RFU */
2175 msg[8] = 0; /* RFU */
2176 msg[9] = 0; /* RFU */
2178 set_msg_len (msg, 0);
2180 rc = usb_bulk_write (handle->idev,
2181 handle->ep_bulk_out,
2183 5000 /* ms timeout */);
2187 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2190 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2195 rc = usb_bulk_read (handle->idev,
2197 (char*)msg, sizeof msg,
2198 5000 /*ms timeout*/);
2201 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2203 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2209 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2210 (unsigned int)msglen);
2211 return CCID_DRIVER_ERR_INV_VALUE;
2215 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2216 return CCID_DRIVER_ERR_INV_VALUE;
2219 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2220 msg[7], msg[8], msg[9]);
2221 if (CCID_COMMAND_FAILED (msg))
2222 print_command_failed (msg);
2224 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2226 handle->seqno = ((seqno + 1) & 0xff);
2227 DEBUGOUT ("sending abort sequence succeeded\n");
2233 /* Note that this function won't return the error codes NO_CARD or
2234 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2235 operation will get returned in RESULT and its length in RESULTLEN.
2236 If the response is larger than RESULTMAX, an error is returned and
2237 the required buffer length returned in RESULTLEN. */
2239 send_escape_cmd (ccid_driver_t handle,
2240 const unsigned char *data, size_t datalen,
2241 unsigned char *result, size_t resultmax, size_t *resultlen)
2244 unsigned char msg[100];
2246 unsigned char seqno;
2251 if (datalen > sizeof msg - 10)
2252 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2254 msg[0] = PC_to_RDR_Escape;
2255 msg[5] = 0; /* slot */
2256 msg[6] = seqno = handle->seqno++;
2257 msg[7] = 0; /* RFU */
2258 msg[8] = 0; /* RFU */
2259 msg[9] = 0; /* RFU */
2260 memcpy (msg+10, data, datalen);
2261 msglen = 10 + datalen;
2262 set_msg_len (msg, datalen);
2264 rc = bulk_out (handle, msg, msglen, 0);
2267 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2272 /* We need to ignore certain errorcode here. */
2274 case CCID_DRIVER_ERR_CARD_INACTIVE:
2275 case CCID_DRIVER_ERR_NO_CARD:
2277 if (msglen > resultmax)
2278 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2281 memcpy (result, msg, msglen);
2282 *resultlen = msglen;
2296 ccid_transceive_escape (ccid_driver_t handle,
2297 const unsigned char *data, size_t datalen,
2298 unsigned char *resp, size_t maxresplen, size_t *nresp)
2300 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2307 ccid_poll (ccid_driver_t handle)
2310 unsigned char msg[10];
2316 rc = usb_bulk_read (handle->idev,
2318 (char*)msg, sizeof msg,
2319 0 /* ms timeout */ );
2320 if (rc < 0 && errno == ETIMEDOUT)
2328 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2329 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2337 DEBUGOUT ("intr-in msg too short\n");
2338 return CCID_DRIVER_ERR_INV_VALUE;
2341 if (msg[0] == RDR_to_PC_NotifySlotChange)
2343 DEBUGOUT ("notify slot change:");
2344 for (i=1; i < msglen; i++)
2345 for (j=0; j < 4; j++)
2346 DEBUGOUT_CONT_3 (" %d:%c%c",
2348 (msg[i] & (1<<(j*2)))? 'p':'-',
2349 (msg[i] & (2<<(j*2)))? '*':' ');
2352 else if (msg[0] == RDR_to_PC_HardwareError)
2354 DEBUGOUT ("hardware error occured\n");
2358 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2365 /* Note that this function won't return the error codes NO_CARD or
2368 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2371 unsigned char msg[100];
2373 unsigned char seqno;
2377 msg[0] = PC_to_RDR_GetSlotStatus;
2378 msg[5] = 0; /* slot */
2379 msg[6] = seqno = handle->seqno++;
2380 msg[7] = 0; /* RFU */
2381 msg[8] = 0; /* RFU */
2382 msg[9] = 0; /* RFU */
2383 set_msg_len (msg, 0);
2385 rc = bulk_out (handle, msg, 10, 1);
2388 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2389 get cluttered up by a ticker function checking for the slot
2390 status and debugging enabled. */
2391 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2392 seqno, retries? 1000 : 200, 1);
2393 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2397 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2398 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2399 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2402 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2406 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2407 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2409 *statusbits = (msg[7] & 3);
2415 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2416 Calling this routine, it should prepare default values at PARAM
2417 beforehand. This routine assumes that card is accessed by T=1
2418 protocol. It doesn't analyze historical bytes at all.
2420 Returns < 0 value on error:
2421 -1 for parse error or integrity check error
2422 -2 for card doesn't support T=1 protocol
2423 -3 for parameters are nod explicitly defined by ATR
2424 -4 for this driver doesn't support CRC
2426 Returns >= 0 on success:
2427 0 for card is negotiable mode
2428 1 for card is specific mode (and not negotiable)
2431 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2435 int historical_bytes_num, negotiable = 1;
2437 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2442 param[1] |= 0x02; /* Convention is inverse. */
2446 historical_bytes_num = atr[i] & 0x0f;
2451 param[0] = atr[i]; /* TA1 - Fi & Di */
2456 NEXTBYTE (); /* TB1 - ignore */
2460 param[2] = atr[i]; /* TC1 - Guard Time */
2466 y = (atr[i] >> 4); /* TD1 */
2471 { /* TA2 - PPS mode */
2472 if ((atr[i] & 0x0f) != 1)
2473 return -2; /* Wrong card protocol (!= 1). */
2475 if ((atr[i] & 0x10) != 0x10)
2476 return -3; /* Transmission parameters are implicitly defined. */
2478 negotiable = 0; /* TA2 means specific mode. */
2483 NEXTBYTE (); /* TB2 - ignore */
2486 NEXTBYTE (); /* TC2 - ignore */
2490 y = (atr[i] >> 4); /* TD2 */
2502 param[5] = atr[i]; /* IFSC */
2504 /* XXX: check voltage? */
2505 param[4] = (atr[i] >> 6); /* ClockStop */
2513 param[3] = atr[i]; /* TBx - BWI & CWI */
2520 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2523 if (param[1] & 0x01)
2524 return -4; /* CRC not supported yet. */
2529 y = (atr[i] >> 4); /* TDx */
2538 i += historical_bytes_num - 1;
2560 /* Return the ATR of the card. This is not a cached value and thus an
2561 actual reset is done. */
2563 ccid_get_atr (ccid_driver_t handle,
2564 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2568 unsigned char msg[100];
2569 unsigned char *tpdu;
2570 size_t msglen, tpdulen;
2571 unsigned char seqno;
2576 unsigned char param[7] = { /* For Protocol T=1 */
2577 0x11, /* bmFindexDindex */
2578 0x10, /* bmTCCKST1 */
2579 0x00, /* bGuardTimeT1 */
2580 0x4d, /* bmWaitingIntegersT1 */
2581 0x00, /* bClockStop */
2583 0x00 /* bNadValue */
2586 /* First check whether a card is available. */
2587 rc = ccid_slot_status (handle, &statusbits);
2590 if (statusbits == 2)
2591 return CCID_DRIVER_ERR_NO_CARD;
2593 /* For an inactive and also for an active card, issue the PowerOn
2594 command to get the ATR. */
2596 msg[0] = PC_to_RDR_IccPowerOn;
2597 msg[5] = 0; /* slot */
2598 msg[6] = seqno = handle->seqno++;
2599 /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2600 msg[7] = handle->auto_voltage ? 0 : 1;
2601 msg[8] = 0; /* RFU */
2602 msg[9] = 0; /* RFU */
2603 set_msg_len (msg, 0);
2606 rc = bulk_out (handle, msg, msglen, 0);
2609 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2613 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2614 && ((handle->id_vendor == VENDOR_CHERRY
2615 && handle->id_product == 0x0005)
2616 || (handle->id_vendor == VENDOR_GEMPC
2617 && handle->id_product == 0x4433)
2621 /* Try switching to ISO mode. */
2622 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2626 else if (CCID_COMMAND_FAILED (msg))
2627 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2630 handle->powered_off = 0;
2634 size_t n = msglen - 10;
2638 memcpy (atr, msg+10, n);
2642 param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2643 rc = update_param_by_atr (param, msg+10, msglen - 10);
2646 DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2647 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2652 if (handle->auto_param)
2654 msg[0] = PC_to_RDR_GetParameters;
2655 msg[5] = 0; /* slot */
2656 msg[6] = seqno = handle->seqno++;
2657 msg[7] = 0; /* RFU */
2658 msg[8] = 0; /* RFU */
2659 msg[9] = 0; /* RFU */
2660 set_msg_len (msg, 0);
2662 rc = bulk_out (handle, msg, msglen, 0);
2664 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2667 DEBUGOUT ("GetParameters failed\n");
2668 else if (msglen == 17 && msg[9] == 1)
2671 else if (handle->auto_pps)
2673 else if (rc == 1) /* It's negotiable, send PPS. */
2675 msg[0] = PC_to_RDR_XfrBlock;
2676 msg[5] = 0; /* slot */
2677 msg[6] = seqno = handle->seqno++;
2681 msg[10] = 0xff; /* PPSS */
2682 msg[11] = 0x11; /* PPS0: PPS1, Protocol T=1 */
2683 msg[12] = param[0]; /* PPS1: Fi / Di */
2684 msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2685 set_msg_len (msg, 4);
2688 rc = bulk_out (handle, msg, msglen, 0);
2692 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2697 if (msglen != 10 + 4)
2699 DEBUGOUT_1 ("Setting PPS failed: %d\n", (int)msglen);
2700 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2703 if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2705 DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2706 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2710 /* Setup parameters to select T=1. */
2711 msg[0] = PC_to_RDR_SetParameters;
2712 msg[5] = 0; /* slot */
2713 msg[6] = seqno = handle->seqno++;
2714 msg[7] = 1; /* Select T=1. */
2715 msg[8] = 0; /* RFU */
2716 msg[9] = 0; /* RFU */
2719 memcpy (&msg[10], param, 7);
2720 set_msg_len (msg, 7);
2723 rc = bulk_out (handle, msg, msglen, 0);
2726 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2729 DEBUGOUT ("SetParameters failed (ignored)\n");
2731 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2732 handle->ifsc = msg[15];
2734 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2736 if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2738 DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2739 handle->nonnull_nad = 0;
2745 /* Send an S-Block with our maximum IFSD to the CCID. */
2746 if (!handle->apdu_level && !handle->auto_ifsd)
2749 /* NAD: DAD=1, SAD=0 */
2750 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2751 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2753 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2755 edc = compute_edc (tpdu, tpdulen, use_crc);
2757 tpdu[tpdulen++] = (edc >> 8);
2758 tpdu[tpdulen++] = edc;
2760 msg[0] = PC_to_RDR_XfrBlock;
2761 msg[5] = 0; /* slot */
2762 msg[6] = seqno = handle->seqno++;
2764 msg[8] = 0; /* RFU */
2765 msg[9] = 0; /* RFU */
2766 set_msg_len (msg, tpdulen);
2767 msglen = 10 + tpdulen;
2769 if (debug_level > 1)
2770 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2771 ((msg[11] & 0xc0) == 0x80)? 'R' :
2772 (msg[11] & 0x80)? 'S' : 'I',
2773 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2774 : !!(msg[11] & 0x40)),
2775 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2777 rc = bulk_out (handle, msg, msglen, 0);
2782 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2783 RDR_to_PC_DataBlock, seqno, 5000, 0);
2788 tpdulen = msglen - 10;
2791 return CCID_DRIVER_ERR_ABORTED;
2793 if (debug_level > 1)
2794 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2795 ((msg[11] & 0xc0) == 0x80)? 'R' :
2796 (msg[11] & 0x80)? 'S' : 'I',
2797 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2798 : !!(msg[11] & 0x40)),
2799 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2800 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2802 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2804 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2807 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2817 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2821 return 0x42; /* Not yet implemented. */
2825 unsigned char crc = 0;
2827 for (; datalen; datalen--)
2834 /* Return true if APDU is an extended length one. */
2836 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2838 if (apdulen < 7 || apdu[4])
2839 return 0; /* Too short or no Z byte. */
2844 /* Helper for ccid_transceive used for APDU level exchanges. */
2846 ccid_transceive_apdu_level (ccid_driver_t handle,
2847 const unsigned char *apdu_buf, size_t apdu_len,
2848 unsigned char *resp, size_t maxresplen,
2852 unsigned char msg[CCID_MAX_BUF];
2853 const unsigned char *apdu_p;
2854 size_t apdu_part_len;
2856 unsigned char seqno;
2858 unsigned char chain = 0;
2860 if (apdu_len == 0 || apdu_len > sizeof (msg) - 10)
2861 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2866 apdu_part_len = apdu_len;
2867 if (apdu_part_len > handle->max_ccid_msglen - 10)
2869 apdu_part_len = handle->max_ccid_msglen - 10;
2873 msg[0] = PC_to_RDR_XfrBlock;
2874 msg[5] = 0; /* slot */
2875 msg[6] = seqno = handle->seqno++;
2879 memcpy (msg+10, apdu_p, apdu_part_len);
2880 set_msg_len (msg, apdu_part_len);
2881 msglen = 10 + apdu_part_len;
2883 rc = bulk_out (handle, msg, msglen, 0);
2887 apdu_p += apdu_part_len;
2888 apdu_len -= apdu_part_len;
2890 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2891 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
2895 if (!(chain & 0x01))
2904 apdu_part_len = msglen - 10;
2905 if (resp && apdu_len + apdu_part_len <= maxresplen)
2906 memcpy (resp + apdu_len, msg+10, apdu_part_len);
2907 apdu_len += apdu_part_len;
2909 if (!(msg[9] & 0x01))
2912 msg[0] = PC_to_RDR_XfrBlock;
2913 msg[5] = 0; /* slot */
2914 msg[6] = seqno = handle->seqno++;
2916 msg[8] = 0x10; /* Request next data block */
2918 set_msg_len (msg, 0);
2921 rc = bulk_out (handle, msg, msglen, 0);
2925 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2926 RDR_to_PC_DataBlock, seqno, CCID_CMD_TIMEOUT, 0);
2933 if (apdu_len > maxresplen)
2935 DEBUGOUT_2 ("provided buffer too short for received data "
2937 (unsigned int)apdu_len, (unsigned int)maxresplen);
2938 return CCID_DRIVER_ERR_INV_VALUE;
2950 Protocol T=1 overview
2954 1 byte Node Address (NAD)
2955 1 byte Protocol Control Byte (PCB)
2958 0-254 byte APDU or Control Information (INF)
2960 1 byte Error Detection Code (EDC)
2964 bit 4..6 Destination Node Address (DAD)
2966 bit 2..0 Source Node Address (SAD)
2968 If node adresses are not used, SAD and DAD should be set to 0 on
2969 the first block sent to the card. If they are used they should
2970 have different values (0 for one is okay); that first block sets up
2971 the addresses of the nodes.
2974 Information Block (I-Block):
2976 bit 6 Sequence number (yep, that is modulo 2)
2979 Received-Ready Block (R-Block):
2983 bit 4 Sequence number
2984 bit 3..0 0 = no error
2985 1 = EDC or parity error
2987 other values are reserved
2988 Supervisory Block (S-Block):
2991 bit 5 clear=request,set=response
2992 bit 4..0 0 = resyncronisation request
2993 1 = information field size request
2995 3 = extension of BWT request
2997 other values are reserved
3002 ccid_transceive (ccid_driver_t handle,
3003 const unsigned char *apdu_buf, size_t apdu_buflen,
3004 unsigned char *resp, size_t maxresplen, size_t *nresp)
3007 /* The size of the buffer used to be 10+259. For the via_escape
3008 hack we need one extra byte, thus 11+259. */
3009 unsigned char send_buffer[11+259], recv_buffer[11+259];
3010 const unsigned char *apdu;
3012 unsigned char *msg, *tpdu, *p;
3013 size_t msglen, tpdulen, last_tpdulen, n;
3014 unsigned char seqno;
3027 nresp = &dummy_nresp;
3030 /* Smarter readers allow to send APDUs directly; divert here. */
3031 if (handle->apdu_level)
3033 /* We employ a hack for Omnikey readers which are able to send
3034 TPDUs using an escape sequence. There is no documentation
3035 but the Windows driver does it this way. Tested using a
3036 CM6121. This method works also for the Cherry XX44
3037 keyboards; however there are problems with the
3038 ccid_tranceive_secure which leads to a loss of sync on the
3039 CCID level. If Cherry wants to make their keyboard work
3040 again, they should hand over some docs. */
3041 if ((handle->id_vendor == VENDOR_OMNIKEY
3042 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
3043 && handle->apdu_level < 2
3044 && is_exlen_apdu (apdu_buf, apdu_buflen))
3047 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3048 resp, maxresplen, nresp);
3051 /* The other readers we support require sending TPDUs. */
3053 tpdulen = 0; /* Avoid compiler warning about no initialization. */
3055 hdrlen = via_escape? 11 : 10;
3057 /* NAD: DAD=1, SAD=0 */
3058 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3062 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
3070 apdulen = apdu_buflen;
3073 /* Construct an I-Block. */
3074 tpdu = msg + hdrlen;
3076 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3077 if (apdulen > handle->ifsc )
3079 apdulen = handle->ifsc;
3080 apdu_buf += handle->ifsc;
3081 apdu_buflen -= handle->ifsc;
3082 tpdu[1] |= (1 << 5); /* Set more bit. */
3085 memcpy (tpdu+3, apdu, apdulen);
3086 tpdulen = 3 + apdulen;
3087 edc = compute_edc (tpdu, tpdulen, use_crc);
3089 tpdu[tpdulen++] = (edc >> 8);
3090 tpdu[tpdulen++] = edc;
3095 msg[0] = PC_to_RDR_Escape;
3096 msg[5] = 0; /* slot */
3097 msg[6] = seqno = handle->seqno++;
3098 msg[7] = 0; /* RFU */
3099 msg[8] = 0; /* RFU */
3100 msg[9] = 0; /* RFU */
3101 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
3102 set_msg_len (msg, 1 + tpdulen);
3106 msg[0] = PC_to_RDR_XfrBlock;
3107 msg[5] = 0; /* slot */
3108 msg[6] = seqno = handle->seqno++;
3109 msg[7] = 4; /* bBWI */
3110 msg[8] = 0; /* RFU */
3111 msg[9] = 0; /* RFU */
3112 set_msg_len (msg, tpdulen);
3114 msglen = hdrlen + tpdulen;
3116 last_tpdulen = tpdulen;
3119 if (debug_level > 1)
3120 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3121 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3122 (msg[pcboff] & 0x80)? 'S' : 'I',
3123 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3124 : !!(msg[pcboff] & 0x40)),
3125 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3128 rc = bulk_out (handle, msg, msglen, 0);
3133 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3134 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
3135 seqno, CCID_CMD_TIMEOUT, 0);
3139 tpdu = msg + hdrlen;
3140 tpdulen = msglen - hdrlen;
3145 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3146 return CCID_DRIVER_ERR_ABORTED;
3149 if (debug_level > 1)
3150 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3151 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3152 (msg[pcboff] & 0x80)? 'S' : 'I',
3153 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3154 : !!(msg[pcboff] & 0x40)),
3155 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3156 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3159 if (!(tpdu[1] & 0x80))
3160 { /* This is an I-block. */
3163 { /* last block sent was successful. */
3168 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3169 { /* Reponse does not match our sequence number. */
3171 tpdu = msg + hdrlen;
3173 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3176 edc = compute_edc (tpdu, tpdulen, use_crc);
3178 tpdu[tpdulen++] = (edc >> 8);
3179 tpdu[tpdulen++] = edc;
3186 p = tpdu + 3; /* Skip the prologue field. */
3187 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3188 /* fixme: verify the checksum. */
3193 DEBUGOUT_2 ("provided buffer too short for received data "
3195 (unsigned int)n, (unsigned int)maxresplen);
3196 return CCID_DRIVER_ERR_INV_VALUE;
3199 memcpy (resp, p, n);
3205 if (!(tpdu[1] & 0x20))
3206 return 0; /* No chaining requested - ready. */
3209 tpdu = msg + hdrlen;
3211 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3214 edc = compute_edc (tpdu, tpdulen, use_crc);
3216 tpdu[tpdulen++] = (edc >> 8);
3217 tpdu[tpdulen++] = edc;
3219 else if ((tpdu[1] & 0xc0) == 0x80)
3220 { /* This is a R-block. */
3221 if ( (tpdu[1] & 0x0f))
3224 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3226 /* Error probably due to switching to TPDU. Send a
3227 resync request. We use the recv_buffer so that
3228 we don't corrupt the send_buffer. */
3230 tpdu = msg + hdrlen;
3232 tpdu[1] = 0xc0; /* S-block resync request. */
3235 edc = compute_edc (tpdu, tpdulen, use_crc);
3237 tpdu[tpdulen++] = (edc >> 8);
3238 tpdu[tpdulen++] = edc;
3240 DEBUGOUT ("T=1: requesting resync\n");
3242 else if (retries > 3)
3244 DEBUGOUT ("T=1: 3 failed retries\n");
3245 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3249 /* Error: repeat last block */
3251 tpdulen = last_tpdulen;
3254 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3255 { /* Response does not match our sequence number. */
3256 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3257 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3260 { /* Send next chunk. */
3268 DEBUGOUT ("unexpected ACK R-block received\n");
3269 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3273 { /* This is a S-block. */
3275 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3276 (tpdu[1] & 0x20)? "response": "request",
3278 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3280 /* Information field size request. */
3281 unsigned char ifsc = tpdu[3];
3283 if (ifsc < 16 || ifsc > 254)
3284 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3287 tpdu = msg + hdrlen;
3289 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3293 edc = compute_edc (tpdu, tpdulen, use_crc);
3295 tpdu[tpdulen++] = (edc >> 8);
3296 tpdu[tpdulen++] = edc;
3297 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3299 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3301 /* Wait time extension request. */
3302 unsigned char bwi = tpdu[3];
3304 tpdu = msg + hdrlen;
3306 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3310 edc = compute_edc (tpdu, tpdulen, use_crc);
3312 tpdu[tpdulen++] = (edc >> 8);
3313 tpdu[tpdulen++] = edc;
3314 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3315 print_progress (handle);
3317 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3319 DEBUGOUT ("T=1: resync ack from reader\n");
3320 /* Repeat previous block. */
3322 tpdulen = last_tpdulen;
3325 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3327 } /* end T=1 protocol loop. */
3333 /* Send the CCID Secure command to the reader. APDU_BUF should
3334 contain the APDU template. PIN_MODE defines how the pin gets
3337 1 := The PIN is ASCII encoded and of variable length. The
3338 length of the PIN entered will be put into Lc by the reader.
3339 The APDU should me made up of 4 bytes without Lc.
3341 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3342 may be used t enable reasonable defaults.
3344 When called with RESP and NRESP set to NULL, the function will
3345 merely check whether the reader supports the secure command for the
3346 given APDU and PIN_MODE. */
3348 ccid_transceive_secure (ccid_driver_t handle,
3349 const unsigned char *apdu_buf, size_t apdu_buflen,
3351 unsigned char *resp, size_t maxresplen, size_t *nresp)
3354 unsigned char send_buffer[10+259], recv_buffer[10+259];
3355 unsigned char *msg, *tpdu, *p;
3356 size_t msglen, tpdulen, n;
3357 unsigned char seqno;
3360 int cherry_mode = 0;
3362 int enable_varlen = 0;
3364 testmode = !resp && !nresp;
3367 nresp = &dummy_nresp;
3370 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3372 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3375 return CCID_DRIVER_ERR_NO_PINPAD;
3377 if (!pininfo->minlen)
3378 pininfo->minlen = 1;
3379 if (!pininfo->maxlen)
3380 pininfo->maxlen = 15;
3382 /* Note that the 25 is the maximum value the SPR532 allows. */
3383 if (pininfo->minlen < 1 || pininfo->minlen > 25
3384 || pininfo->maxlen < 1 || pininfo->maxlen > 25
3385 || pininfo->minlen > pininfo->maxlen)
3386 return CCID_DRIVER_ERR_INV_VALUE;
3388 /* We have only tested a few readers so better don't risk anything
3389 and do not allow the use with other readers. */
3390 switch (handle->id_vendor)
3392 case VENDOR_SCM: /* Tested with SPR 532. */
3393 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3394 case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3395 pininfo->maxlen = 25;
3398 case VENDOR_REINER: /* Tested with cyberJack go */
3399 case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3403 pininfo->maxlen = 15;
3405 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3406 character on the keyboard channel. We use a special variant
3407 of PC_to_RDR_Secure which directs these characters to the
3408 smart card's bulk-in channel. We also need to append a zero
3409 Lc byte to the APDU. It seems that it will be replaced with
3410 the actual length instead of being appended before the APDU
3411 is send to the card. */
3413 if (handle->id_product != CHERRY_ST2000)
3417 if ((handle->id_vendor == VENDOR_GEMPC &&
3418 handle->id_product == GEMPC_PINPAD)
3419 || (handle->id_vendor == VENDOR_VEGA &&
3420 handle->id_product == VEGA_ALPHA))
3423 pininfo->minlen = 4;
3424 pininfo->maxlen = 8;
3427 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3431 pininfo->fixedlen = 0;
3434 return 0; /* Success */
3436 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3437 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3440 if (handle->id_vendor == VENDOR_SCM)
3442 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3443 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3449 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3450 msg[5] = 0; /* slot */
3451 msg[6] = seqno = handle->seqno++;
3452 msg[7] = 0; /* bBWI */
3453 msg[8] = 0; /* RFU */
3454 msg[9] = 0; /* RFU */
3455 msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3456 /* Perform PIN verification or PIN modification. */
3457 msg[11] = 0; /* Timeout in seconds. */
3458 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3459 if (handle->id_vendor == VENDOR_SCM)
3461 /* For the SPR532 the next 2 bytes need to be zero. We do this
3462 for all SCM products. Kudos to Martin Paljak for this
3464 msg[13] = msg[14] = 0;
3468 msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3469 0 bits of pin length to insert.
3470 PIN block size by fixedlen. */
3471 msg[14] = 0x00; /* bmPINLengthFormat:
3472 Units are bytes, position is 0. */
3476 if (apdu_buf[1] == 0x24)
3478 msg[msglen++] = 0; /* bInsertionOffsetOld */
3479 msg[msglen++] = pininfo->fixedlen; /* bInsertionOffsetNew */
3482 /* The following is a little endian word. */
3483 msg[msglen++] = pininfo->maxlen; /* wPINMaxExtraDigit-Maximum. */
3484 msg[msglen++] = pininfo->minlen; /* wPINMaxExtraDigit-Minimum. */
3486 if (apdu_buf[1] == 0x24)
3487 msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3489 * 0x00: new PIN once
3490 * 0x01: new PIN twice (confirmation)
3491 * 0x02: old PIN and new PIN once
3492 * 0x03: old PIN and new PIN twice (confirmation)
3495 msg[msglen] = 0x02; /* bEntryValidationCondition:
3496 Validation key pressed */
3497 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3498 msg[msglen] |= 0x01; /* Max size reached. */
3501 if (apdu_buf[1] == 0x20)
3502 msg[msglen++] = 0x01; /* bNumberMessage. */
3504 msg[msglen++] = 0x03; /* bNumberMessage. */
3506 msg[msglen++] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3507 msg[msglen++] = 0x04; /* wLangId-High. */
3509 if (apdu_buf[1] == 0x20)
3510 msg[msglen++] = 0; /* bMsgIndex. */
3513 msg[msglen++] = 0; /* bMsgIndex1. */
3514 msg[msglen++] = 1; /* bMsgIndex2. */
3515 msg[msglen++] = 2; /* bMsgIndex3. */
3519 n = pininfo->fixedlen;
3520 if (apdu_buf[1] == 0x24)
3521 n += pininfo->fixedlen;
3523 /* bTeoProlog follows: */
3524 msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3525 msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3527 msg[msglen++] = n + 5; /* apdulen should be filled for fixed length. */
3529 msg[msglen++] = 0; /* The apdulen will be filled in by the reader. */
3531 msg[msglen++] = apdu_buf[0]; /* CLA */
3532 msg[msglen++] = apdu_buf[1]; /* INS */
3533 msg[msglen++] = apdu_buf[2]; /* P1 */
3534 msg[msglen++] = apdu_buf[3]; /* P2 */
3537 else if (pininfo->fixedlen != 0)
3540 memset (&msg[msglen], 0xff, n);
3543 /* An EDC is not required. */
3544 set_msg_len (msg, msglen - 10);
3546 rc = bulk_out (handle, msg, msglen, 0);
3551 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3552 RDR_to_PC_DataBlock, seqno, 30000, 0);
3557 tpdulen = msglen - 10;
3559 if (handle->apdu_level)
3563 if (tpdulen > maxresplen)
3565 DEBUGOUT_2 ("provided buffer too short for received data "
3567 (unsigned int)tpdulen, (unsigned int)maxresplen);
3568 return CCID_DRIVER_ERR_INV_VALUE;
3571 memcpy (resp, tpdu, tpdulen);
3579 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3580 return CCID_DRIVER_ERR_ABORTED;
3582 if (debug_level > 1)
3583 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3584 ((msg[11] & 0xc0) == 0x80)? 'R' :
3585 (msg[11] & 0x80)? 'S' : 'I',
3586 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3587 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3588 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3590 if (!(tpdu[1] & 0x80))
3591 { /* This is an I-block. */
3592 /* Last block sent was successful. */
3595 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3596 { /* Reponse does not match our sequence number. */
3597 DEBUGOUT ("I-block with wrong seqno received\n");
3598 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3603 p = tpdu + 3; /* Skip the prologue field. */
3604 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3605 /* fixme: verify the checksum. */
3610 DEBUGOUT_2 ("provided buffer too short for received data "
3612 (unsigned int)n, (unsigned int)maxresplen);
3613 return CCID_DRIVER_ERR_INV_VALUE;
3616 memcpy (resp, p, n);
3622 if (!(tpdu[1] & 0x20))
3623 return 0; /* No chaining requested - ready. */
3625 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3626 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3628 else if ((tpdu[1] & 0xc0) == 0x80)
3629 { /* This is a R-block. */
3630 if ( (tpdu[1] & 0x0f))
3631 { /* Error: repeat last block */
3632 DEBUGOUT ("No retries supported for Secure operation\n");
3633 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3635 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3636 { /* Reponse does not match our sequence number. */
3637 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3638 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3641 { /* Send next chunk. */
3642 DEBUGOUT ("chaining not supported on Secure operation\n");
3643 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3647 { /* This is a S-block. */
3648 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3649 (tpdu[1] & 0x20)? "response": "request",
3651 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3664 print_error (int err)
3671 case 0: p = "success";
3672 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3673 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3674 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3675 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3676 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3677 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3678 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3679 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3680 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3681 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3682 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3683 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3684 default: sprintf (buf, "0x%05x", err); p = buf; break;
3686 fprintf (stderr, "operation failed: %s\n", p);
3691 print_data (const unsigned char *data, size_t length)
3695 fprintf (stderr, "operation status: %02X%02X\n",
3696 data[length-2], data[length-1]);
3701 fputs (" returned data:", stderr);
3702 for (; length; length--, data++)
3703 fprintf (stderr, " %02X", *data);
3704 putc ('\n', stderr);
3709 print_result (int rc, const unsigned char *data, size_t length)
3714 print_data (data, length);
3718 main (int argc, char **argv)
3723 unsigned char result[512];
3726 int verify_123456 = 0;
3738 if ( !strcmp (*argv, "--list"))
3741 p = ccid_get_reader_list ();
3748 else if ( !strcmp (*argv, "--debug"))
3750 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3753 else if ( !strcmp (*argv, "--no-poll"))
3758 else if ( !strcmp (*argv, "--no-pinpad"))
3763 else if ( !strcmp (*argv, "--verify-123456"))
3772 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3778 fputs ("getting ATR ...\n", stderr);
3779 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3788 fputs ("getting slot status ...\n", stderr);
3789 rc = ccid_slot_status (ccid, &slotstat);
3799 fputs ("selecting application OpenPGP ....\n", stderr);
3801 static unsigned char apdu[] = {
3802 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3803 rc = ccid_transceive (ccid,
3805 result, sizeof result, &resultlen);
3806 print_result (rc, result, resultlen);
3813 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3815 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3816 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3817 result, sizeof result, &resultlen);
3818 print_result (rc, result, resultlen);
3827 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3830 if (ccid_transceive_secure (ccid,
3834 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3837 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3839 rc = ccid_transceive_secure (ccid,
3842 result, sizeof result, &resultlen);
3843 print_result (rc, result, resultlen);
3848 if (verify_123456 && !did_verify)
3850 fputs ("verifying that CHV1 is 123456....\n", stderr);
3852 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3853 6, '1','2','3','4','5','6'};
3854 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3855 result, sizeof result, &resultlen);
3856 print_result (rc, result, resultlen);
3862 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3864 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3865 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3866 result, sizeof result, &resultlen);
3867 print_result (rc, result, resultlen);
3871 ccid_close_reader (ccid);
3878 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3882 #endif /*HAVE_LIBUSB*/