Prepare for OpenPGP cards with extended length support.
[gnupg.git] / scd / ccid-driver.c
blobc159b5cd169c7f47162178c860af0153b9a265c8
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007
3 * 2008 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>
88 #include <usb.h>
90 #include "ccid-driver.h"
92 #define DRVNAME "ccid-driver: "
95 /* Depending on how this source is used we either define our error
96 output to go to stderr or to the jnlib based logging functions. We
97 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
98 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
100 #if defined(GNUPG_MAJOR_VERSION) \
101 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
103 #if defined(GNUPG_SCD_MAIN_HEADER)
104 # include GNUPG_SCD_MAIN_HEADER
105 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
106 # include "options.h"
107 # include "util.h"
108 # include "memory.h"
109 # include "cardglue.h"
110 # else /* This is the modularized GnuPG 1.9 or later. */
111 # include "scdaemon.h"
112 #endif
115 # define DEBUGOUT(t) do { if (debug_level) \
116 log_debug (DRVNAME t); } while (0)
117 # define DEBUGOUT_1(t,a) do { if (debug_level) \
118 log_debug (DRVNAME t,(a)); } while (0)
119 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
120 log_debug (DRVNAME t,(a),(b)); } while (0)
121 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
122 log_debug (DRVNAME t,(a),(b),(c));} while (0)
123 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
124 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
125 # define DEBUGOUT_CONT(t) do { if (debug_level) \
126 log_printf (t); } while (0)
127 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
128 log_printf (t,(a)); } while (0)
129 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
130 log_printf (t,(a),(b)); } while (0)
131 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
132 log_printf (t,(a),(b),(c)); } while (0)
133 # define DEBUGOUT_LF() do { if (debug_level) \
134 log_printf ("\n"); } while (0)
136 #else /* Other usage of this source - don't use gnupg specifics. */
138 # define DEBUGOUT(t) do { if (debug_level) \
139 fprintf (stderr, DRVNAME t); } while (0)
140 # define DEBUGOUT_1(t,a) do { if (debug_level) \
141 fprintf (stderr, DRVNAME t, (a)); } while (0)
142 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
143 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
144 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
145 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
146 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
147 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
148 # define DEBUGOUT_CONT(t) do { if (debug_level) \
149 fprintf (stderr, t); } while (0)
150 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
151 fprintf (stderr, t, (a)); } while (0)
152 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
153 fprintf (stderr, t, (a), (b)); } while (0)
154 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
155 fprintf (stderr, t, (a), (b), (c)); } while (0)
156 # define DEBUGOUT_LF() do { if (debug_level) \
157 putc ('\n', stderr); } while (0)
159 #endif /* This source not used by scdaemon. */
163 enum {
164 RDR_to_PC_NotifySlotChange= 0x50,
165 RDR_to_PC_HardwareError = 0x51,
167 PC_to_RDR_SetParameters = 0x61,
168 PC_to_RDR_IccPowerOn = 0x62,
169 PC_to_RDR_IccPowerOff = 0x63,
170 PC_to_RDR_GetSlotStatus = 0x65,
171 PC_to_RDR_Secure = 0x69,
172 PC_to_RDR_T0APDU = 0x6a,
173 PC_to_RDR_Escape = 0x6b,
174 PC_to_RDR_GetParameters = 0x6c,
175 PC_to_RDR_ResetParameters = 0x6d,
176 PC_to_RDR_IccClock = 0x6e,
177 PC_to_RDR_XfrBlock = 0x6f,
178 PC_to_RDR_Mechanical = 0x71,
179 PC_to_RDR_Abort = 0x72,
180 PC_to_RDR_SetDataRate = 0x73,
182 RDR_to_PC_DataBlock = 0x80,
183 RDR_to_PC_SlotStatus = 0x81,
184 RDR_to_PC_Parameters = 0x82,
185 RDR_to_PC_Escape = 0x83,
186 RDR_to_PC_DataRate = 0x84
190 /* Two macro to detect whether a CCID command has failed and to get
191 the error code. These macros assume that we can access the
192 mandatory first 10 bytes of a CCID message in BUF. */
193 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
194 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
197 /* We need to know the vendor to do some hacks. */
198 enum {
199 VENDOR_CHERRY = 0x046a,
200 VENDOR_SCM = 0x04e6,
201 VENDOR_OMNIKEY= 0x076b,
202 VENDOR_GEMPC = 0x08e6,
203 VENDOR_KAAN = 0x0d46
206 /* A list and a table with special transport descriptions. */
207 enum {
208 TRANSPORT_USB = 0, /* Standard USB transport. */
209 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
212 static struct
214 char *name; /* Device name. */
215 int type;
217 } transports[] = {
218 { "/dev/cmx0", TRANSPORT_CM4040 },
219 { "/dev/cmx1", TRANSPORT_CM4040 },
220 { NULL },
224 /* Store information on the driver's state. A pointer to such a
225 structure is used as handle for most functions. */
226 struct ccid_driver_s
228 usb_dev_handle *idev;
229 char *rid;
230 int dev_fd; /* -1 for USB transport or file descriptor of the
231 transport device. */
232 unsigned short id_vendor;
233 unsigned short id_product;
234 unsigned short bcd_device;
235 int ifc_no;
236 int ep_bulk_out;
237 int ep_bulk_in;
238 int ep_intr;
239 int seqno;
240 unsigned char t1_ns;
241 unsigned char t1_nr;
242 int nonnull_nad;
243 int auto_ifsd;
244 int max_ifsd;
245 int ifsd;
246 int ifsc;
247 int powered_off;
248 int has_pinpad;
249 int apdu_level; /* Reader supports short APDU level exchange. */
253 static int initialized_usb; /* Tracks whether USB has been initialized. */
254 static int debug_level; /* Flag to control the debug output.
255 0 = No debugging
256 1 = USB I/O info
257 2 = Level 1 + T=1 protocol tracing
258 3 = Level 2 + USB/I/O tracing of SlotStatus.
262 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
263 int use_crc);
264 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
265 int no_debug);
266 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
267 size_t *nread, int expected_type, int seqno, int timeout,
268 int no_debug);
269 static int abort_cmd (ccid_driver_t handle);
271 /* Convert a little endian stored 4 byte value into an unsigned
272 integer. */
273 static unsigned int
274 convert_le_u32 (const unsigned char *buf)
276 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
280 /* Convert a little endian stored 2 byte value into an unsigned
281 integer. */
282 static unsigned int
283 convert_le_u16 (const unsigned char *buf)
285 return buf[0] | (buf[1] << 8);
288 static void
289 set_msg_len (unsigned char *msg, unsigned int length)
291 msg[1] = length;
292 msg[2] = length >> 8;
293 msg[3] = length >> 16;
294 msg[4] = length >> 24;
298 /* Pint an error message for a failed CCID command including a textual
299 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
300 static void
301 print_command_failed (const unsigned char *msg)
303 const char *t;
304 char buffer[100];
305 int ec;
307 if (!debug_level)
308 return;
310 ec = CCID_ERROR_CODE (msg);
311 switch (ec)
313 case 0x00: t = "Command not supported"; break;
315 case 0xE0: t = "Slot busy"; break;
316 case 0xEF: t = "PIN cancelled"; break;
317 case 0xF0: t = "PIN timeout"; break;
319 case 0xF2: t = "Automatic sequence ongoing"; break;
320 case 0xF3: t = "Deactivated Protocol"; break;
321 case 0xF4: t = "Procedure byte conflict"; break;
322 case 0xF5: t = "ICC class not supported"; break;
323 case 0xF6: t = "ICC protocol not supported"; break;
324 case 0xF7: t = "Bad checksum in ATR"; break;
325 case 0xF8: t = "Bad TS in ATR"; break;
327 case 0xFB: t = "An all inclusive hardware error occurred"; break;
328 case 0xFC: t = "Overrun error while talking to the ICC"; break;
329 case 0xFD: t = "Parity error while talking to the ICC"; break;
330 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
331 case 0xFF: t = "Host aborted the current activity"; break;
333 default:
334 if (ec > 0 && ec < 128)
335 sprintf (buffer, "Parameter error at offset %d", ec);
336 else
337 sprintf (buffer, "Error code %02X", ec);
338 t = buffer;
339 break;
341 DEBUGOUT_1 ("CCID command failed: %s\n", t);
345 static void
346 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
348 int any = 0;
350 for (; off < datalen; off++)
352 if (!any || !(off % 16))
354 if (any)
355 DEBUGOUT_LF ();
356 DEBUGOUT_1 (" [%04d] ", off);
358 DEBUGOUT_CONT_1 (" %02X", data[off]);
359 any = 1;
361 if (any && (off % 16))
362 DEBUGOUT_LF ();
366 static void
367 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
369 DEBUGOUT_1 ("%s:\n", name);
370 if (msglen < 7)
371 return;
372 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
373 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
374 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
378 static void
379 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
381 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
382 if (msglen < 10)
383 return;
384 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
385 msg[7] == 0? "auto":
386 msg[7] == 1? "5.0 V":
387 msg[7] == 2? "3.0 V":
388 msg[7] == 3? "1.8 V":"");
389 print_pr_data (msg, msglen, 8);
393 static void
394 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
396 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
397 print_pr_data (msg, msglen, 7);
401 static void
402 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
404 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
405 print_pr_data (msg, msglen, 7);
409 static void
410 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
412 unsigned int val;
414 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
415 if (msglen < 10)
416 return;
417 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
418 val = convert_le_u16 (msg+8);
419 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
420 val == 1? " (continued)":
421 val == 2? " (continues+ends)":
422 val == 3? " (continues+continued)":
423 val == 16? " (DataBlock-expected)":"");
424 print_pr_data (msg, msglen, 10);
428 static void
429 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
431 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
432 print_pr_data (msg, msglen, 7);
436 static void
437 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
439 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
440 print_pr_data (msg, msglen, 7);
444 static void
445 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
447 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
448 if (msglen < 10)
449 return;
450 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
451 print_pr_data (msg, msglen, 8);
455 static void
456 print_p2r_escape (const unsigned char *msg, size_t msglen)
458 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
459 print_pr_data (msg, msglen, 7);
463 static void
464 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
466 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
467 if (msglen < 10)
468 return;
469 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
470 print_pr_data (msg, msglen, 8);
474 static void
475 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
477 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
478 if (msglen < 10)
479 return;
480 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
481 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
482 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
483 print_pr_data (msg, msglen, 10);
487 static void
488 print_p2r_secure (const unsigned char *msg, size_t msglen)
490 unsigned int val;
492 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
493 if (msglen < 10)
494 return;
495 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
496 val = convert_le_u16 (msg+8);
497 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
498 val == 1? " (continued)":
499 val == 2? " (continues+ends)":
500 val == 3? " (continues+continued)":
501 val == 16? " (DataBlock-expected)":"");
502 print_pr_data (msg, msglen, 10);
506 static void
507 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
509 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
510 if (msglen < 10)
511 return;
512 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
513 print_pr_data (msg, msglen, 8);
517 static void
518 print_p2r_abort (const unsigned char *msg, size_t msglen)
520 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
521 print_pr_data (msg, msglen, 7);
525 static void
526 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
528 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
529 if (msglen < 10)
530 return;
531 print_pr_data (msg, msglen, 7);
535 static void
536 print_p2r_unknown (const unsigned char *msg, size_t msglen)
538 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
539 if (msglen < 10)
540 return;
541 print_pr_data (msg, msglen, 0);
545 static void
546 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
548 DEBUGOUT_1 ("%s:\n", name);
549 if (msglen < 9)
550 return;
551 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
552 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
553 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
554 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
555 if (msg[8])
556 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
560 static void
561 print_r2p_datablock (const unsigned char *msg, size_t msglen)
563 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
564 if (msglen < 10)
565 return;
566 if (msg[9])
567 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
568 msg[9] == 1? " (continued)":
569 msg[9] == 2? " (continues+ends)":
570 msg[9] == 3? " (continues+continued)":
571 msg[9] == 16? " (XferBlock-expected)":"");
572 print_pr_data (msg, msglen, 10);
576 static void
577 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
579 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
580 if (msglen < 10)
581 return;
582 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
583 msg[9] == 0? " (running)":
584 msg[9] == 1? " (stopped-L)":
585 msg[9] == 2? " (stopped-H)":
586 msg[9] == 3? " (stopped)":"");
587 print_pr_data (msg, msglen, 10);
591 static void
592 print_r2p_parameters (const unsigned char *msg, size_t msglen)
594 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
595 if (msglen < 10)
596 return;
598 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
599 if (msglen == 17 && msg[9] == 1)
601 /* Protocol T=1. */
602 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
603 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
604 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
605 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
606 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
607 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
608 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
610 else
611 print_pr_data (msg, msglen, 10);
615 static void
616 print_r2p_escape (const unsigned char *msg, size_t msglen)
618 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
619 if (msglen < 10)
620 return;
621 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
622 print_pr_data (msg, msglen, 10);
626 static void
627 print_r2p_datarate (const unsigned char *msg, size_t msglen)
629 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
630 if (msglen < 10)
631 return;
632 if (msglen >= 18)
634 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
635 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
636 print_pr_data (msg, msglen, 18);
638 else
639 print_pr_data (msg, msglen, 10);
643 static void
644 print_r2p_unknown (const unsigned char *msg, size_t msglen)
646 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
647 if (msglen < 10)
648 return;
649 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
650 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
651 print_pr_data (msg, msglen, 10);
655 /* Given a handle used for special transport prepare it for use. In
656 particular setup all information in way that resembles what
657 parse_cccid_descriptor does. */
658 static void
659 prepare_special_transport (ccid_driver_t handle)
661 assert (!handle->id_vendor);
663 handle->nonnull_nad = 0;
664 handle->auto_ifsd = 0;
665 handle->max_ifsd = 32;
666 handle->ifsd = 0;
667 handle->has_pinpad = 0;
668 handle->apdu_level = 0;
669 switch (handle->id_product)
671 case TRANSPORT_CM4040:
672 DEBUGOUT ("setting up transport for CardMan 4040\n");
673 handle->apdu_level = 1;
674 break;
676 default: assert (!"transport not defined");
680 /* Parse a CCID descriptor, optionally print all available features
681 and test whether this reader is usable by this driver. Returns 0
682 if it is usable.
684 Note, that this code is based on the one in lsusb.c of the
685 usb-utils package, I wrote on 2003-09-01. -wk. */
686 static int
687 parse_ccid_descriptor (ccid_driver_t handle,
688 const unsigned char *buf, size_t buflen)
690 unsigned int i;
691 unsigned int us;
692 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
695 handle->nonnull_nad = 0;
696 handle->auto_ifsd = 0;
697 handle->max_ifsd = 32;
698 handle->ifsd = 0;
699 handle->has_pinpad = 0;
700 handle->apdu_level = 0;
701 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
702 handle->id_vendor, handle->id_product, handle->bcd_device);
703 if (buflen < 54 || buf[0] < 54)
705 DEBUGOUT ("CCID device descriptor is too short\n");
706 return -1;
709 DEBUGOUT ("ChipCard Interface Descriptor:\n");
710 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
711 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
712 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
713 if (buf[3] != 1 || buf[2] != 0)
714 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
715 DEBUGOUT_LF ();
717 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
718 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
719 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
720 : buf[5] == 3? "1.8V":"?"));
722 us = convert_le_u32 (buf+6);
723 DEBUGOUT_1 (" dwProtocols %5u ", us);
724 if ((us & 1))
725 DEBUGOUT_CONT (" T=0");
726 if ((us & 2))
728 DEBUGOUT_CONT (" T=1");
729 have_t1 = 1;
731 if ((us & ~3))
732 DEBUGOUT_CONT (" (Invalid values detected)");
733 DEBUGOUT_LF ();
735 us = convert_le_u32(buf+10);
736 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
737 us = convert_le_u32(buf+14);
738 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
739 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
740 us = convert_le_u32(buf+19);
741 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
742 us = convert_le_u32(buf+23);
743 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
744 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
746 us = convert_le_u32(buf+28);
747 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
748 handle->max_ifsd = us;
750 us = convert_le_u32(buf+32);
751 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
752 if ((us&1))
753 DEBUGOUT_CONT ( " 2-wire");
754 if ((us&2))
755 DEBUGOUT_CONT ( " 3-wire");
756 if ((us&4))
757 DEBUGOUT_CONT ( " I2C");
758 DEBUGOUT_LF ();
760 us = convert_le_u32(buf+36);
761 DEBUGOUT_1 (" dwMechanical %08X ", us);
762 if ((us & 1))
763 DEBUGOUT_CONT (" accept");
764 if ((us & 2))
765 DEBUGOUT_CONT (" eject");
766 if ((us & 4))
767 DEBUGOUT_CONT (" capture");
768 if ((us & 8))
769 DEBUGOUT_CONT (" lock");
770 DEBUGOUT_LF ();
772 us = convert_le_u32(buf+40);
773 DEBUGOUT_1 (" dwFeatures %08X\n", us);
774 if ((us & 0x0002))
776 DEBUGOUT (" Auto configuration based on ATR\n");
777 have_auto_conf = 1;
779 if ((us & 0x0004))
780 DEBUGOUT (" Auto activation on insert\n");
781 if ((us & 0x0008))
782 DEBUGOUT (" Auto voltage selection\n");
783 if ((us & 0x0010))
784 DEBUGOUT (" Auto clock change\n");
785 if ((us & 0x0020))
786 DEBUGOUT (" Auto baud rate change\n");
787 if ((us & 0x0040))
788 DEBUGOUT (" Auto parameter negotation made by CCID\n");
789 else if ((us & 0x0080))
790 DEBUGOUT (" Auto PPS made by CCID\n");
791 else if ((us & (0x0040 | 0x0080)))
792 DEBUGOUT (" WARNING: conflicting negotation features\n");
794 if ((us & 0x0100))
795 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
796 if ((us & 0x0200))
798 DEBUGOUT (" NAD value other than 0x00 accepted\n");
799 handle->nonnull_nad = 1;
801 if ((us & 0x0400))
803 DEBUGOUT (" Auto IFSD exchange\n");
804 handle->auto_ifsd = 1;
807 if ((us & 0x00010000))
809 DEBUGOUT (" TPDU level exchange\n");
810 have_tpdu = 1;
812 else if ((us & 0x00020000))
814 DEBUGOUT (" Short APDU level exchange\n");
815 handle->apdu_level = 1;
817 else if ((us & 0x00040000))
819 DEBUGOUT (" Short and extended APDU level exchange\n");
820 handle->apdu_level = 1;
822 else if ((us & 0x00070000))
823 DEBUGOUT (" WARNING: conflicting exchange levels\n");
825 us = convert_le_u32(buf+44);
826 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
828 DEBUGOUT ( " bClassGetResponse ");
829 if (buf[48] == 0xff)
830 DEBUGOUT_CONT ("echo\n");
831 else
832 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
834 DEBUGOUT ( " bClassEnvelope ");
835 if (buf[49] == 0xff)
836 DEBUGOUT_CONT ("echo\n");
837 else
838 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
840 DEBUGOUT ( " wlcdLayout ");
841 if (!buf[50] && !buf[51])
842 DEBUGOUT_CONT ("none\n");
843 else
844 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
846 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
847 if ((buf[52] & 1))
849 DEBUGOUT_CONT ( " verification");
850 handle->has_pinpad |= 1;
852 if ((buf[52] & 2))
854 DEBUGOUT_CONT ( " modification");
855 handle->has_pinpad |= 2;
857 DEBUGOUT_LF ();
859 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
861 if (buf[0] > 54) {
862 DEBUGOUT (" junk ");
863 for (i=54; i < buf[0]-54; i++)
864 DEBUGOUT_CONT_1 (" %02X", buf[i]);
865 DEBUGOUT_LF ();
868 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
870 DEBUGOUT ("this drivers requires that the reader supports T=1, "
871 "TPDU or APDU level exchange and auto configuration - "
872 "this is not available\n");
873 return -1;
877 /* SCM drivers get stuck in their internal USB stack if they try to
878 send a frame of n*wMaxPacketSize back to us. Given that
879 wMaxPacketSize is 64 for these readers we set the IFSD to a value
880 lower than that:
881 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
882 Product Ids:
883 0xe001 - SCR 331
884 0x5111 - SCR 331-DI
885 0x5115 - SCR 335
886 0xe003 - SPR 532
888 if (handle->id_vendor == VENDOR_SCM
889 && handle->max_ifsd > 48
890 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
891 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
892 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
893 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
896 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
897 handle->max_ifsd = 48;
901 return 0;
905 static char *
906 get_escaped_usb_string (usb_dev_handle *idev, int idx,
907 const char *prefix, const char *suffix)
909 int rc;
910 unsigned char buf[280];
911 unsigned char *s;
912 unsigned int langid;
913 size_t i, n, len;
914 char *result;
916 if (!idx)
917 return NULL;
919 /* Fixme: The next line is for the current Valgrid without support
920 for USB IOCTLs. */
921 memset (buf, 0, sizeof buf);
923 /* First get the list of supported languages and use the first one.
924 If we do don't find it we try to use English. Note that this is
925 all in a 2 bute Unicode encoding using little endian. */
926 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
927 (USB_DT_STRING << 8), 0,
928 (char*)buf, sizeof buf, 1000 /* ms timeout */);
929 if (rc < 4)
930 langid = 0x0409; /* English. */
931 else
932 langid = (buf[3] << 8) | buf[2];
934 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
935 (USB_DT_STRING << 8) + idx, langid,
936 (char*)buf, sizeof buf, 1000 /* ms timeout */);
937 if (rc < 2 || buf[1] != USB_DT_STRING)
938 return NULL; /* Error or not a string. */
939 len = buf[0];
940 if (len > rc)
941 return NULL; /* Larger than our buffer. */
943 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
945 if (s[1])
946 n++; /* High byte set. */
947 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
948 n += 3 ;
949 else
950 n++;
953 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
954 if (!result)
955 return NULL;
957 strcpy (result, prefix);
958 n = strlen (prefix);
959 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
961 if (s[1])
962 result[n++] = '\xff'; /* High byte set. */
963 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
965 sprintf (result+n, "%%%02X", *s);
966 n += 3;
968 else
969 result[n++] = *s;
971 strcpy (result+n, suffix);
973 return result;
976 /* This function creates an reader id to be used to find the same
977 physical reader after a reset. It returns an allocated and possibly
978 percent escaped string or NULL if not enough memory is available. */
979 static char *
980 make_reader_id (usb_dev_handle *idev,
981 unsigned int vendor, unsigned int product,
982 unsigned char serialno_index)
984 char *rid;
985 char prefix[20];
987 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
988 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
989 if (!rid)
991 rid = malloc (strlen (prefix) + 3 + 1);
992 if (!rid)
993 return NULL;
994 strcpy (rid, prefix);
995 strcat (rid, "X:0");
997 return rid;
1001 /* Helper to find the endpoint from an interface descriptor. */
1002 static int
1003 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1005 int no;
1006 int want_bulk_in = 0;
1008 if (mode == 1)
1009 want_bulk_in = 0x80;
1010 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1012 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1013 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1015 else if (mode == 2
1016 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1017 == USB_ENDPOINT_TYPE_INTERRUPT)
1018 && (ep->bEndpointAddress & 0x80))
1019 return (ep->bEndpointAddress & 0x0f);
1020 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1021 == USB_ENDPOINT_TYPE_BULK)
1022 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1023 return (ep->bEndpointAddress & 0x0f);
1025 /* Should never happen. */
1026 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1030 /* Helper for scan_or_find_devices. This function returns true if a
1031 requested device has been found or the caller should stop scanning
1032 for other reasons. */
1033 static int
1034 scan_or_find_usb_device (int scan_mode,
1035 int *readerno, int *count, char **rid_list,
1036 const char *readerid,
1037 struct usb_device *dev,
1038 char **r_rid,
1039 struct usb_device **r_dev,
1040 usb_dev_handle **r_idev,
1041 unsigned char **ifcdesc_extra,
1042 size_t *ifcdesc_extra_len,
1043 int *interface_number,
1044 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1046 int cfg_no;
1047 int ifc_no;
1048 int set_no;
1049 struct usb_config_descriptor *config;
1050 struct usb_interface *interface;
1051 struct usb_interface_descriptor *ifcdesc;
1052 char *rid;
1053 usb_dev_handle *idev;
1055 *r_idev = NULL;
1057 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1059 config = dev->config + cfg_no;
1060 if(!config)
1061 continue;
1063 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1065 interface = config->interface + ifc_no;
1066 if (!interface)
1067 continue;
1069 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1071 ifcdesc = (interface->altsetting + set_no);
1072 /* The second condition is for older SCM SPR 532 who did
1073 not know about the assigned CCID class. Instead of
1074 trying to interpret the strings we simply check the
1075 product ID. */
1076 if (ifcdesc && ifcdesc->extra
1077 && ((ifcdesc->bInterfaceClass == 11
1078 && ifcdesc->bInterfaceSubClass == 0
1079 && ifcdesc->bInterfaceProtocol == 0)
1080 || (ifcdesc->bInterfaceClass == 255
1081 && dev->descriptor.idVendor == VENDOR_SCM
1082 && dev->descriptor.idProduct == 0xe003)))
1084 idev = usb_open (dev);
1085 if (!idev)
1087 DEBUGOUT_1 ("usb_open failed: %s\n",
1088 strerror (errno));
1089 continue; /* with next setting. */
1092 rid = make_reader_id (idev,
1093 dev->descriptor.idVendor,
1094 dev->descriptor.idProduct,
1095 dev->descriptor.iSerialNumber);
1096 if (rid)
1098 if (scan_mode)
1100 char *p;
1102 /* We are collecting infos about all
1103 available CCID readers. Store them and
1104 continue. */
1105 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1106 *count, rid );
1107 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1108 + strlen (rid) + 1);
1109 if (p)
1111 *p = 0;
1112 if (*rid_list)
1114 strcat (p, *rid_list);
1115 free (*rid_list);
1117 strcat (p, rid);
1118 strcat (p, "\n");
1119 *rid_list = p;
1121 else /* Out of memory. */
1122 free (rid);
1124 rid = NULL;
1125 ++*count;
1127 else if (!*readerno
1128 || (*readerno < 0
1129 && readerid
1130 && !strcmp (readerid, rid)))
1132 /* We found the requested reader. */
1133 if (ifcdesc_extra && ifcdesc_extra_len)
1135 *ifcdesc_extra = malloc (ifcdesc
1136 ->extralen);
1137 if (!*ifcdesc_extra)
1139 usb_close (idev);
1140 free (rid);
1141 return 1; /* Out of core. */
1143 memcpy (*ifcdesc_extra, ifcdesc->extra,
1144 ifcdesc->extralen);
1145 *ifcdesc_extra_len = ifcdesc->extralen;
1148 if (interface_number)
1149 *interface_number = (ifcdesc->bInterfaceNumber);
1151 if (ep_bulk_out)
1152 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1153 if (ep_bulk_in)
1154 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1155 if (ep_intr)
1156 *ep_intr = find_endpoint (ifcdesc, 2);
1158 if (r_dev)
1159 *r_dev = dev;
1160 if (r_rid)
1162 *r_rid = rid;
1163 rid = NULL;
1165 else
1166 free (rid);
1168 *r_idev = idev;
1169 return 1; /* Found requested device. */
1171 else
1173 /* This is not yet the reader we want.
1174 fixme: We should avoid the extra usb_open
1175 in this case. */
1176 if (*readerno >= 0)
1177 --*readerno;
1179 free (rid);
1182 usb_close (idev);
1183 idev = NULL;
1184 return 0;
1190 return 0;
1193 /* Combination function to either scan all CCID devices or to find and
1194 open one specific device.
1196 The function returns 0 if a reader has been found or when a scan
1197 returned without error.
1199 With READERNO = -1 and READERID is NULL, scan mode is used and
1200 R_RID should be the address where to store the list of reader_ids
1201 we found. If on return this list is empty, no CCID device has been
1202 found; otherwise it points to an allocated linked list of reader
1203 IDs. Note that in this mode the function always returns NULL.
1205 With READERNO >= 0 or READERID is not NULL find mode is used. This
1206 uses the same algorithm as the scan mode but stops and returns at
1207 the entry number READERNO and return the handle for the the opened
1208 USB device. If R_RID is not NULL it will receive the reader ID of
1209 that device. If R_DEV is not NULL it will the device pointer of
1210 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1211 malloced copy of the interfaces "extra: data filed;
1212 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1213 no reader with number READERNO or that reader is not usable by our
1214 implementation NULL will be returned. The caller must close a
1215 returned USB device handle and free (if not passed as NULL) the
1216 returned reader ID info as well as the IFCDESC_EXTRA. On error
1217 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1218 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1219 the READERID was found.
1221 If R_FD is not -1 on return the device is not using USB for
1222 transport but the device associated with that file descriptor. In
1223 this case INTERFACE will receive the transport type and the other
1224 USB specific return values are not used; the return value is
1225 (void*)(1).
1227 Note that the first entry of the returned reader ID list in scan mode
1228 corresponds with a READERNO of 0 in find mode.
1230 static int
1231 scan_or_find_devices (int readerno, const char *readerid,
1232 char **r_rid,
1233 struct usb_device **r_dev,
1234 unsigned char **ifcdesc_extra,
1235 size_t *ifcdesc_extra_len,
1236 int *interface_number,
1237 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1238 usb_dev_handle **r_idev,
1239 int *r_fd)
1241 char *rid_list = NULL;
1242 int count = 0;
1243 struct usb_bus *busses, *bus;
1244 struct usb_device *dev = NULL;
1245 usb_dev_handle *idev = NULL;
1246 int scan_mode = (readerno == -1 && !readerid);
1247 int i;
1249 /* Set return values to a default. */
1250 if (r_rid)
1251 *r_rid = NULL;
1252 if (r_dev)
1253 *r_dev = NULL;
1254 if (ifcdesc_extra)
1255 *ifcdesc_extra = NULL;
1256 if (ifcdesc_extra_len)
1257 *ifcdesc_extra_len = 0;
1258 if (interface_number)
1259 *interface_number = 0;
1260 if (r_idev)
1261 *r_idev = NULL;
1262 if (r_fd)
1263 *r_fd = -1;
1265 /* See whether we want scan or find mode. */
1266 if (scan_mode)
1268 assert (r_rid);
1271 usb_find_busses();
1272 usb_find_devices();
1274 #ifdef HAVE_USB_GET_BUSSES
1275 busses = usb_get_busses();
1276 #else
1277 busses = usb_busses;
1278 #endif
1280 for (bus = busses; bus; bus = bus->next)
1282 for (dev = bus->devices; dev; dev = dev->next)
1284 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1285 readerid,
1286 dev,
1287 r_rid,
1288 r_dev,
1289 &idev,
1290 ifcdesc_extra,
1291 ifcdesc_extra_len,
1292 interface_number,
1293 ep_bulk_out, ep_bulk_in, ep_intr))
1295 /* Found requested device or out of core. */
1296 if (!idev)
1298 free (rid_list);
1299 return -1; /* error */
1301 *r_idev = idev;
1302 return 0;
1307 /* Now check whether there are any devices with special transport types. */
1308 for (i=0; transports[i].name; i++)
1310 int fd;
1311 char *rid, *p;
1313 fd = open (transports[i].name, O_RDWR);
1314 if (fd == -1 && scan_mode && errno == EBUSY)
1316 /* Ignore this error in scan mode because it indicates that
1317 the device exists but is already open (most likely by us)
1318 and thus in general suitable as a reader. */
1320 else if (fd == -1)
1322 DEBUGOUT_2 ("failed to open `%s': %s\n",
1323 transports[i].name, strerror (errno));
1324 continue;
1327 rid = malloc (strlen (transports[i].name) + 30 + 10);
1328 if (!rid)
1330 if (fd != -1)
1331 close (fd);
1332 free (rid_list);
1333 return -1; /* Error. */
1335 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1336 if (scan_mode)
1338 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1339 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1340 if (!p)
1342 if (fd != -1)
1343 close (fd);
1344 free (rid_list);
1345 free (rid);
1346 return -1; /* Error. */
1348 *p = 0;
1349 if (rid_list)
1351 strcat (p, rid_list);
1352 free (rid_list);
1354 strcat (p, rid);
1355 strcat (p, "\n");
1356 rid_list = p;
1357 ++count;
1359 else if (!readerno ||
1360 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1362 /* Found requested device. */
1363 if (interface_number)
1364 *interface_number = transports[i].type;
1365 if (r_rid)
1366 *r_rid = rid;
1367 else
1368 free (rid);
1369 if (r_fd)
1370 *r_fd = fd;
1371 return 0; /* Okay, found device */
1373 else /* This is not yet the reader we want. */
1375 if (readerno >= 0)
1376 --readerno;
1378 free (rid);
1379 if (fd != -1)
1380 close (fd);
1383 if (scan_mode)
1385 *r_rid = rid_list;
1386 return 0;
1388 else
1389 return -1;
1393 /* Set the level of debugging to LEVEL and return the old level. -1
1394 just returns the old level. A level of 0 disables debugging, 1
1395 enables debugging, 2 enables additional tracing of the T=1
1396 protocol, 3 additionally enables debuggng for GetSlotStatus, other
1397 values are not yet defined.
1399 Note that libusb may provide its own debugging feature which is
1400 enabled by setting the envvar USB_DEBUG. */
1402 ccid_set_debug_level (int level)
1404 int old = debug_level;
1405 if (level != -1)
1406 debug_level = level;
1407 return old;
1411 char *
1412 ccid_get_reader_list (void)
1414 char *reader_list;
1416 if (!initialized_usb)
1418 usb_init ();
1419 initialized_usb = 1;
1422 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1423 NULL, NULL, NULL, NULL, NULL))
1424 return NULL; /* Error. */
1425 return reader_list;
1429 /* Open the reader with the internal number READERNO and return a
1430 pointer to be used as handle in HANDLE. Returns 0 on success. */
1431 int
1432 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1434 int rc = 0;
1435 struct usb_device *dev = NULL;
1436 usb_dev_handle *idev = NULL;
1437 int dev_fd = -1;
1438 char *rid = NULL;
1439 unsigned char *ifcdesc_extra = NULL;
1440 size_t ifcdesc_extra_len;
1441 int readerno;
1442 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1444 *handle = NULL;
1446 if (!initialized_usb)
1448 usb_init ();
1449 initialized_usb = 1;
1452 /* See whether we want to use the reader ID string or a reader
1453 number. A readerno of -1 indicates that the reader ID string is
1454 to be used. */
1455 if (readerid && strchr (readerid, ':'))
1456 readerno = -1; /* We want to use the readerid. */
1457 else if (readerid)
1459 readerno = atoi (readerid);
1460 if (readerno < 0)
1462 DEBUGOUT ("no CCID readers found\n");
1463 rc = CCID_DRIVER_ERR_NO_READER;
1464 goto leave;
1467 else
1468 readerno = 0; /* Default. */
1470 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1471 &ifcdesc_extra, &ifcdesc_extra_len,
1472 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1473 &idev, &dev_fd) )
1475 if (readerno == -1)
1476 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1477 else
1478 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1479 rc = CCID_DRIVER_ERR_NO_READER;
1480 goto leave;
1483 /* Okay, this is a CCID reader. */
1484 *handle = calloc (1, sizeof **handle);
1485 if (!*handle)
1487 DEBUGOUT ("out of memory\n");
1488 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1489 goto leave;
1491 (*handle)->rid = rid;
1492 if (idev) /* Regular USB transport. */
1494 (*handle)->idev = idev;
1495 (*handle)->dev_fd = -1;
1496 (*handle)->id_vendor = dev->descriptor.idVendor;
1497 (*handle)->id_product = dev->descriptor.idProduct;
1498 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1499 (*handle)->ifc_no = ifc_no;
1500 (*handle)->ep_bulk_out = ep_bulk_out;
1501 (*handle)->ep_bulk_in = ep_bulk_in;
1502 (*handle)->ep_intr = ep_intr;
1504 else if (dev_fd != -1) /* Device transport. */
1506 (*handle)->idev = NULL;
1507 (*handle)->dev_fd = dev_fd;
1508 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1509 (*handle)->id_product = ifc_no; /* Transport type */
1510 prepare_special_transport (*handle);
1512 else
1514 assert (!"no transport"); /* Bug. */
1517 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1519 if (idev)
1521 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1523 DEBUGOUT ("device not supported\n");
1524 rc = CCID_DRIVER_ERR_NO_READER;
1525 goto leave;
1528 rc = usb_claim_interface (idev, ifc_no);
1529 if (rc)
1531 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1532 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1533 goto leave;
1537 leave:
1538 free (ifcdesc_extra);
1539 if (rc)
1541 free (rid);
1542 if (idev)
1543 usb_close (idev);
1544 if (dev_fd != -1)
1545 close (dev_fd);
1546 free (*handle);
1547 *handle = NULL;
1550 return rc;
1554 static void
1555 do_close_reader (ccid_driver_t handle)
1557 int rc;
1558 unsigned char msg[100];
1559 size_t msglen;
1560 unsigned char seqno;
1562 if (!handle->powered_off)
1564 msg[0] = PC_to_RDR_IccPowerOff;
1565 msg[5] = 0; /* slot */
1566 msg[6] = seqno = handle->seqno++;
1567 msg[7] = 0; /* RFU */
1568 msg[8] = 0; /* RFU */
1569 msg[9] = 0; /* RFU */
1570 set_msg_len (msg, 0);
1571 msglen = 10;
1573 rc = bulk_out (handle, msg, msglen, 0);
1574 if (!rc)
1575 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1576 seqno, 2000, 0);
1577 handle->powered_off = 1;
1579 if (handle->idev)
1581 usb_release_interface (handle->idev, handle->ifc_no);
1582 usb_close (handle->idev);
1583 handle->idev = NULL;
1585 if (handle->dev_fd != -1)
1587 close (handle->dev_fd);
1588 handle->dev_fd = -1;
1593 /* Reset a reader on HANDLE. This is useful in case a reader has been
1594 plugged of and inserted at a different port. By resetting the
1595 handle, the same reader will be get used. Note, that on error the
1596 handle won't get released.
1598 This does not return an ATR, so ccid_get_atr should be called right
1599 after this one.
1601 int
1602 ccid_shutdown_reader (ccid_driver_t handle)
1604 int rc = 0;
1605 struct usb_device *dev = NULL;
1606 usb_dev_handle *idev = NULL;
1607 unsigned char *ifcdesc_extra = NULL;
1608 size_t ifcdesc_extra_len;
1609 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1611 if (!handle || !handle->rid)
1612 return CCID_DRIVER_ERR_INV_VALUE;
1614 do_close_reader (handle);
1616 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1617 &ifcdesc_extra, &ifcdesc_extra_len,
1618 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1619 &idev, NULL) || !idev)
1621 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1622 return CCID_DRIVER_ERR_NO_READER;
1625 if (idev)
1627 handle->idev = idev;
1628 handle->ifc_no = ifc_no;
1629 handle->ep_bulk_out = ep_bulk_out;
1630 handle->ep_bulk_in = ep_bulk_in;
1631 handle->ep_intr = ep_intr;
1633 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1635 DEBUGOUT ("device not supported\n");
1636 rc = CCID_DRIVER_ERR_NO_READER;
1637 goto leave;
1640 rc = usb_claim_interface (idev, ifc_no);
1641 if (rc)
1643 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1644 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1645 goto leave;
1649 leave:
1650 free (ifcdesc_extra);
1651 if (rc)
1653 if (handle->idev)
1654 usb_close (handle->idev);
1655 handle->idev = NULL;
1656 if (handle->dev_fd != -1)
1657 close (handle->dev_fd);
1658 handle->dev_fd = -1;
1661 return rc;
1666 /* Close the reader HANDLE. */
1667 int
1668 ccid_close_reader (ccid_driver_t handle)
1670 if (!handle || (!handle->idev && handle->dev_fd == -1))
1671 return 0;
1673 do_close_reader (handle);
1674 free (handle->rid);
1675 free (handle);
1676 return 0;
1680 /* Return False if a card is present and powered. */
1682 ccid_check_card_presence (ccid_driver_t handle)
1684 (void)handle; /* Not yet implemented. */
1685 return -1;
1689 /* Write NBYTES of BUF to file descriptor FD. */
1690 static int
1691 writen (int fd, const void *buf, size_t nbytes)
1693 size_t nleft = nbytes;
1694 int nwritten;
1696 while (nleft > 0)
1698 nwritten = write (fd, buf, nleft);
1699 if (nwritten < 0)
1701 if (errno == EINTR)
1702 nwritten = 0;
1703 else
1704 return -1;
1706 nleft -= nwritten;
1707 buf = (const char*)buf + nwritten;
1710 return 0;
1714 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1715 Returns 0 on success. */
1716 static int
1717 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1718 int no_debug)
1720 int rc;
1722 if (debug_level && (!no_debug || debug_level >= 3))
1724 switch (msglen? msg[0]:0)
1726 case PC_to_RDR_IccPowerOn:
1727 print_p2r_iccpoweron (msg, msglen);
1728 break;
1729 case PC_to_RDR_IccPowerOff:
1730 print_p2r_iccpoweroff (msg, msglen);
1731 break;
1732 case PC_to_RDR_GetSlotStatus:
1733 print_p2r_getslotstatus (msg, msglen);
1734 break;
1735 case PC_to_RDR_XfrBlock:
1736 print_p2r_xfrblock (msg, msglen);
1737 break;
1738 case PC_to_RDR_GetParameters:
1739 print_p2r_getparameters (msg, msglen);
1740 break;
1741 case PC_to_RDR_ResetParameters:
1742 print_p2r_resetparameters (msg, msglen);
1743 break;
1744 case PC_to_RDR_SetParameters:
1745 print_p2r_setparameters (msg, msglen);
1746 break;
1747 case PC_to_RDR_Escape:
1748 print_p2r_escape (msg, msglen);
1749 break;
1750 case PC_to_RDR_IccClock:
1751 print_p2r_iccclock (msg, msglen);
1752 break;
1753 case PC_to_RDR_T0APDU:
1754 print_p2r_to0apdu (msg, msglen);
1755 break;
1756 case PC_to_RDR_Secure:
1757 print_p2r_secure (msg, msglen);
1758 break;
1759 case PC_to_RDR_Mechanical:
1760 print_p2r_mechanical (msg, msglen);
1761 break;
1762 case PC_to_RDR_Abort:
1763 print_p2r_abort (msg, msglen);
1764 break;
1765 case PC_to_RDR_SetDataRate:
1766 print_p2r_setdatarate (msg, msglen);
1767 break;
1768 default:
1769 print_p2r_unknown (msg, msglen);
1770 break;
1774 if (handle->idev)
1776 rc = usb_bulk_write (handle->idev,
1777 handle->ep_bulk_out,
1778 (char*)msg, msglen,
1779 5000 /* ms timeout */);
1780 if (rc == msglen)
1781 return 0;
1782 if (rc == -1)
1783 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1784 else
1785 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1787 else
1789 rc = writen (handle->dev_fd, msg, msglen);
1790 if (!rc)
1791 return 0;
1792 DEBUGOUT_2 ("writen to %d failed: %s\n",
1793 handle->dev_fd, strerror (errno));
1796 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1800 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1801 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1802 is the sequence number used to send the request and EXPECTED_TYPE
1803 the type of message we expect. Does checks on the ccid
1804 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1805 avoid debug messages in case of no error; this can be overriden
1806 with a glibal debug level of at least 3. Returns 0 on success. */
1807 static int
1808 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1809 size_t *nread, int expected_type, int seqno, int timeout,
1810 int no_debug)
1812 int rc;
1813 size_t msglen;
1815 /* Fixme: The next line for the current Valgrind without support
1816 for USB IOCTLs. */
1817 memset (buffer, 0, length);
1818 retry:
1819 if (handle->idev)
1821 rc = usb_bulk_read (handle->idev,
1822 handle->ep_bulk_in,
1823 (char*)buffer, length,
1824 timeout);
1825 if (rc < 0)
1827 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (errno));
1828 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1830 *nread = msglen = rc;
1832 else
1834 rc = read (handle->dev_fd, buffer, length);
1835 if (rc < 0)
1837 DEBUGOUT_2 ("read from %d failed: %s\n",
1838 handle->dev_fd, strerror (errno));
1839 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1841 *nread = msglen = rc;
1844 if (msglen < 10)
1846 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1847 abort_cmd (handle);
1848 return CCID_DRIVER_ERR_INV_VALUE;
1850 if (buffer[5] != 0)
1852 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1853 abort_cmd (handle);
1854 return CCID_DRIVER_ERR_INV_VALUE;
1856 if (buffer[6] != seqno)
1858 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1859 seqno, buffer[6]);
1860 abort_cmd (handle);
1861 return CCID_DRIVER_ERR_INV_VALUE;
1864 /* We need to handle the time extension request before we check that
1865 we got the expected message type. This is in particular required
1866 for the Cherry keyboard which sends a time extension request for
1867 each key hit. */
1868 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1870 /* Card present and active, time extension requested. */
1871 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1872 buffer[7], buffer[8]);
1873 goto retry;
1876 if (buffer[0] != expected_type)
1878 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1879 abort_cmd (handle);
1880 return CCID_DRIVER_ERR_INV_VALUE;
1883 if (debug_level && (!no_debug || debug_level >= 3))
1885 switch (buffer[0])
1887 case RDR_to_PC_DataBlock:
1888 print_r2p_datablock (buffer, msglen);
1889 break;
1890 case RDR_to_PC_SlotStatus:
1891 print_r2p_slotstatus (buffer, msglen);
1892 break;
1893 case RDR_to_PC_Parameters:
1894 print_r2p_parameters (buffer, msglen);
1895 break;
1896 case RDR_to_PC_Escape:
1897 print_r2p_escape (buffer, msglen);
1898 break;
1899 case RDR_to_PC_DataRate:
1900 print_r2p_datarate (buffer, msglen);
1901 break;
1902 default:
1903 print_r2p_unknown (buffer, msglen);
1904 break;
1907 if (CCID_COMMAND_FAILED (buffer))
1908 print_command_failed (buffer);
1910 /* Check whether a card is at all available. Note: If you add new
1911 error codes here, check whether they need to be ignored in
1912 send_escape_cmd. */
1913 switch ((buffer[7] & 0x03))
1915 case 0: /* no error */ break;
1916 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1917 case 2: return CCID_DRIVER_ERR_NO_CARD;
1918 case 3: /* RFU */ break;
1920 return 0;
1925 /* Send an abort sequence and wait until everything settled. */
1926 static int
1927 abort_cmd (ccid_driver_t handle)
1929 int rc;
1930 char dummybuf[8];
1931 unsigned char seqno;
1932 unsigned char msg[100];
1933 size_t msglen;
1935 if (!handle->idev)
1937 /* I don't know how to send an abort to non-USB devices. */
1938 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
1941 DEBUGOUT ("sending abort sequence\n");
1942 /* Send the abort command to the control pipe. Note that we don't
1943 need to keep track of sent abort commands because there should
1944 never be another thread using the same slot concurrently. */
1945 seqno = (handle->seqno & 0xff);
1946 rc = usb_control_msg (handle->idev,
1947 0x21,/* bmRequestType: host-to-device,
1948 class specific, to interface. */
1949 1, /* ABORT */
1950 (seqno << 8 | 0 /* slot */),
1951 handle->ifc_no,
1952 dummybuf, 0,
1953 1000 /* ms timeout */);
1954 if (rc < 0)
1956 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
1957 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1960 /* Now send the abort command to the bulk out pipe using the same
1961 SEQNO and SLOT. */
1962 msg[0] = PC_to_RDR_Abort;
1963 msg[5] = 0; /* slot */
1964 msg[6] = seqno;
1965 msg[7] = 0; /* RFU */
1966 msg[8] = 0; /* RFU */
1967 msg[9] = 0; /* RFU */
1968 msglen = 10;
1969 set_msg_len (msg, 0);
1970 handle->seqno++; /* Bumb up for the next use. */
1972 rc = usb_bulk_write (handle->idev,
1973 handle->ep_bulk_out,
1974 (char*)msg, msglen,
1975 5000 /* ms timeout */);
1976 if (rc == msglen)
1977 rc = 0;
1978 else if (rc == -1)
1979 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n", strerror (errno));
1980 else
1981 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
1983 if (rc)
1984 return rc;
1986 /* Wait for the expected response. */
1989 rc = usb_bulk_read (handle->idev,
1990 handle->ep_bulk_in,
1991 (char*)msg, sizeof msg,
1992 5000 /*ms timeout*/);
1993 if (rc < 0)
1995 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
1996 strerror (errno));
1997 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1999 msglen = rc;
2001 if (msglen < 10)
2003 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2004 (unsigned int)msglen);
2005 return CCID_DRIVER_ERR_INV_VALUE;
2007 if (msg[5] != 0)
2009 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2010 return CCID_DRIVER_ERR_INV_VALUE;
2013 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2014 msg[7], msg[8], msg[9]);
2015 if (CCID_COMMAND_FAILED (msg))
2016 print_command_failed (msg);
2018 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2020 DEBUGOUT ("sending abort sequence succeeded\n");
2022 return 0;
2026 /* Note that this function won't return the error codes NO_CARD or
2027 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2028 operation will get returned in RESULT and its length in RESULTLEN.
2029 If the response is larger than RESULTMAX, an error is returned and
2030 the required buffer length returned in RESULTLEN. */
2031 static int
2032 send_escape_cmd (ccid_driver_t handle,
2033 const unsigned char *data, size_t datalen,
2034 unsigned char *result, size_t resultmax, size_t *resultlen)
2036 int rc;
2037 unsigned char msg[100];
2038 size_t msglen;
2039 unsigned char seqno;
2041 if (resultlen)
2042 *resultlen = 0;
2044 if (datalen > sizeof msg - 10)
2045 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2047 msg[0] = PC_to_RDR_Escape;
2048 msg[5] = 0; /* slot */
2049 msg[6] = seqno = handle->seqno++;
2050 msg[7] = 0; /* RFU */
2051 msg[8] = 0; /* RFU */
2052 msg[9] = 0; /* RFU */
2053 memcpy (msg+10, data, datalen);
2054 msglen = 10 + datalen;
2055 set_msg_len (msg, datalen);
2057 rc = bulk_out (handle, msg, msglen, 0);
2058 if (rc)
2059 return rc;
2060 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2061 seqno, 5000, 0);
2062 if (result)
2063 switch (rc)
2065 /* We need to ignore certain errorcode here. */
2066 case 0:
2067 case CCID_DRIVER_ERR_CARD_INACTIVE:
2068 case CCID_DRIVER_ERR_NO_CARD:
2070 if (msglen > resultmax)
2071 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2072 else
2074 memcpy (result, msg, msglen);
2075 *resultlen = msglen;
2077 rc = 0;
2079 break;
2080 default:
2081 break;
2084 return rc;
2089 ccid_transceive_escape (ccid_driver_t handle,
2090 const unsigned char *data, size_t datalen,
2091 unsigned char *resp, size_t maxresplen, size_t *nresp)
2093 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2098 /* experimental */
2100 ccid_poll (ccid_driver_t handle)
2102 int rc;
2103 unsigned char msg[10];
2104 size_t msglen;
2105 int i, j;
2107 if (handle->idev)
2109 rc = usb_bulk_read (handle->idev,
2110 handle->ep_intr,
2111 (char*)msg, sizeof msg,
2112 0 /* ms timeout */ );
2113 if (rc < 0 && errno == ETIMEDOUT)
2114 return 0;
2116 else
2117 return 0;
2119 if (rc < 0)
2121 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2122 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2125 msglen = rc;
2126 rc = 0;
2128 if (msglen < 1)
2130 DEBUGOUT ("intr-in msg too short\n");
2131 return CCID_DRIVER_ERR_INV_VALUE;
2134 if (msg[0] == RDR_to_PC_NotifySlotChange)
2136 DEBUGOUT ("notify slot change:");
2137 for (i=1; i < msglen; i++)
2138 for (j=0; j < 4; j++)
2139 DEBUGOUT_CONT_3 (" %d:%c%c",
2140 (i-1)*4+j,
2141 (msg[i] & (1<<(j*2)))? 'p':'-',
2142 (msg[i] & (2<<(j*2)))? '*':' ');
2143 DEBUGOUT_LF ();
2145 else if (msg[0] == RDR_to_PC_HardwareError)
2147 DEBUGOUT ("hardware error occured\n");
2149 else
2151 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2154 return 0;
2158 /* Note that this fucntion won't return the error codes NO_CARD or
2159 CARD_INACTIVE */
2160 int
2161 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2163 int rc;
2164 unsigned char msg[100];
2165 size_t msglen;
2166 unsigned char seqno;
2167 int retries = 0;
2169 retry:
2170 msg[0] = PC_to_RDR_GetSlotStatus;
2171 msg[5] = 0; /* slot */
2172 msg[6] = seqno = handle->seqno++;
2173 msg[7] = 0; /* RFU */
2174 msg[8] = 0; /* RFU */
2175 msg[9] = 0; /* RFU */
2176 set_msg_len (msg, 0);
2178 rc = bulk_out (handle, msg, 10, 1);
2179 if (rc)
2180 return rc;
2181 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2182 get cluttered up by a ticker function checking for the slot
2183 status and debugging enabled. */
2184 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2185 seqno, retries? 1000 : 200, 1);
2186 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2188 if (!retries)
2190 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2191 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2192 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2194 else
2195 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2196 retries++;
2197 goto retry;
2199 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2200 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2201 return rc;
2202 *statusbits = (msg[7] & 3);
2204 return 0;
2208 /* Return the ATR of the card. This is not a cached value and thus an
2209 actual reset is done. */
2210 int
2211 ccid_get_atr (ccid_driver_t handle,
2212 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2214 int rc;
2215 int statusbits;
2216 unsigned char msg[100];
2217 unsigned char *tpdu;
2218 size_t msglen, tpdulen;
2219 unsigned char seqno;
2220 int use_crc = 0;
2221 unsigned int edc;
2222 int tried_iso = 0;
2223 int got_param;
2225 /* First check whether a card is available. */
2226 rc = ccid_slot_status (handle, &statusbits);
2227 if (rc)
2228 return rc;
2229 if (statusbits == 2)
2230 return CCID_DRIVER_ERR_NO_CARD;
2232 /* For an inactive and also for an active card, issue the PowerOn
2233 command to get the ATR. */
2234 again:
2235 msg[0] = PC_to_RDR_IccPowerOn;
2236 msg[5] = 0; /* slot */
2237 msg[6] = seqno = handle->seqno++;
2238 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2239 msg[8] = 0; /* RFU */
2240 msg[9] = 0; /* RFU */
2241 set_msg_len (msg, 0);
2242 msglen = 10;
2244 rc = bulk_out (handle, msg, msglen, 0);
2245 if (rc)
2246 return rc;
2247 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2248 seqno, 5000, 0);
2249 if (rc)
2250 return rc;
2251 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2252 && ((handle->id_vendor == VENDOR_CHERRY
2253 && handle->id_product == 0x0005)
2254 || (handle->id_vendor == VENDOR_GEMPC
2255 && handle->id_product == 0x4433)
2258 tried_iso = 1;
2259 /* Try switching to ISO mode. */
2260 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2261 NULL, 0, NULL))
2262 goto again;
2264 else if (CCID_COMMAND_FAILED (msg))
2265 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2268 handle->powered_off = 0;
2270 if (atr)
2272 size_t n = msglen - 10;
2274 if (n > maxatrlen)
2275 n = maxatrlen;
2276 memcpy (atr, msg+10, n);
2277 *atrlen = n;
2280 got_param = 0;
2281 msg[0] = PC_to_RDR_GetParameters;
2282 msg[5] = 0; /* slot */
2283 msg[6] = seqno = handle->seqno++;
2284 msg[7] = 0; /* RFU */
2285 msg[8] = 0; /* RFU */
2286 msg[9] = 0; /* RFU */
2287 set_msg_len (msg, 0);
2288 msglen = 10;
2289 rc = bulk_out (handle, msg, msglen, 0);
2290 if (!rc)
2291 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2292 seqno, 2000, 0);
2293 if (rc)
2294 DEBUGOUT ("GetParameters failed\n");
2295 else if (msglen == 17 && msg[9] == 1)
2296 got_param = 1;
2298 /* Setup parameters to select T=1. */
2299 msg[0] = PC_to_RDR_SetParameters;
2300 msg[5] = 0; /* slot */
2301 msg[6] = seqno = handle->seqno++;
2302 msg[7] = 1; /* Select T=1. */
2303 msg[8] = 0; /* RFU */
2304 msg[9] = 0; /* RFU */
2306 if (!got_param)
2308 /* FIXME: Get those values from the ATR. */
2309 msg[10]= 0x01; /* Fi/Di */
2310 msg[11]= 0x10; /* LRC, direct convention. */
2311 msg[12]= 0; /* Extra guardtime. */
2312 msg[13]= 0x41; /* BWI/CWI */
2313 msg[14]= 0; /* No clock stoppping. */
2314 msg[15]= 254; /* IFSC */
2315 msg[16]= 0; /* Does not support non default NAD values. */
2317 set_msg_len (msg, 7);
2318 msglen = 10 + 7;
2320 rc = bulk_out (handle, msg, msglen, 0);
2321 if (rc)
2322 return rc;
2323 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2324 seqno, 5000, 0);
2325 if (rc)
2326 DEBUGOUT ("SetParameters failed (ignored)\n");
2328 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2329 handle->ifsc = msg[15];
2330 else
2331 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2333 handle->t1_ns = 0;
2334 handle->t1_nr = 0;
2336 /* Send an S-Block with our maximum IFSD to the CCID. */
2337 if (!handle->apdu_level && !handle->auto_ifsd)
2339 tpdu = msg+10;
2340 /* NAD: DAD=1, SAD=0 */
2341 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2342 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2343 tpdu[2] = 1;
2344 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2345 tpdulen = 4;
2346 edc = compute_edc (tpdu, tpdulen, use_crc);
2347 if (use_crc)
2348 tpdu[tpdulen++] = (edc >> 8);
2349 tpdu[tpdulen++] = edc;
2351 msg[0] = PC_to_RDR_XfrBlock;
2352 msg[5] = 0; /* slot */
2353 msg[6] = seqno = handle->seqno++;
2354 msg[7] = 0;
2355 msg[8] = 0; /* RFU */
2356 msg[9] = 0; /* RFU */
2357 set_msg_len (msg, tpdulen);
2358 msglen = 10 + tpdulen;
2360 if (debug_level > 1)
2361 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2362 ((msg[11] & 0xc0) == 0x80)? 'R' :
2363 (msg[11] & 0x80)? 'S' : 'I',
2364 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2365 : !!(msg[11] & 0x40)),
2366 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2368 rc = bulk_out (handle, msg, msglen, 0);
2369 if (rc)
2370 return rc;
2373 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2374 RDR_to_PC_DataBlock, seqno, 5000, 0);
2375 if (rc)
2376 return rc;
2378 tpdu = msg + 10;
2379 tpdulen = msglen - 10;
2381 if (tpdulen < 4)
2382 return CCID_DRIVER_ERR_ABORTED;
2384 if (debug_level > 1)
2385 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2386 ((msg[11] & 0xc0) == 0x80)? 'R' :
2387 (msg[11] & 0x80)? 'S' : 'I',
2388 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2389 : !!(msg[11] & 0x40)),
2390 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2391 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2393 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2395 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2396 return -1;
2398 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2401 return 0;
2407 static unsigned int
2408 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2410 if (use_crc)
2412 return 0x42; /* Not yet implemented. */
2414 else
2416 unsigned char crc = 0;
2418 for (; datalen; datalen--)
2419 crc ^= *data++;
2420 return crc;
2425 /* Helper for ccid_transceive used for APDU level exchanges. */
2426 static int
2427 ccid_transceive_apdu_level (ccid_driver_t handle,
2428 const unsigned char *apdu_buf, size_t apdu_buflen,
2429 unsigned char *resp, size_t maxresplen,
2430 size_t *nresp)
2432 int rc;
2433 unsigned char send_buffer[10+261], recv_buffer[10+261];
2434 const unsigned char *apdu;
2435 size_t apdulen;
2436 unsigned char *msg;
2437 size_t msglen;
2438 unsigned char seqno;
2440 msg = send_buffer;
2442 apdu = apdu_buf;
2443 apdulen = apdu_buflen;
2444 assert (apdulen);
2446 /* The maximum length for a short APDU T=1 block is 261. For an
2447 extended APDU T=1 block the maximum length 65544; however
2448 extended APDU exchange level is not yet supported. */
2449 if (apdulen > 261)
2450 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2452 msg[0] = PC_to_RDR_XfrBlock;
2453 msg[5] = 0; /* slot */
2454 msg[6] = seqno = handle->seqno++;
2455 msg[7] = 4; /* bBWI */
2456 msg[8] = 0; /* RFU */
2457 msg[9] = 0; /* RFU */
2458 memcpy (msg+10, apdu, apdulen);
2459 set_msg_len (msg, apdulen);
2460 msglen = 10 + apdulen;
2462 rc = bulk_out (handle, msg, msglen, 0);
2463 if (rc)
2464 return rc;
2466 msg = recv_buffer;
2467 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2468 RDR_to_PC_DataBlock, seqno, 5000, 0);
2469 if (rc)
2470 return rc;
2472 apdu = msg + 10;
2473 apdulen = msglen - 10;
2475 if (resp)
2477 if (apdulen > maxresplen)
2479 DEBUGOUT_2 ("provided buffer too short for received data "
2480 "(%u/%u)\n",
2481 (unsigned int)apdulen, (unsigned int)maxresplen);
2482 return CCID_DRIVER_ERR_INV_VALUE;
2485 memcpy (resp, apdu, apdulen);
2486 *nresp = apdulen;
2489 return 0;
2495 Protocol T=1 overview
2497 Block Structure:
2498 Prologue Field:
2499 1 byte Node Address (NAD)
2500 1 byte Protocol Control Byte (PCB)
2501 1 byte Length (LEN)
2502 Information Field:
2503 0-254 byte APDU or Control Information (INF)
2504 Epilogue Field:
2505 1 byte Error Detection Code (EDC)
2507 NAD:
2508 bit 7 unused
2509 bit 4..6 Destination Node Address (DAD)
2510 bit 3 unused
2511 bit 2..0 Source Node Address (SAD)
2513 If node adresses are not used, SAD and DAD should be set to 0 on
2514 the first block sent to the card. If they are used they should
2515 have different values (0 for one is okay); that first block sets up
2516 the addresses of the nodes.
2518 PCB:
2519 Information Block (I-Block):
2520 bit 7 0
2521 bit 6 Sequence number (yep, that is modulo 2)
2522 bit 5 Chaining flag
2523 bit 4..0 reserved
2524 Received-Ready Block (R-Block):
2525 bit 7 1
2526 bit 6 0
2527 bit 5 0
2528 bit 4 Sequence number
2529 bit 3..0 0 = no error
2530 1 = EDC or parity error
2531 2 = other error
2532 other values are reserved
2533 Supervisory Block (S-Block):
2534 bit 7 1
2535 bit 6 1
2536 bit 5 clear=request,set=response
2537 bit 4..0 0 = resyncronisation request
2538 1 = information field size request
2539 2 = abort request
2540 3 = extension of BWT request
2541 4 = VPP error
2542 other values are reserved
2547 ccid_transceive (ccid_driver_t handle,
2548 const unsigned char *apdu_buf, size_t apdu_buflen,
2549 unsigned char *resp, size_t maxresplen, size_t *nresp)
2551 int rc;
2552 unsigned char send_buffer[10+259], recv_buffer[10+259];
2553 const unsigned char *apdu;
2554 size_t apdulen;
2555 unsigned char *msg, *tpdu, *p;
2556 size_t msglen, tpdulen, last_tpdulen, n;
2557 unsigned char seqno;
2558 unsigned int edc;
2559 int use_crc = 0;
2560 size_t dummy_nresp;
2561 int next_chunk = 1;
2562 int sending = 1;
2563 int retries = 0;
2565 if (!nresp)
2566 nresp = &dummy_nresp;
2567 *nresp = 0;
2569 /* Smarter readers allow to send APDUs directly; divert here. */
2570 if (handle->apdu_level)
2571 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2572 resp, maxresplen, nresp);
2574 /* The other readers we support require sending TPDUs. */
2576 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2577 msg = send_buffer;
2578 for (;;)
2580 if (next_chunk)
2582 next_chunk = 0;
2584 apdu = apdu_buf;
2585 apdulen = apdu_buflen;
2586 assert (apdulen);
2588 /* Construct an I-Block. */
2589 tpdu = msg+10;
2590 /* NAD: DAD=1, SAD=0 */
2591 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2592 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2593 if (apdulen > handle->ifsc )
2595 apdulen = handle->ifsc;
2596 apdu_buf += handle->ifsc;
2597 apdu_buflen -= handle->ifsc;
2598 tpdu[1] |= (1 << 5); /* Set more bit. */
2600 tpdu[2] = apdulen;
2601 memcpy (tpdu+3, apdu, apdulen);
2602 tpdulen = 3 + apdulen;
2603 edc = compute_edc (tpdu, tpdulen, use_crc);
2604 if (use_crc)
2605 tpdu[tpdulen++] = (edc >> 8);
2606 tpdu[tpdulen++] = edc;
2609 msg[0] = PC_to_RDR_XfrBlock;
2610 msg[5] = 0; /* slot */
2611 msg[6] = seqno = handle->seqno++;
2612 msg[7] = 4; /* bBWI */
2613 msg[8] = 0; /* RFU */
2614 msg[9] = 0; /* RFU */
2615 set_msg_len (msg, tpdulen);
2616 msglen = 10 + tpdulen;
2617 last_tpdulen = tpdulen;
2619 if (debug_level > 1)
2620 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2621 ((msg[11] & 0xc0) == 0x80)? 'R' :
2622 (msg[11] & 0x80)? 'S' : 'I',
2623 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2624 : !!(msg[11] & 0x40)),
2625 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2627 rc = bulk_out (handle, msg, msglen, 0);
2628 if (rc)
2629 return rc;
2631 msg = recv_buffer;
2632 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2633 RDR_to_PC_DataBlock, seqno, 5000, 0);
2634 if (rc)
2635 return rc;
2637 tpdu = msg + 10;
2638 tpdulen = msglen - 10;
2640 if (tpdulen < 4)
2642 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2643 return CCID_DRIVER_ERR_ABORTED;
2646 if (debug_level > 1)
2647 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2648 ((msg[11] & 0xc0) == 0x80)? 'R' :
2649 (msg[11] & 0x80)? 'S' : 'I',
2650 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2651 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2652 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2654 if (!(tpdu[1] & 0x80))
2655 { /* This is an I-block. */
2656 retries = 0;
2657 if (sending)
2658 { /* last block sent was successful. */
2659 handle->t1_ns ^= 1;
2660 sending = 0;
2663 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2664 { /* Reponse does not match our sequence number. */
2665 msg = send_buffer;
2666 tpdu = msg+10;
2667 /* NAD: DAD=1, SAD=0 */
2668 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2669 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
2670 tpdu[2] = 0;
2671 tpdulen = 3;
2672 edc = compute_edc (tpdu, tpdulen, use_crc);
2673 if (use_crc)
2674 tpdu[tpdulen++] = (edc >> 8);
2675 tpdu[tpdulen++] = edc;
2677 continue;
2680 handle->t1_nr ^= 1;
2682 p = tpdu + 3; /* Skip the prologue field. */
2683 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2684 /* fixme: verify the checksum. */
2685 if (resp)
2687 if (n > maxresplen)
2689 DEBUGOUT_2 ("provided buffer too short for received data "
2690 "(%u/%u)\n",
2691 (unsigned int)n, (unsigned int)maxresplen);
2692 return CCID_DRIVER_ERR_INV_VALUE;
2695 memcpy (resp, p, n);
2696 resp += n;
2697 *nresp += n;
2698 maxresplen -= n;
2701 if (!(tpdu[1] & 0x20))
2702 return 0; /* No chaining requested - ready. */
2704 msg = send_buffer;
2705 tpdu = msg+10;
2706 /* NAD: DAD=1, SAD=0 */
2707 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2708 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
2709 tpdu[2] = 0;
2710 tpdulen = 3;
2711 edc = compute_edc (tpdu, tpdulen, use_crc);
2712 if (use_crc)
2713 tpdu[tpdulen++] = (edc >> 8);
2714 tpdu[tpdulen++] = edc;
2716 else if ((tpdu[1] & 0xc0) == 0x80)
2717 { /* This is a R-block. */
2718 if ( (tpdu[1] & 0x0f))
2719 { /* Error: repeat last block */
2720 if (++retries > 3)
2722 DEBUGOUT ("3 failed retries\n");
2723 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2725 msg = send_buffer;
2726 tpdulen = last_tpdulen;
2728 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
2729 { /* Response does not match our sequence number. */
2730 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2731 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2733 else if (sending)
2734 { /* Send next chunk. */
2735 retries = 0;
2736 msg = send_buffer;
2737 next_chunk = 1;
2738 handle->t1_ns ^= 1;
2740 else
2742 DEBUGOUT ("unexpected ACK R-block received\n");
2743 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2746 else
2747 { /* This is a S-block. */
2748 retries = 0;
2749 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d\n",
2750 (tpdu[1] & 0x20)? "response": "request",
2751 (tpdu[1] & 0x1f));
2752 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
2754 /* Information field size request. */
2755 unsigned char ifsc = tpdu[3];
2757 if (ifsc < 16 || ifsc > 254)
2758 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2760 msg = send_buffer;
2761 tpdu = msg+10;
2762 /* NAD: DAD=1, SAD=0 */
2763 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2764 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
2765 tpdu[2] = 1;
2766 tpdu[3] = ifsc;
2767 tpdulen = 4;
2768 edc = compute_edc (tpdu, tpdulen, use_crc);
2769 if (use_crc)
2770 tpdu[tpdulen++] = (edc >> 8);
2771 tpdu[tpdulen++] = edc;
2772 DEBUGOUT_1 ("T=1 requesting an ifsc=%d\n", ifsc);
2774 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
2776 /* Wait time extension request. */
2777 unsigned char bwi = tpdu[3];
2778 msg = send_buffer;
2779 tpdu = msg+10;
2780 /* NAD: DAD=1, SAD=0 */
2781 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2782 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
2783 tpdu[2] = 1;
2784 tpdu[3] = bwi;
2785 tpdulen = 4;
2786 edc = compute_edc (tpdu, tpdulen, use_crc);
2787 if (use_crc)
2788 tpdu[tpdulen++] = (edc >> 8);
2789 tpdu[tpdulen++] = edc;
2790 DEBUGOUT_1 ("T=1 waittime extension of bwi=%d\n", bwi);
2792 else
2793 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2795 } /* end T=1 protocol loop. */
2797 return 0;
2801 /* Send the CCID Secure command to the reader. APDU_BUF should
2802 contain the APDU template. PIN_MODE defines how the pin gets
2803 formatted:
2805 1 := The PIN is ASCII encoded and of variable length. The
2806 length of the PIN entered will be put into Lc by the reader.
2807 The APDU should me made up of 4 bytes without Lc.
2809 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2810 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2812 When called with RESP and NRESP set to NULL, the function will
2813 merely check whether the reader supports the secure command for the
2814 given APDU and PIN_MODE. */
2816 ccid_transceive_secure (ccid_driver_t handle,
2817 const unsigned char *apdu_buf, size_t apdu_buflen,
2818 int pin_mode, int pinlen_min, int pinlen_max,
2819 int pin_padlen,
2820 unsigned char *resp, size_t maxresplen, size_t *nresp)
2822 int rc;
2823 unsigned char send_buffer[10+259], recv_buffer[10+259];
2824 unsigned char *msg, *tpdu, *p;
2825 size_t msglen, tpdulen, n;
2826 unsigned char seqno;
2827 size_t dummy_nresp;
2828 int testmode;
2829 int cherry_mode = 0;
2831 testmode = !resp && !nresp;
2833 if (!nresp)
2834 nresp = &dummy_nresp;
2835 *nresp = 0;
2837 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2839 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2840 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2841 else
2842 return CCID_DRIVER_ERR_NO_KEYPAD;
2844 if (pin_mode != 1)
2845 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2847 if (pin_padlen != 0)
2848 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2850 if (!pinlen_min)
2851 pinlen_min = 1;
2852 if (!pinlen_max)
2853 pinlen_max = 25;
2855 /* Note that the 25 is the maximum value the SPR532 allows. */
2856 if (pinlen_min < 1 || pinlen_min > 25
2857 || pinlen_max < 1 || pinlen_max > 25
2858 || pinlen_min > pinlen_max)
2859 return CCID_DRIVER_ERR_INV_VALUE;
2861 /* We have only tested a few readers so better don't risk anything
2862 and do not allow the use with other readers. */
2863 switch (handle->id_vendor)
2865 case VENDOR_SCM: /* Tested with SPR 532. */
2866 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
2867 break;
2868 case VENDOR_CHERRY:
2869 /* The CHERRY XX44 keyboard echos an asterisk for each entered
2870 character on the keyboard channel. We use a special variant
2871 of PC_to_RDR_Secure which directs these characters to the
2872 smart card's bulk-in channel. We also need to append a zero
2873 Lc byte to the APDU. It seems that it will be replaced with
2874 the actual length instead of being appended before the APDU
2875 is send to the card. */
2876 cherry_mode = 1;
2877 break;
2878 default:
2879 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2882 if (testmode)
2883 return 0; /* Success */
2885 msg = send_buffer;
2886 if (handle->id_vendor == VENDOR_SCM)
2888 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
2889 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
2890 NULL, 0, NULL);
2891 if (rc)
2892 return rc;
2895 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
2896 msg[5] = 0; /* slot */
2897 msg[6] = seqno = handle->seqno++;
2898 msg[7] = 0; /* bBWI */
2899 msg[8] = 0; /* RFU */
2900 msg[9] = 0; /* RFU */
2901 msg[10] = 0; /* Perform PIN verification. */
2902 msg[11] = 0; /* Timeout in seconds. */
2903 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2904 if (handle->id_vendor == VENDOR_SCM)
2906 /* For the SPR532 the next 2 bytes need to be zero. We do this
2907 for all SCM products. Kudos to Martin Paljak for this
2908 hint. */
2909 msg[13] = msg[14] = 0;
2911 else
2913 msg[13] = 0x00; /* bmPINBlockString:
2914 0 bits of pin length to insert.
2915 0 bytes of PIN block size. */
2916 msg[14] = 0x00; /* bmPINLengthFormat:
2917 Units are bytes, position is 0. */
2920 /* The following is a little endian word. */
2921 msg[15] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
2922 msg[16] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
2924 msg[17] = 0x02; /* bEntryValidationCondition:
2925 Validation key pressed */
2926 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
2927 msg[17] |= 0x01; /* Max size reached. */
2928 msg[18] = 0xff; /* bNumberMessage: Default. */
2929 msg[19] = 0x04; /* wLangId-High. */
2930 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
2931 msg[21] = 0; /* bMsgIndex. */
2932 /* bTeoProlog follows: */
2933 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2934 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
2935 msg[24] = 0; /* The apdulen will be filled in by the reader. */
2936 /* APDU follows: */
2937 msg[25] = apdu_buf[0]; /* CLA */
2938 msg[26] = apdu_buf[1]; /* INS */
2939 msg[27] = apdu_buf[2]; /* P1 */
2940 msg[28] = apdu_buf[3]; /* P2 */
2941 msglen = 29;
2942 if (cherry_mode)
2943 msg[msglen++] = 0;
2944 /* An EDC is not required. */
2945 set_msg_len (msg, msglen - 10);
2947 rc = bulk_out (handle, msg, msglen, 0);
2948 if (rc)
2949 return rc;
2951 msg = recv_buffer;
2952 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2953 RDR_to_PC_DataBlock, seqno, 30000, 0);
2954 if (rc)
2955 return rc;
2957 tpdu = msg + 10;
2958 tpdulen = msglen - 10;
2960 if (handle->apdu_level)
2962 if (resp)
2964 if (tpdulen > maxresplen)
2966 DEBUGOUT_2 ("provided buffer too short for received data "
2967 "(%u/%u)\n",
2968 (unsigned int)tpdulen, (unsigned int)maxresplen);
2969 return CCID_DRIVER_ERR_INV_VALUE;
2972 memcpy (resp, tpdu, tpdulen);
2973 *nresp = tpdulen;
2975 return 0;
2978 if (tpdulen < 4)
2980 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2981 return CCID_DRIVER_ERR_ABORTED;
2983 if (debug_level > 1)
2984 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2985 ((msg[11] & 0xc0) == 0x80)? 'R' :
2986 (msg[11] & 0x80)? 'S' : 'I',
2987 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2988 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2989 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2991 if (!(tpdu[1] & 0x80))
2992 { /* This is an I-block. */
2993 /* Last block sent was successful. */
2994 handle->t1_ns ^= 1;
2996 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2997 { /* Reponse does not match our sequence number. */
2998 DEBUGOUT ("I-block with wrong seqno received\n");
2999 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3002 handle->t1_nr ^= 1;
3004 p = tpdu + 3; /* Skip the prologue field. */
3005 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3006 /* fixme: verify the checksum. */
3007 if (resp)
3009 if (n > maxresplen)
3011 DEBUGOUT_2 ("provided buffer too short for received data "
3012 "(%u/%u)\n",
3013 (unsigned int)n, (unsigned int)maxresplen);
3014 return CCID_DRIVER_ERR_INV_VALUE;
3017 memcpy (resp, p, n);
3018 resp += n;
3019 *nresp += n;
3020 maxresplen -= n;
3023 if (!(tpdu[1] & 0x20))
3024 return 0; /* No chaining requested - ready. */
3026 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3027 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3029 else if ((tpdu[1] & 0xc0) == 0x80)
3030 { /* This is a R-block. */
3031 if ( (tpdu[1] & 0x0f))
3032 { /* Error: repeat last block */
3033 DEBUGOUT ("No retries supported for Secure operation\n");
3034 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3036 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3037 { /* Reponse does not match our sequence number. */
3038 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3039 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3041 else
3042 { /* Send next chunk. */
3043 DEBUGOUT ("chaining not supported on Secure operation\n");
3044 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3047 else
3048 { /* This is a S-block. */
3049 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d for Secure operation\n",
3050 (tpdu[1] & 0x20)? "response": "request",
3051 (tpdu[1] & 0x1f));
3052 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3055 return 0;
3061 #ifdef TEST
3064 static void
3065 print_error (int err)
3067 const char *p;
3068 char buf[50];
3070 switch (err)
3072 case 0: p = "success";
3073 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3074 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3075 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3076 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3077 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3078 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3079 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3080 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3081 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3082 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3083 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3084 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3085 default: sprintf (buf, "0x%05x", err); p = buf; break;
3087 fprintf (stderr, "operation failed: %s\n", p);
3091 static void
3092 print_data (const unsigned char *data, size_t length)
3094 if (length >= 2)
3096 fprintf (stderr, "operation status: %02X%02X\n",
3097 data[length-2], data[length-1]);
3098 length -= 2;
3100 if (length)
3102 fputs (" returned data:", stderr);
3103 for (; length; length--, data++)
3104 fprintf (stderr, " %02X", *data);
3105 putc ('\n', stderr);
3109 static void
3110 print_result (int rc, const unsigned char *data, size_t length)
3112 if (rc)
3113 print_error (rc);
3114 else if (data)
3115 print_data (data, length);
3119 main (int argc, char **argv)
3121 int rc;
3122 ccid_driver_t ccid;
3123 int slotstat;
3124 unsigned char result[512];
3125 size_t resultlen;
3126 int no_pinpad = 0;
3127 int verify_123456 = 0;
3128 int did_verify = 0;
3129 int no_poll = 0;
3131 if (argc)
3133 argc--;
3134 argv++;
3137 while (argc)
3139 if ( !strcmp (*argv, "--list"))
3141 char *p;
3142 p = ccid_get_reader_list ();
3143 if (!p)
3144 return 1;
3145 fputs (p, stderr);
3146 free (p);
3147 return 0;
3149 else if ( !strcmp (*argv, "--debug"))
3151 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3152 argc--; argv++;
3154 else if ( !strcmp (*argv, "--no-poll"))
3156 no_poll = 1;
3157 argc--; argv++;
3159 else if ( !strcmp (*argv, "--no-pinpad"))
3161 no_pinpad = 1;
3162 argc--; argv++;
3164 else if ( !strcmp (*argv, "--verify-123456"))
3166 verify_123456 = 1;
3167 argc--; argv++;
3169 else
3170 break;
3173 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3174 if (rc)
3175 return 1;
3177 if (!no_poll)
3178 ccid_poll (ccid);
3179 fputs ("getting ATR ...\n", stderr);
3180 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3181 if (rc)
3183 print_error (rc);
3184 return 1;
3187 if (!no_poll)
3188 ccid_poll (ccid);
3189 fputs ("getting slot status ...\n", stderr);
3190 rc = ccid_slot_status (ccid, &slotstat);
3191 if (rc)
3193 print_error (rc);
3194 return 1;
3197 if (!no_poll)
3198 ccid_poll (ccid);
3200 fputs ("selecting application OpenPGP ....\n", stderr);
3202 static unsigned char apdu[] = {
3203 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3204 rc = ccid_transceive (ccid,
3205 apdu, sizeof apdu,
3206 result, sizeof result, &resultlen);
3207 print_result (rc, result, resultlen);
3211 if (!no_poll)
3212 ccid_poll (ccid);
3214 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3216 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3217 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3218 result, sizeof result, &resultlen);
3219 print_result (rc, result, resultlen);
3222 if (!no_pinpad)
3226 if (!no_pinpad)
3228 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3231 if (ccid_transceive_secure (ccid,
3232 apdu, sizeof apdu,
3233 1, 0, 0, 0,
3234 NULL, 0, NULL))
3235 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3236 else
3238 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3240 rc = ccid_transceive_secure (ccid,
3241 apdu, sizeof apdu,
3242 1, 0, 0, 0,
3243 result, sizeof result, &resultlen);
3244 print_result (rc, result, resultlen);
3245 did_verify = 1;
3249 if (verify_123456 && !did_verify)
3251 fputs ("verifying that CHV1 is 123456....\n", stderr);
3253 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3254 6, '1','2','3','4','5','6'};
3255 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3256 result, sizeof result, &resultlen);
3257 print_result (rc, result, resultlen);
3261 if (!rc)
3263 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3265 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3266 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3267 result, sizeof result, &resultlen);
3268 print_result (rc, result, resultlen);
3272 ccid_close_reader (ccid);
3274 return 0;
3278 * Local Variables:
3279 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3280 * End:
3282 #endif /*TEST*/
3283 #endif /*HAVE_LIBUSB*/