2009-05-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / ccid-driver.c
blob8d0df52eea0983e9c45b6829f26e39fbd71b2324
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. */
162 #ifndef EAGAIN
163 #define EAGAIN EWOULDBLOCK
164 #endif
168 enum {
169 RDR_to_PC_NotifySlotChange= 0x50,
170 RDR_to_PC_HardwareError = 0x51,
172 PC_to_RDR_SetParameters = 0x61,
173 PC_to_RDR_IccPowerOn = 0x62,
174 PC_to_RDR_IccPowerOff = 0x63,
175 PC_to_RDR_GetSlotStatus = 0x65,
176 PC_to_RDR_Secure = 0x69,
177 PC_to_RDR_T0APDU = 0x6a,
178 PC_to_RDR_Escape = 0x6b,
179 PC_to_RDR_GetParameters = 0x6c,
180 PC_to_RDR_ResetParameters = 0x6d,
181 PC_to_RDR_IccClock = 0x6e,
182 PC_to_RDR_XfrBlock = 0x6f,
183 PC_to_RDR_Mechanical = 0x71,
184 PC_to_RDR_Abort = 0x72,
185 PC_to_RDR_SetDataRate = 0x73,
187 RDR_to_PC_DataBlock = 0x80,
188 RDR_to_PC_SlotStatus = 0x81,
189 RDR_to_PC_Parameters = 0x82,
190 RDR_to_PC_Escape = 0x83,
191 RDR_to_PC_DataRate = 0x84
195 /* Two macro to detect whether a CCID command has failed and to get
196 the error code. These macros assume that we can access the
197 mandatory first 10 bytes of a CCID message in BUF. */
198 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
199 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
202 /* We need to know the vendor to do some hacks. */
203 enum {
204 VENDOR_CHERRY = 0x046a,
205 VENDOR_SCM = 0x04e6,
206 VENDOR_OMNIKEY= 0x076b,
207 VENDOR_GEMPC = 0x08e6,
208 VENDOR_KAAN = 0x0d46
211 /* A list and a table with special transport descriptions. */
212 enum {
213 TRANSPORT_USB = 0, /* Standard USB transport. */
214 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
217 static struct
219 char *name; /* Device name. */
220 int type;
222 } transports[] = {
223 { "/dev/cmx0", TRANSPORT_CM4040 },
224 { "/dev/cmx1", TRANSPORT_CM4040 },
225 { NULL },
229 /* Store information on the driver's state. A pointer to such a
230 structure is used as handle for most functions. */
231 struct ccid_driver_s
233 usb_dev_handle *idev;
234 char *rid;
235 int dev_fd; /* -1 for USB transport or file descriptor of the
236 transport device. */
237 unsigned short id_vendor;
238 unsigned short id_product;
239 unsigned short bcd_device;
240 int ifc_no;
241 int ep_bulk_out;
242 int ep_bulk_in;
243 int ep_intr;
244 int seqno;
245 unsigned char t1_ns;
246 unsigned char t1_nr;
247 int nonnull_nad;
248 int auto_ifsd;
249 int max_ifsd;
250 int ifsd;
251 int ifsc;
252 int powered_off;
253 int has_pinpad;
254 int apdu_level; /* Reader supports short APDU level exchange. */
258 static int initialized_usb; /* Tracks whether USB has been initialized. */
259 static int debug_level; /* Flag to control the debug output.
260 0 = No debugging
261 1 = USB I/O info
262 2 = Level 1 + T=1 protocol tracing
263 3 = Level 2 + USB/I/O tracing of SlotStatus.
267 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
268 int use_crc);
269 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
270 int no_debug);
271 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
272 size_t *nread, int expected_type, int seqno, int timeout,
273 int no_debug);
274 static int abort_cmd (ccid_driver_t handle, int seqno);
276 /* Convert a little endian stored 4 byte value into an unsigned
277 integer. */
278 static unsigned int
279 convert_le_u32 (const unsigned char *buf)
281 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
285 /* Convert a little endian stored 2 byte value into an unsigned
286 integer. */
287 static unsigned int
288 convert_le_u16 (const unsigned char *buf)
290 return buf[0] | (buf[1] << 8);
293 static void
294 set_msg_len (unsigned char *msg, unsigned int length)
296 msg[1] = length;
297 msg[2] = length >> 8;
298 msg[3] = length >> 16;
299 msg[4] = length >> 24;
303 /* Pint an error message for a failed CCID command including a textual
304 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
305 static void
306 print_command_failed (const unsigned char *msg)
308 const char *t;
309 char buffer[100];
310 int ec;
312 if (!debug_level)
313 return;
315 ec = CCID_ERROR_CODE (msg);
316 switch (ec)
318 case 0x00: t = "Command not supported"; break;
320 case 0xE0: t = "Slot busy"; break;
321 case 0xEF: t = "PIN cancelled"; break;
322 case 0xF0: t = "PIN timeout"; break;
324 case 0xF2: t = "Automatic sequence ongoing"; break;
325 case 0xF3: t = "Deactivated Protocol"; break;
326 case 0xF4: t = "Procedure byte conflict"; break;
327 case 0xF5: t = "ICC class not supported"; break;
328 case 0xF6: t = "ICC protocol not supported"; break;
329 case 0xF7: t = "Bad checksum in ATR"; break;
330 case 0xF8: t = "Bad TS in ATR"; break;
332 case 0xFB: t = "An all inclusive hardware error occurred"; break;
333 case 0xFC: t = "Overrun error while talking to the ICC"; break;
334 case 0xFD: t = "Parity error while talking to the ICC"; break;
335 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
336 case 0xFF: t = "Host aborted the current activity"; break;
338 default:
339 if (ec > 0 && ec < 128)
340 sprintf (buffer, "Parameter error at offset %d", ec);
341 else
342 sprintf (buffer, "Error code %02X", ec);
343 t = buffer;
344 break;
346 DEBUGOUT_1 ("CCID command failed: %s\n", t);
350 static void
351 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
353 int any = 0;
355 for (; off < datalen; off++)
357 if (!any || !(off % 16))
359 if (any)
360 DEBUGOUT_LF ();
361 DEBUGOUT_1 (" [%04d] ", off);
363 DEBUGOUT_CONT_1 (" %02X", data[off]);
364 any = 1;
366 if (any && (off % 16))
367 DEBUGOUT_LF ();
371 static void
372 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
374 DEBUGOUT_1 ("%s:\n", name);
375 if (msglen < 7)
376 return;
377 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
378 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
379 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
383 static void
384 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
386 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
387 if (msglen < 10)
388 return;
389 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
390 msg[7] == 0? "auto":
391 msg[7] == 1? "5.0 V":
392 msg[7] == 2? "3.0 V":
393 msg[7] == 3? "1.8 V":"");
394 print_pr_data (msg, msglen, 8);
398 static void
399 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
401 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
402 print_pr_data (msg, msglen, 7);
406 static void
407 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
409 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
410 print_pr_data (msg, msglen, 7);
414 static void
415 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
417 unsigned int val;
419 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
420 if (msglen < 10)
421 return;
422 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
423 val = convert_le_u16 (msg+8);
424 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
425 val == 1? " (continued)":
426 val == 2? " (continues+ends)":
427 val == 3? " (continues+continued)":
428 val == 16? " (DataBlock-expected)":"");
429 print_pr_data (msg, msglen, 10);
433 static void
434 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
436 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
437 print_pr_data (msg, msglen, 7);
441 static void
442 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
444 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
445 print_pr_data (msg, msglen, 7);
449 static void
450 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
452 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
453 if (msglen < 10)
454 return;
455 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
456 print_pr_data (msg, msglen, 8);
460 static void
461 print_p2r_escape (const unsigned char *msg, size_t msglen)
463 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
464 print_pr_data (msg, msglen, 7);
468 static void
469 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
471 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
472 if (msglen < 10)
473 return;
474 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
475 print_pr_data (msg, msglen, 8);
479 static void
480 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
482 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
483 if (msglen < 10)
484 return;
485 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
486 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
487 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
488 print_pr_data (msg, msglen, 10);
492 static void
493 print_p2r_secure (const unsigned char *msg, size_t msglen)
495 unsigned int val;
497 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
498 if (msglen < 10)
499 return;
500 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
501 val = convert_le_u16 (msg+8);
502 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
503 val == 1? " (continued)":
504 val == 2? " (continues+ends)":
505 val == 3? " (continues+continued)":
506 val == 16? " (DataBlock-expected)":"");
507 print_pr_data (msg, msglen, 10);
511 static void
512 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
514 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
515 if (msglen < 10)
516 return;
517 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
518 print_pr_data (msg, msglen, 8);
522 static void
523 print_p2r_abort (const unsigned char *msg, size_t msglen)
525 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
526 print_pr_data (msg, msglen, 7);
530 static void
531 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
533 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
534 if (msglen < 10)
535 return;
536 print_pr_data (msg, msglen, 7);
540 static void
541 print_p2r_unknown (const unsigned char *msg, size_t msglen)
543 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
544 if (msglen < 10)
545 return;
546 print_pr_data (msg, msglen, 0);
550 static void
551 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
553 DEBUGOUT_1 ("%s:\n", name);
554 if (msglen < 9)
555 return;
556 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
557 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
558 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
559 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
560 if (msg[8])
561 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
565 static void
566 print_r2p_datablock (const unsigned char *msg, size_t msglen)
568 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
569 if (msglen < 10)
570 return;
571 if (msg[9])
572 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
573 msg[9] == 1? " (continued)":
574 msg[9] == 2? " (continues+ends)":
575 msg[9] == 3? " (continues+continued)":
576 msg[9] == 16? " (XferBlock-expected)":"");
577 print_pr_data (msg, msglen, 10);
581 static void
582 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
584 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
585 if (msglen < 10)
586 return;
587 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
588 msg[9] == 0? " (running)":
589 msg[9] == 1? " (stopped-L)":
590 msg[9] == 2? " (stopped-H)":
591 msg[9] == 3? " (stopped)":"");
592 print_pr_data (msg, msglen, 10);
596 static void
597 print_r2p_parameters (const unsigned char *msg, size_t msglen)
599 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
600 if (msglen < 10)
601 return;
603 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
604 if (msglen == 17 && msg[9] == 1)
606 /* Protocol T=1. */
607 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
608 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
609 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
610 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
611 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
612 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
613 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
615 else
616 print_pr_data (msg, msglen, 10);
620 static void
621 print_r2p_escape (const unsigned char *msg, size_t msglen)
623 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
624 if (msglen < 10)
625 return;
626 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
627 print_pr_data (msg, msglen, 10);
631 static void
632 print_r2p_datarate (const unsigned char *msg, size_t msglen)
634 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
635 if (msglen < 10)
636 return;
637 if (msglen >= 18)
639 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
640 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
641 print_pr_data (msg, msglen, 18);
643 else
644 print_pr_data (msg, msglen, 10);
648 static void
649 print_r2p_unknown (const unsigned char *msg, size_t msglen)
651 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
652 if (msglen < 10)
653 return;
654 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
655 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
656 print_pr_data (msg, msglen, 10);
660 /* Given a handle used for special transport prepare it for use. In
661 particular setup all information in way that resembles what
662 parse_cccid_descriptor does. */
663 static void
664 prepare_special_transport (ccid_driver_t handle)
666 assert (!handle->id_vendor);
668 handle->nonnull_nad = 0;
669 handle->auto_ifsd = 0;
670 handle->max_ifsd = 32;
671 handle->ifsd = 0;
672 handle->has_pinpad = 0;
673 handle->apdu_level = 0;
674 switch (handle->id_product)
676 case TRANSPORT_CM4040:
677 DEBUGOUT ("setting up transport for CardMan 4040\n");
678 handle->apdu_level = 1;
679 break;
681 default: assert (!"transport not defined");
685 /* Parse a CCID descriptor, optionally print all available features
686 and test whether this reader is usable by this driver. Returns 0
687 if it is usable.
689 Note, that this code is based on the one in lsusb.c of the
690 usb-utils package, I wrote on 2003-09-01. -wk. */
691 static int
692 parse_ccid_descriptor (ccid_driver_t handle,
693 const unsigned char *buf, size_t buflen)
695 unsigned int i;
696 unsigned int us;
697 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
700 handle->nonnull_nad = 0;
701 handle->auto_ifsd = 0;
702 handle->max_ifsd = 32;
703 handle->ifsd = 0;
704 handle->has_pinpad = 0;
705 handle->apdu_level = 0;
706 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
707 handle->id_vendor, handle->id_product, handle->bcd_device);
708 if (buflen < 54 || buf[0] < 54)
710 DEBUGOUT ("CCID device descriptor is too short\n");
711 return -1;
714 DEBUGOUT ("ChipCard Interface Descriptor:\n");
715 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
716 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
717 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
718 if (buf[3] != 1 || buf[2] != 0)
719 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
720 DEBUGOUT_LF ();
722 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
723 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
724 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
725 : buf[5] == 3? "1.8V":"?"));
727 us = convert_le_u32 (buf+6);
728 DEBUGOUT_1 (" dwProtocols %5u ", us);
729 if ((us & 1))
730 DEBUGOUT_CONT (" T=0");
731 if ((us & 2))
733 DEBUGOUT_CONT (" T=1");
734 have_t1 = 1;
736 if ((us & ~3))
737 DEBUGOUT_CONT (" (Invalid values detected)");
738 DEBUGOUT_LF ();
740 us = convert_le_u32(buf+10);
741 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
742 us = convert_le_u32(buf+14);
743 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
744 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
745 us = convert_le_u32(buf+19);
746 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
747 us = convert_le_u32(buf+23);
748 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
749 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
751 us = convert_le_u32(buf+28);
752 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
753 handle->max_ifsd = us;
755 us = convert_le_u32(buf+32);
756 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
757 if ((us&1))
758 DEBUGOUT_CONT ( " 2-wire");
759 if ((us&2))
760 DEBUGOUT_CONT ( " 3-wire");
761 if ((us&4))
762 DEBUGOUT_CONT ( " I2C");
763 DEBUGOUT_LF ();
765 us = convert_le_u32(buf+36);
766 DEBUGOUT_1 (" dwMechanical %08X ", us);
767 if ((us & 1))
768 DEBUGOUT_CONT (" accept");
769 if ((us & 2))
770 DEBUGOUT_CONT (" eject");
771 if ((us & 4))
772 DEBUGOUT_CONT (" capture");
773 if ((us & 8))
774 DEBUGOUT_CONT (" lock");
775 DEBUGOUT_LF ();
777 us = convert_le_u32(buf+40);
778 DEBUGOUT_1 (" dwFeatures %08X\n", us);
779 if ((us & 0x0002))
781 DEBUGOUT (" Auto configuration based on ATR\n");
782 have_auto_conf = 1;
784 if ((us & 0x0004))
785 DEBUGOUT (" Auto activation on insert\n");
786 if ((us & 0x0008))
787 DEBUGOUT (" Auto voltage selection\n");
788 if ((us & 0x0010))
789 DEBUGOUT (" Auto clock change\n");
790 if ((us & 0x0020))
791 DEBUGOUT (" Auto baud rate change\n");
792 if ((us & 0x0040))
793 DEBUGOUT (" Auto parameter negotation made by CCID\n");
794 else if ((us & 0x0080))
795 DEBUGOUT (" Auto PPS made by CCID\n");
796 else if ((us & (0x0040 | 0x0080)))
797 DEBUGOUT (" WARNING: conflicting negotation features\n");
799 if ((us & 0x0100))
800 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
801 if ((us & 0x0200))
803 DEBUGOUT (" NAD value other than 0x00 accepted\n");
804 handle->nonnull_nad = 1;
806 if ((us & 0x0400))
808 DEBUGOUT (" Auto IFSD exchange\n");
809 handle->auto_ifsd = 1;
812 if ((us & 0x00010000))
814 DEBUGOUT (" TPDU level exchange\n");
815 have_tpdu = 1;
817 else if ((us & 0x00020000))
819 DEBUGOUT (" Short APDU level exchange\n");
820 handle->apdu_level = 1;
822 else if ((us & 0x00040000))
824 DEBUGOUT (" Short and extended APDU level exchange\n");
825 handle->apdu_level = 1;
827 else if ((us & 0x00070000))
828 DEBUGOUT (" WARNING: conflicting exchange levels\n");
830 us = convert_le_u32(buf+44);
831 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
833 DEBUGOUT ( " bClassGetResponse ");
834 if (buf[48] == 0xff)
835 DEBUGOUT_CONT ("echo\n");
836 else
837 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
839 DEBUGOUT ( " bClassEnvelope ");
840 if (buf[49] == 0xff)
841 DEBUGOUT_CONT ("echo\n");
842 else
843 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
845 DEBUGOUT ( " wlcdLayout ");
846 if (!buf[50] && !buf[51])
847 DEBUGOUT_CONT ("none\n");
848 else
849 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
851 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
852 if ((buf[52] & 1))
854 DEBUGOUT_CONT ( " verification");
855 handle->has_pinpad |= 1;
857 if ((buf[52] & 2))
859 DEBUGOUT_CONT ( " modification");
860 handle->has_pinpad |= 2;
862 DEBUGOUT_LF ();
864 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
866 if (buf[0] > 54) {
867 DEBUGOUT (" junk ");
868 for (i=54; i < buf[0]-54; i++)
869 DEBUGOUT_CONT_1 (" %02X", buf[i]);
870 DEBUGOUT_LF ();
873 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
875 DEBUGOUT ("this drivers requires that the reader supports T=1, "
876 "TPDU or APDU level exchange and auto configuration - "
877 "this is not available\n");
878 return -1;
882 /* SCM drivers get stuck in their internal USB stack if they try to
883 send a frame of n*wMaxPacketSize back to us. Given that
884 wMaxPacketSize is 64 for these readers we set the IFSD to a value
885 lower than that:
886 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
887 Product Ids:
888 0xe001 - SCR 331
889 0x5111 - SCR 331-DI
890 0x5115 - SCR 335
891 0xe003 - SPR 532
893 if (handle->id_vendor == VENDOR_SCM
894 && handle->max_ifsd > 48
895 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
896 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
897 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
898 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
901 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
902 handle->max_ifsd = 48;
906 return 0;
910 static char *
911 get_escaped_usb_string (usb_dev_handle *idev, int idx,
912 const char *prefix, const char *suffix)
914 int rc;
915 unsigned char buf[280];
916 unsigned char *s;
917 unsigned int langid;
918 size_t i, n, len;
919 char *result;
921 if (!idx)
922 return NULL;
924 /* Fixme: The next line is for the current Valgrid without support
925 for USB IOCTLs. */
926 memset (buf, 0, sizeof buf);
928 /* First get the list of supported languages and use the first one.
929 If we do don't find it we try to use English. Note that this is
930 all in a 2 bute Unicode encoding using little endian. */
931 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
932 (USB_DT_STRING << 8), 0,
933 (char*)buf, sizeof buf, 1000 /* ms timeout */);
934 if (rc < 4)
935 langid = 0x0409; /* English. */
936 else
937 langid = (buf[3] << 8) | buf[2];
939 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
940 (USB_DT_STRING << 8) + idx, langid,
941 (char*)buf, sizeof buf, 1000 /* ms timeout */);
942 if (rc < 2 || buf[1] != USB_DT_STRING)
943 return NULL; /* Error or not a string. */
944 len = buf[0];
945 if (len > rc)
946 return NULL; /* Larger than our buffer. */
948 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
950 if (s[1])
951 n++; /* High byte set. */
952 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
953 n += 3 ;
954 else
955 n++;
958 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
959 if (!result)
960 return NULL;
962 strcpy (result, prefix);
963 n = strlen (prefix);
964 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
966 if (s[1])
967 result[n++] = '\xff'; /* High byte set. */
968 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
970 sprintf (result+n, "%%%02X", *s);
971 n += 3;
973 else
974 result[n++] = *s;
976 strcpy (result+n, suffix);
978 return result;
981 /* This function creates an reader id to be used to find the same
982 physical reader after a reset. It returns an allocated and possibly
983 percent escaped string or NULL if not enough memory is available. */
984 static char *
985 make_reader_id (usb_dev_handle *idev,
986 unsigned int vendor, unsigned int product,
987 unsigned char serialno_index)
989 char *rid;
990 char prefix[20];
992 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
993 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
994 if (!rid)
996 rid = malloc (strlen (prefix) + 3 + 1);
997 if (!rid)
998 return NULL;
999 strcpy (rid, prefix);
1000 strcat (rid, "X:0");
1002 return rid;
1006 /* Helper to find the endpoint from an interface descriptor. */
1007 static int
1008 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1010 int no;
1011 int want_bulk_in = 0;
1013 if (mode == 1)
1014 want_bulk_in = 0x80;
1015 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1017 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1018 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1020 else if (mode == 2
1021 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1022 == USB_ENDPOINT_TYPE_INTERRUPT)
1023 && (ep->bEndpointAddress & 0x80))
1024 return (ep->bEndpointAddress & 0x0f);
1025 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1026 == USB_ENDPOINT_TYPE_BULK)
1027 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1028 return (ep->bEndpointAddress & 0x0f);
1030 /* Should never happen. */
1031 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1035 /* Helper for scan_or_find_devices. This function returns true if a
1036 requested device has been found or the caller should stop scanning
1037 for other reasons. */
1038 static int
1039 scan_or_find_usb_device (int scan_mode,
1040 int *readerno, int *count, char **rid_list,
1041 const char *readerid,
1042 struct usb_device *dev,
1043 char **r_rid,
1044 struct usb_device **r_dev,
1045 usb_dev_handle **r_idev,
1046 unsigned char **ifcdesc_extra,
1047 size_t *ifcdesc_extra_len,
1048 int *interface_number,
1049 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1051 int cfg_no;
1052 int ifc_no;
1053 int set_no;
1054 struct usb_config_descriptor *config;
1055 struct usb_interface *interface;
1056 struct usb_interface_descriptor *ifcdesc;
1057 char *rid;
1058 usb_dev_handle *idev;
1060 *r_idev = NULL;
1062 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1064 config = dev->config + cfg_no;
1065 if(!config)
1066 continue;
1068 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1070 interface = config->interface + ifc_no;
1071 if (!interface)
1072 continue;
1074 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1076 ifcdesc = (interface->altsetting + set_no);
1077 /* The second condition is for older SCM SPR 532 who did
1078 not know about the assigned CCID class. Instead of
1079 trying to interpret the strings we simply check the
1080 product ID. */
1081 if (ifcdesc && ifcdesc->extra
1082 && ((ifcdesc->bInterfaceClass == 11
1083 && ifcdesc->bInterfaceSubClass == 0
1084 && ifcdesc->bInterfaceProtocol == 0)
1085 || (ifcdesc->bInterfaceClass == 255
1086 && dev->descriptor.idVendor == VENDOR_SCM
1087 && dev->descriptor.idProduct == 0xe003)))
1089 idev = usb_open (dev);
1090 if (!idev)
1092 DEBUGOUT_1 ("usb_open failed: %s\n",
1093 strerror (errno));
1094 continue; /* with next setting. */
1097 rid = make_reader_id (idev,
1098 dev->descriptor.idVendor,
1099 dev->descriptor.idProduct,
1100 dev->descriptor.iSerialNumber);
1101 if (rid)
1103 if (scan_mode)
1105 char *p;
1107 /* We are collecting infos about all
1108 available CCID readers. Store them and
1109 continue. */
1110 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1111 *count, rid );
1112 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1113 + strlen (rid) + 1);
1114 if (p)
1116 *p = 0;
1117 if (*rid_list)
1119 strcat (p, *rid_list);
1120 free (*rid_list);
1122 strcat (p, rid);
1123 strcat (p, "\n");
1124 *rid_list = p;
1126 else /* Out of memory. */
1127 free (rid);
1129 rid = NULL;
1130 ++*count;
1132 else if (!*readerno
1133 || (*readerno < 0
1134 && readerid
1135 && !strcmp (readerid, rid)))
1137 /* We found the requested reader. */
1138 if (ifcdesc_extra && ifcdesc_extra_len)
1140 *ifcdesc_extra = malloc (ifcdesc
1141 ->extralen);
1142 if (!*ifcdesc_extra)
1144 usb_close (idev);
1145 free (rid);
1146 return 1; /* Out of core. */
1148 memcpy (*ifcdesc_extra, ifcdesc->extra,
1149 ifcdesc->extralen);
1150 *ifcdesc_extra_len = ifcdesc->extralen;
1153 if (interface_number)
1154 *interface_number = (ifcdesc->bInterfaceNumber);
1156 if (ep_bulk_out)
1157 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1158 if (ep_bulk_in)
1159 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1160 if (ep_intr)
1161 *ep_intr = find_endpoint (ifcdesc, 2);
1163 if (r_dev)
1164 *r_dev = dev;
1165 if (r_rid)
1167 *r_rid = rid;
1168 rid = NULL;
1170 else
1171 free (rid);
1173 *r_idev = idev;
1174 return 1; /* Found requested device. */
1176 else
1178 /* This is not yet the reader we want.
1179 fixme: We should avoid the extra usb_open
1180 in this case. */
1181 if (*readerno >= 0)
1182 --*readerno;
1184 free (rid);
1187 usb_close (idev);
1188 idev = NULL;
1189 return 0;
1195 return 0;
1198 /* Combination function to either scan all CCID devices or to find and
1199 open one specific device.
1201 The function returns 0 if a reader has been found or when a scan
1202 returned without error.
1204 With READERNO = -1 and READERID is NULL, scan mode is used and
1205 R_RID should be the address where to store the list of reader_ids
1206 we found. If on return this list is empty, no CCID device has been
1207 found; otherwise it points to an allocated linked list of reader
1208 IDs. Note that in this mode the function always returns NULL.
1210 With READERNO >= 0 or READERID is not NULL find mode is used. This
1211 uses the same algorithm as the scan mode but stops and returns at
1212 the entry number READERNO and return the handle for the the opened
1213 USB device. If R_RID is not NULL it will receive the reader ID of
1214 that device. If R_DEV is not NULL it will the device pointer of
1215 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1216 malloced copy of the interfaces "extra: data filed;
1217 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1218 no reader with number READERNO or that reader is not usable by our
1219 implementation NULL will be returned. The caller must close a
1220 returned USB device handle and free (if not passed as NULL) the
1221 returned reader ID info as well as the IFCDESC_EXTRA. On error
1222 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1223 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1224 the READERID was found.
1226 If R_FD is not -1 on return the device is not using USB for
1227 transport but the device associated with that file descriptor. In
1228 this case INTERFACE will receive the transport type and the other
1229 USB specific return values are not used; the return value is
1230 (void*)(1).
1232 Note that the first entry of the returned reader ID list in scan mode
1233 corresponds with a READERNO of 0 in find mode.
1235 static int
1236 scan_or_find_devices (int readerno, const char *readerid,
1237 char **r_rid,
1238 struct usb_device **r_dev,
1239 unsigned char **ifcdesc_extra,
1240 size_t *ifcdesc_extra_len,
1241 int *interface_number,
1242 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1243 usb_dev_handle **r_idev,
1244 int *r_fd)
1246 char *rid_list = NULL;
1247 int count = 0;
1248 struct usb_bus *busses, *bus;
1249 struct usb_device *dev = NULL;
1250 usb_dev_handle *idev = NULL;
1251 int scan_mode = (readerno == -1 && !readerid);
1252 int i;
1254 /* Set return values to a default. */
1255 if (r_rid)
1256 *r_rid = NULL;
1257 if (r_dev)
1258 *r_dev = NULL;
1259 if (ifcdesc_extra)
1260 *ifcdesc_extra = NULL;
1261 if (ifcdesc_extra_len)
1262 *ifcdesc_extra_len = 0;
1263 if (interface_number)
1264 *interface_number = 0;
1265 if (r_idev)
1266 *r_idev = NULL;
1267 if (r_fd)
1268 *r_fd = -1;
1270 /* See whether we want scan or find mode. */
1271 if (scan_mode)
1273 assert (r_rid);
1276 usb_find_busses();
1277 usb_find_devices();
1279 #ifdef HAVE_USB_GET_BUSSES
1280 busses = usb_get_busses();
1281 #else
1282 busses = usb_busses;
1283 #endif
1285 for (bus = busses; bus; bus = bus->next)
1287 for (dev = bus->devices; dev; dev = dev->next)
1289 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1290 readerid,
1291 dev,
1292 r_rid,
1293 r_dev,
1294 &idev,
1295 ifcdesc_extra,
1296 ifcdesc_extra_len,
1297 interface_number,
1298 ep_bulk_out, ep_bulk_in, ep_intr))
1300 /* Found requested device or out of core. */
1301 if (!idev)
1303 free (rid_list);
1304 return -1; /* error */
1306 *r_idev = idev;
1307 return 0;
1312 /* Now check whether there are any devices with special transport types. */
1313 for (i=0; transports[i].name; i++)
1315 int fd;
1316 char *rid, *p;
1318 fd = open (transports[i].name, O_RDWR);
1319 if (fd == -1 && scan_mode && errno == EBUSY)
1321 /* Ignore this error in scan mode because it indicates that
1322 the device exists but is already open (most likely by us)
1323 and thus in general suitable as a reader. */
1325 else if (fd == -1)
1327 DEBUGOUT_2 ("failed to open `%s': %s\n",
1328 transports[i].name, strerror (errno));
1329 continue;
1332 rid = malloc (strlen (transports[i].name) + 30 + 10);
1333 if (!rid)
1335 if (fd != -1)
1336 close (fd);
1337 free (rid_list);
1338 return -1; /* Error. */
1340 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1341 if (scan_mode)
1343 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1344 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1345 if (!p)
1347 if (fd != -1)
1348 close (fd);
1349 free (rid_list);
1350 free (rid);
1351 return -1; /* Error. */
1353 *p = 0;
1354 if (rid_list)
1356 strcat (p, rid_list);
1357 free (rid_list);
1359 strcat (p, rid);
1360 strcat (p, "\n");
1361 rid_list = p;
1362 ++count;
1364 else if (!readerno ||
1365 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1367 /* Found requested device. */
1368 if (interface_number)
1369 *interface_number = transports[i].type;
1370 if (r_rid)
1371 *r_rid = rid;
1372 else
1373 free (rid);
1374 if (r_fd)
1375 *r_fd = fd;
1376 return 0; /* Okay, found device */
1378 else /* This is not yet the reader we want. */
1380 if (readerno >= 0)
1381 --readerno;
1383 free (rid);
1384 if (fd != -1)
1385 close (fd);
1388 if (scan_mode)
1390 *r_rid = rid_list;
1391 return 0;
1393 else
1394 return -1;
1398 /* Set the level of debugging to LEVEL and return the old level. -1
1399 just returns the old level. A level of 0 disables debugging, 1
1400 enables debugging, 2 enables additional tracing of the T=1
1401 protocol, 3 additionally enables debuggng for GetSlotStatus, other
1402 values are not yet defined.
1404 Note that libusb may provide its own debugging feature which is
1405 enabled by setting the envvar USB_DEBUG. */
1407 ccid_set_debug_level (int level)
1409 int old = debug_level;
1410 if (level != -1)
1411 debug_level = level;
1412 return old;
1416 char *
1417 ccid_get_reader_list (void)
1419 char *reader_list;
1421 if (!initialized_usb)
1423 usb_init ();
1424 initialized_usb = 1;
1427 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1428 NULL, NULL, NULL, NULL, NULL))
1429 return NULL; /* Error. */
1430 return reader_list;
1434 /* Open the reader with the internal number READERNO and return a
1435 pointer to be used as handle in HANDLE. Returns 0 on success. */
1436 int
1437 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1439 int rc = 0;
1440 struct usb_device *dev = NULL;
1441 usb_dev_handle *idev = NULL;
1442 int dev_fd = -1;
1443 char *rid = NULL;
1444 unsigned char *ifcdesc_extra = NULL;
1445 size_t ifcdesc_extra_len;
1446 int readerno;
1447 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1449 *handle = NULL;
1451 if (!initialized_usb)
1453 usb_init ();
1454 initialized_usb = 1;
1457 /* See whether we want to use the reader ID string or a reader
1458 number. A readerno of -1 indicates that the reader ID string is
1459 to be used. */
1460 if (readerid && strchr (readerid, ':'))
1461 readerno = -1; /* We want to use the readerid. */
1462 else if (readerid)
1464 readerno = atoi (readerid);
1465 if (readerno < 0)
1467 DEBUGOUT ("no CCID readers found\n");
1468 rc = CCID_DRIVER_ERR_NO_READER;
1469 goto leave;
1472 else
1473 readerno = 0; /* Default. */
1475 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1476 &ifcdesc_extra, &ifcdesc_extra_len,
1477 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1478 &idev, &dev_fd) )
1480 if (readerno == -1)
1481 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1482 else
1483 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1484 rc = CCID_DRIVER_ERR_NO_READER;
1485 goto leave;
1488 /* Okay, this is a CCID reader. */
1489 *handle = calloc (1, sizeof **handle);
1490 if (!*handle)
1492 DEBUGOUT ("out of memory\n");
1493 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1494 goto leave;
1496 (*handle)->rid = rid;
1497 if (idev) /* Regular USB transport. */
1499 (*handle)->idev = idev;
1500 (*handle)->dev_fd = -1;
1501 (*handle)->id_vendor = dev->descriptor.idVendor;
1502 (*handle)->id_product = dev->descriptor.idProduct;
1503 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1504 (*handle)->ifc_no = ifc_no;
1505 (*handle)->ep_bulk_out = ep_bulk_out;
1506 (*handle)->ep_bulk_in = ep_bulk_in;
1507 (*handle)->ep_intr = ep_intr;
1509 else if (dev_fd != -1) /* Device transport. */
1511 (*handle)->idev = NULL;
1512 (*handle)->dev_fd = dev_fd;
1513 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1514 (*handle)->id_product = ifc_no; /* Transport type */
1515 prepare_special_transport (*handle);
1517 else
1519 assert (!"no transport"); /* Bug. */
1522 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1524 if (idev)
1526 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1528 DEBUGOUT ("device not supported\n");
1529 rc = CCID_DRIVER_ERR_NO_READER;
1530 goto leave;
1533 rc = usb_claim_interface (idev, ifc_no);
1534 if (rc)
1536 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1537 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1538 goto leave;
1542 leave:
1543 free (ifcdesc_extra);
1544 if (rc)
1546 free (rid);
1547 if (idev)
1548 usb_close (idev);
1549 if (dev_fd != -1)
1550 close (dev_fd);
1551 free (*handle);
1552 *handle = NULL;
1555 return rc;
1559 static void
1560 do_close_reader (ccid_driver_t handle)
1562 int rc;
1563 unsigned char msg[100];
1564 size_t msglen;
1565 unsigned char seqno;
1567 if (!handle->powered_off)
1569 msg[0] = PC_to_RDR_IccPowerOff;
1570 msg[5] = 0; /* slot */
1571 msg[6] = seqno = handle->seqno++;
1572 msg[7] = 0; /* RFU */
1573 msg[8] = 0; /* RFU */
1574 msg[9] = 0; /* RFU */
1575 set_msg_len (msg, 0);
1576 msglen = 10;
1578 rc = bulk_out (handle, msg, msglen, 0);
1579 if (!rc)
1580 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1581 seqno, 2000, 0);
1582 handle->powered_off = 1;
1584 if (handle->idev)
1586 usb_release_interface (handle->idev, handle->ifc_no);
1587 usb_close (handle->idev);
1588 handle->idev = NULL;
1590 if (handle->dev_fd != -1)
1592 close (handle->dev_fd);
1593 handle->dev_fd = -1;
1598 /* Reset a reader on HANDLE. This is useful in case a reader has been
1599 plugged of and inserted at a different port. By resetting the
1600 handle, the same reader will be get used. Note, that on error the
1601 handle won't get released.
1603 This does not return an ATR, so ccid_get_atr should be called right
1604 after this one.
1606 int
1607 ccid_shutdown_reader (ccid_driver_t handle)
1609 int rc = 0;
1610 struct usb_device *dev = NULL;
1611 usb_dev_handle *idev = NULL;
1612 unsigned char *ifcdesc_extra = NULL;
1613 size_t ifcdesc_extra_len;
1614 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1616 if (!handle || !handle->rid)
1617 return CCID_DRIVER_ERR_INV_VALUE;
1619 do_close_reader (handle);
1621 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1622 &ifcdesc_extra, &ifcdesc_extra_len,
1623 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1624 &idev, NULL) || !idev)
1626 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1627 return CCID_DRIVER_ERR_NO_READER;
1630 if (idev)
1632 handle->idev = idev;
1633 handle->ifc_no = ifc_no;
1634 handle->ep_bulk_out = ep_bulk_out;
1635 handle->ep_bulk_in = ep_bulk_in;
1636 handle->ep_intr = ep_intr;
1638 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1640 DEBUGOUT ("device not supported\n");
1641 rc = CCID_DRIVER_ERR_NO_READER;
1642 goto leave;
1645 rc = usb_claim_interface (idev, ifc_no);
1646 if (rc)
1648 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1649 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1650 goto leave;
1654 leave:
1655 free (ifcdesc_extra);
1656 if (rc)
1658 if (handle->idev)
1659 usb_close (handle->idev);
1660 handle->idev = NULL;
1661 if (handle->dev_fd != -1)
1662 close (handle->dev_fd);
1663 handle->dev_fd = -1;
1666 return rc;
1671 /* Close the reader HANDLE. */
1672 int
1673 ccid_close_reader (ccid_driver_t handle)
1675 if (!handle || (!handle->idev && handle->dev_fd == -1))
1676 return 0;
1678 do_close_reader (handle);
1679 free (handle->rid);
1680 free (handle);
1681 return 0;
1685 /* Return False if a card is present and powered. */
1687 ccid_check_card_presence (ccid_driver_t handle)
1689 (void)handle; /* Not yet implemented. */
1690 return -1;
1694 /* Write NBYTES of BUF to file descriptor FD. */
1695 static int
1696 writen (int fd, const void *buf, size_t nbytes)
1698 size_t nleft = nbytes;
1699 int nwritten;
1701 while (nleft > 0)
1703 nwritten = write (fd, buf, nleft);
1704 if (nwritten < 0)
1706 if (errno == EINTR)
1707 nwritten = 0;
1708 else
1709 return -1;
1711 nleft -= nwritten;
1712 buf = (const char*)buf + nwritten;
1715 return 0;
1719 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1720 Returns 0 on success. */
1721 static int
1722 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1723 int no_debug)
1725 int rc;
1727 if (debug_level && (!no_debug || debug_level >= 3))
1729 switch (msglen? msg[0]:0)
1731 case PC_to_RDR_IccPowerOn:
1732 print_p2r_iccpoweron (msg, msglen);
1733 break;
1734 case PC_to_RDR_IccPowerOff:
1735 print_p2r_iccpoweroff (msg, msglen);
1736 break;
1737 case PC_to_RDR_GetSlotStatus:
1738 print_p2r_getslotstatus (msg, msglen);
1739 break;
1740 case PC_to_RDR_XfrBlock:
1741 print_p2r_xfrblock (msg, msglen);
1742 break;
1743 case PC_to_RDR_GetParameters:
1744 print_p2r_getparameters (msg, msglen);
1745 break;
1746 case PC_to_RDR_ResetParameters:
1747 print_p2r_resetparameters (msg, msglen);
1748 break;
1749 case PC_to_RDR_SetParameters:
1750 print_p2r_setparameters (msg, msglen);
1751 break;
1752 case PC_to_RDR_Escape:
1753 print_p2r_escape (msg, msglen);
1754 break;
1755 case PC_to_RDR_IccClock:
1756 print_p2r_iccclock (msg, msglen);
1757 break;
1758 case PC_to_RDR_T0APDU:
1759 print_p2r_to0apdu (msg, msglen);
1760 break;
1761 case PC_to_RDR_Secure:
1762 print_p2r_secure (msg, msglen);
1763 break;
1764 case PC_to_RDR_Mechanical:
1765 print_p2r_mechanical (msg, msglen);
1766 break;
1767 case PC_to_RDR_Abort:
1768 print_p2r_abort (msg, msglen);
1769 break;
1770 case PC_to_RDR_SetDataRate:
1771 print_p2r_setdatarate (msg, msglen);
1772 break;
1773 default:
1774 print_p2r_unknown (msg, msglen);
1775 break;
1779 if (handle->idev)
1781 rc = usb_bulk_write (handle->idev,
1782 handle->ep_bulk_out,
1783 (char*)msg, msglen,
1784 5000 /* ms timeout */);
1785 if (rc == msglen)
1786 return 0;
1787 if (rc == -1)
1788 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1789 else
1790 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1792 else
1794 rc = writen (handle->dev_fd, msg, msglen);
1795 if (!rc)
1796 return 0;
1797 DEBUGOUT_2 ("writen to %d failed: %s\n",
1798 handle->dev_fd, strerror (errno));
1801 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1805 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1806 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1807 is the sequence number used to send the request and EXPECTED_TYPE
1808 the type of message we expect. Does checks on the ccid
1809 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1810 avoid debug messages in case of no error; this can be overriden
1811 with a glibal debug level of at least 3. Returns 0 on success. */
1812 static int
1813 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1814 size_t *nread, int expected_type, int seqno, int timeout,
1815 int no_debug)
1817 int rc;
1818 size_t msglen;
1819 int eagain_retries = 0;
1821 /* Fixme: The next line for the current Valgrind without support
1822 for USB IOCTLs. */
1823 memset (buffer, 0, length);
1824 retry:
1825 if (handle->idev)
1827 rc = usb_bulk_read (handle->idev,
1828 handle->ep_bulk_in,
1829 (char*)buffer, length,
1830 timeout);
1831 if (rc < 0)
1833 rc = errno;
1834 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
1835 if (rc == EAGAIN && eagain_retries++ < 3)
1837 #ifndef TEST
1838 gnupg_sleep (1);
1839 #endif
1840 goto retry;
1842 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1844 *nread = msglen = rc;
1846 else
1848 rc = read (handle->dev_fd, buffer, length);
1849 if (rc < 0)
1851 rc = errno;
1852 DEBUGOUT_2 ("read from %d failed: %s\n",
1853 handle->dev_fd, strerror (rc));
1854 if (rc == EAGAIN && eagain_retries++ < 5)
1856 #ifndef TEST
1857 gnupg_sleep (1);
1858 #endif
1859 goto retry;
1861 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1863 *nread = msglen = rc;
1865 eagain_retries = 0;
1867 if (msglen < 10)
1869 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1870 abort_cmd (handle, seqno);
1871 return CCID_DRIVER_ERR_INV_VALUE;
1873 if (buffer[5] != 0)
1875 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1876 return CCID_DRIVER_ERR_INV_VALUE;
1878 if (buffer[6] != seqno)
1880 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1881 seqno, buffer[6]);
1882 /* Retry until we are synced again. */
1883 goto retry;
1886 /* We need to handle the time extension request before we check that
1887 we got the expected message type. This is in particular required
1888 for the Cherry keyboard which sends a time extension request for
1889 each key hit. */
1890 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1892 /* Card present and active, time extension requested. */
1893 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1894 buffer[7], buffer[8]);
1895 goto retry;
1898 if (buffer[0] != expected_type)
1900 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1901 abort_cmd (handle, seqno);
1902 return CCID_DRIVER_ERR_INV_VALUE;
1905 if (debug_level && (!no_debug || debug_level >= 3))
1907 switch (buffer[0])
1909 case RDR_to_PC_DataBlock:
1910 print_r2p_datablock (buffer, msglen);
1911 break;
1912 case RDR_to_PC_SlotStatus:
1913 print_r2p_slotstatus (buffer, msglen);
1914 break;
1915 case RDR_to_PC_Parameters:
1916 print_r2p_parameters (buffer, msglen);
1917 break;
1918 case RDR_to_PC_Escape:
1919 print_r2p_escape (buffer, msglen);
1920 break;
1921 case RDR_to_PC_DataRate:
1922 print_r2p_datarate (buffer, msglen);
1923 break;
1924 default:
1925 print_r2p_unknown (buffer, msglen);
1926 break;
1929 if (CCID_COMMAND_FAILED (buffer))
1930 print_command_failed (buffer);
1932 /* Check whether a card is at all available. Note: If you add new
1933 error codes here, check whether they need to be ignored in
1934 send_escape_cmd. */
1935 switch ((buffer[7] & 0x03))
1937 case 0: /* no error */ break;
1938 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1939 case 2: return CCID_DRIVER_ERR_NO_CARD;
1940 case 3: /* RFU */ break;
1942 return 0;
1947 /* Send an abort sequence and wait until everything settled. */
1948 static int
1949 abort_cmd (ccid_driver_t handle, int seqno)
1951 int rc;
1952 char dummybuf[8];
1953 unsigned char msg[100];
1954 size_t msglen;
1956 if (!handle->idev)
1958 /* I don't know how to send an abort to non-USB devices. */
1959 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
1962 seqno &= 0xff;
1963 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
1964 /* Send the abort command to the control pipe. Note that we don't
1965 need to keep track of sent abort commands because there should
1966 never be another thread using the same slot concurrently. */
1967 rc = usb_control_msg (handle->idev,
1968 0x21,/* bmRequestType: host-to-device,
1969 class specific, to interface. */
1970 1, /* ABORT */
1971 (seqno << 8 | 0 /* slot */),
1972 handle->ifc_no,
1973 dummybuf, 0,
1974 1000 /* ms timeout */);
1975 if (rc < 0)
1977 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
1978 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1981 /* Now send the abort command to the bulk out pipe using the same
1982 SEQNO and SLOT. Do this in a loop to so that all seqno are
1983 tried. */
1984 seqno--; /* Adjust for next increment. */
1987 seqno++;
1988 msg[0] = PC_to_RDR_Abort;
1989 msg[5] = 0; /* slot */
1990 msg[6] = seqno;
1991 msg[7] = 0; /* RFU */
1992 msg[8] = 0; /* RFU */
1993 msg[9] = 0; /* RFU */
1994 msglen = 10;
1995 set_msg_len (msg, 0);
1997 rc = usb_bulk_write (handle->idev,
1998 handle->ep_bulk_out,
1999 (char*)msg, msglen,
2000 5000 /* ms timeout */);
2001 if (rc == msglen)
2002 rc = 0;
2003 else if (rc == -1)
2004 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2005 strerror (errno));
2006 else
2007 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2009 if (rc)
2010 return rc;
2012 rc = usb_bulk_read (handle->idev,
2013 handle->ep_bulk_in,
2014 (char*)msg, sizeof msg,
2015 5000 /*ms timeout*/);
2016 if (rc < 0)
2018 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2019 strerror (errno));
2020 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2022 msglen = rc;
2024 if (msglen < 10)
2026 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2027 (unsigned int)msglen);
2028 return CCID_DRIVER_ERR_INV_VALUE;
2030 if (msg[5] != 0)
2032 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2033 return CCID_DRIVER_ERR_INV_VALUE;
2036 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2037 msg[7], msg[8], msg[9]);
2038 if (CCID_COMMAND_FAILED (msg))
2039 print_command_failed (msg);
2041 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2043 handle->seqno = ((seqno + 1) & 0xff);
2044 DEBUGOUT ("sending abort sequence succeeded\n");
2046 return 0;
2050 /* Note that this function won't return the error codes NO_CARD or
2051 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2052 operation will get returned in RESULT and its length in RESULTLEN.
2053 If the response is larger than RESULTMAX, an error is returned and
2054 the required buffer length returned in RESULTLEN. */
2055 static int
2056 send_escape_cmd (ccid_driver_t handle,
2057 const unsigned char *data, size_t datalen,
2058 unsigned char *result, size_t resultmax, size_t *resultlen)
2060 int rc;
2061 unsigned char msg[100];
2062 size_t msglen;
2063 unsigned char seqno;
2065 if (resultlen)
2066 *resultlen = 0;
2068 if (datalen > sizeof msg - 10)
2069 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2071 msg[0] = PC_to_RDR_Escape;
2072 msg[5] = 0; /* slot */
2073 msg[6] = seqno = handle->seqno++;
2074 msg[7] = 0; /* RFU */
2075 msg[8] = 0; /* RFU */
2076 msg[9] = 0; /* RFU */
2077 memcpy (msg+10, data, datalen);
2078 msglen = 10 + datalen;
2079 set_msg_len (msg, datalen);
2081 rc = bulk_out (handle, msg, msglen, 0);
2082 if (rc)
2083 return rc;
2084 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2085 seqno, 5000, 0);
2086 if (result)
2087 switch (rc)
2089 /* We need to ignore certain errorcode here. */
2090 case 0:
2091 case CCID_DRIVER_ERR_CARD_INACTIVE:
2092 case CCID_DRIVER_ERR_NO_CARD:
2094 if (msglen > resultmax)
2095 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2096 else
2098 memcpy (result, msg, msglen);
2099 *resultlen = msglen;
2101 rc = 0;
2103 break;
2104 default:
2105 break;
2108 return rc;
2113 ccid_transceive_escape (ccid_driver_t handle,
2114 const unsigned char *data, size_t datalen,
2115 unsigned char *resp, size_t maxresplen, size_t *nresp)
2117 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2122 /* experimental */
2124 ccid_poll (ccid_driver_t handle)
2126 int rc;
2127 unsigned char msg[10];
2128 size_t msglen;
2129 int i, j;
2131 if (handle->idev)
2133 rc = usb_bulk_read (handle->idev,
2134 handle->ep_intr,
2135 (char*)msg, sizeof msg,
2136 0 /* ms timeout */ );
2137 if (rc < 0 && errno == ETIMEDOUT)
2138 return 0;
2140 else
2141 return 0;
2143 if (rc < 0)
2145 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2146 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2149 msglen = rc;
2150 rc = 0;
2152 if (msglen < 1)
2154 DEBUGOUT ("intr-in msg too short\n");
2155 return CCID_DRIVER_ERR_INV_VALUE;
2158 if (msg[0] == RDR_to_PC_NotifySlotChange)
2160 DEBUGOUT ("notify slot change:");
2161 for (i=1; i < msglen; i++)
2162 for (j=0; j < 4; j++)
2163 DEBUGOUT_CONT_3 (" %d:%c%c",
2164 (i-1)*4+j,
2165 (msg[i] & (1<<(j*2)))? 'p':'-',
2166 (msg[i] & (2<<(j*2)))? '*':' ');
2167 DEBUGOUT_LF ();
2169 else if (msg[0] == RDR_to_PC_HardwareError)
2171 DEBUGOUT ("hardware error occured\n");
2173 else
2175 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2178 return 0;
2182 /* Note that this function won't return the error codes NO_CARD or
2183 CARD_INACTIVE */
2184 int
2185 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2187 int rc;
2188 unsigned char msg[100];
2189 size_t msglen;
2190 unsigned char seqno;
2191 int retries = 0;
2193 retry:
2194 msg[0] = PC_to_RDR_GetSlotStatus;
2195 msg[5] = 0; /* slot */
2196 msg[6] = seqno = handle->seqno++;
2197 msg[7] = 0; /* RFU */
2198 msg[8] = 0; /* RFU */
2199 msg[9] = 0; /* RFU */
2200 set_msg_len (msg, 0);
2202 rc = bulk_out (handle, msg, 10, 1);
2203 if (rc)
2204 return rc;
2205 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2206 get cluttered up by a ticker function checking for the slot
2207 status and debugging enabled. */
2208 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2209 seqno, retries? 1000 : 200, 1);
2210 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2212 if (!retries)
2214 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2215 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2216 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2218 else
2219 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2220 retries++;
2221 goto retry;
2223 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2224 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2225 return rc;
2226 *statusbits = (msg[7] & 3);
2228 return 0;
2232 /* Return the ATR of the card. This is not a cached value and thus an
2233 actual reset is done. */
2234 int
2235 ccid_get_atr (ccid_driver_t handle,
2236 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2238 int rc;
2239 int statusbits;
2240 unsigned char msg[100];
2241 unsigned char *tpdu;
2242 size_t msglen, tpdulen;
2243 unsigned char seqno;
2244 int use_crc = 0;
2245 unsigned int edc;
2246 int tried_iso = 0;
2247 int got_param;
2249 /* First check whether a card is available. */
2250 rc = ccid_slot_status (handle, &statusbits);
2251 if (rc)
2252 return rc;
2253 if (statusbits == 2)
2254 return CCID_DRIVER_ERR_NO_CARD;
2256 /* For an inactive and also for an active card, issue the PowerOn
2257 command to get the ATR. */
2258 again:
2259 msg[0] = PC_to_RDR_IccPowerOn;
2260 msg[5] = 0; /* slot */
2261 msg[6] = seqno = handle->seqno++;
2262 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2263 msg[8] = 0; /* RFU */
2264 msg[9] = 0; /* RFU */
2265 set_msg_len (msg, 0);
2266 msglen = 10;
2268 rc = bulk_out (handle, msg, msglen, 0);
2269 if (rc)
2270 return rc;
2271 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2272 seqno, 5000, 0);
2273 if (rc)
2274 return rc;
2275 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2276 && ((handle->id_vendor == VENDOR_CHERRY
2277 && handle->id_product == 0x0005)
2278 || (handle->id_vendor == VENDOR_GEMPC
2279 && handle->id_product == 0x4433)
2282 tried_iso = 1;
2283 /* Try switching to ISO mode. */
2284 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2285 NULL, 0, NULL))
2286 goto again;
2288 else if (CCID_COMMAND_FAILED (msg))
2289 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2292 handle->powered_off = 0;
2294 if (atr)
2296 size_t n = msglen - 10;
2298 if (n > maxatrlen)
2299 n = maxatrlen;
2300 memcpy (atr, msg+10, n);
2301 *atrlen = n;
2304 got_param = 0;
2305 msg[0] = PC_to_RDR_GetParameters;
2306 msg[5] = 0; /* slot */
2307 msg[6] = seqno = handle->seqno++;
2308 msg[7] = 0; /* RFU */
2309 msg[8] = 0; /* RFU */
2310 msg[9] = 0; /* RFU */
2311 set_msg_len (msg, 0);
2312 msglen = 10;
2313 rc = bulk_out (handle, msg, msglen, 0);
2314 if (!rc)
2315 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2316 seqno, 2000, 0);
2317 if (rc)
2318 DEBUGOUT ("GetParameters failed\n");
2319 else if (msglen == 17 && msg[9] == 1)
2320 got_param = 1;
2322 /* Setup parameters to select T=1. */
2323 msg[0] = PC_to_RDR_SetParameters;
2324 msg[5] = 0; /* slot */
2325 msg[6] = seqno = handle->seqno++;
2326 msg[7] = 1; /* Select T=1. */
2327 msg[8] = 0; /* RFU */
2328 msg[9] = 0; /* RFU */
2330 if (!got_param)
2332 /* FIXME: Get those values from the ATR. */
2333 msg[10]= 0x01; /* Fi/Di */
2334 msg[11]= 0x10; /* LRC, direct convention. */
2335 msg[12]= 0; /* Extra guardtime. */
2336 msg[13]= 0x41; /* BWI/CWI */
2337 msg[14]= 0; /* No clock stoppping. */
2338 msg[15]= 254; /* IFSC */
2339 msg[16]= 0; /* Does not support non default NAD values. */
2341 set_msg_len (msg, 7);
2342 msglen = 10 + 7;
2344 rc = bulk_out (handle, msg, msglen, 0);
2345 if (rc)
2346 return rc;
2347 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2348 seqno, 5000, 0);
2349 if (rc)
2350 DEBUGOUT ("SetParameters failed (ignored)\n");
2352 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2353 handle->ifsc = msg[15];
2354 else
2355 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2357 handle->t1_ns = 0;
2358 handle->t1_nr = 0;
2360 /* Send an S-Block with our maximum IFSD to the CCID. */
2361 if (!handle->apdu_level && !handle->auto_ifsd)
2363 tpdu = msg+10;
2364 /* NAD: DAD=1, SAD=0 */
2365 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2366 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2367 tpdu[2] = 1;
2368 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2369 tpdulen = 4;
2370 edc = compute_edc (tpdu, tpdulen, use_crc);
2371 if (use_crc)
2372 tpdu[tpdulen++] = (edc >> 8);
2373 tpdu[tpdulen++] = edc;
2375 msg[0] = PC_to_RDR_XfrBlock;
2376 msg[5] = 0; /* slot */
2377 msg[6] = seqno = handle->seqno++;
2378 msg[7] = 0;
2379 msg[8] = 0; /* RFU */
2380 msg[9] = 0; /* RFU */
2381 set_msg_len (msg, tpdulen);
2382 msglen = 10 + tpdulen;
2384 if (debug_level > 1)
2385 DEBUGOUT_3 ("T=1: put %c-block seq=%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] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2392 rc = bulk_out (handle, msg, msglen, 0);
2393 if (rc)
2394 return rc;
2397 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2398 RDR_to_PC_DataBlock, seqno, 5000, 0);
2399 if (rc)
2400 return rc;
2402 tpdu = msg + 10;
2403 tpdulen = msglen - 10;
2405 if (tpdulen < 4)
2406 return CCID_DRIVER_ERR_ABORTED;
2408 if (debug_level > 1)
2409 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2410 ((msg[11] & 0xc0) == 0x80)? 'R' :
2411 (msg[11] & 0x80)? 'S' : 'I',
2412 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2413 : !!(msg[11] & 0x40)),
2414 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2415 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2417 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2419 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2420 return -1;
2422 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2425 return 0;
2431 static unsigned int
2432 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2434 if (use_crc)
2436 return 0x42; /* Not yet implemented. */
2438 else
2440 unsigned char crc = 0;
2442 for (; datalen; datalen--)
2443 crc ^= *data++;
2444 return crc;
2449 /* Helper for ccid_transceive used for APDU level exchanges. */
2450 static int
2451 ccid_transceive_apdu_level (ccid_driver_t handle,
2452 const unsigned char *apdu_buf, size_t apdu_buflen,
2453 unsigned char *resp, size_t maxresplen,
2454 size_t *nresp)
2456 int rc;
2457 unsigned char send_buffer[10+261+300], recv_buffer[10+261+300];
2458 const unsigned char *apdu;
2459 size_t apdulen;
2460 unsigned char *msg;
2461 size_t msglen;
2462 unsigned char seqno;
2463 int bwi = 4;
2465 msg = send_buffer;
2467 apdu = apdu_buf;
2468 apdulen = apdu_buflen;
2469 assert (apdulen);
2471 /* The maximum length for a short APDU T=1 block is 261. For an
2472 extended APDU T=1 block the maximum length 65544; however
2473 extended APDU exchange level is not yet supported. */
2474 if (apdulen > 261)
2475 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2477 msg[0] = PC_to_RDR_XfrBlock;
2478 msg[5] = 0; /* slot */
2479 msg[6] = seqno = handle->seqno++;
2480 msg[7] = bwi; /* bBWI */
2481 msg[8] = 0; /* RFU */
2482 msg[9] = 0; /* RFU */
2483 memcpy (msg+10, apdu, apdulen);
2484 set_msg_len (msg, apdulen);
2485 msglen = 10 + apdulen;
2487 rc = bulk_out (handle, msg, msglen, 0);
2488 if (rc)
2489 return rc;
2491 msg = recv_buffer;
2492 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2493 RDR_to_PC_DataBlock, seqno, 5000, 0);
2494 if (rc)
2495 return rc;
2497 apdu = msg + 10;
2498 apdulen = msglen - 10;
2500 if (resp)
2502 if (apdulen > maxresplen)
2504 DEBUGOUT_2 ("provided buffer too short for received data "
2505 "(%u/%u)\n",
2506 (unsigned int)apdulen, (unsigned int)maxresplen);
2507 return CCID_DRIVER_ERR_INV_VALUE;
2510 memcpy (resp, apdu, apdulen);
2511 *nresp = apdulen;
2514 return 0;
2520 Protocol T=1 overview
2522 Block Structure:
2523 Prologue Field:
2524 1 byte Node Address (NAD)
2525 1 byte Protocol Control Byte (PCB)
2526 1 byte Length (LEN)
2527 Information Field:
2528 0-254 byte APDU or Control Information (INF)
2529 Epilogue Field:
2530 1 byte Error Detection Code (EDC)
2532 NAD:
2533 bit 7 unused
2534 bit 4..6 Destination Node Address (DAD)
2535 bit 3 unused
2536 bit 2..0 Source Node Address (SAD)
2538 If node adresses are not used, SAD and DAD should be set to 0 on
2539 the first block sent to the card. If they are used they should
2540 have different values (0 for one is okay); that first block sets up
2541 the addresses of the nodes.
2543 PCB:
2544 Information Block (I-Block):
2545 bit 7 0
2546 bit 6 Sequence number (yep, that is modulo 2)
2547 bit 5 Chaining flag
2548 bit 4..0 reserved
2549 Received-Ready Block (R-Block):
2550 bit 7 1
2551 bit 6 0
2552 bit 5 0
2553 bit 4 Sequence number
2554 bit 3..0 0 = no error
2555 1 = EDC or parity error
2556 2 = other error
2557 other values are reserved
2558 Supervisory Block (S-Block):
2559 bit 7 1
2560 bit 6 1
2561 bit 5 clear=request,set=response
2562 bit 4..0 0 = resyncronisation request
2563 1 = information field size request
2564 2 = abort request
2565 3 = extension of BWT request
2566 4 = VPP error
2567 other values are reserved
2572 ccid_transceive (ccid_driver_t handle,
2573 const unsigned char *apdu_buf, size_t apdu_buflen,
2574 unsigned char *resp, size_t maxresplen, size_t *nresp)
2576 int rc;
2577 unsigned char send_buffer[10+259], recv_buffer[10+259];
2578 const unsigned char *apdu;
2579 size_t apdulen;
2580 unsigned char *msg, *tpdu, *p;
2581 size_t msglen, tpdulen, last_tpdulen, n;
2582 unsigned char seqno;
2583 unsigned int edc;
2584 int use_crc = 0;
2585 size_t dummy_nresp;
2586 int next_chunk = 1;
2587 int sending = 1;
2588 int retries = 0;
2590 if (!nresp)
2591 nresp = &dummy_nresp;
2592 *nresp = 0;
2594 /* Smarter readers allow to send APDUs directly; divert here. */
2595 if (handle->apdu_level)
2596 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2597 resp, maxresplen, nresp);
2599 /* The other readers we support require sending TPDUs. */
2601 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2602 msg = send_buffer;
2603 for (;;)
2605 if (next_chunk)
2607 next_chunk = 0;
2609 apdu = apdu_buf;
2610 apdulen = apdu_buflen;
2611 assert (apdulen);
2613 /* Construct an I-Block. */
2614 tpdu = msg+10;
2615 /* NAD: DAD=1, SAD=0 */
2616 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2617 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2618 if (apdulen > handle->ifsc )
2620 apdulen = handle->ifsc;
2621 apdu_buf += handle->ifsc;
2622 apdu_buflen -= handle->ifsc;
2623 tpdu[1] |= (1 << 5); /* Set more bit. */
2625 tpdu[2] = apdulen;
2626 memcpy (tpdu+3, apdu, apdulen);
2627 tpdulen = 3 + apdulen;
2628 edc = compute_edc (tpdu, tpdulen, use_crc);
2629 if (use_crc)
2630 tpdu[tpdulen++] = (edc >> 8);
2631 tpdu[tpdulen++] = edc;
2634 msg[0] = PC_to_RDR_XfrBlock;
2635 msg[5] = 0; /* slot */
2636 msg[6] = seqno = handle->seqno++;
2637 msg[7] = 4; /* bBWI */
2638 msg[8] = 0; /* RFU */
2639 msg[9] = 0; /* RFU */
2640 set_msg_len (msg, tpdulen);
2641 msglen = 10 + tpdulen;
2642 last_tpdulen = tpdulen;
2644 if (debug_level > 1)
2645 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2646 ((msg[11] & 0xc0) == 0x80)? 'R' :
2647 (msg[11] & 0x80)? 'S' : 'I',
2648 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2649 : !!(msg[11] & 0x40)),
2650 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2652 rc = bulk_out (handle, msg, msglen, 0);
2653 if (rc)
2654 return rc;
2656 msg = recv_buffer;
2657 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2658 RDR_to_PC_DataBlock, seqno, 5000, 0);
2659 if (rc)
2660 return rc;
2662 tpdu = msg + 10;
2663 tpdulen = msglen - 10;
2665 if (tpdulen < 4)
2667 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2668 return CCID_DRIVER_ERR_ABORTED;
2671 if (debug_level > 1)
2672 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2673 ((msg[11] & 0xc0) == 0x80)? 'R' :
2674 (msg[11] & 0x80)? 'S' : 'I',
2675 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2676 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2677 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2679 if (!(tpdu[1] & 0x80))
2680 { /* This is an I-block. */
2681 retries = 0;
2682 if (sending)
2683 { /* last block sent was successful. */
2684 handle->t1_ns ^= 1;
2685 sending = 0;
2688 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2689 { /* Reponse does not match our sequence number. */
2690 msg = send_buffer;
2691 tpdu = msg+10;
2692 /* NAD: DAD=1, SAD=0 */
2693 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2694 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
2695 tpdu[2] = 0;
2696 tpdulen = 3;
2697 edc = compute_edc (tpdu, tpdulen, use_crc);
2698 if (use_crc)
2699 tpdu[tpdulen++] = (edc >> 8);
2700 tpdu[tpdulen++] = edc;
2702 continue;
2705 handle->t1_nr ^= 1;
2707 p = tpdu + 3; /* Skip the prologue field. */
2708 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2709 /* fixme: verify the checksum. */
2710 if (resp)
2712 if (n > maxresplen)
2714 DEBUGOUT_2 ("provided buffer too short for received data "
2715 "(%u/%u)\n",
2716 (unsigned int)n, (unsigned int)maxresplen);
2717 return CCID_DRIVER_ERR_INV_VALUE;
2720 memcpy (resp, p, n);
2721 resp += n;
2722 *nresp += n;
2723 maxresplen -= n;
2726 if (!(tpdu[1] & 0x20))
2727 return 0; /* No chaining requested - ready. */
2729 msg = send_buffer;
2730 tpdu = msg+10;
2731 /* NAD: DAD=1, SAD=0 */
2732 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2733 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
2734 tpdu[2] = 0;
2735 tpdulen = 3;
2736 edc = compute_edc (tpdu, tpdulen, use_crc);
2737 if (use_crc)
2738 tpdu[tpdulen++] = (edc >> 8);
2739 tpdu[tpdulen++] = edc;
2741 else if ((tpdu[1] & 0xc0) == 0x80)
2742 { /* This is a R-block. */
2743 if ( (tpdu[1] & 0x0f))
2744 { /* Error: repeat last block */
2745 if (++retries > 3)
2747 DEBUGOUT ("3 failed retries\n");
2748 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2750 msg = send_buffer;
2751 tpdulen = last_tpdulen;
2753 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
2754 { /* Response does not match our sequence number. */
2755 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2756 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2758 else if (sending)
2759 { /* Send next chunk. */
2760 retries = 0;
2761 msg = send_buffer;
2762 next_chunk = 1;
2763 handle->t1_ns ^= 1;
2765 else
2767 DEBUGOUT ("unexpected ACK R-block received\n");
2768 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2771 else
2772 { /* This is a S-block. */
2773 retries = 0;
2774 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d\n",
2775 (tpdu[1] & 0x20)? "response": "request",
2776 (tpdu[1] & 0x1f));
2777 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
2779 /* Information field size request. */
2780 unsigned char ifsc = tpdu[3];
2782 if (ifsc < 16 || ifsc > 254)
2783 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2785 msg = send_buffer;
2786 tpdu = msg+10;
2787 /* NAD: DAD=1, SAD=0 */
2788 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2789 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
2790 tpdu[2] = 1;
2791 tpdu[3] = ifsc;
2792 tpdulen = 4;
2793 edc = compute_edc (tpdu, tpdulen, use_crc);
2794 if (use_crc)
2795 tpdu[tpdulen++] = (edc >> 8);
2796 tpdu[tpdulen++] = edc;
2797 DEBUGOUT_1 ("T=1 requesting an ifsc=%d\n", ifsc);
2799 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
2801 /* Wait time extension request. */
2802 unsigned char bwi = tpdu[3];
2803 msg = send_buffer;
2804 tpdu = msg+10;
2805 /* NAD: DAD=1, SAD=0 */
2806 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2807 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
2808 tpdu[2] = 1;
2809 tpdu[3] = bwi;
2810 tpdulen = 4;
2811 edc = compute_edc (tpdu, tpdulen, use_crc);
2812 if (use_crc)
2813 tpdu[tpdulen++] = (edc >> 8);
2814 tpdu[tpdulen++] = edc;
2815 DEBUGOUT_1 ("T=1 waittime extension of bwi=%d\n", bwi);
2817 else
2818 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2820 } /* end T=1 protocol loop. */
2822 return 0;
2826 /* Send the CCID Secure command to the reader. APDU_BUF should
2827 contain the APDU template. PIN_MODE defines how the pin gets
2828 formatted:
2830 1 := The PIN is ASCII encoded and of variable length. The
2831 length of the PIN entered will be put into Lc by the reader.
2832 The APDU should me made up of 4 bytes without Lc.
2834 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2835 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2837 When called with RESP and NRESP set to NULL, the function will
2838 merely check whether the reader supports the secure command for the
2839 given APDU and PIN_MODE. */
2841 ccid_transceive_secure (ccid_driver_t handle,
2842 const unsigned char *apdu_buf, size_t apdu_buflen,
2843 int pin_mode, int pinlen_min, int pinlen_max,
2844 int pin_padlen,
2845 unsigned char *resp, size_t maxresplen, size_t *nresp)
2847 int rc;
2848 unsigned char send_buffer[10+259], recv_buffer[10+259];
2849 unsigned char *msg, *tpdu, *p;
2850 size_t msglen, tpdulen, n;
2851 unsigned char seqno;
2852 size_t dummy_nresp;
2853 int testmode;
2854 int cherry_mode = 0;
2856 testmode = !resp && !nresp;
2858 if (!nresp)
2859 nresp = &dummy_nresp;
2860 *nresp = 0;
2862 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2864 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2865 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2866 else
2867 return CCID_DRIVER_ERR_NO_KEYPAD;
2869 if (pin_mode != 1)
2870 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2872 if (pin_padlen != 0)
2873 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2875 if (!pinlen_min)
2876 pinlen_min = 1;
2877 if (!pinlen_max)
2878 pinlen_max = 25;
2880 /* Note that the 25 is the maximum value the SPR532 allows. */
2881 if (pinlen_min < 1 || pinlen_min > 25
2882 || pinlen_max < 1 || pinlen_max > 25
2883 || pinlen_min > pinlen_max)
2884 return CCID_DRIVER_ERR_INV_VALUE;
2886 /* We have only tested a few readers so better don't risk anything
2887 and do not allow the use with other readers. */
2888 switch (handle->id_vendor)
2890 case VENDOR_SCM: /* Tested with SPR 532. */
2891 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
2892 break;
2893 case VENDOR_CHERRY:
2894 /* The CHERRY XX44 keyboard echos an asterisk for each entered
2895 character on the keyboard channel. We use a special variant
2896 of PC_to_RDR_Secure which directs these characters to the
2897 smart card's bulk-in channel. We also need to append a zero
2898 Lc byte to the APDU. It seems that it will be replaced with
2899 the actual length instead of being appended before the APDU
2900 is send to the card. */
2901 cherry_mode = 1;
2902 break;
2903 default:
2904 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2907 if (testmode)
2908 return 0; /* Success */
2910 msg = send_buffer;
2911 if (handle->id_vendor == VENDOR_SCM)
2913 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
2914 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
2915 NULL, 0, NULL);
2916 if (rc)
2917 return rc;
2920 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
2921 msg[5] = 0; /* slot */
2922 msg[6] = seqno = handle->seqno++;
2923 msg[7] = 0; /* bBWI */
2924 msg[8] = 0; /* RFU */
2925 msg[9] = 0; /* RFU */
2926 msg[10] = 0; /* Perform PIN verification. */
2927 msg[11] = 0; /* Timeout in seconds. */
2928 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2929 if (handle->id_vendor == VENDOR_SCM)
2931 /* For the SPR532 the next 2 bytes need to be zero. We do this
2932 for all SCM products. Kudos to Martin Paljak for this
2933 hint. */
2934 msg[13] = msg[14] = 0;
2936 else
2938 msg[13] = 0x00; /* bmPINBlockString:
2939 0 bits of pin length to insert.
2940 0 bytes of PIN block size. */
2941 msg[14] = 0x00; /* bmPINLengthFormat:
2942 Units are bytes, position is 0. */
2945 /* The following is a little endian word. */
2946 msg[15] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
2947 msg[16] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
2949 msg[17] = 0x02; /* bEntryValidationCondition:
2950 Validation key pressed */
2951 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
2952 msg[17] |= 0x01; /* Max size reached. */
2953 msg[18] = 0xff; /* bNumberMessage: Default. */
2954 msg[19] = 0x04; /* wLangId-High. */
2955 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
2956 msg[21] = 0; /* bMsgIndex. */
2957 /* bTeoProlog follows: */
2958 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2959 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
2960 msg[24] = 0; /* The apdulen will be filled in by the reader. */
2961 /* APDU follows: */
2962 msg[25] = apdu_buf[0]; /* CLA */
2963 msg[26] = apdu_buf[1]; /* INS */
2964 msg[27] = apdu_buf[2]; /* P1 */
2965 msg[28] = apdu_buf[3]; /* P2 */
2966 msglen = 29;
2967 if (cherry_mode)
2968 msg[msglen++] = 0;
2969 /* An EDC is not required. */
2970 set_msg_len (msg, msglen - 10);
2972 rc = bulk_out (handle, msg, msglen, 0);
2973 if (rc)
2974 return rc;
2976 msg = recv_buffer;
2977 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2978 RDR_to_PC_DataBlock, seqno, 30000, 0);
2979 if (rc)
2980 return rc;
2982 tpdu = msg + 10;
2983 tpdulen = msglen - 10;
2985 if (handle->apdu_level)
2987 if (resp)
2989 if (tpdulen > maxresplen)
2991 DEBUGOUT_2 ("provided buffer too short for received data "
2992 "(%u/%u)\n",
2993 (unsigned int)tpdulen, (unsigned int)maxresplen);
2994 return CCID_DRIVER_ERR_INV_VALUE;
2997 memcpy (resp, tpdu, tpdulen);
2998 *nresp = tpdulen;
3000 return 0;
3003 if (tpdulen < 4)
3005 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3006 return CCID_DRIVER_ERR_ABORTED;
3008 if (debug_level > 1)
3009 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3010 ((msg[11] & 0xc0) == 0x80)? 'R' :
3011 (msg[11] & 0x80)? 'S' : 'I',
3012 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3013 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3014 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3016 if (!(tpdu[1] & 0x80))
3017 { /* This is an I-block. */
3018 /* Last block sent was successful. */
3019 handle->t1_ns ^= 1;
3021 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3022 { /* Reponse does not match our sequence number. */
3023 DEBUGOUT ("I-block with wrong seqno received\n");
3024 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3027 handle->t1_nr ^= 1;
3029 p = tpdu + 3; /* Skip the prologue field. */
3030 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3031 /* fixme: verify the checksum. */
3032 if (resp)
3034 if (n > maxresplen)
3036 DEBUGOUT_2 ("provided buffer too short for received data "
3037 "(%u/%u)\n",
3038 (unsigned int)n, (unsigned int)maxresplen);
3039 return CCID_DRIVER_ERR_INV_VALUE;
3042 memcpy (resp, p, n);
3043 resp += n;
3044 *nresp += n;
3045 maxresplen -= n;
3048 if (!(tpdu[1] & 0x20))
3049 return 0; /* No chaining requested - ready. */
3051 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3052 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3054 else if ((tpdu[1] & 0xc0) == 0x80)
3055 { /* This is a R-block. */
3056 if ( (tpdu[1] & 0x0f))
3057 { /* Error: repeat last block */
3058 DEBUGOUT ("No retries supported for Secure operation\n");
3059 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3061 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3062 { /* Reponse does not match our sequence number. */
3063 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3064 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3066 else
3067 { /* Send next chunk. */
3068 DEBUGOUT ("chaining not supported on Secure operation\n");
3069 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3072 else
3073 { /* This is a S-block. */
3074 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d for Secure operation\n",
3075 (tpdu[1] & 0x20)? "response": "request",
3076 (tpdu[1] & 0x1f));
3077 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3080 return 0;
3086 #ifdef TEST
3089 static void
3090 print_error (int err)
3092 const char *p;
3093 char buf[50];
3095 switch (err)
3097 case 0: p = "success";
3098 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3099 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3100 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3101 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3102 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3103 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3104 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3105 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3106 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3107 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3108 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3109 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3110 default: sprintf (buf, "0x%05x", err); p = buf; break;
3112 fprintf (stderr, "operation failed: %s\n", p);
3116 static void
3117 print_data (const unsigned char *data, size_t length)
3119 if (length >= 2)
3121 fprintf (stderr, "operation status: %02X%02X\n",
3122 data[length-2], data[length-1]);
3123 length -= 2;
3125 if (length)
3127 fputs (" returned data:", stderr);
3128 for (; length; length--, data++)
3129 fprintf (stderr, " %02X", *data);
3130 putc ('\n', stderr);
3134 static void
3135 print_result (int rc, const unsigned char *data, size_t length)
3137 if (rc)
3138 print_error (rc);
3139 else if (data)
3140 print_data (data, length);
3144 main (int argc, char **argv)
3146 int rc;
3147 ccid_driver_t ccid;
3148 int slotstat;
3149 unsigned char result[512];
3150 size_t resultlen;
3151 int no_pinpad = 0;
3152 int verify_123456 = 0;
3153 int did_verify = 0;
3154 int no_poll = 0;
3156 if (argc)
3158 argc--;
3159 argv++;
3162 while (argc)
3164 if ( !strcmp (*argv, "--list"))
3166 char *p;
3167 p = ccid_get_reader_list ();
3168 if (!p)
3169 return 1;
3170 fputs (p, stderr);
3171 free (p);
3172 return 0;
3174 else if ( !strcmp (*argv, "--debug"))
3176 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3177 argc--; argv++;
3179 else if ( !strcmp (*argv, "--no-poll"))
3181 no_poll = 1;
3182 argc--; argv++;
3184 else if ( !strcmp (*argv, "--no-pinpad"))
3186 no_pinpad = 1;
3187 argc--; argv++;
3189 else if ( !strcmp (*argv, "--verify-123456"))
3191 verify_123456 = 1;
3192 argc--; argv++;
3194 else
3195 break;
3198 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3199 if (rc)
3200 return 1;
3202 if (!no_poll)
3203 ccid_poll (ccid);
3204 fputs ("getting ATR ...\n", stderr);
3205 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3206 if (rc)
3208 print_error (rc);
3209 return 1;
3212 if (!no_poll)
3213 ccid_poll (ccid);
3214 fputs ("getting slot status ...\n", stderr);
3215 rc = ccid_slot_status (ccid, &slotstat);
3216 if (rc)
3218 print_error (rc);
3219 return 1;
3222 if (!no_poll)
3223 ccid_poll (ccid);
3225 fputs ("selecting application OpenPGP ....\n", stderr);
3227 static unsigned char apdu[] = {
3228 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3229 rc = ccid_transceive (ccid,
3230 apdu, sizeof apdu,
3231 result, sizeof result, &resultlen);
3232 print_result (rc, result, resultlen);
3236 if (!no_poll)
3237 ccid_poll (ccid);
3239 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3241 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3242 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3243 result, sizeof result, &resultlen);
3244 print_result (rc, result, resultlen);
3247 if (!no_pinpad)
3251 if (!no_pinpad)
3253 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3256 if (ccid_transceive_secure (ccid,
3257 apdu, sizeof apdu,
3258 1, 0, 0, 0,
3259 NULL, 0, NULL))
3260 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3261 else
3263 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3265 rc = ccid_transceive_secure (ccid,
3266 apdu, sizeof apdu,
3267 1, 0, 0, 0,
3268 result, sizeof result, &resultlen);
3269 print_result (rc, result, resultlen);
3270 did_verify = 1;
3274 if (verify_123456 && !did_verify)
3276 fputs ("verifying that CHV1 is 123456....\n", stderr);
3278 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3279 6, '1','2','3','4','5','6'};
3280 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3281 result, sizeof result, &resultlen);
3282 print_result (rc, result, resultlen);
3286 if (!rc)
3288 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3290 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3291 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3292 result, sizeof result, &resultlen);
3293 print_result (rc, result, resultlen);
3297 ccid_close_reader (ccid);
3299 return 0;
3303 * Local Variables:
3304 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3305 * End:
3307 #endif /*TEST*/
3308 #endif /*HAVE_LIBUSB*/