Add code to better handle unplugging of a reader.
[gnupg.git] / scd / ccid-driver.c
blob373f55f8aa293105c4da4957fd51a33112f1e570
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007
3 * 2008, 2009 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
28 * below.
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
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
41 * written permission.
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.
55 * $Date$
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.
73 #ifdef HAVE_CONFIG_H
74 # include <config.h>
75 #endif
77 #if defined(HAVE_LIBUSB) || defined(TEST)
79 #include <errno.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <assert.h>
84 #include <sys/types.h>
85 #include <sys/stat.h>
86 #include <fcntl.h>
87 #include <time.h>
89 #include <usb.h>
91 #include "ccid-driver.h"
93 #define DRVNAME "ccid-driver: "
96 /* Depending on how this source is used we either define our error
97 output to go to stderr or to the jnlib based logging functions. We
98 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
99 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
101 #if defined(GNUPG_MAJOR_VERSION) \
102 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
104 #if defined(GNUPG_SCD_MAIN_HEADER)
105 # include GNUPG_SCD_MAIN_HEADER
106 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
107 # include "options.h"
108 # include "util.h"
109 # include "memory.h"
110 # include "cardglue.h"
111 # else /* This is the modularized GnuPG 1.9 or later. */
112 # include "scdaemon.h"
113 #endif
116 # define DEBUGOUT(t) do { if (debug_level) \
117 log_debug (DRVNAME t); } while (0)
118 # define DEBUGOUT_1(t,a) do { if (debug_level) \
119 log_debug (DRVNAME t,(a)); } while (0)
120 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
121 log_debug (DRVNAME t,(a),(b)); } while (0)
122 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
123 log_debug (DRVNAME t,(a),(b),(c));} while (0)
124 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
125 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
126 # define DEBUGOUT_CONT(t) do { if (debug_level) \
127 log_printf (t); } while (0)
128 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
129 log_printf (t,(a)); } while (0)
130 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
131 log_printf (t,(a),(b)); } while (0)
132 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
133 log_printf (t,(a),(b),(c)); } while (0)
134 # define DEBUGOUT_LF() do { if (debug_level) \
135 log_printf ("\n"); } while (0)
137 #else /* Other usage of this source - don't use gnupg specifics. */
139 # define DEBUGOUT(t) do { if (debug_level) \
140 fprintf (stderr, DRVNAME t); } while (0)
141 # define DEBUGOUT_1(t,a) do { if (debug_level) \
142 fprintf (stderr, DRVNAME t, (a)); } while (0)
143 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
144 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
145 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
146 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
147 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
148 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
149 # define DEBUGOUT_CONT(t) do { if (debug_level) \
150 fprintf (stderr, t); } while (0)
151 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
152 fprintf (stderr, t, (a)); } while (0)
153 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
154 fprintf (stderr, t, (a), (b)); } while (0)
155 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
156 fprintf (stderr, t, (a), (b), (c)); } while (0)
157 # define DEBUGOUT_LF() do { if (debug_level) \
158 putc ('\n', stderr); } while (0)
160 #endif /* This source not used by scdaemon. */
163 #ifndef EAGAIN
164 #define EAGAIN EWOULDBLOCK
165 #endif
169 enum {
170 RDR_to_PC_NotifySlotChange= 0x50,
171 RDR_to_PC_HardwareError = 0x51,
173 PC_to_RDR_SetParameters = 0x61,
174 PC_to_RDR_IccPowerOn = 0x62,
175 PC_to_RDR_IccPowerOff = 0x63,
176 PC_to_RDR_GetSlotStatus = 0x65,
177 PC_to_RDR_Secure = 0x69,
178 PC_to_RDR_T0APDU = 0x6a,
179 PC_to_RDR_Escape = 0x6b,
180 PC_to_RDR_GetParameters = 0x6c,
181 PC_to_RDR_ResetParameters = 0x6d,
182 PC_to_RDR_IccClock = 0x6e,
183 PC_to_RDR_XfrBlock = 0x6f,
184 PC_to_RDR_Mechanical = 0x71,
185 PC_to_RDR_Abort = 0x72,
186 PC_to_RDR_SetDataRate = 0x73,
188 RDR_to_PC_DataBlock = 0x80,
189 RDR_to_PC_SlotStatus = 0x81,
190 RDR_to_PC_Parameters = 0x82,
191 RDR_to_PC_Escape = 0x83,
192 RDR_to_PC_DataRate = 0x84
196 /* Two macro to detect whether a CCID command has failed and to get
197 the error code. These macros assume that we can access the
198 mandatory first 10 bytes of a CCID message in BUF. */
199 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
200 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
203 /* We need to know the vendor to do some hacks. */
204 enum {
205 VENDOR_CHERRY = 0x046a,
206 VENDOR_SCM = 0x04e6,
207 VENDOR_OMNIKEY= 0x076b,
208 VENDOR_GEMPC = 0x08e6,
209 VENDOR_KAAN = 0x0d46
212 /* A list and a table with special transport descriptions. */
213 enum {
214 TRANSPORT_USB = 0, /* Standard USB transport. */
215 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
218 static struct
220 char *name; /* Device name. */
221 int type;
223 } transports[] = {
224 { "/dev/cmx0", TRANSPORT_CM4040 },
225 { "/dev/cmx1", TRANSPORT_CM4040 },
226 { NULL },
230 /* Store information on the driver's state. A pointer to such a
231 structure is used as handle for most functions. */
232 struct ccid_driver_s
234 usb_dev_handle *idev;
235 char *rid;
236 int dev_fd; /* -1 for USB transport or file descriptor of the
237 transport device. */
238 unsigned short id_vendor;
239 unsigned short id_product;
240 unsigned short bcd_device;
241 int ifc_no;
242 int ep_bulk_out;
243 int ep_bulk_in;
244 int ep_intr;
245 int seqno;
246 unsigned char t1_ns;
247 unsigned char t1_nr;
248 unsigned char nonnull_nad;
249 int max_ifsd;
250 int ifsd;
251 int ifsc;
252 unsigned char apdu_level:2; /* Reader supports short APDU level
253 exchange. With a value of 2 short
254 and extended level is supported.*/
255 unsigned int auto_ifsd:1;
256 unsigned int powered_off:1;
257 unsigned int has_pinpad:2;
258 unsigned int enodev_seen:1;
260 time_t last_progress; /* Last time we sent progress line. */
262 /* The progress callback and its first arg as supplied to
263 ccid_set_progress_cb. */
264 void (*progress_cb)(void *, const char *, int, int, int);
265 void *progress_cb_arg;
269 static int initialized_usb; /* Tracks whether USB has been initialized. */
270 static int debug_level; /* Flag to control the debug output.
271 0 = No debugging
272 1 = USB I/O info
273 2 = Level 1 + T=1 protocol tracing
274 3 = Level 2 + USB/I/O tracing of SlotStatus.
278 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
279 int use_crc);
280 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
281 int no_debug);
282 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
283 size_t *nread, int expected_type, int seqno, int timeout,
284 int no_debug);
285 static int abort_cmd (ccid_driver_t handle, int seqno);
287 /* Convert a little endian stored 4 byte value into an unsigned
288 integer. */
289 static unsigned int
290 convert_le_u32 (const unsigned char *buf)
292 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
296 /* Convert a little endian stored 2 byte value into an unsigned
297 integer. */
298 static unsigned int
299 convert_le_u16 (const unsigned char *buf)
301 return buf[0] | (buf[1] << 8);
304 static void
305 set_msg_len (unsigned char *msg, unsigned int length)
307 msg[1] = length;
308 msg[2] = length >> 8;
309 msg[3] = length >> 16;
310 msg[4] = length >> 24;
314 static void
315 print_progress (ccid_driver_t handle)
317 time_t ct = time (NULL);
319 /* We don't want to print progress lines too often. */
320 if (ct == handle->last_progress)
321 return;
323 if (handle->progress_cb)
324 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
326 handle->last_progress = ct;
331 /* Pint an error message for a failed CCID command including a textual
332 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
333 static void
334 print_command_failed (const unsigned char *msg)
336 const char *t;
337 char buffer[100];
338 int ec;
340 if (!debug_level)
341 return;
343 ec = CCID_ERROR_CODE (msg);
344 switch (ec)
346 case 0x00: t = "Command not supported"; break;
348 case 0xE0: t = "Slot busy"; break;
349 case 0xEF: t = "PIN cancelled"; break;
350 case 0xF0: t = "PIN timeout"; break;
352 case 0xF2: t = "Automatic sequence ongoing"; break;
353 case 0xF3: t = "Deactivated Protocol"; break;
354 case 0xF4: t = "Procedure byte conflict"; break;
355 case 0xF5: t = "ICC class not supported"; break;
356 case 0xF6: t = "ICC protocol not supported"; break;
357 case 0xF7: t = "Bad checksum in ATR"; break;
358 case 0xF8: t = "Bad TS in ATR"; break;
360 case 0xFB: t = "An all inclusive hardware error occurred"; break;
361 case 0xFC: t = "Overrun error while talking to the ICC"; break;
362 case 0xFD: t = "Parity error while talking to the ICC"; break;
363 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
364 case 0xFF: t = "Host aborted the current activity"; break;
366 default:
367 if (ec > 0 && ec < 128)
368 sprintf (buffer, "Parameter error at offset %d", ec);
369 else
370 sprintf (buffer, "Error code %02X", ec);
371 t = buffer;
372 break;
374 DEBUGOUT_1 ("CCID command failed: %s\n", t);
378 static void
379 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
381 int any = 0;
383 for (; off < datalen; off++)
385 if (!any || !(off % 16))
387 if (any)
388 DEBUGOUT_LF ();
389 DEBUGOUT_1 (" [%04d] ", off);
391 DEBUGOUT_CONT_1 (" %02X", data[off]);
392 any = 1;
394 if (any && (off % 16))
395 DEBUGOUT_LF ();
399 static void
400 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
402 DEBUGOUT_1 ("%s:\n", name);
403 if (msglen < 7)
404 return;
405 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
406 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
407 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
411 static void
412 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
414 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
415 if (msglen < 10)
416 return;
417 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
418 msg[7] == 0? "auto":
419 msg[7] == 1? "5.0 V":
420 msg[7] == 2? "3.0 V":
421 msg[7] == 3? "1.8 V":"");
422 print_pr_data (msg, msglen, 8);
426 static void
427 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
429 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
430 print_pr_data (msg, msglen, 7);
434 static void
435 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
437 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
438 print_pr_data (msg, msglen, 7);
442 static void
443 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
445 unsigned int val;
447 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
448 if (msglen < 10)
449 return;
450 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
451 val = convert_le_u16 (msg+8);
452 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
453 val == 1? " (continued)":
454 val == 2? " (continues+ends)":
455 val == 3? " (continues+continued)":
456 val == 16? " (DataBlock-expected)":"");
457 print_pr_data (msg, msglen, 10);
461 static void
462 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
464 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
465 print_pr_data (msg, msglen, 7);
469 static void
470 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
472 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
473 print_pr_data (msg, msglen, 7);
477 static void
478 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
480 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
481 if (msglen < 10)
482 return;
483 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
484 print_pr_data (msg, msglen, 8);
488 static void
489 print_p2r_escape (const unsigned char *msg, size_t msglen)
491 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
492 print_pr_data (msg, msglen, 7);
496 static void
497 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
499 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
500 if (msglen < 10)
501 return;
502 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
503 print_pr_data (msg, msglen, 8);
507 static void
508 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
510 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
511 if (msglen < 10)
512 return;
513 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
514 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
515 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
516 print_pr_data (msg, msglen, 10);
520 static void
521 print_p2r_secure (const unsigned char *msg, size_t msglen)
523 unsigned int val;
525 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
526 if (msglen < 10)
527 return;
528 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
529 val = convert_le_u16 (msg+8);
530 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
531 val == 1? " (continued)":
532 val == 2? " (continues+ends)":
533 val == 3? " (continues+continued)":
534 val == 16? " (DataBlock-expected)":"");
535 print_pr_data (msg, msglen, 10);
539 static void
540 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
542 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
543 if (msglen < 10)
544 return;
545 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
546 print_pr_data (msg, msglen, 8);
550 static void
551 print_p2r_abort (const unsigned char *msg, size_t msglen)
553 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
554 print_pr_data (msg, msglen, 7);
558 static void
559 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
561 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
562 if (msglen < 10)
563 return;
564 print_pr_data (msg, msglen, 7);
568 static void
569 print_p2r_unknown (const unsigned char *msg, size_t msglen)
571 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
572 if (msglen < 10)
573 return;
574 print_pr_data (msg, msglen, 0);
578 static void
579 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
581 DEBUGOUT_1 ("%s:\n", name);
582 if (msglen < 9)
583 return;
584 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
585 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
586 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
587 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
588 if (msg[8])
589 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
593 static void
594 print_r2p_datablock (const unsigned char *msg, size_t msglen)
596 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
597 if (msglen < 10)
598 return;
599 if (msg[9])
600 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
601 msg[9] == 1? " (continued)":
602 msg[9] == 2? " (continues+ends)":
603 msg[9] == 3? " (continues+continued)":
604 msg[9] == 16? " (XferBlock-expected)":"");
605 print_pr_data (msg, msglen, 10);
609 static void
610 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
612 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
613 if (msglen < 10)
614 return;
615 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
616 msg[9] == 0? " (running)":
617 msg[9] == 1? " (stopped-L)":
618 msg[9] == 2? " (stopped-H)":
619 msg[9] == 3? " (stopped)":"");
620 print_pr_data (msg, msglen, 10);
624 static void
625 print_r2p_parameters (const unsigned char *msg, size_t msglen)
627 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
628 if (msglen < 10)
629 return;
631 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
632 if (msglen == 17 && msg[9] == 1)
634 /* Protocol T=1. */
635 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
636 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
637 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
638 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
639 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
640 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
641 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
643 else
644 print_pr_data (msg, msglen, 10);
648 static void
649 print_r2p_escape (const unsigned char *msg, size_t msglen)
651 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
652 if (msglen < 10)
653 return;
654 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
655 print_pr_data (msg, msglen, 10);
659 static void
660 print_r2p_datarate (const unsigned char *msg, size_t msglen)
662 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
663 if (msglen < 10)
664 return;
665 if (msglen >= 18)
667 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
668 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
669 print_pr_data (msg, msglen, 18);
671 else
672 print_pr_data (msg, msglen, 10);
676 static void
677 print_r2p_unknown (const unsigned char *msg, size_t msglen)
679 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
680 if (msglen < 10)
681 return;
682 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
683 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
684 print_pr_data (msg, msglen, 10);
688 /* Given a handle used for special transport prepare it for use. In
689 particular setup all information in way that resembles what
690 parse_cccid_descriptor does. */
691 static void
692 prepare_special_transport (ccid_driver_t handle)
694 assert (!handle->id_vendor);
696 handle->nonnull_nad = 0;
697 handle->auto_ifsd = 0;
698 handle->max_ifsd = 32;
699 handle->ifsd = 0;
700 handle->has_pinpad = 0;
701 handle->apdu_level = 0;
702 switch (handle->id_product)
704 case TRANSPORT_CM4040:
705 DEBUGOUT ("setting up transport for CardMan 4040\n");
706 handle->apdu_level = 1;
707 break;
709 default: assert (!"transport not defined");
713 /* Parse a CCID descriptor, optionally print all available features
714 and test whether this reader is usable by this driver. Returns 0
715 if it is usable.
717 Note, that this code is based on the one in lsusb.c of the
718 usb-utils package, I wrote on 2003-09-01. -wk. */
719 static int
720 parse_ccid_descriptor (ccid_driver_t handle,
721 const unsigned char *buf, size_t buflen)
723 unsigned int i;
724 unsigned int us;
725 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
728 handle->nonnull_nad = 0;
729 handle->auto_ifsd = 0;
730 handle->max_ifsd = 32;
731 handle->ifsd = 0;
732 handle->has_pinpad = 0;
733 handle->apdu_level = 0;
734 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
735 handle->id_vendor, handle->id_product, handle->bcd_device);
736 if (buflen < 54 || buf[0] < 54)
738 DEBUGOUT ("CCID device descriptor is too short\n");
739 return -1;
742 DEBUGOUT ("ChipCard Interface Descriptor:\n");
743 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
744 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
745 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
746 if (buf[3] != 1 || buf[2] != 0)
747 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
748 DEBUGOUT_LF ();
750 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
751 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
752 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
753 : buf[5] == 3? "1.8V":"?"));
755 us = convert_le_u32 (buf+6);
756 DEBUGOUT_1 (" dwProtocols %5u ", us);
757 if ((us & 1))
758 DEBUGOUT_CONT (" T=0");
759 if ((us & 2))
761 DEBUGOUT_CONT (" T=1");
762 have_t1 = 1;
764 if ((us & ~3))
765 DEBUGOUT_CONT (" (Invalid values detected)");
766 DEBUGOUT_LF ();
768 us = convert_le_u32(buf+10);
769 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
770 us = convert_le_u32(buf+14);
771 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
772 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
773 us = convert_le_u32(buf+19);
774 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
775 us = convert_le_u32(buf+23);
776 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
777 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
779 us = convert_le_u32(buf+28);
780 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
781 handle->max_ifsd = us;
783 us = convert_le_u32(buf+32);
784 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
785 if ((us&1))
786 DEBUGOUT_CONT ( " 2-wire");
787 if ((us&2))
788 DEBUGOUT_CONT ( " 3-wire");
789 if ((us&4))
790 DEBUGOUT_CONT ( " I2C");
791 DEBUGOUT_LF ();
793 us = convert_le_u32(buf+36);
794 DEBUGOUT_1 (" dwMechanical %08X ", us);
795 if ((us & 1))
796 DEBUGOUT_CONT (" accept");
797 if ((us & 2))
798 DEBUGOUT_CONT (" eject");
799 if ((us & 4))
800 DEBUGOUT_CONT (" capture");
801 if ((us & 8))
802 DEBUGOUT_CONT (" lock");
803 DEBUGOUT_LF ();
805 us = convert_le_u32(buf+40);
806 DEBUGOUT_1 (" dwFeatures %08X\n", us);
807 if ((us & 0x0002))
809 DEBUGOUT (" Auto configuration based on ATR\n");
810 have_auto_conf = 1;
812 if ((us & 0x0004))
813 DEBUGOUT (" Auto activation on insert\n");
814 if ((us & 0x0008))
815 DEBUGOUT (" Auto voltage selection\n");
816 if ((us & 0x0010))
817 DEBUGOUT (" Auto clock change\n");
818 if ((us & 0x0020))
819 DEBUGOUT (" Auto baud rate change\n");
820 if ((us & 0x0040))
821 DEBUGOUT (" Auto parameter negotation made by CCID\n");
822 else if ((us & 0x0080))
823 DEBUGOUT (" Auto PPS made by CCID\n");
824 else if ((us & (0x0040 | 0x0080)))
825 DEBUGOUT (" WARNING: conflicting negotation features\n");
827 if ((us & 0x0100))
828 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
829 if ((us & 0x0200))
831 DEBUGOUT (" NAD value other than 0x00 accepted\n");
832 handle->nonnull_nad = 1;
834 if ((us & 0x0400))
836 DEBUGOUT (" Auto IFSD exchange\n");
837 handle->auto_ifsd = 1;
840 if ((us & 0x00010000))
842 DEBUGOUT (" TPDU level exchange\n");
843 have_tpdu = 1;
845 else if ((us & 0x00020000))
847 DEBUGOUT (" Short APDU level exchange\n");
848 handle->apdu_level = 1;
850 else if ((us & 0x00040000))
852 DEBUGOUT (" Short and extended APDU level exchange\n");
853 handle->apdu_level = 2;
855 else if ((us & 0x00070000))
856 DEBUGOUT (" WARNING: conflicting exchange levels\n");
858 us = convert_le_u32(buf+44);
859 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
861 DEBUGOUT ( " bClassGetResponse ");
862 if (buf[48] == 0xff)
863 DEBUGOUT_CONT ("echo\n");
864 else
865 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
867 DEBUGOUT ( " bClassEnvelope ");
868 if (buf[49] == 0xff)
869 DEBUGOUT_CONT ("echo\n");
870 else
871 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
873 DEBUGOUT ( " wlcdLayout ");
874 if (!buf[50] && !buf[51])
875 DEBUGOUT_CONT ("none\n");
876 else
877 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
879 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
880 if ((buf[52] & 1))
882 DEBUGOUT_CONT ( " verification");
883 handle->has_pinpad |= 1;
885 if ((buf[52] & 2))
887 DEBUGOUT_CONT ( " modification");
888 handle->has_pinpad |= 2;
890 DEBUGOUT_LF ();
892 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
894 if (buf[0] > 54) {
895 DEBUGOUT (" junk ");
896 for (i=54; i < buf[0]-54; i++)
897 DEBUGOUT_CONT_1 (" %02X", buf[i]);
898 DEBUGOUT_LF ();
901 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
903 DEBUGOUT ("this drivers requires that the reader supports T=1, "
904 "TPDU or APDU level exchange and auto configuration - "
905 "this is not available\n");
906 return -1;
910 /* SCM drivers get stuck in their internal USB stack if they try to
911 send a frame of n*wMaxPacketSize back to us. Given that
912 wMaxPacketSize is 64 for these readers we set the IFSD to a value
913 lower than that:
914 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
915 Product Ids:
916 0xe001 - SCR 331
917 0x5111 - SCR 331-DI
918 0x5115 - SCR 335
919 0xe003 - SPR 532
921 if (handle->id_vendor == VENDOR_SCM
922 && handle->max_ifsd > 48
923 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
924 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
925 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
926 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
929 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
930 handle->max_ifsd = 48;
934 return 0;
938 static char *
939 get_escaped_usb_string (usb_dev_handle *idev, int idx,
940 const char *prefix, const char *suffix)
942 int rc;
943 unsigned char buf[280];
944 unsigned char *s;
945 unsigned int langid;
946 size_t i, n, len;
947 char *result;
949 if (!idx)
950 return NULL;
952 /* Fixme: The next line is for the current Valgrid without support
953 for USB IOCTLs. */
954 memset (buf, 0, sizeof buf);
956 /* First get the list of supported languages and use the first one.
957 If we do don't find it we try to use English. Note that this is
958 all in a 2 bute Unicode encoding using little endian. */
959 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
960 (USB_DT_STRING << 8), 0,
961 (char*)buf, sizeof buf, 1000 /* ms timeout */);
962 if (rc < 4)
963 langid = 0x0409; /* English. */
964 else
965 langid = (buf[3] << 8) | buf[2];
967 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
968 (USB_DT_STRING << 8) + idx, langid,
969 (char*)buf, sizeof buf, 1000 /* ms timeout */);
970 if (rc < 2 || buf[1] != USB_DT_STRING)
971 return NULL; /* Error or not a string. */
972 len = buf[0];
973 if (len > rc)
974 return NULL; /* Larger than our buffer. */
976 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
978 if (s[1])
979 n++; /* High byte set. */
980 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
981 n += 3 ;
982 else
983 n++;
986 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
987 if (!result)
988 return NULL;
990 strcpy (result, prefix);
991 n = strlen (prefix);
992 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
994 if (s[1])
995 result[n++] = '\xff'; /* High byte set. */
996 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
998 sprintf (result+n, "%%%02X", *s);
999 n += 3;
1001 else
1002 result[n++] = *s;
1004 strcpy (result+n, suffix);
1006 return result;
1009 /* This function creates an reader id to be used to find the same
1010 physical reader after a reset. It returns an allocated and possibly
1011 percent escaped string or NULL if not enough memory is available. */
1012 static char *
1013 make_reader_id (usb_dev_handle *idev,
1014 unsigned int vendor, unsigned int product,
1015 unsigned char serialno_index)
1017 char *rid;
1018 char prefix[20];
1020 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1021 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1022 if (!rid)
1024 rid = malloc (strlen (prefix) + 3 + 1);
1025 if (!rid)
1026 return NULL;
1027 strcpy (rid, prefix);
1028 strcat (rid, "X:0");
1030 return rid;
1034 /* Helper to find the endpoint from an interface descriptor. */
1035 static int
1036 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1038 int no;
1039 int want_bulk_in = 0;
1041 if (mode == 1)
1042 want_bulk_in = 0x80;
1043 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1045 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1046 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1048 else if (mode == 2
1049 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1050 == USB_ENDPOINT_TYPE_INTERRUPT)
1051 && (ep->bEndpointAddress & 0x80))
1052 return (ep->bEndpointAddress & 0x0f);
1053 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1054 == USB_ENDPOINT_TYPE_BULK)
1055 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1056 return (ep->bEndpointAddress & 0x0f);
1058 /* Should never happen. */
1059 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1063 /* Helper for scan_or_find_devices. This function returns true if a
1064 requested device has been found or the caller should stop scanning
1065 for other reasons. */
1066 static int
1067 scan_or_find_usb_device (int scan_mode,
1068 int *readerno, int *count, char **rid_list,
1069 const char *readerid,
1070 struct usb_device *dev,
1071 char **r_rid,
1072 struct usb_device **r_dev,
1073 usb_dev_handle **r_idev,
1074 unsigned char **ifcdesc_extra,
1075 size_t *ifcdesc_extra_len,
1076 int *interface_number,
1077 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1079 int cfg_no;
1080 int ifc_no;
1081 int set_no;
1082 struct usb_config_descriptor *config;
1083 struct usb_interface *interface;
1084 struct usb_interface_descriptor *ifcdesc;
1085 char *rid;
1086 usb_dev_handle *idev;
1088 *r_idev = NULL;
1090 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1092 config = dev->config + cfg_no;
1093 if(!config)
1094 continue;
1096 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1098 interface = config->interface + ifc_no;
1099 if (!interface)
1100 continue;
1102 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1104 ifcdesc = (interface->altsetting + set_no);
1105 /* The second condition is for older SCM SPR 532 who did
1106 not know about the assigned CCID class. Instead of
1107 trying to interpret the strings we simply check the
1108 product ID. */
1109 if (ifcdesc && ifcdesc->extra
1110 && ((ifcdesc->bInterfaceClass == 11
1111 && ifcdesc->bInterfaceSubClass == 0
1112 && ifcdesc->bInterfaceProtocol == 0)
1113 || (ifcdesc->bInterfaceClass == 255
1114 && dev->descriptor.idVendor == VENDOR_SCM
1115 && dev->descriptor.idProduct == 0xe003)))
1117 idev = usb_open (dev);
1118 if (!idev)
1120 DEBUGOUT_1 ("usb_open failed: %s\n",
1121 strerror (errno));
1122 continue; /* with next setting. */
1125 rid = make_reader_id (idev,
1126 dev->descriptor.idVendor,
1127 dev->descriptor.idProduct,
1128 dev->descriptor.iSerialNumber);
1129 if (rid)
1131 if (scan_mode)
1133 char *p;
1135 /* We are collecting infos about all
1136 available CCID readers. Store them and
1137 continue. */
1138 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1139 *count, rid );
1140 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1141 + strlen (rid) + 1);
1142 if (p)
1144 *p = 0;
1145 if (*rid_list)
1147 strcat (p, *rid_list);
1148 free (*rid_list);
1150 strcat (p, rid);
1151 strcat (p, "\n");
1152 *rid_list = p;
1154 else /* Out of memory. */
1155 free (rid);
1157 rid = NULL;
1158 ++*count;
1160 else if (!*readerno
1161 || (*readerno < 0
1162 && readerid
1163 && !strcmp (readerid, rid)))
1165 /* We found the requested reader. */
1166 if (ifcdesc_extra && ifcdesc_extra_len)
1168 *ifcdesc_extra = malloc (ifcdesc
1169 ->extralen);
1170 if (!*ifcdesc_extra)
1172 usb_close (idev);
1173 free (rid);
1174 return 1; /* Out of core. */
1176 memcpy (*ifcdesc_extra, ifcdesc->extra,
1177 ifcdesc->extralen);
1178 *ifcdesc_extra_len = ifcdesc->extralen;
1181 if (interface_number)
1182 *interface_number = (ifcdesc->bInterfaceNumber);
1184 if (ep_bulk_out)
1185 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1186 if (ep_bulk_in)
1187 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1188 if (ep_intr)
1189 *ep_intr = find_endpoint (ifcdesc, 2);
1191 if (r_dev)
1192 *r_dev = dev;
1193 if (r_rid)
1195 *r_rid = rid;
1196 rid = NULL;
1198 else
1199 free (rid);
1201 *r_idev = idev;
1202 return 1; /* Found requested device. */
1204 else
1206 /* This is not yet the reader we want.
1207 fixme: We should avoid the extra usb_open
1208 in this case. */
1209 if (*readerno >= 0)
1210 --*readerno;
1212 free (rid);
1215 usb_close (idev);
1216 idev = NULL;
1217 return 0;
1223 return 0;
1226 /* Combination function to either scan all CCID devices or to find and
1227 open one specific device.
1229 The function returns 0 if a reader has been found or when a scan
1230 returned without error.
1232 With READERNO = -1 and READERID is NULL, scan mode is used and
1233 R_RID should be the address where to store the list of reader_ids
1234 we found. If on return this list is empty, no CCID device has been
1235 found; otherwise it points to an allocated linked list of reader
1236 IDs. Note that in this mode the function always returns NULL.
1238 With READERNO >= 0 or READERID is not NULL find mode is used. This
1239 uses the same algorithm as the scan mode but stops and returns at
1240 the entry number READERNO and return the handle for the the opened
1241 USB device. If R_RID is not NULL it will receive the reader ID of
1242 that device. If R_DEV is not NULL it will the device pointer of
1243 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1244 malloced copy of the interfaces "extra: data filed;
1245 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1246 no reader with number READERNO or that reader is not usable by our
1247 implementation NULL will be returned. The caller must close a
1248 returned USB device handle and free (if not passed as NULL) the
1249 returned reader ID info as well as the IFCDESC_EXTRA. On error
1250 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1251 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1252 the READERID was found.
1254 If R_FD is not -1 on return the device is not using USB for
1255 transport but the device associated with that file descriptor. In
1256 this case INTERFACE will receive the transport type and the other
1257 USB specific return values are not used; the return value is
1258 (void*)(1).
1260 Note that the first entry of the returned reader ID list in scan mode
1261 corresponds with a READERNO of 0 in find mode.
1263 static int
1264 scan_or_find_devices (int readerno, const char *readerid,
1265 char **r_rid,
1266 struct usb_device **r_dev,
1267 unsigned char **ifcdesc_extra,
1268 size_t *ifcdesc_extra_len,
1269 int *interface_number,
1270 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1271 usb_dev_handle **r_idev,
1272 int *r_fd)
1274 char *rid_list = NULL;
1275 int count = 0;
1276 struct usb_bus *busses, *bus;
1277 struct usb_device *dev = NULL;
1278 usb_dev_handle *idev = NULL;
1279 int scan_mode = (readerno == -1 && !readerid);
1280 int i;
1282 /* Set return values to a default. */
1283 if (r_rid)
1284 *r_rid = NULL;
1285 if (r_dev)
1286 *r_dev = NULL;
1287 if (ifcdesc_extra)
1288 *ifcdesc_extra = NULL;
1289 if (ifcdesc_extra_len)
1290 *ifcdesc_extra_len = 0;
1291 if (interface_number)
1292 *interface_number = 0;
1293 if (r_idev)
1294 *r_idev = NULL;
1295 if (r_fd)
1296 *r_fd = -1;
1298 /* See whether we want scan or find mode. */
1299 if (scan_mode)
1301 assert (r_rid);
1304 usb_find_busses();
1305 usb_find_devices();
1307 #ifdef HAVE_USB_GET_BUSSES
1308 busses = usb_get_busses();
1309 #else
1310 busses = usb_busses;
1311 #endif
1313 for (bus = busses; bus; bus = bus->next)
1315 for (dev = bus->devices; dev; dev = dev->next)
1317 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1318 readerid,
1319 dev,
1320 r_rid,
1321 r_dev,
1322 &idev,
1323 ifcdesc_extra,
1324 ifcdesc_extra_len,
1325 interface_number,
1326 ep_bulk_out, ep_bulk_in, ep_intr))
1328 /* Found requested device or out of core. */
1329 if (!idev)
1331 free (rid_list);
1332 return -1; /* error */
1334 *r_idev = idev;
1335 return 0;
1340 /* Now check whether there are any devices with special transport types. */
1341 for (i=0; transports[i].name; i++)
1343 int fd;
1344 char *rid, *p;
1346 fd = open (transports[i].name, O_RDWR);
1347 if (fd == -1 && scan_mode && errno == EBUSY)
1349 /* Ignore this error in scan mode because it indicates that
1350 the device exists but is already open (most likely by us)
1351 and thus in general suitable as a reader. */
1353 else if (fd == -1)
1355 DEBUGOUT_2 ("failed to open `%s': %s\n",
1356 transports[i].name, strerror (errno));
1357 continue;
1360 rid = malloc (strlen (transports[i].name) + 30 + 10);
1361 if (!rid)
1363 if (fd != -1)
1364 close (fd);
1365 free (rid_list);
1366 return -1; /* Error. */
1368 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1369 if (scan_mode)
1371 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1372 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1373 if (!p)
1375 if (fd != -1)
1376 close (fd);
1377 free (rid_list);
1378 free (rid);
1379 return -1; /* Error. */
1381 *p = 0;
1382 if (rid_list)
1384 strcat (p, rid_list);
1385 free (rid_list);
1387 strcat (p, rid);
1388 strcat (p, "\n");
1389 rid_list = p;
1390 ++count;
1392 else if (!readerno ||
1393 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1395 /* Found requested device. */
1396 if (interface_number)
1397 *interface_number = transports[i].type;
1398 if (r_rid)
1399 *r_rid = rid;
1400 else
1401 free (rid);
1402 if (r_fd)
1403 *r_fd = fd;
1404 return 0; /* Okay, found device */
1406 else /* This is not yet the reader we want. */
1408 if (readerno >= 0)
1409 --readerno;
1411 free (rid);
1412 if (fd != -1)
1413 close (fd);
1416 if (scan_mode)
1418 *r_rid = rid_list;
1419 return 0;
1421 else
1422 return -1;
1426 /* Set the level of debugging to LEVEL and return the old level. -1
1427 just returns the old level. A level of 0 disables debugging, 1
1428 enables debugging, 2 enables additional tracing of the T=1
1429 protocol, 3 additionally enables debugging for GetSlotStatus, other
1430 values are not yet defined.
1432 Note that libusb may provide its own debugging feature which is
1433 enabled by setting the envvar USB_DEBUG. */
1435 ccid_set_debug_level (int level)
1437 int old = debug_level;
1438 if (level != -1)
1439 debug_level = level;
1440 return old;
1444 char *
1445 ccid_get_reader_list (void)
1447 char *reader_list;
1449 if (!initialized_usb)
1451 usb_init ();
1452 initialized_usb = 1;
1455 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1456 NULL, NULL, NULL, NULL, NULL))
1457 return NULL; /* Error. */
1458 return reader_list;
1462 /* Open the reader with the internal number READERNO and return a
1463 pointer to be used as handle in HANDLE. Returns 0 on success. */
1464 int
1465 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1467 int rc = 0;
1468 struct usb_device *dev = NULL;
1469 usb_dev_handle *idev = NULL;
1470 int dev_fd = -1;
1471 char *rid = NULL;
1472 unsigned char *ifcdesc_extra = NULL;
1473 size_t ifcdesc_extra_len;
1474 int readerno;
1475 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1477 *handle = NULL;
1479 if (!initialized_usb)
1481 usb_init ();
1482 initialized_usb = 1;
1485 /* See whether we want to use the reader ID string or a reader
1486 number. A readerno of -1 indicates that the reader ID string is
1487 to be used. */
1488 if (readerid && strchr (readerid, ':'))
1489 readerno = -1; /* We want to use the readerid. */
1490 else if (readerid)
1492 readerno = atoi (readerid);
1493 if (readerno < 0)
1495 DEBUGOUT ("no CCID readers found\n");
1496 rc = CCID_DRIVER_ERR_NO_READER;
1497 goto leave;
1500 else
1501 readerno = 0; /* Default. */
1503 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1504 &ifcdesc_extra, &ifcdesc_extra_len,
1505 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1506 &idev, &dev_fd) )
1508 if (readerno == -1)
1509 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1510 else
1511 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1512 rc = CCID_DRIVER_ERR_NO_READER;
1513 goto leave;
1516 /* Okay, this is a CCID reader. */
1517 *handle = calloc (1, sizeof **handle);
1518 if (!*handle)
1520 DEBUGOUT ("out of memory\n");
1521 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1522 goto leave;
1524 (*handle)->rid = rid;
1525 if (idev) /* Regular USB transport. */
1527 (*handle)->idev = idev;
1528 (*handle)->dev_fd = -1;
1529 (*handle)->id_vendor = dev->descriptor.idVendor;
1530 (*handle)->id_product = dev->descriptor.idProduct;
1531 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1532 (*handle)->ifc_no = ifc_no;
1533 (*handle)->ep_bulk_out = ep_bulk_out;
1534 (*handle)->ep_bulk_in = ep_bulk_in;
1535 (*handle)->ep_intr = ep_intr;
1537 else if (dev_fd != -1) /* Device transport. */
1539 (*handle)->idev = NULL;
1540 (*handle)->dev_fd = dev_fd;
1541 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1542 (*handle)->id_product = ifc_no; /* Transport type */
1543 prepare_special_transport (*handle);
1545 else
1547 assert (!"no transport"); /* Bug. */
1550 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1552 if (idev)
1554 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1556 DEBUGOUT ("device not supported\n");
1557 rc = CCID_DRIVER_ERR_NO_READER;
1558 goto leave;
1561 rc = usb_claim_interface (idev, ifc_no);
1562 if (rc)
1564 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1565 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1566 goto leave;
1570 leave:
1571 free (ifcdesc_extra);
1572 if (rc)
1574 free (rid);
1575 if (idev)
1576 usb_close (idev);
1577 if (dev_fd != -1)
1578 close (dev_fd);
1579 free (*handle);
1580 *handle = NULL;
1583 return rc;
1587 static void
1588 do_close_reader (ccid_driver_t handle)
1590 int rc;
1591 unsigned char msg[100];
1592 size_t msglen;
1593 unsigned char seqno;
1595 if (!handle->powered_off)
1597 msg[0] = PC_to_RDR_IccPowerOff;
1598 msg[5] = 0; /* slot */
1599 msg[6] = seqno = handle->seqno++;
1600 msg[7] = 0; /* RFU */
1601 msg[8] = 0; /* RFU */
1602 msg[9] = 0; /* RFU */
1603 set_msg_len (msg, 0);
1604 msglen = 10;
1606 rc = bulk_out (handle, msg, msglen, 0);
1607 if (!rc)
1608 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1609 seqno, 2000, 0);
1610 handle->powered_off = 1;
1612 if (handle->idev)
1614 usb_release_interface (handle->idev, handle->ifc_no);
1615 usb_close (handle->idev);
1616 handle->idev = NULL;
1618 if (handle->dev_fd != -1)
1620 close (handle->dev_fd);
1621 handle->dev_fd = -1;
1626 /* Reset a reader on HANDLE. This is useful in case a reader has been
1627 plugged of and inserted at a different port. By resetting the
1628 handle, the same reader will be get used. Note, that on error the
1629 handle won't get released.
1631 This does not return an ATR, so ccid_get_atr should be called right
1632 after this one.
1634 int
1635 ccid_shutdown_reader (ccid_driver_t handle)
1637 int rc = 0;
1638 struct usb_device *dev = NULL;
1639 usb_dev_handle *idev = NULL;
1640 unsigned char *ifcdesc_extra = NULL;
1641 size_t ifcdesc_extra_len;
1642 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1644 if (!handle || !handle->rid)
1645 return CCID_DRIVER_ERR_INV_VALUE;
1647 do_close_reader (handle);
1649 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1650 &ifcdesc_extra, &ifcdesc_extra_len,
1651 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1652 &idev, NULL) || !idev)
1654 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1655 return CCID_DRIVER_ERR_NO_READER;
1658 if (idev)
1660 handle->idev = idev;
1661 handle->ifc_no = ifc_no;
1662 handle->ep_bulk_out = ep_bulk_out;
1663 handle->ep_bulk_in = ep_bulk_in;
1664 handle->ep_intr = ep_intr;
1666 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1668 DEBUGOUT ("device not supported\n");
1669 rc = CCID_DRIVER_ERR_NO_READER;
1670 goto leave;
1673 rc = usb_claim_interface (idev, ifc_no);
1674 if (rc)
1676 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1677 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1678 goto leave;
1682 leave:
1683 free (ifcdesc_extra);
1684 if (rc)
1686 if (handle->idev)
1687 usb_close (handle->idev);
1688 handle->idev = NULL;
1689 if (handle->dev_fd != -1)
1690 close (handle->dev_fd);
1691 handle->dev_fd = -1;
1694 return rc;
1699 int
1700 ccid_set_progress_cb (ccid_driver_t handle,
1701 void (*cb)(void *, const char *, int, int, int),
1702 void *cb_arg)
1704 if (!handle || !handle->rid)
1705 return CCID_DRIVER_ERR_INV_VALUE;
1707 handle->progress_cb = cb;
1708 handle->progress_cb_arg = cb_arg;
1709 return 0;
1713 /* Close the reader HANDLE. */
1714 int
1715 ccid_close_reader (ccid_driver_t handle)
1717 if (!handle || (!handle->idev && handle->dev_fd == -1))
1718 return 0;
1720 do_close_reader (handle);
1721 free (handle->rid);
1722 free (handle);
1723 return 0;
1727 /* Return False if a card is present and powered. */
1729 ccid_check_card_presence (ccid_driver_t handle)
1731 (void)handle; /* Not yet implemented. */
1732 return -1;
1736 /* Write NBYTES of BUF to file descriptor FD. */
1737 static int
1738 writen (int fd, const void *buf, size_t nbytes)
1740 size_t nleft = nbytes;
1741 int nwritten;
1743 while (nleft > 0)
1745 nwritten = write (fd, buf, nleft);
1746 if (nwritten < 0)
1748 if (errno == EINTR)
1749 nwritten = 0;
1750 else
1751 return -1;
1753 nleft -= nwritten;
1754 buf = (const char*)buf + nwritten;
1757 return 0;
1761 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1762 Returns 0 on success. */
1763 static int
1764 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1765 int no_debug)
1767 int rc;
1769 /* No need to continue and clutter the log withy USB error if we
1770 ever got an ENODEV. */
1771 if (handle->enodev_seen)
1772 return CCID_DRIVER_ERR_NO_READER;
1774 if (debug_level && (!no_debug || debug_level >= 3))
1776 switch (msglen? msg[0]:0)
1778 case PC_to_RDR_IccPowerOn:
1779 print_p2r_iccpoweron (msg, msglen);
1780 break;
1781 case PC_to_RDR_IccPowerOff:
1782 print_p2r_iccpoweroff (msg, msglen);
1783 break;
1784 case PC_to_RDR_GetSlotStatus:
1785 print_p2r_getslotstatus (msg, msglen);
1786 break;
1787 case PC_to_RDR_XfrBlock:
1788 print_p2r_xfrblock (msg, msglen);
1789 break;
1790 case PC_to_RDR_GetParameters:
1791 print_p2r_getparameters (msg, msglen);
1792 break;
1793 case PC_to_RDR_ResetParameters:
1794 print_p2r_resetparameters (msg, msglen);
1795 break;
1796 case PC_to_RDR_SetParameters:
1797 print_p2r_setparameters (msg, msglen);
1798 break;
1799 case PC_to_RDR_Escape:
1800 print_p2r_escape (msg, msglen);
1801 break;
1802 case PC_to_RDR_IccClock:
1803 print_p2r_iccclock (msg, msglen);
1804 break;
1805 case PC_to_RDR_T0APDU:
1806 print_p2r_to0apdu (msg, msglen);
1807 break;
1808 case PC_to_RDR_Secure:
1809 print_p2r_secure (msg, msglen);
1810 break;
1811 case PC_to_RDR_Mechanical:
1812 print_p2r_mechanical (msg, msglen);
1813 break;
1814 case PC_to_RDR_Abort:
1815 print_p2r_abort (msg, msglen);
1816 break;
1817 case PC_to_RDR_SetDataRate:
1818 print_p2r_setdatarate (msg, msglen);
1819 break;
1820 default:
1821 print_p2r_unknown (msg, msglen);
1822 break;
1826 if (handle->idev)
1828 rc = usb_bulk_write (handle->idev,
1829 handle->ep_bulk_out,
1830 (char*)msg, msglen,
1831 5000 /* ms timeout */);
1832 if (rc == msglen)
1833 return 0;
1834 #ifdef ENODEV
1835 if (rc == -(ENODEV))
1837 /* The Linux libusb returns a negative error value. Catch
1838 the most important one. */
1839 errno = ENODEV;
1840 rc = -1;
1842 #endif /*ENODEV*/
1844 if (rc == -1)
1846 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1847 #ifdef ENODEV
1848 if (errno == ENODEV)
1850 handle->enodev_seen = 1;
1851 return CCID_DRIVER_ERR_NO_READER;
1853 #endif /*ENODEV*/
1855 else
1856 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1858 else
1860 rc = writen (handle->dev_fd, msg, msglen);
1861 if (!rc)
1862 return 0;
1863 DEBUGOUT_2 ("writen to %d failed: %s\n",
1864 handle->dev_fd, strerror (errno));
1867 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1871 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1872 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1873 is the sequence number used to send the request and EXPECTED_TYPE
1874 the type of message we expect. Does checks on the ccid
1875 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1876 avoid debug messages in case of no error; this can be overriden
1877 with a glibal debug level of at least 3. Returns 0 on success. */
1878 static int
1879 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1880 size_t *nread, int expected_type, int seqno, int timeout,
1881 int no_debug)
1883 int rc;
1884 size_t msglen;
1885 int eagain_retries = 0;
1887 /* Fixme: The next line for the current Valgrind without support
1888 for USB IOCTLs. */
1889 memset (buffer, 0, length);
1890 retry:
1891 if (handle->idev)
1893 rc = usb_bulk_read (handle->idev,
1894 handle->ep_bulk_in,
1895 (char*)buffer, length,
1896 timeout);
1897 if (rc < 0)
1899 rc = errno;
1900 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
1901 if (rc == EAGAIN && eagain_retries++ < 3)
1903 #ifndef TEST
1904 gnupg_sleep (1);
1905 #endif
1906 goto retry;
1908 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1910 *nread = msglen = rc;
1912 else
1914 rc = read (handle->dev_fd, buffer, length);
1915 if (rc < 0)
1917 rc = errno;
1918 DEBUGOUT_2 ("read from %d failed: %s\n",
1919 handle->dev_fd, strerror (rc));
1920 if (rc == EAGAIN && eagain_retries++ < 5)
1922 #ifndef TEST
1923 gnupg_sleep (1);
1924 #endif
1925 goto retry;
1927 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1929 *nread = msglen = rc;
1931 eagain_retries = 0;
1933 if (msglen < 10)
1935 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1936 abort_cmd (handle, seqno);
1937 return CCID_DRIVER_ERR_INV_VALUE;
1939 if (buffer[5] != 0)
1941 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1942 return CCID_DRIVER_ERR_INV_VALUE;
1944 if (buffer[6] != seqno)
1946 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1947 seqno, buffer[6]);
1948 /* Retry until we are synced again. */
1949 goto retry;
1952 /* We need to handle the time extension request before we check that
1953 we got the expected message type. This is in particular required
1954 for the Cherry keyboard which sends a time extension request for
1955 each key hit. */
1956 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1958 /* Card present and active, time extension requested. */
1959 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1960 buffer[7], buffer[8]);
1961 goto retry;
1964 if (buffer[0] != expected_type)
1966 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1967 abort_cmd (handle, seqno);
1968 return CCID_DRIVER_ERR_INV_VALUE;
1971 if (debug_level && (!no_debug || debug_level >= 3))
1973 switch (buffer[0])
1975 case RDR_to_PC_DataBlock:
1976 print_r2p_datablock (buffer, msglen);
1977 break;
1978 case RDR_to_PC_SlotStatus:
1979 print_r2p_slotstatus (buffer, msglen);
1980 break;
1981 case RDR_to_PC_Parameters:
1982 print_r2p_parameters (buffer, msglen);
1983 break;
1984 case RDR_to_PC_Escape:
1985 print_r2p_escape (buffer, msglen);
1986 break;
1987 case RDR_to_PC_DataRate:
1988 print_r2p_datarate (buffer, msglen);
1989 break;
1990 default:
1991 print_r2p_unknown (buffer, msglen);
1992 break;
1995 if (CCID_COMMAND_FAILED (buffer))
1996 print_command_failed (buffer);
1998 /* Check whether a card is at all available. Note: If you add new
1999 error codes here, check whether they need to be ignored in
2000 send_escape_cmd. */
2001 switch ((buffer[7] & 0x03))
2003 case 0: /* no error */ break;
2004 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2005 case 2: return CCID_DRIVER_ERR_NO_CARD;
2006 case 3: /* RFU */ break;
2008 return 0;
2013 /* Send an abort sequence and wait until everything settled. */
2014 static int
2015 abort_cmd (ccid_driver_t handle, int seqno)
2017 int rc;
2018 char dummybuf[8];
2019 unsigned char msg[100];
2020 size_t msglen;
2022 if (!handle->idev)
2024 /* I don't know how to send an abort to non-USB devices. */
2025 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2028 seqno &= 0xff;
2029 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2030 /* Send the abort command to the control pipe. Note that we don't
2031 need to keep track of sent abort commands because there should
2032 never be another thread using the same slot concurrently. */
2033 rc = usb_control_msg (handle->idev,
2034 0x21,/* bmRequestType: host-to-device,
2035 class specific, to interface. */
2036 1, /* ABORT */
2037 (seqno << 8 | 0 /* slot */),
2038 handle->ifc_no,
2039 dummybuf, 0,
2040 1000 /* ms timeout */);
2041 if (rc < 0)
2043 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
2044 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2047 /* Now send the abort command to the bulk out pipe using the same
2048 SEQNO and SLOT. Do this in a loop to so that all seqno are
2049 tried. */
2050 seqno--; /* Adjust for next increment. */
2053 seqno++;
2054 msg[0] = PC_to_RDR_Abort;
2055 msg[5] = 0; /* slot */
2056 msg[6] = seqno;
2057 msg[7] = 0; /* RFU */
2058 msg[8] = 0; /* RFU */
2059 msg[9] = 0; /* RFU */
2060 msglen = 10;
2061 set_msg_len (msg, 0);
2063 rc = usb_bulk_write (handle->idev,
2064 handle->ep_bulk_out,
2065 (char*)msg, msglen,
2066 5000 /* ms timeout */);
2067 if (rc == msglen)
2068 rc = 0;
2069 else if (rc == -1)
2070 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2071 strerror (errno));
2072 else
2073 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2075 if (rc)
2076 return rc;
2078 rc = usb_bulk_read (handle->idev,
2079 handle->ep_bulk_in,
2080 (char*)msg, sizeof msg,
2081 5000 /*ms timeout*/);
2082 if (rc < 0)
2084 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2085 strerror (errno));
2086 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2088 msglen = rc;
2090 if (msglen < 10)
2092 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2093 (unsigned int)msglen);
2094 return CCID_DRIVER_ERR_INV_VALUE;
2096 if (msg[5] != 0)
2098 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2099 return CCID_DRIVER_ERR_INV_VALUE;
2102 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2103 msg[7], msg[8], msg[9]);
2104 if (CCID_COMMAND_FAILED (msg))
2105 print_command_failed (msg);
2107 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2109 handle->seqno = ((seqno + 1) & 0xff);
2110 DEBUGOUT ("sending abort sequence succeeded\n");
2112 return 0;
2116 /* Note that this function won't return the error codes NO_CARD or
2117 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2118 operation will get returned in RESULT and its length in RESULTLEN.
2119 If the response is larger than RESULTMAX, an error is returned and
2120 the required buffer length returned in RESULTLEN. */
2121 static int
2122 send_escape_cmd (ccid_driver_t handle,
2123 const unsigned char *data, size_t datalen,
2124 unsigned char *result, size_t resultmax, size_t *resultlen)
2126 int rc;
2127 unsigned char msg[100];
2128 size_t msglen;
2129 unsigned char seqno;
2131 if (resultlen)
2132 *resultlen = 0;
2134 if (datalen > sizeof msg - 10)
2135 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2137 msg[0] = PC_to_RDR_Escape;
2138 msg[5] = 0; /* slot */
2139 msg[6] = seqno = handle->seqno++;
2140 msg[7] = 0; /* RFU */
2141 msg[8] = 0; /* RFU */
2142 msg[9] = 0; /* RFU */
2143 memcpy (msg+10, data, datalen);
2144 msglen = 10 + datalen;
2145 set_msg_len (msg, datalen);
2147 rc = bulk_out (handle, msg, msglen, 0);
2148 if (rc)
2149 return rc;
2150 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2151 seqno, 5000, 0);
2152 if (result)
2153 switch (rc)
2155 /* We need to ignore certain errorcode here. */
2156 case 0:
2157 case CCID_DRIVER_ERR_CARD_INACTIVE:
2158 case CCID_DRIVER_ERR_NO_CARD:
2160 if (msglen > resultmax)
2161 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2162 else
2164 memcpy (result, msg, msglen);
2165 *resultlen = msglen;
2167 rc = 0;
2169 break;
2170 default:
2171 break;
2174 return rc;
2179 ccid_transceive_escape (ccid_driver_t handle,
2180 const unsigned char *data, size_t datalen,
2181 unsigned char *resp, size_t maxresplen, size_t *nresp)
2183 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2188 /* experimental */
2190 ccid_poll (ccid_driver_t handle)
2192 int rc;
2193 unsigned char msg[10];
2194 size_t msglen;
2195 int i, j;
2197 if (handle->idev)
2199 rc = usb_bulk_read (handle->idev,
2200 handle->ep_intr,
2201 (char*)msg, sizeof msg,
2202 0 /* ms timeout */ );
2203 if (rc < 0 && errno == ETIMEDOUT)
2204 return 0;
2206 else
2207 return 0;
2209 if (rc < 0)
2211 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2212 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2215 msglen = rc;
2216 rc = 0;
2218 if (msglen < 1)
2220 DEBUGOUT ("intr-in msg too short\n");
2221 return CCID_DRIVER_ERR_INV_VALUE;
2224 if (msg[0] == RDR_to_PC_NotifySlotChange)
2226 DEBUGOUT ("notify slot change:");
2227 for (i=1; i < msglen; i++)
2228 for (j=0; j < 4; j++)
2229 DEBUGOUT_CONT_3 (" %d:%c%c",
2230 (i-1)*4+j,
2231 (msg[i] & (1<<(j*2)))? 'p':'-',
2232 (msg[i] & (2<<(j*2)))? '*':' ');
2233 DEBUGOUT_LF ();
2235 else if (msg[0] == RDR_to_PC_HardwareError)
2237 DEBUGOUT ("hardware error occured\n");
2239 else
2241 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2244 return 0;
2248 /* Note that this function won't return the error codes NO_CARD or
2249 CARD_INACTIVE */
2250 int
2251 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2253 int rc;
2254 unsigned char msg[100];
2255 size_t msglen;
2256 unsigned char seqno;
2257 int retries = 0;
2259 retry:
2260 msg[0] = PC_to_RDR_GetSlotStatus;
2261 msg[5] = 0; /* slot */
2262 msg[6] = seqno = handle->seqno++;
2263 msg[7] = 0; /* RFU */
2264 msg[8] = 0; /* RFU */
2265 msg[9] = 0; /* RFU */
2266 set_msg_len (msg, 0);
2268 rc = bulk_out (handle, msg, 10, 1);
2269 if (rc)
2270 return rc;
2271 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2272 get cluttered up by a ticker function checking for the slot
2273 status and debugging enabled. */
2274 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2275 seqno, retries? 1000 : 200, 1);
2276 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2278 if (!retries)
2280 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2281 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2282 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2284 else
2285 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2286 retries++;
2287 goto retry;
2289 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2290 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2291 return rc;
2292 *statusbits = (msg[7] & 3);
2294 return 0;
2298 /* Return the ATR of the card. This is not a cached value and thus an
2299 actual reset is done. */
2300 int
2301 ccid_get_atr (ccid_driver_t handle,
2302 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2304 int rc;
2305 int statusbits;
2306 unsigned char msg[100];
2307 unsigned char *tpdu;
2308 size_t msglen, tpdulen;
2309 unsigned char seqno;
2310 int use_crc = 0;
2311 unsigned int edc;
2312 int tried_iso = 0;
2313 int got_param;
2315 /* First check whether a card is available. */
2316 rc = ccid_slot_status (handle, &statusbits);
2317 if (rc)
2318 return rc;
2319 if (statusbits == 2)
2320 return CCID_DRIVER_ERR_NO_CARD;
2322 /* For an inactive and also for an active card, issue the PowerOn
2323 command to get the ATR. */
2324 again:
2325 msg[0] = PC_to_RDR_IccPowerOn;
2326 msg[5] = 0; /* slot */
2327 msg[6] = seqno = handle->seqno++;
2328 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2329 msg[8] = 0; /* RFU */
2330 msg[9] = 0; /* RFU */
2331 set_msg_len (msg, 0);
2332 msglen = 10;
2334 rc = bulk_out (handle, msg, msglen, 0);
2335 if (rc)
2336 return rc;
2337 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2338 seqno, 5000, 0);
2339 if (rc)
2340 return rc;
2341 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2342 && ((handle->id_vendor == VENDOR_CHERRY
2343 && handle->id_product == 0x0005)
2344 || (handle->id_vendor == VENDOR_GEMPC
2345 && handle->id_product == 0x4433)
2348 tried_iso = 1;
2349 /* Try switching to ISO mode. */
2350 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2351 NULL, 0, NULL))
2352 goto again;
2354 else if (CCID_COMMAND_FAILED (msg))
2355 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2358 handle->powered_off = 0;
2360 if (atr)
2362 size_t n = msglen - 10;
2364 if (n > maxatrlen)
2365 n = maxatrlen;
2366 memcpy (atr, msg+10, n);
2367 *atrlen = n;
2370 got_param = 0;
2371 msg[0] = PC_to_RDR_GetParameters;
2372 msg[5] = 0; /* slot */
2373 msg[6] = seqno = handle->seqno++;
2374 msg[7] = 0; /* RFU */
2375 msg[8] = 0; /* RFU */
2376 msg[9] = 0; /* RFU */
2377 set_msg_len (msg, 0);
2378 msglen = 10;
2379 rc = bulk_out (handle, msg, msglen, 0);
2380 if (!rc)
2381 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2382 seqno, 2000, 0);
2383 if (rc)
2384 DEBUGOUT ("GetParameters failed\n");
2385 else if (msglen == 17 && msg[9] == 1)
2386 got_param = 1;
2388 /* Setup parameters to select T=1. */
2389 msg[0] = PC_to_RDR_SetParameters;
2390 msg[5] = 0; /* slot */
2391 msg[6] = seqno = handle->seqno++;
2392 msg[7] = 1; /* Select T=1. */
2393 msg[8] = 0; /* RFU */
2394 msg[9] = 0; /* RFU */
2396 if (!got_param)
2398 /* FIXME: Get those values from the ATR. */
2399 msg[10]= 0x01; /* Fi/Di */
2400 msg[11]= 0x10; /* LRC, direct convention. */
2401 msg[12]= 0; /* Extra guardtime. */
2402 msg[13]= 0x41; /* BWI/CWI */
2403 msg[14]= 0; /* No clock stoppping. */
2404 msg[15]= 254; /* IFSC */
2405 msg[16]= 0; /* Does not support non default NAD values. */
2407 set_msg_len (msg, 7);
2408 msglen = 10 + 7;
2410 rc = bulk_out (handle, msg, msglen, 0);
2411 if (rc)
2412 return rc;
2413 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2414 seqno, 5000, 0);
2415 if (rc)
2416 DEBUGOUT ("SetParameters failed (ignored)\n");
2418 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2419 handle->ifsc = msg[15];
2420 else
2421 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2423 handle->t1_ns = 0;
2424 handle->t1_nr = 0;
2426 /* Send an S-Block with our maximum IFSD to the CCID. */
2427 if (!handle->apdu_level && !handle->auto_ifsd)
2429 tpdu = msg+10;
2430 /* NAD: DAD=1, SAD=0 */
2431 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2432 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2433 tpdu[2] = 1;
2434 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2435 tpdulen = 4;
2436 edc = compute_edc (tpdu, tpdulen, use_crc);
2437 if (use_crc)
2438 tpdu[tpdulen++] = (edc >> 8);
2439 tpdu[tpdulen++] = edc;
2441 msg[0] = PC_to_RDR_XfrBlock;
2442 msg[5] = 0; /* slot */
2443 msg[6] = seqno = handle->seqno++;
2444 msg[7] = 0;
2445 msg[8] = 0; /* RFU */
2446 msg[9] = 0; /* RFU */
2447 set_msg_len (msg, tpdulen);
2448 msglen = 10 + tpdulen;
2450 if (debug_level > 1)
2451 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2452 ((msg[11] & 0xc0) == 0x80)? 'R' :
2453 (msg[11] & 0x80)? 'S' : 'I',
2454 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2455 : !!(msg[11] & 0x40)),
2456 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2458 rc = bulk_out (handle, msg, msglen, 0);
2459 if (rc)
2460 return rc;
2463 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2464 RDR_to_PC_DataBlock, seqno, 5000, 0);
2465 if (rc)
2466 return rc;
2468 tpdu = msg + 10;
2469 tpdulen = msglen - 10;
2471 if (tpdulen < 4)
2472 return CCID_DRIVER_ERR_ABORTED;
2474 if (debug_level > 1)
2475 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2476 ((msg[11] & 0xc0) == 0x80)? 'R' :
2477 (msg[11] & 0x80)? 'S' : 'I',
2478 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2479 : !!(msg[11] & 0x40)),
2480 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2481 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2483 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2485 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2486 return -1;
2488 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2491 return 0;
2497 static unsigned int
2498 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2500 if (use_crc)
2502 return 0x42; /* Not yet implemented. */
2504 else
2506 unsigned char crc = 0;
2508 for (; datalen; datalen--)
2509 crc ^= *data++;
2510 return crc;
2515 /* Return true if APDU is an extended length one. */
2516 static int
2517 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2519 if (apdulen < 7 || apdu[4])
2520 return 0; /* Too short or no Z byte. */
2521 return 1;
2525 /* Helper for ccid_transceive used for APDU level exchanges. */
2526 static int
2527 ccid_transceive_apdu_level (ccid_driver_t handle,
2528 const unsigned char *apdu_buf, size_t apdu_buflen,
2529 unsigned char *resp, size_t maxresplen,
2530 size_t *nresp)
2532 int rc;
2533 unsigned char send_buffer[10+261+300], recv_buffer[10+261+300];
2534 const unsigned char *apdu;
2535 size_t apdulen;
2536 unsigned char *msg;
2537 size_t msglen;
2538 unsigned char seqno;
2539 int bwi = 4;
2541 msg = send_buffer;
2543 apdu = apdu_buf;
2544 apdulen = apdu_buflen;
2545 assert (apdulen);
2547 /* The maximum length for a short APDU T=1 block is 261. For an
2548 extended APDU T=1 block the maximum length 65544; however
2549 extended APDU exchange level is not yet supported. */
2550 if (apdulen > 261)
2551 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2553 msg[0] = PC_to_RDR_XfrBlock;
2554 msg[5] = 0; /* slot */
2555 msg[6] = seqno = handle->seqno++;
2556 msg[7] = bwi; /* bBWI */
2557 msg[8] = 0; /* RFU */
2558 msg[9] = 0; /* RFU */
2559 memcpy (msg+10, apdu, apdulen);
2560 set_msg_len (msg, apdulen);
2561 msglen = 10 + apdulen;
2563 rc = bulk_out (handle, msg, msglen, 0);
2564 if (rc)
2565 return rc;
2567 msg = recv_buffer;
2568 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2569 RDR_to_PC_DataBlock, seqno, 5000, 0);
2570 if (rc)
2571 return rc;
2573 apdu = msg + 10;
2574 apdulen = msglen - 10;
2576 if (resp)
2578 if (apdulen > maxresplen)
2580 DEBUGOUT_2 ("provided buffer too short for received data "
2581 "(%u/%u)\n",
2582 (unsigned int)apdulen, (unsigned int)maxresplen);
2583 return CCID_DRIVER_ERR_INV_VALUE;
2586 memcpy (resp, apdu, apdulen);
2587 *nresp = apdulen;
2590 return 0;
2596 Protocol T=1 overview
2598 Block Structure:
2599 Prologue Field:
2600 1 byte Node Address (NAD)
2601 1 byte Protocol Control Byte (PCB)
2602 1 byte Length (LEN)
2603 Information Field:
2604 0-254 byte APDU or Control Information (INF)
2605 Epilogue Field:
2606 1 byte Error Detection Code (EDC)
2608 NAD:
2609 bit 7 unused
2610 bit 4..6 Destination Node Address (DAD)
2611 bit 3 unused
2612 bit 2..0 Source Node Address (SAD)
2614 If node adresses are not used, SAD and DAD should be set to 0 on
2615 the first block sent to the card. If they are used they should
2616 have different values (0 for one is okay); that first block sets up
2617 the addresses of the nodes.
2619 PCB:
2620 Information Block (I-Block):
2621 bit 7 0
2622 bit 6 Sequence number (yep, that is modulo 2)
2623 bit 5 Chaining flag
2624 bit 4..0 reserved
2625 Received-Ready Block (R-Block):
2626 bit 7 1
2627 bit 6 0
2628 bit 5 0
2629 bit 4 Sequence number
2630 bit 3..0 0 = no error
2631 1 = EDC or parity error
2632 2 = other error
2633 other values are reserved
2634 Supervisory Block (S-Block):
2635 bit 7 1
2636 bit 6 1
2637 bit 5 clear=request,set=response
2638 bit 4..0 0 = resyncronisation request
2639 1 = information field size request
2640 2 = abort request
2641 3 = extension of BWT request
2642 4 = VPP error
2643 other values are reserved
2648 ccid_transceive (ccid_driver_t handle,
2649 const unsigned char *apdu_buf, size_t apdu_buflen,
2650 unsigned char *resp, size_t maxresplen, size_t *nresp)
2652 int rc;
2653 /* The size of the buffer used to be 10+259. For the via_escape
2654 hack we need one extra byte, thus 11+259. */
2655 unsigned char send_buffer[11+259], recv_buffer[11+259];
2656 const unsigned char *apdu;
2657 size_t apdulen;
2658 unsigned char *msg, *tpdu, *p;
2659 size_t msglen, tpdulen, last_tpdulen, n;
2660 unsigned char seqno;
2661 unsigned int edc;
2662 int use_crc = 0;
2663 int hdrlen, pcboff;
2664 size_t dummy_nresp;
2665 int via_escape = 0;
2666 int next_chunk = 1;
2667 int sending = 1;
2668 int retries = 0;
2669 int resyncing = 0;
2670 int nad_byte;
2672 if (!nresp)
2673 nresp = &dummy_nresp;
2674 *nresp = 0;
2676 /* Smarter readers allow to send APDUs directly; divert here. */
2677 if (handle->apdu_level)
2679 /* We employ a hack for Omnikey readers which are able to send
2680 TPDUs using an escape sequence. There is no documentation
2681 but the Windows driver does it this way. Tested using a
2682 CM6121. This method works also for the Cherry XX44
2683 keyboards; however there are problems with the
2684 ccid_tranceive_secure which leads to a loss of sync on the
2685 CCID level. If Cherry wants to make their keyboard work
2686 again, they should hand over some docs. */
2687 if ((handle->id_vendor == VENDOR_OMNIKEY
2688 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
2689 && handle->apdu_level < 2
2690 && is_exlen_apdu (apdu_buf, apdu_buflen))
2691 via_escape = 1;
2692 else
2693 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2694 resp, maxresplen, nresp);
2697 /* The other readers we support require sending TPDUs. */
2699 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2700 msg = send_buffer;
2701 hdrlen = via_escape? 11 : 10;
2703 /* NAD: DAD=1, SAD=0 */
2704 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
2705 if (via_escape)
2706 nad_byte = 0;
2708 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
2709 for (;;)
2711 if (next_chunk)
2713 next_chunk = 0;
2715 apdu = apdu_buf;
2716 apdulen = apdu_buflen;
2717 assert (apdulen);
2719 /* Construct an I-Block. */
2720 tpdu = msg + hdrlen;
2721 tpdu[0] = nad_byte;
2722 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2723 if (apdulen > handle->ifsc )
2725 apdulen = handle->ifsc;
2726 apdu_buf += handle->ifsc;
2727 apdu_buflen -= handle->ifsc;
2728 tpdu[1] |= (1 << 5); /* Set more bit. */
2730 tpdu[2] = apdulen;
2731 memcpy (tpdu+3, apdu, apdulen);
2732 tpdulen = 3 + apdulen;
2733 edc = compute_edc (tpdu, tpdulen, use_crc);
2734 if (use_crc)
2735 tpdu[tpdulen++] = (edc >> 8);
2736 tpdu[tpdulen++] = edc;
2739 if (via_escape)
2741 msg[0] = PC_to_RDR_Escape;
2742 msg[5] = 0; /* slot */
2743 msg[6] = seqno = handle->seqno++;
2744 msg[7] = 0; /* RFU */
2745 msg[8] = 0; /* RFU */
2746 msg[9] = 0; /* RFU */
2747 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
2748 set_msg_len (msg, 1 + tpdulen);
2750 else
2752 msg[0] = PC_to_RDR_XfrBlock;
2753 msg[5] = 0; /* slot */
2754 msg[6] = seqno = handle->seqno++;
2755 msg[7] = 4; /* bBWI */
2756 msg[8] = 0; /* RFU */
2757 msg[9] = 0; /* RFU */
2758 set_msg_len (msg, tpdulen);
2760 msglen = hdrlen + tpdulen;
2761 if (!resyncing)
2762 last_tpdulen = tpdulen;
2763 pcboff = hdrlen+1;
2765 if (debug_level > 1)
2766 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2767 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
2768 (msg[pcboff] & 0x80)? 'S' : 'I',
2769 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
2770 : !!(msg[pcboff] & 0x40)),
2771 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
2772 " [more]":""));
2774 rc = bulk_out (handle, msg, msglen, 0);
2775 if (rc)
2776 return rc;
2778 msg = recv_buffer;
2779 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2780 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
2781 seqno, 5000, 0);
2782 if (rc)
2783 return rc;
2785 tpdu = msg + hdrlen;
2786 tpdulen = msglen - hdrlen;
2787 resyncing = 0;
2789 if (tpdulen < 4)
2791 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2792 return CCID_DRIVER_ERR_ABORTED;
2795 if (debug_level > 1)
2796 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2797 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
2798 (msg[pcboff] & 0x80)? 'S' : 'I',
2799 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
2800 : !!(msg[pcboff] & 0x40)),
2801 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
2802 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
2803 " [more]":""));
2805 if (!(tpdu[1] & 0x80))
2806 { /* This is an I-block. */
2807 retries = 0;
2808 if (sending)
2809 { /* last block sent was successful. */
2810 handle->t1_ns ^= 1;
2811 sending = 0;
2814 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2815 { /* Reponse does not match our sequence number. */
2816 msg = send_buffer;
2817 tpdu = msg + hdrlen;
2818 tpdu[0] = nad_byte;
2819 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
2820 tpdu[2] = 0;
2821 tpdulen = 3;
2822 edc = compute_edc (tpdu, tpdulen, use_crc);
2823 if (use_crc)
2824 tpdu[tpdulen++] = (edc >> 8);
2825 tpdu[tpdulen++] = edc;
2827 continue;
2830 handle->t1_nr ^= 1;
2832 p = tpdu + 3; /* Skip the prologue field. */
2833 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2834 /* fixme: verify the checksum. */
2835 if (resp)
2837 if (n > maxresplen)
2839 DEBUGOUT_2 ("provided buffer too short for received data "
2840 "(%u/%u)\n",
2841 (unsigned int)n, (unsigned int)maxresplen);
2842 return CCID_DRIVER_ERR_INV_VALUE;
2845 memcpy (resp, p, n);
2846 resp += n;
2847 *nresp += n;
2848 maxresplen -= n;
2851 if (!(tpdu[1] & 0x20))
2852 return 0; /* No chaining requested - ready. */
2854 msg = send_buffer;
2855 tpdu = msg + hdrlen;
2856 tpdu[0] = nad_byte;
2857 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
2858 tpdu[2] = 0;
2859 tpdulen = 3;
2860 edc = compute_edc (tpdu, tpdulen, use_crc);
2861 if (use_crc)
2862 tpdu[tpdulen++] = (edc >> 8);
2863 tpdu[tpdulen++] = edc;
2865 else if ((tpdu[1] & 0xc0) == 0x80)
2866 { /* This is a R-block. */
2867 if ( (tpdu[1] & 0x0f))
2869 retries++;
2870 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
2872 /* Error probably due to switching to TPDU. Send a
2873 resync request. We use the recv_buffer so that
2874 we don't corrupt the send_buffer. */
2875 msg = recv_buffer;
2876 tpdu = msg + hdrlen;
2877 tpdu[0] = nad_byte;
2878 tpdu[1] = 0xc0; /* S-block resync request. */
2879 tpdu[2] = 0;
2880 tpdulen = 3;
2881 edc = compute_edc (tpdu, tpdulen, use_crc);
2882 if (use_crc)
2883 tpdu[tpdulen++] = (edc >> 8);
2884 tpdu[tpdulen++] = edc;
2885 resyncing = 1;
2886 DEBUGOUT ("T=1: requesting resync\n");
2888 else if (retries > 3)
2890 DEBUGOUT ("T=1: 3 failed retries\n");
2891 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2893 else
2895 /* Error: repeat last block */
2896 msg = send_buffer;
2897 tpdulen = last_tpdulen;
2900 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
2901 { /* Response does not match our sequence number. */
2902 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2903 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2905 else if (sending)
2906 { /* Send next chunk. */
2907 retries = 0;
2908 msg = send_buffer;
2909 next_chunk = 1;
2910 handle->t1_ns ^= 1;
2912 else
2914 DEBUGOUT ("unexpected ACK R-block received\n");
2915 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2918 else
2919 { /* This is a S-block. */
2920 retries = 0;
2921 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
2922 (tpdu[1] & 0x20)? "response": "request",
2923 (tpdu[1] & 0x1f));
2924 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
2926 /* Information field size request. */
2927 unsigned char ifsc = tpdu[3];
2929 if (ifsc < 16 || ifsc > 254)
2930 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2932 msg = send_buffer;
2933 tpdu = msg + hdrlen;
2934 tpdu[0] = nad_byte;
2935 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
2936 tpdu[2] = 1;
2937 tpdu[3] = ifsc;
2938 tpdulen = 4;
2939 edc = compute_edc (tpdu, tpdulen, use_crc);
2940 if (use_crc)
2941 tpdu[tpdulen++] = (edc >> 8);
2942 tpdu[tpdulen++] = edc;
2943 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
2945 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
2947 /* Wait time extension request. */
2948 unsigned char bwi = tpdu[3];
2949 msg = send_buffer;
2950 tpdu = msg + hdrlen;
2951 tpdu[0] = nad_byte;
2952 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
2953 tpdu[2] = 1;
2954 tpdu[3] = bwi;
2955 tpdulen = 4;
2956 edc = compute_edc (tpdu, tpdulen, use_crc);
2957 if (use_crc)
2958 tpdu[tpdulen++] = (edc >> 8);
2959 tpdu[tpdulen++] = edc;
2960 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
2961 print_progress (handle);
2963 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
2965 DEBUGOUT ("T=1: resync ack from reader\n");
2966 /* Repeat previous block. */
2967 msg = send_buffer;
2968 tpdulen = last_tpdulen;
2970 else
2971 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2973 } /* end T=1 protocol loop. */
2975 return 0;
2979 /* Send the CCID Secure command to the reader. APDU_BUF should
2980 contain the APDU template. PIN_MODE defines how the pin gets
2981 formatted:
2983 1 := The PIN is ASCII encoded and of variable length. The
2984 length of the PIN entered will be put into Lc by the reader.
2985 The APDU should me made up of 4 bytes without Lc.
2987 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2988 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2990 When called with RESP and NRESP set to NULL, the function will
2991 merely check whether the reader supports the secure command for the
2992 given APDU and PIN_MODE. */
2994 ccid_transceive_secure (ccid_driver_t handle,
2995 const unsigned char *apdu_buf, size_t apdu_buflen,
2996 int pin_mode, int pinlen_min, int pinlen_max,
2997 int pin_padlen,
2998 unsigned char *resp, size_t maxresplen, size_t *nresp)
3000 int rc;
3001 unsigned char send_buffer[10+259], recv_buffer[10+259];
3002 unsigned char *msg, *tpdu, *p;
3003 size_t msglen, tpdulen, n;
3004 unsigned char seqno;
3005 size_t dummy_nresp;
3006 int testmode;
3007 int cherry_mode = 0;
3009 testmode = !resp && !nresp;
3011 if (!nresp)
3012 nresp = &dummy_nresp;
3013 *nresp = 0;
3015 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3017 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3018 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
3019 else
3020 return CCID_DRIVER_ERR_NO_KEYPAD;
3022 if (pin_mode != 1)
3023 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3025 if (pin_padlen != 0)
3026 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3028 if (!pinlen_min)
3029 pinlen_min = 1;
3030 if (!pinlen_max)
3031 pinlen_max = 25;
3033 /* Note that the 25 is the maximum value the SPR532 allows. */
3034 if (pinlen_min < 1 || pinlen_min > 25
3035 || pinlen_max < 1 || pinlen_max > 25
3036 || pinlen_min > pinlen_max)
3037 return CCID_DRIVER_ERR_INV_VALUE;
3039 /* We have only tested a few readers so better don't risk anything
3040 and do not allow the use with other readers. */
3041 switch (handle->id_vendor)
3043 case VENDOR_SCM: /* Tested with SPR 532. */
3044 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3045 break;
3046 case VENDOR_CHERRY:
3047 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3048 character on the keyboard channel. We use a special variant
3049 of PC_to_RDR_Secure which directs these characters to the
3050 smart card's bulk-in channel. We also need to append a zero
3051 Lc byte to the APDU. It seems that it will be replaced with
3052 the actual length instead of being appended before the APDU
3053 is send to the card. */
3054 cherry_mode = 1;
3055 break;
3056 default:
3057 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3060 if (testmode)
3061 return 0; /* Success */
3063 msg = send_buffer;
3064 if (handle->id_vendor == VENDOR_SCM)
3066 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3067 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3068 NULL, 0, NULL);
3069 if (rc)
3070 return rc;
3073 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3074 msg[5] = 0; /* slot */
3075 msg[6] = seqno = handle->seqno++;
3076 msg[7] = 0; /* bBWI */
3077 msg[8] = 0; /* RFU */
3078 msg[9] = 0; /* RFU */
3079 msg[10] = 0; /* Perform PIN verification. */
3080 msg[11] = 0; /* Timeout in seconds. */
3081 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3082 if (handle->id_vendor == VENDOR_SCM)
3084 /* For the SPR532 the next 2 bytes need to be zero. We do this
3085 for all SCM products. Kudos to Martin Paljak for this
3086 hint. */
3087 msg[13] = msg[14] = 0;
3089 else
3091 msg[13] = 0x00; /* bmPINBlockString:
3092 0 bits of pin length to insert.
3093 0 bytes of PIN block size. */
3094 msg[14] = 0x00; /* bmPINLengthFormat:
3095 Units are bytes, position is 0. */
3098 /* The following is a little endian word. */
3099 msg[15] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
3100 msg[16] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
3102 msg[17] = 0x02; /* bEntryValidationCondition:
3103 Validation key pressed */
3104 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
3105 msg[17] |= 0x01; /* Max size reached. */
3106 msg[18] = 0xff; /* bNumberMessage: Default. */
3107 msg[19] = 0x04; /* wLangId-High. */
3108 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3109 msg[21] = 0; /* bMsgIndex. */
3110 /* bTeoProlog follows: */
3111 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3112 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
3113 msg[24] = 0; /* The apdulen will be filled in by the reader. */
3114 /* APDU follows: */
3115 msg[25] = apdu_buf[0]; /* CLA */
3116 msg[26] = apdu_buf[1]; /* INS */
3117 msg[27] = apdu_buf[2]; /* P1 */
3118 msg[28] = apdu_buf[3]; /* P2 */
3119 msglen = 29;
3120 if (cherry_mode)
3121 msg[msglen++] = 0;
3122 /* An EDC is not required. */
3123 set_msg_len (msg, msglen - 10);
3125 rc = bulk_out (handle, msg, msglen, 0);
3126 if (rc)
3127 return rc;
3129 msg = recv_buffer;
3130 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3131 RDR_to_PC_DataBlock, seqno, 30000, 0);
3132 if (rc)
3133 return rc;
3135 tpdu = msg + 10;
3136 tpdulen = msglen - 10;
3138 if (handle->apdu_level)
3140 if (resp)
3142 if (tpdulen > maxresplen)
3144 DEBUGOUT_2 ("provided buffer too short for received data "
3145 "(%u/%u)\n",
3146 (unsigned int)tpdulen, (unsigned int)maxresplen);
3147 return CCID_DRIVER_ERR_INV_VALUE;
3150 memcpy (resp, tpdu, tpdulen);
3151 *nresp = tpdulen;
3153 return 0;
3156 if (tpdulen < 4)
3158 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3159 return CCID_DRIVER_ERR_ABORTED;
3161 if (debug_level > 1)
3162 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3163 ((msg[11] & 0xc0) == 0x80)? 'R' :
3164 (msg[11] & 0x80)? 'S' : 'I',
3165 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3166 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3167 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3169 if (!(tpdu[1] & 0x80))
3170 { /* This is an I-block. */
3171 /* Last block sent was successful. */
3172 handle->t1_ns ^= 1;
3174 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3175 { /* Reponse does not match our sequence number. */
3176 DEBUGOUT ("I-block with wrong seqno received\n");
3177 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3180 handle->t1_nr ^= 1;
3182 p = tpdu + 3; /* Skip the prologue field. */
3183 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3184 /* fixme: verify the checksum. */
3185 if (resp)
3187 if (n > maxresplen)
3189 DEBUGOUT_2 ("provided buffer too short for received data "
3190 "(%u/%u)\n",
3191 (unsigned int)n, (unsigned int)maxresplen);
3192 return CCID_DRIVER_ERR_INV_VALUE;
3195 memcpy (resp, p, n);
3196 resp += n;
3197 *nresp += n;
3198 maxresplen -= n;
3201 if (!(tpdu[1] & 0x20))
3202 return 0; /* No chaining requested - ready. */
3204 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3205 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3207 else if ((tpdu[1] & 0xc0) == 0x80)
3208 { /* This is a R-block. */
3209 if ( (tpdu[1] & 0x0f))
3210 { /* Error: repeat last block */
3211 DEBUGOUT ("No retries supported for Secure operation\n");
3212 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3214 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3215 { /* Reponse does not match our sequence number. */
3216 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3217 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3219 else
3220 { /* Send next chunk. */
3221 DEBUGOUT ("chaining not supported on Secure operation\n");
3222 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3225 else
3226 { /* This is a S-block. */
3227 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3228 (tpdu[1] & 0x20)? "response": "request",
3229 (tpdu[1] & 0x1f));
3230 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3233 return 0;
3239 #ifdef TEST
3242 static void
3243 print_error (int err)
3245 const char *p;
3246 char buf[50];
3248 switch (err)
3250 case 0: p = "success";
3251 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3252 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3253 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3254 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3255 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3256 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3257 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3258 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3259 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3260 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3261 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3262 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3263 default: sprintf (buf, "0x%05x", err); p = buf; break;
3265 fprintf (stderr, "operation failed: %s\n", p);
3269 static void
3270 print_data (const unsigned char *data, size_t length)
3272 if (length >= 2)
3274 fprintf (stderr, "operation status: %02X%02X\n",
3275 data[length-2], data[length-1]);
3276 length -= 2;
3278 if (length)
3280 fputs (" returned data:", stderr);
3281 for (; length; length--, data++)
3282 fprintf (stderr, " %02X", *data);
3283 putc ('\n', stderr);
3287 static void
3288 print_result (int rc, const unsigned char *data, size_t length)
3290 if (rc)
3291 print_error (rc);
3292 else if (data)
3293 print_data (data, length);
3297 main (int argc, char **argv)
3299 int rc;
3300 ccid_driver_t ccid;
3301 int slotstat;
3302 unsigned char result[512];
3303 size_t resultlen;
3304 int no_pinpad = 0;
3305 int verify_123456 = 0;
3306 int did_verify = 0;
3307 int no_poll = 0;
3309 if (argc)
3311 argc--;
3312 argv++;
3315 while (argc)
3317 if ( !strcmp (*argv, "--list"))
3319 char *p;
3320 p = ccid_get_reader_list ();
3321 if (!p)
3322 return 1;
3323 fputs (p, stderr);
3324 free (p);
3325 return 0;
3327 else if ( !strcmp (*argv, "--debug"))
3329 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3330 argc--; argv++;
3332 else if ( !strcmp (*argv, "--no-poll"))
3334 no_poll = 1;
3335 argc--; argv++;
3337 else if ( !strcmp (*argv, "--no-pinpad"))
3339 no_pinpad = 1;
3340 argc--; argv++;
3342 else if ( !strcmp (*argv, "--verify-123456"))
3344 verify_123456 = 1;
3345 argc--; argv++;
3347 else
3348 break;
3351 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3352 if (rc)
3353 return 1;
3355 if (!no_poll)
3356 ccid_poll (ccid);
3357 fputs ("getting ATR ...\n", stderr);
3358 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3359 if (rc)
3361 print_error (rc);
3362 return 1;
3365 if (!no_poll)
3366 ccid_poll (ccid);
3367 fputs ("getting slot status ...\n", stderr);
3368 rc = ccid_slot_status (ccid, &slotstat);
3369 if (rc)
3371 print_error (rc);
3372 return 1;
3375 if (!no_poll)
3376 ccid_poll (ccid);
3378 fputs ("selecting application OpenPGP ....\n", stderr);
3380 static unsigned char apdu[] = {
3381 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3382 rc = ccid_transceive (ccid,
3383 apdu, sizeof apdu,
3384 result, sizeof result, &resultlen);
3385 print_result (rc, result, resultlen);
3389 if (!no_poll)
3390 ccid_poll (ccid);
3392 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3394 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3395 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3396 result, sizeof result, &resultlen);
3397 print_result (rc, result, resultlen);
3400 if (!no_pinpad)
3404 if (!no_pinpad)
3406 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3409 if (ccid_transceive_secure (ccid,
3410 apdu, sizeof apdu,
3411 1, 0, 0, 0,
3412 NULL, 0, NULL))
3413 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3414 else
3416 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3418 rc = ccid_transceive_secure (ccid,
3419 apdu, sizeof apdu,
3420 1, 0, 0, 0,
3421 result, sizeof result, &resultlen);
3422 print_result (rc, result, resultlen);
3423 did_verify = 1;
3427 if (verify_123456 && !did_verify)
3429 fputs ("verifying that CHV1 is 123456....\n", stderr);
3431 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3432 6, '1','2','3','4','5','6'};
3433 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3434 result, sizeof result, &resultlen);
3435 print_result (rc, result, resultlen);
3439 if (!rc)
3441 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3443 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3444 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3445 result, sizeof result, &resultlen);
3446 print_result (rc, result, resultlen);
3450 ccid_close_reader (ccid);
3452 return 0;
3456 * Local Variables:
3457 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3458 * End:
3460 #endif /*TEST*/
3461 #endif /*HAVE_LIBUSB*/