Fixed EOF detection for encrypted packets.
[gnupg.git] / scd / ccid-driver.c
blob844058e0b8802dc4d641c065459f52f6009da777
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007
3 * 2008, 2009 Free Software Foundation, Inc.
4 * Written by Werner Koch.
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 * ALTERNATIVELY, this file may be distributed under the terms of the
22 * following license, in which case the provisions of this license are
23 * required INSTEAD OF the GNU General Public License. If you wish to
24 * allow use of your version of this file only under the terms of the
25 * GNU General Public License, and not to allow others to use your
26 * version of this file under the terms of the following license,
27 * indicate your decision by deleting this paragraph and the license
28 * below.
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
32 * are met:
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, and the entire permission notice in its entirety,
35 * including the disclaimer of warranties.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
39 * 3. The name of the author may not be used to endorse or promote
40 * products derived from this software without specific prior
41 * written permission.
43 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
44 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53 * OF THE POSSIBILITY OF SUCH DAMAGE.
55 * $Date$
59 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
60 smartcard via a reader connected to the USB.
62 This is a limited driver allowing to use some CCID drivers directly
63 without any other specila drivers. This is a fallback driver to be
64 used when nothing else works or the system should be kept minimal
65 for security reasons. It makes use of the libusb library to gain
66 portable access to USB.
68 This driver has been tested with the SCM SCR335 and SPR532
69 smartcard readers and requires that a reader implements APDU or
70 TPDU level exchange and does fully automatic initialization.
73 #ifdef HAVE_CONFIG_H
74 # include <config.h>
75 #endif
77 #if defined(HAVE_LIBUSB) || defined(TEST)
79 #include <errno.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <assert.h>
84 #include <sys/types.h>
85 #include <sys/stat.h>
86 #include <fcntl.h>
87 #include <time.h>
88 #ifdef HAVE_PTH
89 # include <pth.h>
90 #endif /*HAVE_PTH*/
92 #include <usb.h>
94 #include "ccid-driver.h"
96 #define DRVNAME "ccid-driver: "
99 /* Depending on how this source is used we either define our error
100 output to go to stderr or to the jnlib based logging functions. We
101 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
102 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
104 #if defined(GNUPG_MAJOR_VERSION) \
105 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
107 #if defined(GNUPG_SCD_MAIN_HEADER)
108 # include GNUPG_SCD_MAIN_HEADER
109 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
110 # include "options.h"
111 # include "util.h"
112 # include "memory.h"
113 # include "cardglue.h"
114 # else /* This is the modularized GnuPG 1.9 or later. */
115 # include "scdaemon.h"
116 #endif
119 # define DEBUGOUT(t) do { if (debug_level) \
120 log_debug (DRVNAME t); } while (0)
121 # define DEBUGOUT_1(t,a) do { if (debug_level) \
122 log_debug (DRVNAME t,(a)); } while (0)
123 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
124 log_debug (DRVNAME t,(a),(b)); } while (0)
125 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
126 log_debug (DRVNAME t,(a),(b),(c));} while (0)
127 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
128 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
129 # define DEBUGOUT_CONT(t) do { if (debug_level) \
130 log_printf (t); } while (0)
131 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
132 log_printf (t,(a)); } while (0)
133 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
134 log_printf (t,(a),(b)); } while (0)
135 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
136 log_printf (t,(a),(b),(c)); } while (0)
137 # define DEBUGOUT_LF() do { if (debug_level) \
138 log_printf ("\n"); } while (0)
140 #else /* Other usage of this source - don't use gnupg specifics. */
142 # define DEBUGOUT(t) do { if (debug_level) \
143 fprintf (stderr, DRVNAME t); } while (0)
144 # define DEBUGOUT_1(t,a) do { if (debug_level) \
145 fprintf (stderr, DRVNAME t, (a)); } while (0)
146 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
147 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
148 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
149 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
150 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
151 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
152 # define DEBUGOUT_CONT(t) do { if (debug_level) \
153 fprintf (stderr, t); } while (0)
154 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
155 fprintf (stderr, t, (a)); } while (0)
156 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
157 fprintf (stderr, t, (a), (b)); } while (0)
158 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
159 fprintf (stderr, t, (a), (b), (c)); } while (0)
160 # define DEBUGOUT_LF() do { if (debug_level) \
161 putc ('\n', stderr); } while (0)
163 #endif /* This source not used by scdaemon. */
166 #ifndef EAGAIN
167 #define EAGAIN EWOULDBLOCK
168 #endif
172 enum {
173 RDR_to_PC_NotifySlotChange= 0x50,
174 RDR_to_PC_HardwareError = 0x51,
176 PC_to_RDR_SetParameters = 0x61,
177 PC_to_RDR_IccPowerOn = 0x62,
178 PC_to_RDR_IccPowerOff = 0x63,
179 PC_to_RDR_GetSlotStatus = 0x65,
180 PC_to_RDR_Secure = 0x69,
181 PC_to_RDR_T0APDU = 0x6a,
182 PC_to_RDR_Escape = 0x6b,
183 PC_to_RDR_GetParameters = 0x6c,
184 PC_to_RDR_ResetParameters = 0x6d,
185 PC_to_RDR_IccClock = 0x6e,
186 PC_to_RDR_XfrBlock = 0x6f,
187 PC_to_RDR_Mechanical = 0x71,
188 PC_to_RDR_Abort = 0x72,
189 PC_to_RDR_SetDataRate = 0x73,
191 RDR_to_PC_DataBlock = 0x80,
192 RDR_to_PC_SlotStatus = 0x81,
193 RDR_to_PC_Parameters = 0x82,
194 RDR_to_PC_Escape = 0x83,
195 RDR_to_PC_DataRate = 0x84
199 /* Two macro to detect whether a CCID command has failed and to get
200 the error code. These macros assume that we can access the
201 mandatory first 10 bytes of a CCID message in BUF. */
202 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
203 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
206 /* We need to know the vendor to do some hacks. */
207 enum {
208 VENDOR_CHERRY = 0x046a,
209 VENDOR_SCM = 0x04e6,
210 VENDOR_OMNIKEY= 0x076b,
211 VENDOR_GEMPC = 0x08e6,
212 VENDOR_KAAN = 0x0d46
215 /* A list and a table with special transport descriptions. */
216 enum {
217 TRANSPORT_USB = 0, /* Standard USB transport. */
218 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
221 static struct
223 char *name; /* Device name. */
224 int type;
226 } transports[] = {
227 { "/dev/cmx0", TRANSPORT_CM4040 },
228 { "/dev/cmx1", TRANSPORT_CM4040 },
229 { NULL },
233 /* Store information on the driver's state. A pointer to such a
234 structure is used as handle for most functions. */
235 struct ccid_driver_s
237 usb_dev_handle *idev;
238 char *rid;
239 int dev_fd; /* -1 for USB transport or file descriptor of the
240 transport device. */
241 unsigned short id_vendor;
242 unsigned short id_product;
243 unsigned short bcd_device;
244 int ifc_no;
245 int ep_bulk_out;
246 int ep_bulk_in;
247 int ep_intr;
248 int seqno;
249 unsigned char t1_ns;
250 unsigned char t1_nr;
251 unsigned char nonnull_nad;
252 int max_ifsd;
253 int ifsd;
254 int ifsc;
255 unsigned char apdu_level:2; /* Reader supports short APDU level
256 exchange. With a value of 2 short
257 and extended level is supported.*/
258 unsigned int auto_ifsd:1;
259 unsigned int powered_off:1;
260 unsigned int has_pinpad:2;
261 unsigned int enodev_seen:1;
263 time_t last_progress; /* Last time we sent progress line. */
265 /* The progress callback and its first arg as supplied to
266 ccid_set_progress_cb. */
267 void (*progress_cb)(void *, const char *, int, int, int);
268 void *progress_cb_arg;
272 static int initialized_usb; /* Tracks whether USB has been initialized. */
273 static int debug_level; /* Flag to control the debug output.
274 0 = No debugging
275 1 = USB I/O info
276 2 = Level 1 + T=1 protocol tracing
277 3 = Level 2 + USB/I/O tracing of SlotStatus.
281 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
282 int use_crc);
283 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
284 int no_debug);
285 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
286 size_t *nread, int expected_type, int seqno, int timeout,
287 int no_debug);
288 static int abort_cmd (ccid_driver_t handle, int seqno);
290 /* Convert a little endian stored 4 byte value into an unsigned
291 integer. */
292 static unsigned int
293 convert_le_u32 (const unsigned char *buf)
295 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
299 /* Convert a little endian stored 2 byte value into an unsigned
300 integer. */
301 static unsigned int
302 convert_le_u16 (const unsigned char *buf)
304 return buf[0] | (buf[1] << 8);
307 static void
308 set_msg_len (unsigned char *msg, unsigned int length)
310 msg[1] = length;
311 msg[2] = length >> 8;
312 msg[3] = length >> 16;
313 msg[4] = length >> 24;
317 static void
318 my_sleep (int seconds)
320 #ifdef HAVE_PTH
321 /* With Pth we also call the standard sleep(0) so that the process
322 may give up its timeslot. */
323 if (!seconds)
325 # ifdef HAVE_W32_SYSTEM
326 Sleep (0);
327 # else
328 sleep (0);
329 # endif
331 pth_sleep (seconds);
332 #else
333 # ifdef HAVE_W32_SYSTEM
334 Sleep (seconds*1000);
335 # else
336 sleep (seconds);
337 # endif
338 #endif
341 static void
342 print_progress (ccid_driver_t handle)
344 time_t ct = time (NULL);
346 /* We don't want to print progress lines too often. */
347 if (ct == handle->last_progress)
348 return;
350 if (handle->progress_cb)
351 handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
353 handle->last_progress = ct;
358 /* Pint an error message for a failed CCID command including a textual
359 error code. MSG shall be the CCID message at a minimum of 10 bytes. */
360 static void
361 print_command_failed (const unsigned char *msg)
363 const char *t;
364 char buffer[100];
365 int ec;
367 if (!debug_level)
368 return;
370 ec = CCID_ERROR_CODE (msg);
371 switch (ec)
373 case 0x00: t = "Command not supported"; break;
375 case 0xE0: t = "Slot busy"; break;
376 case 0xEF: t = "PIN cancelled"; break;
377 case 0xF0: t = "PIN timeout"; break;
379 case 0xF2: t = "Automatic sequence ongoing"; break;
380 case 0xF3: t = "Deactivated Protocol"; break;
381 case 0xF4: t = "Procedure byte conflict"; break;
382 case 0xF5: t = "ICC class not supported"; break;
383 case 0xF6: t = "ICC protocol not supported"; break;
384 case 0xF7: t = "Bad checksum in ATR"; break;
385 case 0xF8: t = "Bad TS in ATR"; break;
387 case 0xFB: t = "An all inclusive hardware error occurred"; break;
388 case 0xFC: t = "Overrun error while talking to the ICC"; break;
389 case 0xFD: t = "Parity error while talking to the ICC"; break;
390 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
391 case 0xFF: t = "Host aborted the current activity"; break;
393 default:
394 if (ec > 0 && ec < 128)
395 sprintf (buffer, "Parameter error at offset %d", ec);
396 else
397 sprintf (buffer, "Error code %02X", ec);
398 t = buffer;
399 break;
401 DEBUGOUT_1 ("CCID command failed: %s\n", t);
405 static void
406 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
408 int any = 0;
410 for (; off < datalen; off++)
412 if (!any || !(off % 16))
414 if (any)
415 DEBUGOUT_LF ();
416 DEBUGOUT_1 (" [%04lu] ", (unsigned long) off);
418 DEBUGOUT_CONT_1 (" %02X", data[off]);
419 any = 1;
421 if (any && (off % 16))
422 DEBUGOUT_LF ();
426 static void
427 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
429 DEBUGOUT_1 ("%s:\n", name);
430 if (msglen < 7)
431 return;
432 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
433 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
434 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
438 static void
439 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
441 print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
442 if (msglen < 10)
443 return;
444 DEBUGOUT_2 (" bPowerSelect ......: 0x%02x (%s)\n", msg[7],
445 msg[7] == 0? "auto":
446 msg[7] == 1? "5.0 V":
447 msg[7] == 2? "3.0 V":
448 msg[7] == 3? "1.8 V":"");
449 print_pr_data (msg, msglen, 8);
453 static void
454 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
456 print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
457 print_pr_data (msg, msglen, 7);
461 static void
462 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
464 print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
465 print_pr_data (msg, msglen, 7);
469 static void
470 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
472 unsigned int val;
474 print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
475 if (msglen < 10)
476 return;
477 DEBUGOUT_1 (" bBWI ..............: 0x%02x\n", msg[7]);
478 val = convert_le_u16 (msg+8);
479 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
480 val == 1? " (continued)":
481 val == 2? " (continues+ends)":
482 val == 3? " (continues+continued)":
483 val == 16? " (DataBlock-expected)":"");
484 print_pr_data (msg, msglen, 10);
488 static void
489 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
491 print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
492 print_pr_data (msg, msglen, 7);
496 static void
497 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
499 print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
500 print_pr_data (msg, msglen, 7);
504 static void
505 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
507 print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
508 if (msglen < 10)
509 return;
510 DEBUGOUT_1 (" bProtocolNum ......: 0x%02x\n", msg[7]);
511 print_pr_data (msg, msglen, 8);
515 static void
516 print_p2r_escape (const unsigned char *msg, size_t msglen)
518 print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
519 print_pr_data (msg, msglen, 7);
523 static void
524 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
526 print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
527 if (msglen < 10)
528 return;
529 DEBUGOUT_1 (" bClockCommand .....: 0x%02x\n", msg[7]);
530 print_pr_data (msg, msglen, 8);
534 static void
535 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
537 print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
538 if (msglen < 10)
539 return;
540 DEBUGOUT_1 (" bmChanges .........: 0x%02x\n", msg[7]);
541 DEBUGOUT_1 (" bClassGetResponse .: 0x%02x\n", msg[8]);
542 DEBUGOUT_1 (" bClassEnvelope ....: 0x%02x\n", msg[9]);
543 print_pr_data (msg, msglen, 10);
547 static void
548 print_p2r_secure (const unsigned char *msg, size_t msglen)
550 unsigned int val;
552 print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
553 if (msglen < 10)
554 return;
555 DEBUGOUT_1 (" bBMI ..............: 0x%02x\n", msg[7]);
556 val = convert_le_u16 (msg+8);
557 DEBUGOUT_2 (" wLevelParameter ...: 0x%04x%s\n", val,
558 val == 1? " (continued)":
559 val == 2? " (continues+ends)":
560 val == 3? " (continues+continued)":
561 val == 16? " (DataBlock-expected)":"");
562 print_pr_data (msg, msglen, 10);
566 static void
567 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
569 print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
570 if (msglen < 10)
571 return;
572 DEBUGOUT_1 (" bFunction .........: 0x%02x\n", msg[7]);
573 print_pr_data (msg, msglen, 8);
577 static void
578 print_p2r_abort (const unsigned char *msg, size_t msglen)
580 print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
581 print_pr_data (msg, msglen, 7);
585 static void
586 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
588 print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
589 if (msglen < 10)
590 return;
591 print_pr_data (msg, msglen, 7);
595 static void
596 print_p2r_unknown (const unsigned char *msg, size_t msglen)
598 print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
599 if (msglen < 10)
600 return;
601 print_pr_data (msg, msglen, 0);
605 static void
606 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
608 DEBUGOUT_1 ("%s:\n", name);
609 if (msglen < 9)
610 return;
611 DEBUGOUT_1 (" dwLength ..........: %u\n", convert_le_u32 (msg+1));
612 DEBUGOUT_1 (" bSlot .............: %u\n", msg[5]);
613 DEBUGOUT_1 (" bSeq ..............: %u\n", msg[6]);
614 DEBUGOUT_1 (" bStatus ...........: %u\n", msg[7]);
615 if (msg[8])
616 DEBUGOUT_1 (" bError ............: %u\n", msg[8]);
620 static void
621 print_r2p_datablock (const unsigned char *msg, size_t msglen)
623 print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
624 if (msglen < 10)
625 return;
626 if (msg[9])
627 DEBUGOUT_2 (" bChainParameter ...: 0x%02x%s\n", msg[9],
628 msg[9] == 1? " (continued)":
629 msg[9] == 2? " (continues+ends)":
630 msg[9] == 3? " (continues+continued)":
631 msg[9] == 16? " (XferBlock-expected)":"");
632 print_pr_data (msg, msglen, 10);
636 static void
637 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
639 print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
640 if (msglen < 10)
641 return;
642 DEBUGOUT_2 (" bClockStatus ......: 0x%02x%s\n", msg[9],
643 msg[9] == 0? " (running)":
644 msg[9] == 1? " (stopped-L)":
645 msg[9] == 2? " (stopped-H)":
646 msg[9] == 3? " (stopped)":"");
647 print_pr_data (msg, msglen, 10);
651 static void
652 print_r2p_parameters (const unsigned char *msg, size_t msglen)
654 print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
655 if (msglen < 10)
656 return;
658 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
659 if (msglen == 17 && msg[9] == 1)
661 /* Protocol T=1. */
662 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
663 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
664 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
665 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
666 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
667 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
668 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
670 else
671 print_pr_data (msg, msglen, 10);
675 static void
676 print_r2p_escape (const unsigned char *msg, size_t msglen)
678 print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
679 if (msglen < 10)
680 return;
681 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
682 print_pr_data (msg, msglen, 10);
686 static void
687 print_r2p_datarate (const unsigned char *msg, size_t msglen)
689 print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
690 if (msglen < 10)
691 return;
692 if (msglen >= 18)
694 DEBUGOUT_1 (" dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
695 DEBUGOUT_1 (" dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
696 print_pr_data (msg, msglen, 18);
698 else
699 print_pr_data (msg, msglen, 10);
703 static void
704 print_r2p_unknown (const unsigned char *msg, size_t msglen)
706 print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
707 if (msglen < 10)
708 return;
709 DEBUGOUT_1 (" bMessageType ......: %02X\n", msg[0]);
710 DEBUGOUT_1 (" buffer[9] .........: %02X\n", msg[9]);
711 print_pr_data (msg, msglen, 10);
715 /* Given a handle used for special transport prepare it for use. In
716 particular setup all information in way that resembles what
717 parse_cccid_descriptor does. */
718 static void
719 prepare_special_transport (ccid_driver_t handle)
721 assert (!handle->id_vendor);
723 handle->nonnull_nad = 0;
724 handle->auto_ifsd = 0;
725 handle->max_ifsd = 32;
726 handle->ifsd = 0;
727 handle->has_pinpad = 0;
728 handle->apdu_level = 0;
729 switch (handle->id_product)
731 case TRANSPORT_CM4040:
732 DEBUGOUT ("setting up transport for CardMan 4040\n");
733 handle->apdu_level = 1;
734 break;
736 default: assert (!"transport not defined");
740 /* Parse a CCID descriptor, optionally print all available features
741 and test whether this reader is usable by this driver. Returns 0
742 if it is usable.
744 Note, that this code is based on the one in lsusb.c of the
745 usb-utils package, I wrote on 2003-09-01. -wk. */
746 static int
747 parse_ccid_descriptor (ccid_driver_t handle,
748 const unsigned char *buf, size_t buflen)
750 unsigned int i;
751 unsigned int us;
752 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
755 handle->nonnull_nad = 0;
756 handle->auto_ifsd = 0;
757 handle->max_ifsd = 32;
758 handle->ifsd = 0;
759 handle->has_pinpad = 0;
760 handle->apdu_level = 0;
761 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
762 handle->id_vendor, handle->id_product, handle->bcd_device);
763 if (buflen < 54 || buf[0] < 54)
765 DEBUGOUT ("CCID device descriptor is too short\n");
766 return -1;
769 DEBUGOUT ("ChipCard Interface Descriptor:\n");
770 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
771 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
772 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
773 if (buf[3] != 1 || buf[2] != 0)
774 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
775 DEBUGOUT_LF ();
777 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
778 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
779 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
780 : buf[5] == 3? "1.8V":"?"));
782 us = convert_le_u32 (buf+6);
783 DEBUGOUT_1 (" dwProtocols %5u ", us);
784 if ((us & 1))
785 DEBUGOUT_CONT (" T=0");
786 if ((us & 2))
788 DEBUGOUT_CONT (" T=1");
789 have_t1 = 1;
791 if ((us & ~3))
792 DEBUGOUT_CONT (" (Invalid values detected)");
793 DEBUGOUT_LF ();
795 us = convert_le_u32(buf+10);
796 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
797 us = convert_le_u32(buf+14);
798 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
799 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
800 us = convert_le_u32(buf+19);
801 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
802 us = convert_le_u32(buf+23);
803 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
804 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
806 us = convert_le_u32(buf+28);
807 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
808 handle->max_ifsd = us;
810 us = convert_le_u32(buf+32);
811 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
812 if ((us&1))
813 DEBUGOUT_CONT ( " 2-wire");
814 if ((us&2))
815 DEBUGOUT_CONT ( " 3-wire");
816 if ((us&4))
817 DEBUGOUT_CONT ( " I2C");
818 DEBUGOUT_LF ();
820 us = convert_le_u32(buf+36);
821 DEBUGOUT_1 (" dwMechanical %08X ", us);
822 if ((us & 1))
823 DEBUGOUT_CONT (" accept");
824 if ((us & 2))
825 DEBUGOUT_CONT (" eject");
826 if ((us & 4))
827 DEBUGOUT_CONT (" capture");
828 if ((us & 8))
829 DEBUGOUT_CONT (" lock");
830 DEBUGOUT_LF ();
832 us = convert_le_u32(buf+40);
833 DEBUGOUT_1 (" dwFeatures %08X\n", us);
834 if ((us & 0x0002))
836 DEBUGOUT (" Auto configuration based on ATR\n");
837 have_auto_conf = 1;
839 if ((us & 0x0004))
840 DEBUGOUT (" Auto activation on insert\n");
841 if ((us & 0x0008))
842 DEBUGOUT (" Auto voltage selection\n");
843 if ((us & 0x0010))
844 DEBUGOUT (" Auto clock change\n");
845 if ((us & 0x0020))
846 DEBUGOUT (" Auto baud rate change\n");
847 if ((us & 0x0040))
848 DEBUGOUT (" Auto parameter negotation made by CCID\n");
849 else if ((us & 0x0080))
850 DEBUGOUT (" Auto PPS made by CCID\n");
851 else if ((us & (0x0040 | 0x0080)))
852 DEBUGOUT (" WARNING: conflicting negotation features\n");
854 if ((us & 0x0100))
855 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
856 if ((us & 0x0200))
858 DEBUGOUT (" NAD value other than 0x00 accepted\n");
859 handle->nonnull_nad = 1;
861 if ((us & 0x0400))
863 DEBUGOUT (" Auto IFSD exchange\n");
864 handle->auto_ifsd = 1;
867 if ((us & 0x00010000))
869 DEBUGOUT (" TPDU level exchange\n");
870 have_tpdu = 1;
872 else if ((us & 0x00020000))
874 DEBUGOUT (" Short APDU level exchange\n");
875 handle->apdu_level = 1;
877 else if ((us & 0x00040000))
879 DEBUGOUT (" Short and extended APDU level exchange\n");
880 handle->apdu_level = 2;
882 else if ((us & 0x00070000))
883 DEBUGOUT (" WARNING: conflicting exchange levels\n");
885 us = convert_le_u32(buf+44);
886 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
888 DEBUGOUT ( " bClassGetResponse ");
889 if (buf[48] == 0xff)
890 DEBUGOUT_CONT ("echo\n");
891 else
892 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
894 DEBUGOUT ( " bClassEnvelope ");
895 if (buf[49] == 0xff)
896 DEBUGOUT_CONT ("echo\n");
897 else
898 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
900 DEBUGOUT ( " wlcdLayout ");
901 if (!buf[50] && !buf[51])
902 DEBUGOUT_CONT ("none\n");
903 else
904 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
906 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
907 if ((buf[52] & 1))
909 DEBUGOUT_CONT ( " verification");
910 handle->has_pinpad |= 1;
912 if ((buf[52] & 2))
914 DEBUGOUT_CONT ( " modification");
915 handle->has_pinpad |= 2;
917 DEBUGOUT_LF ();
919 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
921 if (buf[0] > 54) {
922 DEBUGOUT (" junk ");
923 for (i=54; i < buf[0]-54; i++)
924 DEBUGOUT_CONT_1 (" %02X", buf[i]);
925 DEBUGOUT_LF ();
928 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
930 DEBUGOUT ("this drivers requires that the reader supports T=1, "
931 "TPDU or APDU level exchange and auto configuration - "
932 "this is not available\n");
933 return -1;
937 /* SCM drivers get stuck in their internal USB stack if they try to
938 send a frame of n*wMaxPacketSize back to us. Given that
939 wMaxPacketSize is 64 for these readers we set the IFSD to a value
940 lower than that:
941 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
942 Product Ids:
943 0xe001 - SCR 331
944 0x5111 - SCR 331-DI
945 0x5115 - SCR 335
946 0xe003 - SPR 532
947 The
948 0x5117 - SCR 3320 USB ID-000 reader
949 seems to be very slow but enabling this workaround boosts the
950 performance to a a more or less acceptable level (tested by David).
953 if (handle->id_vendor == VENDOR_SCM
954 && handle->max_ifsd > 48
955 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
956 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
957 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
958 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
959 ||(handle->id_product == 0x5117 && handle->bcd_device < 0x0522)
962 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
963 handle->max_ifsd = 48;
967 return 0;
971 static char *
972 get_escaped_usb_string (usb_dev_handle *idev, int idx,
973 const char *prefix, const char *suffix)
975 int rc;
976 unsigned char buf[280];
977 unsigned char *s;
978 unsigned int langid;
979 size_t i, n, len;
980 char *result;
982 if (!idx)
983 return NULL;
985 /* Fixme: The next line is for the current Valgrid without support
986 for USB IOCTLs. */
987 memset (buf, 0, sizeof buf);
989 /* First get the list of supported languages and use the first one.
990 If we do don't find it we try to use English. Note that this is
991 all in a 2 bute Unicode encoding using little endian. */
992 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
993 (USB_DT_STRING << 8), 0,
994 (char*)buf, sizeof buf, 1000 /* ms timeout */);
995 if (rc < 4)
996 langid = 0x0409; /* English. */
997 else
998 langid = (buf[3] << 8) | buf[2];
1000 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1001 (USB_DT_STRING << 8) + idx, langid,
1002 (char*)buf, sizeof buf, 1000 /* ms timeout */);
1003 if (rc < 2 || buf[1] != USB_DT_STRING)
1004 return NULL; /* Error or not a string. */
1005 len = buf[0];
1006 if (len > rc)
1007 return NULL; /* Larger than our buffer. */
1009 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1011 if (s[1])
1012 n++; /* High byte set. */
1013 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1014 n += 3 ;
1015 else
1016 n++;
1019 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1020 if (!result)
1021 return NULL;
1023 strcpy (result, prefix);
1024 n = strlen (prefix);
1025 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1027 if (s[1])
1028 result[n++] = '\xff'; /* High byte set. */
1029 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1031 sprintf (result+n, "%%%02X", *s);
1032 n += 3;
1034 else
1035 result[n++] = *s;
1037 strcpy (result+n, suffix);
1039 return result;
1042 /* This function creates an reader id to be used to find the same
1043 physical reader after a reset. It returns an allocated and possibly
1044 percent escaped string or NULL if not enough memory is available. */
1045 static char *
1046 make_reader_id (usb_dev_handle *idev,
1047 unsigned int vendor, unsigned int product,
1048 unsigned char serialno_index)
1050 char *rid;
1051 char prefix[20];
1053 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1054 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1055 if (!rid)
1057 rid = malloc (strlen (prefix) + 3 + 1);
1058 if (!rid)
1059 return NULL;
1060 strcpy (rid, prefix);
1061 strcat (rid, "X:0");
1063 return rid;
1067 /* Helper to find the endpoint from an interface descriptor. */
1068 static int
1069 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1071 int no;
1072 int want_bulk_in = 0;
1074 if (mode == 1)
1075 want_bulk_in = 0x80;
1076 for (no=0; no < ifcdesc->bNumEndpoints; no++)
1078 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1079 if (ep->bDescriptorType != USB_DT_ENDPOINT)
1081 else if (mode == 2
1082 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1083 == USB_ENDPOINT_TYPE_INTERRUPT)
1084 && (ep->bEndpointAddress & 0x80))
1085 return (ep->bEndpointAddress & 0x0f);
1086 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1087 == USB_ENDPOINT_TYPE_BULK)
1088 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1089 return (ep->bEndpointAddress & 0x0f);
1091 /* Should never happen. */
1092 return mode == 2? 0x83 : mode == 1? 0x82 :1;
1096 /* Helper for scan_or_find_devices. This function returns true if a
1097 requested device has been found or the caller should stop scanning
1098 for other reasons. */
1099 static int
1100 scan_or_find_usb_device (int scan_mode,
1101 int *readerno, int *count, char **rid_list,
1102 const char *readerid,
1103 struct usb_device *dev,
1104 char **r_rid,
1105 struct usb_device **r_dev,
1106 usb_dev_handle **r_idev,
1107 unsigned char **ifcdesc_extra,
1108 size_t *ifcdesc_extra_len,
1109 int *interface_number,
1110 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1112 int cfg_no;
1113 int ifc_no;
1114 int set_no;
1115 struct usb_config_descriptor *config;
1116 struct usb_interface *interface;
1117 struct usb_interface_descriptor *ifcdesc;
1118 char *rid;
1119 usb_dev_handle *idev;
1121 *r_idev = NULL;
1123 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1125 config = dev->config + cfg_no;
1126 if(!config)
1127 continue;
1129 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1131 interface = config->interface + ifc_no;
1132 if (!interface)
1133 continue;
1135 for (set_no=0; set_no < interface->num_altsetting; set_no++)
1137 ifcdesc = (interface->altsetting + set_no);
1138 /* The second condition is for older SCM SPR 532 who did
1139 not know about the assigned CCID class. Instead of
1140 trying to interpret the strings we simply check the
1141 product ID. */
1142 if (ifcdesc && ifcdesc->extra
1143 && ((ifcdesc->bInterfaceClass == 11
1144 && ifcdesc->bInterfaceSubClass == 0
1145 && ifcdesc->bInterfaceProtocol == 0)
1146 || (ifcdesc->bInterfaceClass == 255
1147 && dev->descriptor.idVendor == VENDOR_SCM
1148 && dev->descriptor.idProduct == 0xe003)))
1150 idev = usb_open (dev);
1151 if (!idev)
1153 DEBUGOUT_1 ("usb_open failed: %s\n",
1154 strerror (errno));
1155 continue; /* with next setting. */
1158 rid = make_reader_id (idev,
1159 dev->descriptor.idVendor,
1160 dev->descriptor.idProduct,
1161 dev->descriptor.iSerialNumber);
1162 if (rid)
1164 if (scan_mode)
1166 char *p;
1168 /* We are collecting infos about all
1169 available CCID readers. Store them and
1170 continue. */
1171 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1172 *count, rid );
1173 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1174 + strlen (rid) + 1);
1175 if (p)
1177 *p = 0;
1178 if (*rid_list)
1180 strcat (p, *rid_list);
1181 free (*rid_list);
1183 strcat (p, rid);
1184 strcat (p, "\n");
1185 *rid_list = p;
1187 else /* Out of memory. */
1188 free (rid);
1190 rid = NULL;
1191 ++*count;
1193 else if (!*readerno
1194 || (*readerno < 0
1195 && readerid
1196 && !strcmp (readerid, rid)))
1198 /* We found the requested reader. */
1199 if (ifcdesc_extra && ifcdesc_extra_len)
1201 *ifcdesc_extra = malloc (ifcdesc
1202 ->extralen);
1203 if (!*ifcdesc_extra)
1205 usb_close (idev);
1206 free (rid);
1207 return 1; /* Out of core. */
1209 memcpy (*ifcdesc_extra, ifcdesc->extra,
1210 ifcdesc->extralen);
1211 *ifcdesc_extra_len = ifcdesc->extralen;
1214 if (interface_number)
1215 *interface_number = (ifcdesc->bInterfaceNumber);
1217 if (ep_bulk_out)
1218 *ep_bulk_out = find_endpoint (ifcdesc, 0);
1219 if (ep_bulk_in)
1220 *ep_bulk_in = find_endpoint (ifcdesc, 1);
1221 if (ep_intr)
1222 *ep_intr = find_endpoint (ifcdesc, 2);
1224 if (r_dev)
1225 *r_dev = dev;
1226 if (r_rid)
1228 *r_rid = rid;
1229 rid = NULL;
1231 else
1232 free (rid);
1234 *r_idev = idev;
1235 return 1; /* Found requested device. */
1237 else
1239 /* This is not yet the reader we want.
1240 fixme: We should avoid the extra usb_open
1241 in this case. */
1242 if (*readerno >= 0)
1243 --*readerno;
1245 free (rid);
1248 usb_close (idev);
1249 idev = NULL;
1250 return 0;
1256 return 0;
1259 /* Combination function to either scan all CCID devices or to find and
1260 open one specific device.
1262 The function returns 0 if a reader has been found or when a scan
1263 returned without error.
1265 With READERNO = -1 and READERID is NULL, scan mode is used and
1266 R_RID should be the address where to store the list of reader_ids
1267 we found. If on return this list is empty, no CCID device has been
1268 found; otherwise it points to an allocated linked list of reader
1269 IDs. Note that in this mode the function always returns NULL.
1271 With READERNO >= 0 or READERID is not NULL find mode is used. This
1272 uses the same algorithm as the scan mode but stops and returns at
1273 the entry number READERNO and return the handle for the the opened
1274 USB device. If R_RID is not NULL it will receive the reader ID of
1275 that device. If R_DEV is not NULL it will the device pointer of
1276 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
1277 malloced copy of the interfaces "extra: data filed;
1278 IFCDESC_EXTRA_LEN receive the length of this field. If there is
1279 no reader with number READERNO or that reader is not usable by our
1280 implementation NULL will be returned. The caller must close a
1281 returned USB device handle and free (if not passed as NULL) the
1282 returned reader ID info as well as the IFCDESC_EXTRA. On error
1283 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1284 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
1285 the READERID was found.
1287 If R_FD is not -1 on return the device is not using USB for
1288 transport but the device associated with that file descriptor. In
1289 this case INTERFACE will receive the transport type and the other
1290 USB specific return values are not used; the return value is
1291 (void*)(1).
1293 Note that the first entry of the returned reader ID list in scan mode
1294 corresponds with a READERNO of 0 in find mode.
1296 static int
1297 scan_or_find_devices (int readerno, const char *readerid,
1298 char **r_rid,
1299 struct usb_device **r_dev,
1300 unsigned char **ifcdesc_extra,
1301 size_t *ifcdesc_extra_len,
1302 int *interface_number,
1303 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1304 usb_dev_handle **r_idev,
1305 int *r_fd)
1307 char *rid_list = NULL;
1308 int count = 0;
1309 struct usb_bus *busses, *bus;
1310 struct usb_device *dev = NULL;
1311 usb_dev_handle *idev = NULL;
1312 int scan_mode = (readerno == -1 && !readerid);
1313 int i;
1315 /* Set return values to a default. */
1316 if (r_rid)
1317 *r_rid = NULL;
1318 if (r_dev)
1319 *r_dev = NULL;
1320 if (ifcdesc_extra)
1321 *ifcdesc_extra = NULL;
1322 if (ifcdesc_extra_len)
1323 *ifcdesc_extra_len = 0;
1324 if (interface_number)
1325 *interface_number = 0;
1326 if (r_idev)
1327 *r_idev = NULL;
1328 if (r_fd)
1329 *r_fd = -1;
1331 /* See whether we want scan or find mode. */
1332 if (scan_mode)
1334 assert (r_rid);
1337 usb_find_busses();
1338 usb_find_devices();
1340 #ifdef HAVE_USB_GET_BUSSES
1341 busses = usb_get_busses();
1342 #else
1343 busses = usb_busses;
1344 #endif
1346 for (bus = busses; bus; bus = bus->next)
1348 for (dev = bus->devices; dev; dev = dev->next)
1350 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1351 readerid,
1352 dev,
1353 r_rid,
1354 r_dev,
1355 &idev,
1356 ifcdesc_extra,
1357 ifcdesc_extra_len,
1358 interface_number,
1359 ep_bulk_out, ep_bulk_in, ep_intr))
1361 /* Found requested device or out of core. */
1362 if (!idev)
1364 free (rid_list);
1365 return -1; /* error */
1367 *r_idev = idev;
1368 return 0;
1373 /* Now check whether there are any devices with special transport types. */
1374 for (i=0; transports[i].name; i++)
1376 int fd;
1377 char *rid, *p;
1379 fd = open (transports[i].name, O_RDWR);
1380 if (fd == -1 && scan_mode && errno == EBUSY)
1382 /* Ignore this error in scan mode because it indicates that
1383 the device exists but is already open (most likely by us)
1384 and thus in general suitable as a reader. */
1386 else if (fd == -1)
1388 DEBUGOUT_2 ("failed to open `%s': %s\n",
1389 transports[i].name, strerror (errno));
1390 continue;
1393 rid = malloc (strlen (transports[i].name) + 30 + 10);
1394 if (!rid)
1396 if (fd != -1)
1397 close (fd);
1398 free (rid_list);
1399 return -1; /* Error. */
1401 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1402 if (scan_mode)
1404 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1405 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1406 if (!p)
1408 if (fd != -1)
1409 close (fd);
1410 free (rid_list);
1411 free (rid);
1412 return -1; /* Error. */
1414 *p = 0;
1415 if (rid_list)
1417 strcat (p, rid_list);
1418 free (rid_list);
1420 strcat (p, rid);
1421 strcat (p, "\n");
1422 rid_list = p;
1423 ++count;
1425 else if (!readerno ||
1426 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1428 /* Found requested device. */
1429 if (interface_number)
1430 *interface_number = transports[i].type;
1431 if (r_rid)
1432 *r_rid = rid;
1433 else
1434 free (rid);
1435 if (r_fd)
1436 *r_fd = fd;
1437 return 0; /* Okay, found device */
1439 else /* This is not yet the reader we want. */
1441 if (readerno >= 0)
1442 --readerno;
1444 free (rid);
1445 if (fd != -1)
1446 close (fd);
1449 if (scan_mode)
1451 *r_rid = rid_list;
1452 return 0;
1454 else
1455 return -1;
1459 /* Set the level of debugging to LEVEL and return the old level. -1
1460 just returns the old level. A level of 0 disables debugging, 1
1461 enables debugging, 2 enables additional tracing of the T=1
1462 protocol, 3 additionally enables debugging for GetSlotStatus, other
1463 values are not yet defined.
1465 Note that libusb may provide its own debugging feature which is
1466 enabled by setting the envvar USB_DEBUG. */
1468 ccid_set_debug_level (int level)
1470 int old = debug_level;
1471 if (level != -1)
1472 debug_level = level;
1473 return old;
1477 char *
1478 ccid_get_reader_list (void)
1480 char *reader_list;
1482 if (!initialized_usb)
1484 usb_init ();
1485 initialized_usb = 1;
1488 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1489 NULL, NULL, NULL, NULL, NULL))
1490 return NULL; /* Error. */
1491 return reader_list;
1495 /* Open the reader with the internal number READERNO and return a
1496 pointer to be used as handle in HANDLE. Returns 0 on success. */
1497 int
1498 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1500 int rc = 0;
1501 struct usb_device *dev = NULL;
1502 usb_dev_handle *idev = NULL;
1503 int dev_fd = -1;
1504 char *rid = NULL;
1505 unsigned char *ifcdesc_extra = NULL;
1506 size_t ifcdesc_extra_len;
1507 int readerno;
1508 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1510 *handle = NULL;
1512 if (!initialized_usb)
1514 usb_init ();
1515 initialized_usb = 1;
1518 /* See whether we want to use the reader ID string or a reader
1519 number. A readerno of -1 indicates that the reader ID string is
1520 to be used. */
1521 if (readerid && strchr (readerid, ':'))
1522 readerno = -1; /* We want to use the readerid. */
1523 else if (readerid)
1525 readerno = atoi (readerid);
1526 if (readerno < 0)
1528 DEBUGOUT ("no CCID readers found\n");
1529 rc = CCID_DRIVER_ERR_NO_READER;
1530 goto leave;
1533 else
1534 readerno = 0; /* Default. */
1536 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1537 &ifcdesc_extra, &ifcdesc_extra_len,
1538 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1539 &idev, &dev_fd) )
1541 if (readerno == -1)
1542 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1543 else
1544 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1545 rc = CCID_DRIVER_ERR_NO_READER;
1546 goto leave;
1549 /* Okay, this is a CCID reader. */
1550 *handle = calloc (1, sizeof **handle);
1551 if (!*handle)
1553 DEBUGOUT ("out of memory\n");
1554 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1555 goto leave;
1557 (*handle)->rid = rid;
1558 if (idev) /* Regular USB transport. */
1560 (*handle)->idev = idev;
1561 (*handle)->dev_fd = -1;
1562 (*handle)->id_vendor = dev->descriptor.idVendor;
1563 (*handle)->id_product = dev->descriptor.idProduct;
1564 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1565 (*handle)->ifc_no = ifc_no;
1566 (*handle)->ep_bulk_out = ep_bulk_out;
1567 (*handle)->ep_bulk_in = ep_bulk_in;
1568 (*handle)->ep_intr = ep_intr;
1570 else if (dev_fd != -1) /* Device transport. */
1572 (*handle)->idev = NULL;
1573 (*handle)->dev_fd = dev_fd;
1574 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1575 (*handle)->id_product = ifc_no; /* Transport type */
1576 prepare_special_transport (*handle);
1578 else
1580 assert (!"no transport"); /* Bug. */
1583 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1585 if (idev)
1587 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1589 DEBUGOUT ("device not supported\n");
1590 rc = CCID_DRIVER_ERR_NO_READER;
1591 goto leave;
1594 rc = usb_claim_interface (idev, ifc_no);
1595 if (rc)
1597 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1598 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1599 goto leave;
1603 leave:
1604 free (ifcdesc_extra);
1605 if (rc)
1607 free (rid);
1608 if (idev)
1609 usb_close (idev);
1610 if (dev_fd != -1)
1611 close (dev_fd);
1612 free (*handle);
1613 *handle = NULL;
1616 return rc;
1620 static void
1621 do_close_reader (ccid_driver_t handle)
1623 int rc;
1624 unsigned char msg[100];
1625 size_t msglen;
1626 unsigned char seqno;
1628 if (!handle->powered_off)
1630 msg[0] = PC_to_RDR_IccPowerOff;
1631 msg[5] = 0; /* slot */
1632 msg[6] = seqno = handle->seqno++;
1633 msg[7] = 0; /* RFU */
1634 msg[8] = 0; /* RFU */
1635 msg[9] = 0; /* RFU */
1636 set_msg_len (msg, 0);
1637 msglen = 10;
1639 rc = bulk_out (handle, msg, msglen, 0);
1640 if (!rc)
1641 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1642 seqno, 2000, 0);
1643 handle->powered_off = 1;
1645 if (handle->idev)
1647 usb_release_interface (handle->idev, handle->ifc_no);
1648 usb_close (handle->idev);
1649 handle->idev = NULL;
1651 if (handle->dev_fd != -1)
1653 close (handle->dev_fd);
1654 handle->dev_fd = -1;
1659 /* Reset a reader on HANDLE. This is useful in case a reader has been
1660 plugged of and inserted at a different port. By resetting the
1661 handle, the same reader will be get used. Note, that on error the
1662 handle won't get released.
1664 This does not return an ATR, so ccid_get_atr should be called right
1665 after this one.
1667 int
1668 ccid_shutdown_reader (ccid_driver_t handle)
1670 int rc = 0;
1671 struct usb_device *dev = NULL;
1672 usb_dev_handle *idev = NULL;
1673 unsigned char *ifcdesc_extra = NULL;
1674 size_t ifcdesc_extra_len;
1675 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1677 if (!handle || !handle->rid)
1678 return CCID_DRIVER_ERR_INV_VALUE;
1680 do_close_reader (handle);
1682 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1683 &ifcdesc_extra, &ifcdesc_extra_len,
1684 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1685 &idev, NULL) || !idev)
1687 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1688 return CCID_DRIVER_ERR_NO_READER;
1691 if (idev)
1693 handle->idev = idev;
1694 handle->ifc_no = ifc_no;
1695 handle->ep_bulk_out = ep_bulk_out;
1696 handle->ep_bulk_in = ep_bulk_in;
1697 handle->ep_intr = ep_intr;
1699 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1701 DEBUGOUT ("device not supported\n");
1702 rc = CCID_DRIVER_ERR_NO_READER;
1703 goto leave;
1706 rc = usb_claim_interface (idev, ifc_no);
1707 if (rc)
1709 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1710 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1711 goto leave;
1715 leave:
1716 free (ifcdesc_extra);
1717 if (rc)
1719 if (handle->idev)
1720 usb_close (handle->idev);
1721 handle->idev = NULL;
1722 if (handle->dev_fd != -1)
1723 close (handle->dev_fd);
1724 handle->dev_fd = -1;
1727 return rc;
1732 int
1733 ccid_set_progress_cb (ccid_driver_t handle,
1734 void (*cb)(void *, const char *, int, int, int),
1735 void *cb_arg)
1737 if (!handle || !handle->rid)
1738 return CCID_DRIVER_ERR_INV_VALUE;
1740 handle->progress_cb = cb;
1741 handle->progress_cb_arg = cb_arg;
1742 return 0;
1746 /* Close the reader HANDLE. */
1747 int
1748 ccid_close_reader (ccid_driver_t handle)
1750 if (!handle || (!handle->idev && handle->dev_fd == -1))
1751 return 0;
1753 do_close_reader (handle);
1754 free (handle->rid);
1755 free (handle);
1756 return 0;
1760 /* Return False if a card is present and powered. */
1762 ccid_check_card_presence (ccid_driver_t handle)
1764 (void)handle; /* Not yet implemented. */
1765 return -1;
1769 /* Write NBYTES of BUF to file descriptor FD. */
1770 static int
1771 writen (int fd, const void *buf, size_t nbytes)
1773 size_t nleft = nbytes;
1774 int nwritten;
1776 while (nleft > 0)
1778 nwritten = write (fd, buf, nleft);
1779 if (nwritten < 0)
1781 if (errno == EINTR)
1782 nwritten = 0;
1783 else
1784 return -1;
1786 nleft -= nwritten;
1787 buf = (const char*)buf + nwritten;
1790 return 0;
1794 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1795 Returns 0 on success. */
1796 static int
1797 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1798 int no_debug)
1800 int rc;
1802 /* No need to continue and clutter the log with USB write error
1803 messages after we got the first ENODEV. */
1804 if (handle->enodev_seen)
1805 return CCID_DRIVER_ERR_NO_READER;
1807 if (debug_level && (!no_debug || debug_level >= 3))
1809 switch (msglen? msg[0]:0)
1811 case PC_to_RDR_IccPowerOn:
1812 print_p2r_iccpoweron (msg, msglen);
1813 break;
1814 case PC_to_RDR_IccPowerOff:
1815 print_p2r_iccpoweroff (msg, msglen);
1816 break;
1817 case PC_to_RDR_GetSlotStatus:
1818 print_p2r_getslotstatus (msg, msglen);
1819 break;
1820 case PC_to_RDR_XfrBlock:
1821 print_p2r_xfrblock (msg, msglen);
1822 break;
1823 case PC_to_RDR_GetParameters:
1824 print_p2r_getparameters (msg, msglen);
1825 break;
1826 case PC_to_RDR_ResetParameters:
1827 print_p2r_resetparameters (msg, msglen);
1828 break;
1829 case PC_to_RDR_SetParameters:
1830 print_p2r_setparameters (msg, msglen);
1831 break;
1832 case PC_to_RDR_Escape:
1833 print_p2r_escape (msg, msglen);
1834 break;
1835 case PC_to_RDR_IccClock:
1836 print_p2r_iccclock (msg, msglen);
1837 break;
1838 case PC_to_RDR_T0APDU:
1839 print_p2r_to0apdu (msg, msglen);
1840 break;
1841 case PC_to_RDR_Secure:
1842 print_p2r_secure (msg, msglen);
1843 break;
1844 case PC_to_RDR_Mechanical:
1845 print_p2r_mechanical (msg, msglen);
1846 break;
1847 case PC_to_RDR_Abort:
1848 print_p2r_abort (msg, msglen);
1849 break;
1850 case PC_to_RDR_SetDataRate:
1851 print_p2r_setdatarate (msg, msglen);
1852 break;
1853 default:
1854 print_p2r_unknown (msg, msglen);
1855 break;
1859 if (handle->idev)
1861 rc = usb_bulk_write (handle->idev,
1862 handle->ep_bulk_out,
1863 (char*)msg, msglen,
1864 5000 /* ms timeout */);
1865 if (rc == msglen)
1866 return 0;
1867 #ifdef ENODEV
1868 if (rc == -(ENODEV))
1870 /* The Linux libusb returns a negative error value. Catch
1871 the most important one. */
1872 errno = ENODEV;
1873 rc = -1;
1875 #endif /*ENODEV*/
1877 if (rc == -1)
1879 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1880 #ifdef ENODEV
1881 if (errno == ENODEV)
1883 handle->enodev_seen = 1;
1884 return CCID_DRIVER_ERR_NO_READER;
1886 #endif /*ENODEV*/
1888 else
1889 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1891 else
1893 rc = writen (handle->dev_fd, msg, msglen);
1894 if (!rc)
1895 return 0;
1896 DEBUGOUT_2 ("writen to %d failed: %s\n",
1897 handle->dev_fd, strerror (errno));
1900 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1904 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1905 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1906 is the sequence number used to send the request and EXPECTED_TYPE
1907 the type of message we expect. Does checks on the ccid
1908 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1909 avoid debug messages in case of no error; this can be overriden
1910 with a glibal debug level of at least 3. Returns 0 on success. */
1911 static int
1912 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1913 size_t *nread, int expected_type, int seqno, int timeout,
1914 int no_debug)
1916 int rc;
1917 size_t msglen;
1918 int eagain_retries = 0;
1920 /* Fixme: The next line for the current Valgrind without support
1921 for USB IOCTLs. */
1922 memset (buffer, 0, length);
1923 retry:
1924 if (handle->idev)
1926 rc = usb_bulk_read (handle->idev,
1927 handle->ep_bulk_in,
1928 (char*)buffer, length,
1929 timeout);
1930 if (rc < 0)
1932 rc = errno;
1933 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
1934 if (rc == EAGAIN && eagain_retries++ < 3)
1936 my_sleep (1);
1937 goto retry;
1939 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1941 *nread = msglen = rc;
1943 else
1945 rc = read (handle->dev_fd, buffer, length);
1946 if (rc < 0)
1948 rc = errno;
1949 DEBUGOUT_2 ("read from %d failed: %s\n",
1950 handle->dev_fd, strerror (rc));
1951 if (rc == EAGAIN && eagain_retries++ < 5)
1953 my_sleep (1);
1954 goto retry;
1956 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1958 *nread = msglen = rc;
1960 eagain_retries = 0;
1962 if (msglen < 10)
1964 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1965 abort_cmd (handle, seqno);
1966 return CCID_DRIVER_ERR_INV_VALUE;
1968 if (buffer[5] != 0)
1970 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1971 return CCID_DRIVER_ERR_INV_VALUE;
1973 if (buffer[6] != seqno)
1975 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1976 seqno, buffer[6]);
1977 /* Retry until we are synced again. */
1978 goto retry;
1981 /* We need to handle the time extension request before we check that
1982 we got the expected message type. This is in particular required
1983 for the Cherry keyboard which sends a time extension request for
1984 each key hit. */
1985 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1987 /* Card present and active, time extension requested. */
1988 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1989 buffer[7], buffer[8]);
1990 goto retry;
1993 if (buffer[0] != expected_type)
1995 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1996 abort_cmd (handle, seqno);
1997 return CCID_DRIVER_ERR_INV_VALUE;
2000 if (debug_level && (!no_debug || debug_level >= 3))
2002 switch (buffer[0])
2004 case RDR_to_PC_DataBlock:
2005 print_r2p_datablock (buffer, msglen);
2006 break;
2007 case RDR_to_PC_SlotStatus:
2008 print_r2p_slotstatus (buffer, msglen);
2009 break;
2010 case RDR_to_PC_Parameters:
2011 print_r2p_parameters (buffer, msglen);
2012 break;
2013 case RDR_to_PC_Escape:
2014 print_r2p_escape (buffer, msglen);
2015 break;
2016 case RDR_to_PC_DataRate:
2017 print_r2p_datarate (buffer, msglen);
2018 break;
2019 default:
2020 print_r2p_unknown (buffer, msglen);
2021 break;
2024 if (CCID_COMMAND_FAILED (buffer))
2025 print_command_failed (buffer);
2027 /* Check whether a card is at all available. Note: If you add new
2028 error codes here, check whether they need to be ignored in
2029 send_escape_cmd. */
2030 switch ((buffer[7] & 0x03))
2032 case 0: /* no error */ break;
2033 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2034 case 2: return CCID_DRIVER_ERR_NO_CARD;
2035 case 3: /* RFU */ break;
2037 return 0;
2042 /* Send an abort sequence and wait until everything settled. */
2043 static int
2044 abort_cmd (ccid_driver_t handle, int seqno)
2046 int rc;
2047 char dummybuf[8];
2048 unsigned char msg[100];
2049 size_t msglen;
2051 if (!handle->idev)
2053 /* I don't know how to send an abort to non-USB devices. */
2054 rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2057 seqno &= 0xff;
2058 DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2059 /* Send the abort command to the control pipe. Note that we don't
2060 need to keep track of sent abort commands because there should
2061 never be another thread using the same slot concurrently. */
2062 rc = usb_control_msg (handle->idev,
2063 0x21,/* bmRequestType: host-to-device,
2064 class specific, to interface. */
2065 1, /* ABORT */
2066 (seqno << 8 | 0 /* slot */),
2067 handle->ifc_no,
2068 dummybuf, 0,
2069 1000 /* ms timeout */);
2070 if (rc < 0)
2072 DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
2073 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2076 /* Now send the abort command to the bulk out pipe using the same
2077 SEQNO and SLOT. Do this in a loop to so that all seqno are
2078 tried. */
2079 seqno--; /* Adjust for next increment. */
2082 seqno++;
2083 msg[0] = PC_to_RDR_Abort;
2084 msg[5] = 0; /* slot */
2085 msg[6] = seqno;
2086 msg[7] = 0; /* RFU */
2087 msg[8] = 0; /* RFU */
2088 msg[9] = 0; /* RFU */
2089 msglen = 10;
2090 set_msg_len (msg, 0);
2092 rc = usb_bulk_write (handle->idev,
2093 handle->ep_bulk_out,
2094 (char*)msg, msglen,
2095 5000 /* ms timeout */);
2096 if (rc == msglen)
2097 rc = 0;
2098 else if (rc == -1)
2099 DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2100 strerror (errno));
2101 else
2102 DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2104 if (rc)
2105 return rc;
2107 rc = usb_bulk_read (handle->idev,
2108 handle->ep_bulk_in,
2109 (char*)msg, sizeof msg,
2110 5000 /*ms timeout*/);
2111 if (rc < 0)
2113 DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2114 strerror (errno));
2115 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2117 msglen = rc;
2119 if (msglen < 10)
2121 DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2122 (unsigned int)msglen);
2123 return CCID_DRIVER_ERR_INV_VALUE;
2125 if (msg[5] != 0)
2127 DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2128 return CCID_DRIVER_ERR_INV_VALUE;
2131 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n",
2132 msg[7], msg[8], msg[9]);
2133 if (CCID_COMMAND_FAILED (msg))
2134 print_command_failed (msg);
2136 while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2138 handle->seqno = ((seqno + 1) & 0xff);
2139 DEBUGOUT ("sending abort sequence succeeded\n");
2141 return 0;
2145 /* Note that this function won't return the error codes NO_CARD or
2146 CARD_INACTIVE. IF RESULT is not NULL, the result from the
2147 operation will get returned in RESULT and its length in RESULTLEN.
2148 If the response is larger than RESULTMAX, an error is returned and
2149 the required buffer length returned in RESULTLEN. */
2150 static int
2151 send_escape_cmd (ccid_driver_t handle,
2152 const unsigned char *data, size_t datalen,
2153 unsigned char *result, size_t resultmax, size_t *resultlen)
2155 int rc;
2156 unsigned char msg[100];
2157 size_t msglen;
2158 unsigned char seqno;
2160 if (resultlen)
2161 *resultlen = 0;
2163 if (datalen > sizeof msg - 10)
2164 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
2166 msg[0] = PC_to_RDR_Escape;
2167 msg[5] = 0; /* slot */
2168 msg[6] = seqno = handle->seqno++;
2169 msg[7] = 0; /* RFU */
2170 msg[8] = 0; /* RFU */
2171 msg[9] = 0; /* RFU */
2172 memcpy (msg+10, data, datalen);
2173 msglen = 10 + datalen;
2174 set_msg_len (msg, datalen);
2176 rc = bulk_out (handle, msg, msglen, 0);
2177 if (rc)
2178 return rc;
2179 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2180 seqno, 5000, 0);
2181 if (result)
2182 switch (rc)
2184 /* We need to ignore certain errorcode here. */
2185 case 0:
2186 case CCID_DRIVER_ERR_CARD_INACTIVE:
2187 case CCID_DRIVER_ERR_NO_CARD:
2189 if (msglen > resultmax)
2190 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2191 else
2193 memcpy (result, msg, msglen);
2194 *resultlen = msglen;
2196 rc = 0;
2198 break;
2199 default:
2200 break;
2203 return rc;
2208 ccid_transceive_escape (ccid_driver_t handle,
2209 const unsigned char *data, size_t datalen,
2210 unsigned char *resp, size_t maxresplen, size_t *nresp)
2212 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2217 /* experimental */
2219 ccid_poll (ccid_driver_t handle)
2221 int rc;
2222 unsigned char msg[10];
2223 size_t msglen;
2224 int i, j;
2226 if (handle->idev)
2228 rc = usb_bulk_read (handle->idev,
2229 handle->ep_intr,
2230 (char*)msg, sizeof msg,
2231 0 /* ms timeout */ );
2232 if (rc < 0 && errno == ETIMEDOUT)
2233 return 0;
2235 else
2236 return 0;
2238 if (rc < 0)
2240 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2241 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2244 msglen = rc;
2245 rc = 0;
2247 if (msglen < 1)
2249 DEBUGOUT ("intr-in msg too short\n");
2250 return CCID_DRIVER_ERR_INV_VALUE;
2253 if (msg[0] == RDR_to_PC_NotifySlotChange)
2255 DEBUGOUT ("notify slot change:");
2256 for (i=1; i < msglen; i++)
2257 for (j=0; j < 4; j++)
2258 DEBUGOUT_CONT_3 (" %d:%c%c",
2259 (i-1)*4+j,
2260 (msg[i] & (1<<(j*2)))? 'p':'-',
2261 (msg[i] & (2<<(j*2)))? '*':' ');
2262 DEBUGOUT_LF ();
2264 else if (msg[0] == RDR_to_PC_HardwareError)
2266 DEBUGOUT ("hardware error occured\n");
2268 else
2270 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2273 return 0;
2277 /* Note that this function won't return the error codes NO_CARD or
2278 CARD_INACTIVE */
2279 int
2280 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2282 int rc;
2283 unsigned char msg[100];
2284 size_t msglen;
2285 unsigned char seqno;
2286 int retries = 0;
2288 retry:
2289 msg[0] = PC_to_RDR_GetSlotStatus;
2290 msg[5] = 0; /* slot */
2291 msg[6] = seqno = handle->seqno++;
2292 msg[7] = 0; /* RFU */
2293 msg[8] = 0; /* RFU */
2294 msg[9] = 0; /* RFU */
2295 set_msg_len (msg, 0);
2297 rc = bulk_out (handle, msg, 10, 1);
2298 if (rc)
2299 return rc;
2300 /* Note that we set the NO_DEBUG flag here, so that the logs won't
2301 get cluttered up by a ticker function checking for the slot
2302 status and debugging enabled. */
2303 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2304 seqno, retries? 1000 : 200, 1);
2305 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2307 if (!retries)
2309 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2310 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2311 usb_clear_halt (handle->idev, handle->ep_bulk_out);
2313 else
2314 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2315 retries++;
2316 goto retry;
2318 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2319 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2320 return rc;
2321 *statusbits = (msg[7] & 3);
2323 return 0;
2327 /* Return the ATR of the card. This is not a cached value and thus an
2328 actual reset is done. */
2329 int
2330 ccid_get_atr (ccid_driver_t handle,
2331 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2333 int rc;
2334 int statusbits;
2335 unsigned char msg[100];
2336 unsigned char *tpdu;
2337 size_t msglen, tpdulen;
2338 unsigned char seqno;
2339 int use_crc = 0;
2340 unsigned int edc;
2341 int tried_iso = 0;
2342 int got_param;
2344 /* First check whether a card is available. */
2345 rc = ccid_slot_status (handle, &statusbits);
2346 if (rc)
2347 return rc;
2348 if (statusbits == 2)
2349 return CCID_DRIVER_ERR_NO_CARD;
2351 /* For an inactive and also for an active card, issue the PowerOn
2352 command to get the ATR. */
2353 again:
2354 msg[0] = PC_to_RDR_IccPowerOn;
2355 msg[5] = 0; /* slot */
2356 msg[6] = seqno = handle->seqno++;
2357 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2358 msg[8] = 0; /* RFU */
2359 msg[9] = 0; /* RFU */
2360 set_msg_len (msg, 0);
2361 msglen = 10;
2363 rc = bulk_out (handle, msg, msglen, 0);
2364 if (rc)
2365 return rc;
2366 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2367 seqno, 5000, 0);
2368 if (rc)
2369 return rc;
2370 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2371 && ((handle->id_vendor == VENDOR_CHERRY
2372 && handle->id_product == 0x0005)
2373 || (handle->id_vendor == VENDOR_GEMPC
2374 && handle->id_product == 0x4433)
2377 tried_iso = 1;
2378 /* Try switching to ISO mode. */
2379 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2380 NULL, 0, NULL))
2381 goto again;
2383 else if (CCID_COMMAND_FAILED (msg))
2384 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2387 handle->powered_off = 0;
2389 if (atr)
2391 size_t n = msglen - 10;
2393 if (n > maxatrlen)
2394 n = maxatrlen;
2395 memcpy (atr, msg+10, n);
2396 *atrlen = n;
2399 got_param = 0;
2400 msg[0] = PC_to_RDR_GetParameters;
2401 msg[5] = 0; /* slot */
2402 msg[6] = seqno = handle->seqno++;
2403 msg[7] = 0; /* RFU */
2404 msg[8] = 0; /* RFU */
2405 msg[9] = 0; /* RFU */
2406 set_msg_len (msg, 0);
2407 msglen = 10;
2408 rc = bulk_out (handle, msg, msglen, 0);
2409 if (!rc)
2410 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2411 seqno, 2000, 0);
2412 if (rc)
2413 DEBUGOUT ("GetParameters failed\n");
2414 else if (msglen == 17 && msg[9] == 1)
2415 got_param = 1;
2417 /* Setup parameters to select T=1. */
2418 msg[0] = PC_to_RDR_SetParameters;
2419 msg[5] = 0; /* slot */
2420 msg[6] = seqno = handle->seqno++;
2421 msg[7] = 1; /* Select T=1. */
2422 msg[8] = 0; /* RFU */
2423 msg[9] = 0; /* RFU */
2425 if (!got_param)
2427 /* FIXME: Get those values from the ATR. */
2428 msg[10]= 0x01; /* Fi/Di */
2429 msg[11]= 0x10; /* LRC, direct convention. */
2430 msg[12]= 0; /* Extra guardtime. */
2431 msg[13]= 0x41; /* BWI/CWI */
2432 msg[14]= 0; /* No clock stoppping. */
2433 msg[15]= 254; /* IFSC */
2434 msg[16]= 0; /* Does not support non default NAD values. */
2436 set_msg_len (msg, 7);
2437 msglen = 10 + 7;
2439 rc = bulk_out (handle, msg, msglen, 0);
2440 if (rc)
2441 return rc;
2442 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2443 seqno, 5000, 0);
2444 if (rc)
2445 DEBUGOUT ("SetParameters failed (ignored)\n");
2447 if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2448 handle->ifsc = msg[15];
2449 else
2450 handle->ifsc = 128; /* Something went wrong, assume 128 bytes. */
2452 handle->t1_ns = 0;
2453 handle->t1_nr = 0;
2455 /* Send an S-Block with our maximum IFSD to the CCID. */
2456 if (!handle->apdu_level && !handle->auto_ifsd)
2458 tpdu = msg+10;
2459 /* NAD: DAD=1, SAD=0 */
2460 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2461 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2462 tpdu[2] = 1;
2463 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2464 tpdulen = 4;
2465 edc = compute_edc (tpdu, tpdulen, use_crc);
2466 if (use_crc)
2467 tpdu[tpdulen++] = (edc >> 8);
2468 tpdu[tpdulen++] = edc;
2470 msg[0] = PC_to_RDR_XfrBlock;
2471 msg[5] = 0; /* slot */
2472 msg[6] = seqno = handle->seqno++;
2473 msg[7] = 0;
2474 msg[8] = 0; /* RFU */
2475 msg[9] = 0; /* RFU */
2476 set_msg_len (msg, tpdulen);
2477 msglen = 10 + tpdulen;
2479 if (debug_level > 1)
2480 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2481 ((msg[11] & 0xc0) == 0x80)? 'R' :
2482 (msg[11] & 0x80)? 'S' : 'I',
2483 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2484 : !!(msg[11] & 0x40)),
2485 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2487 rc = bulk_out (handle, msg, msglen, 0);
2488 if (rc)
2489 return rc;
2492 rc = bulk_in (handle, msg, sizeof msg, &msglen,
2493 RDR_to_PC_DataBlock, seqno, 5000, 0);
2494 if (rc)
2495 return rc;
2497 tpdu = msg + 10;
2498 tpdulen = msglen - 10;
2500 if (tpdulen < 4)
2501 return CCID_DRIVER_ERR_ABORTED;
2503 if (debug_level > 1)
2504 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2505 ((msg[11] & 0xc0) == 0x80)? 'R' :
2506 (msg[11] & 0x80)? 'S' : 'I',
2507 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2508 : !!(msg[11] & 0x40)),
2509 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2510 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2512 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2514 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2515 return -1;
2517 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2520 return 0;
2526 static unsigned int
2527 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2529 if (use_crc)
2531 return 0x42; /* Not yet implemented. */
2533 else
2535 unsigned char crc = 0;
2537 for (; datalen; datalen--)
2538 crc ^= *data++;
2539 return crc;
2544 /* Return true if APDU is an extended length one. */
2545 static int
2546 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2548 if (apdulen < 7 || apdu[4])
2549 return 0; /* Too short or no Z byte. */
2550 return 1;
2554 /* Helper for ccid_transceive used for APDU level exchanges. */
2555 static int
2556 ccid_transceive_apdu_level (ccid_driver_t handle,
2557 const unsigned char *apdu_buf, size_t apdu_buflen,
2558 unsigned char *resp, size_t maxresplen,
2559 size_t *nresp)
2561 int rc;
2562 unsigned char send_buffer[10+261+300], recv_buffer[10+261+300];
2563 const unsigned char *apdu;
2564 size_t apdulen;
2565 unsigned char *msg;
2566 size_t msglen;
2567 unsigned char seqno;
2568 int bwi = 4;
2570 msg = send_buffer;
2572 apdu = apdu_buf;
2573 apdulen = apdu_buflen;
2574 assert (apdulen);
2576 /* The maximum length for a short APDU T=1 block is 261. For an
2577 extended APDU T=1 block the maximum length 65544; however
2578 extended APDU exchange level is not yet supported. */
2579 if (apdulen > 261)
2580 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2582 msg[0] = PC_to_RDR_XfrBlock;
2583 msg[5] = 0; /* slot */
2584 msg[6] = seqno = handle->seqno++;
2585 msg[7] = bwi; /* bBWI */
2586 msg[8] = 0; /* RFU */
2587 msg[9] = 0; /* RFU */
2588 memcpy (msg+10, apdu, apdulen);
2589 set_msg_len (msg, apdulen);
2590 msglen = 10 + apdulen;
2592 rc = bulk_out (handle, msg, msglen, 0);
2593 if (rc)
2594 return rc;
2596 msg = recv_buffer;
2597 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2598 RDR_to_PC_DataBlock, seqno, 5000, 0);
2599 if (rc)
2600 return rc;
2602 apdu = msg + 10;
2603 apdulen = msglen - 10;
2605 if (resp)
2607 if (apdulen > maxresplen)
2609 DEBUGOUT_2 ("provided buffer too short for received data "
2610 "(%u/%u)\n",
2611 (unsigned int)apdulen, (unsigned int)maxresplen);
2612 return CCID_DRIVER_ERR_INV_VALUE;
2615 memcpy (resp, apdu, apdulen);
2616 *nresp = apdulen;
2619 return 0;
2625 Protocol T=1 overview
2627 Block Structure:
2628 Prologue Field:
2629 1 byte Node Address (NAD)
2630 1 byte Protocol Control Byte (PCB)
2631 1 byte Length (LEN)
2632 Information Field:
2633 0-254 byte APDU or Control Information (INF)
2634 Epilogue Field:
2635 1 byte Error Detection Code (EDC)
2637 NAD:
2638 bit 7 unused
2639 bit 4..6 Destination Node Address (DAD)
2640 bit 3 unused
2641 bit 2..0 Source Node Address (SAD)
2643 If node adresses are not used, SAD and DAD should be set to 0 on
2644 the first block sent to the card. If they are used they should
2645 have different values (0 for one is okay); that first block sets up
2646 the addresses of the nodes.
2648 PCB:
2649 Information Block (I-Block):
2650 bit 7 0
2651 bit 6 Sequence number (yep, that is modulo 2)
2652 bit 5 Chaining flag
2653 bit 4..0 reserved
2654 Received-Ready Block (R-Block):
2655 bit 7 1
2656 bit 6 0
2657 bit 5 0
2658 bit 4 Sequence number
2659 bit 3..0 0 = no error
2660 1 = EDC or parity error
2661 2 = other error
2662 other values are reserved
2663 Supervisory Block (S-Block):
2664 bit 7 1
2665 bit 6 1
2666 bit 5 clear=request,set=response
2667 bit 4..0 0 = resyncronisation request
2668 1 = information field size request
2669 2 = abort request
2670 3 = extension of BWT request
2671 4 = VPP error
2672 other values are reserved
2677 ccid_transceive (ccid_driver_t handle,
2678 const unsigned char *apdu_buf, size_t apdu_buflen,
2679 unsigned char *resp, size_t maxresplen, size_t *nresp)
2681 int rc;
2682 /* The size of the buffer used to be 10+259. For the via_escape
2683 hack we need one extra byte, thus 11+259. */
2684 unsigned char send_buffer[11+259], recv_buffer[11+259];
2685 const unsigned char *apdu;
2686 size_t apdulen;
2687 unsigned char *msg, *tpdu, *p;
2688 size_t msglen, tpdulen, last_tpdulen, n;
2689 unsigned char seqno;
2690 unsigned int edc;
2691 int use_crc = 0;
2692 int hdrlen, pcboff;
2693 size_t dummy_nresp;
2694 int via_escape = 0;
2695 int next_chunk = 1;
2696 int sending = 1;
2697 int retries = 0;
2698 int resyncing = 0;
2699 int nad_byte;
2701 if (!nresp)
2702 nresp = &dummy_nresp;
2703 *nresp = 0;
2705 /* Smarter readers allow to send APDUs directly; divert here. */
2706 if (handle->apdu_level)
2708 /* We employ a hack for Omnikey readers which are able to send
2709 TPDUs using an escape sequence. There is no documentation
2710 but the Windows driver does it this way. Tested using a
2711 CM6121. This method works also for the Cherry XX44
2712 keyboards; however there are problems with the
2713 ccid_tranceive_secure which leads to a loss of sync on the
2714 CCID level. If Cherry wants to make their keyboard work
2715 again, they should hand over some docs. */
2716 if ((handle->id_vendor == VENDOR_OMNIKEY
2717 || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
2718 && handle->apdu_level < 2
2719 && is_exlen_apdu (apdu_buf, apdu_buflen))
2720 via_escape = 1;
2721 else
2722 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2723 resp, maxresplen, nresp);
2726 /* The other readers we support require sending TPDUs. */
2728 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2729 msg = send_buffer;
2730 hdrlen = via_escape? 11 : 10;
2732 /* NAD: DAD=1, SAD=0 */
2733 nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
2734 if (via_escape)
2735 nad_byte = 0;
2737 last_tpdulen = 0; /* Avoid gcc warning (controlled by RESYNCING). */
2738 for (;;)
2740 if (next_chunk)
2742 next_chunk = 0;
2744 apdu = apdu_buf;
2745 apdulen = apdu_buflen;
2746 assert (apdulen);
2748 /* Construct an I-Block. */
2749 tpdu = msg + hdrlen;
2750 tpdu[0] = nad_byte;
2751 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2752 if (apdulen > handle->ifsc )
2754 apdulen = handle->ifsc;
2755 apdu_buf += handle->ifsc;
2756 apdu_buflen -= handle->ifsc;
2757 tpdu[1] |= (1 << 5); /* Set more bit. */
2759 tpdu[2] = apdulen;
2760 memcpy (tpdu+3, apdu, apdulen);
2761 tpdulen = 3 + apdulen;
2762 edc = compute_edc (tpdu, tpdulen, use_crc);
2763 if (use_crc)
2764 tpdu[tpdulen++] = (edc >> 8);
2765 tpdu[tpdulen++] = edc;
2768 if (via_escape)
2770 msg[0] = PC_to_RDR_Escape;
2771 msg[5] = 0; /* slot */
2772 msg[6] = seqno = handle->seqno++;
2773 msg[7] = 0; /* RFU */
2774 msg[8] = 0; /* RFU */
2775 msg[9] = 0; /* RFU */
2776 msg[10] = 0x1a; /* Omnikey command to send a TPDU. */
2777 set_msg_len (msg, 1 + tpdulen);
2779 else
2781 msg[0] = PC_to_RDR_XfrBlock;
2782 msg[5] = 0; /* slot */
2783 msg[6] = seqno = handle->seqno++;
2784 msg[7] = 4; /* bBWI */
2785 msg[8] = 0; /* RFU */
2786 msg[9] = 0; /* RFU */
2787 set_msg_len (msg, tpdulen);
2789 msglen = hdrlen + tpdulen;
2790 if (!resyncing)
2791 last_tpdulen = tpdulen;
2792 pcboff = hdrlen+1;
2794 if (debug_level > 1)
2795 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2796 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
2797 (msg[pcboff] & 0x80)? 'S' : 'I',
2798 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
2799 : !!(msg[pcboff] & 0x40)),
2800 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
2801 " [more]":""));
2803 rc = bulk_out (handle, msg, msglen, 0);
2804 if (rc)
2805 return rc;
2807 msg = recv_buffer;
2808 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2809 via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
2810 seqno, 5000, 0);
2811 if (rc)
2812 return rc;
2814 tpdu = msg + hdrlen;
2815 tpdulen = msglen - hdrlen;
2816 resyncing = 0;
2818 if (tpdulen < 4)
2820 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2821 return CCID_DRIVER_ERR_ABORTED;
2824 if (debug_level > 1)
2825 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2826 ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
2827 (msg[pcboff] & 0x80)? 'S' : 'I',
2828 ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
2829 : !!(msg[pcboff] & 0x40)),
2830 ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
2831 (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
2832 " [more]":""));
2834 if (!(tpdu[1] & 0x80))
2835 { /* This is an I-block. */
2836 retries = 0;
2837 if (sending)
2838 { /* last block sent was successful. */
2839 handle->t1_ns ^= 1;
2840 sending = 0;
2843 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2844 { /* Reponse does not match our sequence number. */
2845 msg = send_buffer;
2846 tpdu = msg + hdrlen;
2847 tpdu[0] = nad_byte;
2848 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
2849 tpdu[2] = 0;
2850 tpdulen = 3;
2851 edc = compute_edc (tpdu, tpdulen, use_crc);
2852 if (use_crc)
2853 tpdu[tpdulen++] = (edc >> 8);
2854 tpdu[tpdulen++] = edc;
2856 continue;
2859 handle->t1_nr ^= 1;
2861 p = tpdu + 3; /* Skip the prologue field. */
2862 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2863 /* fixme: verify the checksum. */
2864 if (resp)
2866 if (n > maxresplen)
2868 DEBUGOUT_2 ("provided buffer too short for received data "
2869 "(%u/%u)\n",
2870 (unsigned int)n, (unsigned int)maxresplen);
2871 return CCID_DRIVER_ERR_INV_VALUE;
2874 memcpy (resp, p, n);
2875 resp += n;
2876 *nresp += n;
2877 maxresplen -= n;
2880 if (!(tpdu[1] & 0x20))
2881 return 0; /* No chaining requested - ready. */
2883 msg = send_buffer;
2884 tpdu = msg + hdrlen;
2885 tpdu[0] = nad_byte;
2886 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
2887 tpdu[2] = 0;
2888 tpdulen = 3;
2889 edc = compute_edc (tpdu, tpdulen, use_crc);
2890 if (use_crc)
2891 tpdu[tpdulen++] = (edc >> 8);
2892 tpdu[tpdulen++] = edc;
2894 else if ((tpdu[1] & 0xc0) == 0x80)
2895 { /* This is a R-block. */
2896 if ( (tpdu[1] & 0x0f))
2898 retries++;
2899 if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
2901 /* Error probably due to switching to TPDU. Send a
2902 resync request. We use the recv_buffer so that
2903 we don't corrupt the send_buffer. */
2904 msg = recv_buffer;
2905 tpdu = msg + hdrlen;
2906 tpdu[0] = nad_byte;
2907 tpdu[1] = 0xc0; /* S-block resync request. */
2908 tpdu[2] = 0;
2909 tpdulen = 3;
2910 edc = compute_edc (tpdu, tpdulen, use_crc);
2911 if (use_crc)
2912 tpdu[tpdulen++] = (edc >> 8);
2913 tpdu[tpdulen++] = edc;
2914 resyncing = 1;
2915 DEBUGOUT ("T=1: requesting resync\n");
2917 else if (retries > 3)
2919 DEBUGOUT ("T=1: 3 failed retries\n");
2920 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2922 else
2924 /* Error: repeat last block */
2925 msg = send_buffer;
2926 tpdulen = last_tpdulen;
2929 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
2930 { /* Response does not match our sequence number. */
2931 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2932 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2934 else if (sending)
2935 { /* Send next chunk. */
2936 retries = 0;
2937 msg = send_buffer;
2938 next_chunk = 1;
2939 handle->t1_ns ^= 1;
2941 else
2943 DEBUGOUT ("unexpected ACK R-block received\n");
2944 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2947 else
2948 { /* This is a S-block. */
2949 retries = 0;
2950 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
2951 (tpdu[1] & 0x20)? "response": "request",
2952 (tpdu[1] & 0x1f));
2953 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
2955 /* Information field size request. */
2956 unsigned char ifsc = tpdu[3];
2958 if (ifsc < 16 || ifsc > 254)
2959 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2961 msg = send_buffer;
2962 tpdu = msg + hdrlen;
2963 tpdu[0] = nad_byte;
2964 tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
2965 tpdu[2] = 1;
2966 tpdu[3] = ifsc;
2967 tpdulen = 4;
2968 edc = compute_edc (tpdu, tpdulen, use_crc);
2969 if (use_crc)
2970 tpdu[tpdulen++] = (edc >> 8);
2971 tpdu[tpdulen++] = edc;
2972 DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
2974 else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
2976 /* Wait time extension request. */
2977 unsigned char bwi = tpdu[3];
2978 msg = send_buffer;
2979 tpdu = msg + hdrlen;
2980 tpdu[0] = nad_byte;
2981 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
2982 tpdu[2] = 1;
2983 tpdu[3] = bwi;
2984 tpdulen = 4;
2985 edc = compute_edc (tpdu, tpdulen, use_crc);
2986 if (use_crc)
2987 tpdu[tpdulen++] = (edc >> 8);
2988 tpdu[tpdulen++] = edc;
2989 DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
2990 print_progress (handle);
2992 else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
2994 DEBUGOUT ("T=1: resync ack from reader\n");
2995 /* Repeat previous block. */
2996 msg = send_buffer;
2997 tpdulen = last_tpdulen;
2999 else
3000 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3002 } /* end T=1 protocol loop. */
3004 return 0;
3008 /* Send the CCID Secure command to the reader. APDU_BUF should
3009 contain the APDU template. PIN_MODE defines how the pin gets
3010 formatted:
3012 1 := The PIN is ASCII encoded and of variable length. The
3013 length of the PIN entered will be put into Lc by the reader.
3014 The APDU should me made up of 4 bytes without Lc.
3016 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3017 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
3019 When called with RESP and NRESP set to NULL, the function will
3020 merely check whether the reader supports the secure command for the
3021 given APDU and PIN_MODE. */
3023 ccid_transceive_secure (ccid_driver_t handle,
3024 const unsigned char *apdu_buf, size_t apdu_buflen,
3025 int pin_mode, int pinlen_min, int pinlen_max,
3026 int pin_padlen,
3027 unsigned char *resp, size_t maxresplen, size_t *nresp)
3029 int rc;
3030 unsigned char send_buffer[10+259], recv_buffer[10+259];
3031 unsigned char *msg, *tpdu, *p;
3032 size_t msglen, tpdulen, n;
3033 unsigned char seqno;
3034 size_t dummy_nresp;
3035 int testmode;
3036 int cherry_mode = 0;
3038 testmode = !resp && !nresp;
3040 if (!nresp)
3041 nresp = &dummy_nresp;
3042 *nresp = 0;
3044 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3046 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3047 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
3048 else
3049 return CCID_DRIVER_ERR_NO_KEYPAD;
3051 if (pin_mode != 1)
3052 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3054 if (pin_padlen != 0)
3055 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3057 if (!pinlen_min)
3058 pinlen_min = 1;
3059 if (!pinlen_max)
3060 pinlen_max = 25;
3062 /* Note that the 25 is the maximum value the SPR532 allows. */
3063 if (pinlen_min < 1 || pinlen_min > 25
3064 || pinlen_max < 1 || pinlen_max > 25
3065 || pinlen_min > pinlen_max)
3066 return CCID_DRIVER_ERR_INV_VALUE;
3068 /* We have only tested a few readers so better don't risk anything
3069 and do not allow the use with other readers. */
3070 switch (handle->id_vendor)
3072 case VENDOR_SCM: /* Tested with SPR 532. */
3073 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3074 break;
3075 case VENDOR_CHERRY:
3076 /* The CHERRY XX44 keyboard echos an asterisk for each entered
3077 character on the keyboard channel. We use a special variant
3078 of PC_to_RDR_Secure which directs these characters to the
3079 smart card's bulk-in channel. We also need to append a zero
3080 Lc byte to the APDU. It seems that it will be replaced with
3081 the actual length instead of being appended before the APDU
3082 is send to the card. */
3083 cherry_mode = 1;
3084 break;
3085 default:
3086 return CCID_DRIVER_ERR_NOT_SUPPORTED;
3089 if (testmode)
3090 return 0; /* Success */
3092 msg = send_buffer;
3093 if (handle->id_vendor == VENDOR_SCM)
3095 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3096 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3097 NULL, 0, NULL);
3098 if (rc)
3099 return rc;
3102 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3103 msg[5] = 0; /* slot */
3104 msg[6] = seqno = handle->seqno++;
3105 msg[7] = 0; /* bBWI */
3106 msg[8] = 0; /* RFU */
3107 msg[9] = 0; /* RFU */
3108 msg[10] = 0; /* Perform PIN verification. */
3109 msg[11] = 0; /* Timeout in seconds. */
3110 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3111 if (handle->id_vendor == VENDOR_SCM)
3113 /* For the SPR532 the next 2 bytes need to be zero. We do this
3114 for all SCM products. Kudos to Martin Paljak for this
3115 hint. */
3116 msg[13] = msg[14] = 0;
3118 else
3120 msg[13] = 0x00; /* bmPINBlockString:
3121 0 bits of pin length to insert.
3122 0 bytes of PIN block size. */
3123 msg[14] = 0x00; /* bmPINLengthFormat:
3124 Units are bytes, position is 0. */
3127 /* The following is a little endian word. */
3128 msg[15] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
3129 msg[16] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
3131 msg[17] = 0x02; /* bEntryValidationCondition:
3132 Validation key pressed */
3133 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
3134 msg[17] |= 0x01; /* Max size reached. */
3135 msg[18] = 0xff; /* bNumberMessage: Default. */
3136 msg[19] = 0x04; /* wLangId-High. */
3137 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
3138 msg[21] = 0; /* bMsgIndex. */
3139 /* bTeoProlog follows: */
3140 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3141 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
3142 msg[24] = 0; /* The apdulen will be filled in by the reader. */
3143 /* APDU follows: */
3144 msg[25] = apdu_buf[0]; /* CLA */
3145 msg[26] = apdu_buf[1]; /* INS */
3146 msg[27] = apdu_buf[2]; /* P1 */
3147 msg[28] = apdu_buf[3]; /* P2 */
3148 msglen = 29;
3149 if (cherry_mode)
3150 msg[msglen++] = 0;
3151 /* An EDC is not required. */
3152 set_msg_len (msg, msglen - 10);
3154 rc = bulk_out (handle, msg, msglen, 0);
3155 if (rc)
3156 return rc;
3158 msg = recv_buffer;
3159 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3160 RDR_to_PC_DataBlock, seqno, 30000, 0);
3161 if (rc)
3162 return rc;
3164 tpdu = msg + 10;
3165 tpdulen = msglen - 10;
3167 if (handle->apdu_level)
3169 if (resp)
3171 if (tpdulen > maxresplen)
3173 DEBUGOUT_2 ("provided buffer too short for received data "
3174 "(%u/%u)\n",
3175 (unsigned int)tpdulen, (unsigned int)maxresplen);
3176 return CCID_DRIVER_ERR_INV_VALUE;
3179 memcpy (resp, tpdu, tpdulen);
3180 *nresp = tpdulen;
3182 return 0;
3185 if (tpdulen < 4)
3187 usb_clear_halt (handle->idev, handle->ep_bulk_in);
3188 return CCID_DRIVER_ERR_ABORTED;
3190 if (debug_level > 1)
3191 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3192 ((msg[11] & 0xc0) == 0x80)? 'R' :
3193 (msg[11] & 0x80)? 'S' : 'I',
3194 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3195 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3196 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3198 if (!(tpdu[1] & 0x80))
3199 { /* This is an I-block. */
3200 /* Last block sent was successful. */
3201 handle->t1_ns ^= 1;
3203 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3204 { /* Reponse does not match our sequence number. */
3205 DEBUGOUT ("I-block with wrong seqno received\n");
3206 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3209 handle->t1_nr ^= 1;
3211 p = tpdu + 3; /* Skip the prologue field. */
3212 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3213 /* fixme: verify the checksum. */
3214 if (resp)
3216 if (n > maxresplen)
3218 DEBUGOUT_2 ("provided buffer too short for received data "
3219 "(%u/%u)\n",
3220 (unsigned int)n, (unsigned int)maxresplen);
3221 return CCID_DRIVER_ERR_INV_VALUE;
3224 memcpy (resp, p, n);
3225 resp += n;
3226 *nresp += n;
3227 maxresplen -= n;
3230 if (!(tpdu[1] & 0x20))
3231 return 0; /* No chaining requested - ready. */
3233 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3234 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3236 else if ((tpdu[1] & 0xc0) == 0x80)
3237 { /* This is a R-block. */
3238 if ( (tpdu[1] & 0x0f))
3239 { /* Error: repeat last block */
3240 DEBUGOUT ("No retries supported for Secure operation\n");
3241 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3243 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3244 { /* Reponse does not match our sequence number. */
3245 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3246 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3248 else
3249 { /* Send next chunk. */
3250 DEBUGOUT ("chaining not supported on Secure operation\n");
3251 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3254 else
3255 { /* This is a S-block. */
3256 DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3257 (tpdu[1] & 0x20)? "response": "request",
3258 (tpdu[1] & 0x1f));
3259 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3262 return 0;
3268 #ifdef TEST
3271 static void
3272 print_error (int err)
3274 const char *p;
3275 char buf[50];
3277 switch (err)
3279 case 0: p = "success";
3280 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3281 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3282 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3283 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3284 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3285 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3286 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3287 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3288 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3289 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3290 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3291 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3292 default: sprintf (buf, "0x%05x", err); p = buf; break;
3294 fprintf (stderr, "operation failed: %s\n", p);
3298 static void
3299 print_data (const unsigned char *data, size_t length)
3301 if (length >= 2)
3303 fprintf (stderr, "operation status: %02X%02X\n",
3304 data[length-2], data[length-1]);
3305 length -= 2;
3307 if (length)
3309 fputs (" returned data:", stderr);
3310 for (; length; length--, data++)
3311 fprintf (stderr, " %02X", *data);
3312 putc ('\n', stderr);
3316 static void
3317 print_result (int rc, const unsigned char *data, size_t length)
3319 if (rc)
3320 print_error (rc);
3321 else if (data)
3322 print_data (data, length);
3326 main (int argc, char **argv)
3328 int rc;
3329 ccid_driver_t ccid;
3330 int slotstat;
3331 unsigned char result[512];
3332 size_t resultlen;
3333 int no_pinpad = 0;
3334 int verify_123456 = 0;
3335 int did_verify = 0;
3336 int no_poll = 0;
3338 if (argc)
3340 argc--;
3341 argv++;
3344 while (argc)
3346 if ( !strcmp (*argv, "--list"))
3348 char *p;
3349 p = ccid_get_reader_list ();
3350 if (!p)
3351 return 1;
3352 fputs (p, stderr);
3353 free (p);
3354 return 0;
3356 else if ( !strcmp (*argv, "--debug"))
3358 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3359 argc--; argv++;
3361 else if ( !strcmp (*argv, "--no-poll"))
3363 no_poll = 1;
3364 argc--; argv++;
3366 else if ( !strcmp (*argv, "--no-pinpad"))
3368 no_pinpad = 1;
3369 argc--; argv++;
3371 else if ( !strcmp (*argv, "--verify-123456"))
3373 verify_123456 = 1;
3374 argc--; argv++;
3376 else
3377 break;
3380 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3381 if (rc)
3382 return 1;
3384 if (!no_poll)
3385 ccid_poll (ccid);
3386 fputs ("getting ATR ...\n", stderr);
3387 rc = ccid_get_atr (ccid, NULL, 0, NULL);
3388 if (rc)
3390 print_error (rc);
3391 return 1;
3394 if (!no_poll)
3395 ccid_poll (ccid);
3396 fputs ("getting slot status ...\n", stderr);
3397 rc = ccid_slot_status (ccid, &slotstat);
3398 if (rc)
3400 print_error (rc);
3401 return 1;
3404 if (!no_poll)
3405 ccid_poll (ccid);
3407 fputs ("selecting application OpenPGP ....\n", stderr);
3409 static unsigned char apdu[] = {
3410 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3411 rc = ccid_transceive (ccid,
3412 apdu, sizeof apdu,
3413 result, sizeof result, &resultlen);
3414 print_result (rc, result, resultlen);
3418 if (!no_poll)
3419 ccid_poll (ccid);
3421 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3423 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3424 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3425 result, sizeof result, &resultlen);
3426 print_result (rc, result, resultlen);
3429 if (!no_pinpad)
3433 if (!no_pinpad)
3435 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3438 if (ccid_transceive_secure (ccid,
3439 apdu, sizeof apdu,
3440 1, 0, 0, 0,
3441 NULL, 0, NULL))
3442 fputs ("can't verify using a PIN-Pad reader\n", stderr);
3443 else
3445 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3447 rc = ccid_transceive_secure (ccid,
3448 apdu, sizeof apdu,
3449 1, 0, 0, 0,
3450 result, sizeof result, &resultlen);
3451 print_result (rc, result, resultlen);
3452 did_verify = 1;
3456 if (verify_123456 && !did_verify)
3458 fputs ("verifying that CHV1 is 123456....\n", stderr);
3460 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3461 6, '1','2','3','4','5','6'};
3462 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3463 result, sizeof result, &resultlen);
3464 print_result (rc, result, resultlen);
3468 if (!rc)
3470 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3472 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3473 rc = ccid_transceive (ccid, apdu, sizeof apdu,
3474 result, sizeof result, &resultlen);
3475 print_result (rc, result, resultlen);
3479 ccid_close_reader (ccid);
3481 return 0;
3485 * Local Variables:
3486 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3487 * End:
3489 #endif /*TEST*/
3490 #endif /*HAVE_LIBUSB*/