2007-09-14 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / scd / ccid-driver.c
blobec847c6cb82638db6227b8ae5f6e75fffdcdff3b
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
3 * Written by Werner Koch.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 * ALTERNATIVELY, this file may be distributed under the terms of the
21 * following license, in which case the provisions of this license are
22 * required INSTEAD OF the GNU General Public License. If you wish to
23 * allow use of your version of this file only under the terms of the
24 * GNU General Public License, and not to allow others to use your
25 * version of this file under the terms of the following license,
26 * indicate your decision by deleting this paragraph and the license
27 * below.
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
31 * are met:
32 * 1. Redistributions of source code must retain the above copyright
33 * notice, and the entire permission notice in its entirety,
34 * including the disclaimer of warranties.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 * 3. The name of the author may not be used to endorse or promote
39 * products derived from this software without specific prior
40 * written permission.
42 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
43 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
44 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
45 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
46 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
47 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
48 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
50 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
51 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
52 * OF THE POSSIBILITY OF SUCH DAMAGE.
54 * $Date$
58 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
59 smartcard via a reader connected to the USB.
61 This is a limited driver allowing to use some CCID drivers directly
62 without any other specila drivers. This is a fallback driver to be
63 used when nothing else works or the system should be kept minimal
64 for security reasons. It makes use of the libusb library to gain
65 portable access to USB.
67 This driver has been tested with the SCM SCR335 and SPR532
68 smartcard readers and requires that a reader implements APDU or
69 TPDU level exchange and does fully automatic initialization.
72 #ifdef HAVE_CONFIG_H
73 # include <config.h>
74 #endif
76 #if defined(HAVE_LIBUSB) || defined(TEST)
78 #include <errno.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <assert.h>
83 #include <sys/types.h>
84 #include <sys/stat.h>
85 #include <fcntl.h>
87 #include <usb.h>
89 #include "ccid-driver.h"
91 #define DRVNAME "ccid-driver: "
94 /* Depending on how this source is used we either define our error
95 output to go to stderr or to the jnlib based logging functions. We
96 use the latter when GNUPG_MAJOR_VERSION is defines or when both,
97 GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
99 #if defined(GNUPG_MAJOR_VERSION) \
100 || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
102 #if defined(GNUPG_SCD_MAIN_HEADER)
103 # include GNUPG_SCD_MAIN_HEADER
104 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
105 # include "options.h"
106 # include "util.h"
107 # include "memory.h"
108 # include "cardglue.h"
109 # else /* This is the modularized GnuPG 1.9 or later. */
110 # include "scdaemon.h"
111 #endif
114 # define DEBUGOUT(t) do { if (debug_level) \
115 log_debug (DRVNAME t); } while (0)
116 # define DEBUGOUT_1(t,a) do { if (debug_level) \
117 log_debug (DRVNAME t,(a)); } while (0)
118 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
119 log_debug (DRVNAME t,(a),(b)); } while (0)
120 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
121 log_debug (DRVNAME t,(a),(b),(c));} while (0)
122 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
123 log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
124 # define DEBUGOUT_CONT(t) do { if (debug_level) \
125 log_printf (t); } while (0)
126 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
127 log_printf (t,(a)); } while (0)
128 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
129 log_printf (t,(a),(b)); } while (0)
130 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
131 log_printf (t,(a),(b),(c)); } while (0)
132 # define DEBUGOUT_LF() do { if (debug_level) \
133 log_printf ("\n"); } while (0)
135 #else /* Other usage of this source - don't use gnupg specifics. */
137 # define DEBUGOUT(t) do { if (debug_level) \
138 fprintf (stderr, DRVNAME t); } while (0)
139 # define DEBUGOUT_1(t,a) do { if (debug_level) \
140 fprintf (stderr, DRVNAME t, (a)); } while (0)
141 # define DEBUGOUT_2(t,a,b) do { if (debug_level) \
142 fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
143 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
144 fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
145 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
146 fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
147 # define DEBUGOUT_CONT(t) do { if (debug_level) \
148 fprintf (stderr, t); } while (0)
149 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
150 fprintf (stderr, t, (a)); } while (0)
151 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
152 fprintf (stderr, t, (a), (b)); } while (0)
153 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
154 fprintf (stderr, t, (a), (b), (c)); } while (0)
155 # define DEBUGOUT_LF() do { if (debug_level) \
156 putc ('\n', stderr); } while (0)
158 #endif /* This source not used by scdaemon. */
162 enum {
163 RDR_to_PC_NotifySlotChange= 0x50,
164 RDR_to_PC_HardwareError = 0x51,
166 PC_to_RDR_SetParameters = 0x61,
167 PC_to_RDR_IccPowerOn = 0x62,
168 PC_to_RDR_IccPowerOff = 0x63,
169 PC_to_RDR_GetSlotStatus = 0x65,
170 PC_to_RDR_Secure = 0x69,
171 PC_to_RDR_T0APDU = 0x6a,
172 PC_to_RDR_Escape = 0x6b,
173 PC_to_RDR_GetParameters = 0x6c,
174 PC_to_RDR_ResetParameters = 0x6d,
175 PC_to_RDR_IccClock = 0x6e,
176 PC_to_RDR_XfrBlock = 0x6f,
177 PC_to_RDR_Mechanical = 0x71,
178 PC_to_RDR_Abort = 0x72,
179 PC_to_RDR_SetDataRate = 0x73,
181 RDR_to_PC_DataBlock = 0x80,
182 RDR_to_PC_SlotStatus = 0x81,
183 RDR_to_PC_Parameters = 0x82,
184 RDR_to_PC_Escape = 0x83,
185 RDR_to_PC_DataRate = 0x84
189 /* Two macro to detect whether a CCID command has failed and to get
190 the error code. These macros assume that we can access the
191 mandatory first 10 bytes of a CCID message in BUF. */
192 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
193 #define CCID_ERROR_CODE(buf) (((unsigned char *)(buf))[8])
196 /* We need to know the vendor to do some hacks. */
197 enum {
198 VENDOR_CHERRY = 0x046a,
199 VENDOR_SCM = 0x04e6,
200 VENDOR_OMNIKEY= 0x076b,
201 VENDOR_GEMPC = 0x08e6,
202 VENDOR_KAAN = 0x0d46
205 /* A list and a table with special transport descriptions. */
206 enum {
207 TRANSPORT_USB = 0, /* Standard USB transport. */
208 TRANSPORT_CM4040 = 1 /* As used by the Cardman 4040. */
211 static struct
213 char *name; /* Device name. */
214 int type;
216 } transports[] = {
217 { "/dev/cmx0", TRANSPORT_CM4040 },
218 { "/dev/cmx1", TRANSPORT_CM4040 },
219 { NULL },
223 /* Store information on the driver's state. A pointer to such a
224 structure is used as handle for most functions. */
225 struct ccid_driver_s
227 usb_dev_handle *idev;
228 char *rid;
229 int dev_fd; /* -1 for USB transport or file descriptor of the
230 transport device. */
231 unsigned short id_vendor;
232 unsigned short id_product;
233 unsigned short bcd_device;
234 int ifc_no;
235 int ep_bulk_out;
236 int ep_bulk_in;
237 int ep_intr;
238 int seqno;
239 unsigned char t1_ns;
240 unsigned char t1_nr;
241 int nonnull_nad;
242 int auto_ifsd;
243 int max_ifsd;
244 int ifsd;
245 int powered_off;
246 int has_pinpad;
247 int apdu_level; /* Reader supports short APDU level exchange. */
251 static int initialized_usb; /* Tracks whether USB has been initialized. */
252 static int debug_level; /* Flag to control the debug output.
253 0 = No debugging
254 1 = USB I/O info
255 2 = T=1 protocol tracing
259 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
260 int use_crc);
261 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen);
262 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
263 size_t *nread, int expected_type, int seqno, int timeout,
264 int no_debug);
266 /* Convert a little endian stored 4 byte value into an unsigned
267 integer. */
268 static unsigned int
269 convert_le_u32 (const unsigned char *buf)
271 return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
274 static void
275 set_msg_len (unsigned char *msg, unsigned int length)
277 msg[1] = length;
278 msg[2] = length >> 8;
279 msg[3] = length >> 16;
280 msg[4] = length >> 24;
284 /* Pint an error message for a failed CCID command including a textual
285 error code. MSG is shall be the CCID message of at least 10 bytes. */
286 static void
287 print_command_failed (const unsigned char *msg)
289 const char *t;
290 char buffer[100];
291 int ec;
293 if (!debug_level)
294 return;
296 ec = CCID_ERROR_CODE (msg);
297 switch (ec)
299 case 0x00: t = "Command not supported"; break;
301 case 0xE0: t = "Slot busy"; break;
302 case 0xEF: t = "PIN cancelled"; break;
303 case 0xF0: t = "PIN timeout"; break;
305 case 0xF2: t = "Automatic sequence ongoing"; break;
306 case 0xF3: t = "Deactivated Protocol"; break;
307 case 0xF4: t = "Procedure byte conflict"; break;
308 case 0xF5: t = "ICC class not supported"; break;
309 case 0xF6: t = "ICC protocol not supported"; break;
310 case 0xF7: t = "Bad checksum in ATR"; break;
311 case 0xF8: t = "Bad TS in ATR"; break;
313 case 0xFB: t = "An all inclusive hardware error occurred"; break;
314 case 0xFC: t = "Overrun error while talking to the ICC"; break;
315 case 0xFD: t = "Parity error while talking to the ICC"; break;
316 case 0xFE: t = "CCID timed out while talking to the ICC"; break;
317 case 0xFF: t = "Host aborted the current activity"; break;
319 default:
320 if (ec > 0 && ec < 128)
321 sprintf (buffer, "Parameter error at offset %d", ec);
322 else
323 sprintf (buffer, "Error code %02X", ec);
324 t = buffer;
325 break;
327 DEBUGOUT_1 ("CCID command failed: %s\n", t);
331 /* Given a handle used for special transport prepare it for use. In
332 particular setup all information in way that resembles what
333 parse_cccid_descriptor does. */
334 static void
335 prepare_special_transport (ccid_driver_t handle)
337 assert (!handle->id_vendor);
339 handle->nonnull_nad = 0;
340 handle->auto_ifsd = 0;
341 handle->max_ifsd = 32;
342 handle->ifsd = 0;
343 handle->has_pinpad = 0;
344 handle->apdu_level = 0;
345 switch (handle->id_product)
347 case TRANSPORT_CM4040:
348 DEBUGOUT ("setting up transport for CardMan 4040\n");
349 handle->apdu_level = 1;
350 break;
352 default: assert (!"transport not defined");
356 /* Parse a CCID descriptor, optionally print all available features
357 and test whether this reader is usable by this driver. Returns 0
358 if it is usable.
360 Note, that this code is based on the one in lsusb.c of the
361 usb-utils package, I wrote on 2003-09-01. -wk. */
362 static int
363 parse_ccid_descriptor (ccid_driver_t handle,
364 const unsigned char *buf, size_t buflen)
366 unsigned int i;
367 unsigned int us;
368 int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
371 handle->nonnull_nad = 0;
372 handle->auto_ifsd = 0;
373 handle->max_ifsd = 32;
374 handle->ifsd = 0;
375 handle->has_pinpad = 0;
376 handle->apdu_level = 0;
377 DEBUGOUT_3 ("idVendor: %04X idProduct: %04X bcdDevice: %04X\n",
378 handle->id_vendor, handle->id_product, handle->bcd_device);
379 if (buflen < 54 || buf[0] < 54)
381 DEBUGOUT ("CCID device descriptor is too short\n");
382 return -1;
385 DEBUGOUT ("ChipCard Interface Descriptor:\n");
386 DEBUGOUT_1 (" bLength %5u\n", buf[0]);
387 DEBUGOUT_1 (" bDescriptorType %5u\n", buf[1]);
388 DEBUGOUT_2 (" bcdCCID %2x.%02x", buf[3], buf[2]);
389 if (buf[3] != 1 || buf[2] != 0)
390 DEBUGOUT_CONT(" (Warning: Only accurate for version 1.0)");
391 DEBUGOUT_LF ();
393 DEBUGOUT_1 (" nMaxSlotIndex %5u\n", buf[4]);
394 DEBUGOUT_2 (" bVoltageSupport %5u %s\n",
395 buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
396 : buf[5] == 3? "1.8V":"?"));
398 us = convert_le_u32 (buf+6);
399 DEBUGOUT_1 (" dwProtocols %5u ", us);
400 if ((us & 1))
401 DEBUGOUT_CONT (" T=0");
402 if ((us & 2))
404 DEBUGOUT_CONT (" T=1");
405 have_t1 = 1;
407 if ((us & ~3))
408 DEBUGOUT_CONT (" (Invalid values detected)");
409 DEBUGOUT_LF ();
411 us = convert_le_u32(buf+10);
412 DEBUGOUT_1 (" dwDefaultClock %5u\n", us);
413 us = convert_le_u32(buf+14);
414 DEBUGOUT_1 (" dwMaxiumumClock %5u\n", us);
415 DEBUGOUT_1 (" bNumClockSupported %5u\n", buf[18]);
416 us = convert_le_u32(buf+19);
417 DEBUGOUT_1 (" dwDataRate %7u bps\n", us);
418 us = convert_le_u32(buf+23);
419 DEBUGOUT_1 (" dwMaxDataRate %7u bps\n", us);
420 DEBUGOUT_1 (" bNumDataRatesSupp. %5u\n", buf[27]);
422 us = convert_le_u32(buf+28);
423 DEBUGOUT_1 (" dwMaxIFSD %5u\n", us);
424 handle->max_ifsd = us;
426 us = convert_le_u32(buf+32);
427 DEBUGOUT_1 (" dwSyncProtocols %08X ", us);
428 if ((us&1))
429 DEBUGOUT_CONT ( " 2-wire");
430 if ((us&2))
431 DEBUGOUT_CONT ( " 3-wire");
432 if ((us&4))
433 DEBUGOUT_CONT ( " I2C");
434 DEBUGOUT_LF ();
436 us = convert_le_u32(buf+36);
437 DEBUGOUT_1 (" dwMechanical %08X ", us);
438 if ((us & 1))
439 DEBUGOUT_CONT (" accept");
440 if ((us & 2))
441 DEBUGOUT_CONT (" eject");
442 if ((us & 4))
443 DEBUGOUT_CONT (" capture");
444 if ((us & 8))
445 DEBUGOUT_CONT (" lock");
446 DEBUGOUT_LF ();
448 us = convert_le_u32(buf+40);
449 DEBUGOUT_1 (" dwFeatures %08X\n", us);
450 if ((us & 0x0002))
452 DEBUGOUT (" Auto configuration based on ATR\n");
453 have_auto_conf = 1;
455 if ((us & 0x0004))
456 DEBUGOUT (" Auto activation on insert\n");
457 if ((us & 0x0008))
458 DEBUGOUT (" Auto voltage selection\n");
459 if ((us & 0x0010))
460 DEBUGOUT (" Auto clock change\n");
461 if ((us & 0x0020))
462 DEBUGOUT (" Auto baud rate change\n");
463 if ((us & 0x0040))
464 DEBUGOUT (" Auto parameter negotation made by CCID\n");
465 else if ((us & 0x0080))
466 DEBUGOUT (" Auto PPS made by CCID\n");
467 else if ((us & (0x0040 | 0x0080)))
468 DEBUGOUT (" WARNING: conflicting negotation features\n");
470 if ((us & 0x0100))
471 DEBUGOUT (" CCID can set ICC in clock stop mode\n");
472 if ((us & 0x0200))
474 DEBUGOUT (" NAD value other than 0x00 accepted\n");
475 handle->nonnull_nad = 1;
477 if ((us & 0x0400))
479 DEBUGOUT (" Auto IFSD exchange\n");
480 handle->auto_ifsd = 1;
483 if ((us & 0x00010000))
485 DEBUGOUT (" TPDU level exchange\n");
486 have_tpdu = 1;
488 else if ((us & 0x00020000))
490 DEBUGOUT (" Short APDU level exchange\n");
491 handle->apdu_level = 1;
493 else if ((us & 0x00040000))
495 DEBUGOUT (" Short and extended APDU level exchange\n");
496 handle->apdu_level = 1;
498 else if ((us & 0x00070000))
499 DEBUGOUT (" WARNING: conflicting exchange levels\n");
501 us = convert_le_u32(buf+44);
502 DEBUGOUT_1 (" dwMaxCCIDMsgLen %5u\n", us);
504 DEBUGOUT ( " bClassGetResponse ");
505 if (buf[48] == 0xff)
506 DEBUGOUT_CONT ("echo\n");
507 else
508 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
510 DEBUGOUT ( " bClassEnvelope ");
511 if (buf[49] == 0xff)
512 DEBUGOUT_CONT ("echo\n");
513 else
514 DEBUGOUT_CONT_1 (" %02X\n", buf[48]);
516 DEBUGOUT ( " wlcdLayout ");
517 if (!buf[50] && !buf[51])
518 DEBUGOUT_CONT ("none\n");
519 else
520 DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
522 DEBUGOUT_1 (" bPINSupport %5u ", buf[52]);
523 if ((buf[52] & 1))
525 DEBUGOUT_CONT ( " verification");
526 handle->has_pinpad |= 1;
528 if ((buf[52] & 2))
530 DEBUGOUT_CONT ( " modification");
531 handle->has_pinpad |= 2;
533 DEBUGOUT_LF ();
535 DEBUGOUT_1 (" bMaxCCIDBusySlots %5u\n", buf[53]);
537 if (buf[0] > 54) {
538 DEBUGOUT (" junk ");
539 for (i=54; i < buf[0]-54; i++)
540 DEBUGOUT_CONT_1 (" %02X", buf[i]);
541 DEBUGOUT_LF ();
544 if (!have_t1 || !(have_tpdu || handle->apdu_level) || !have_auto_conf)
546 DEBUGOUT ("this drivers requires that the reader supports T=1, "
547 "TPDU or APDU level exchange and auto configuration - "
548 "this is not available\n");
549 return -1;
553 /* SCM drivers get stuck in their internal USB stack if they try to
554 send a frame of n*wMaxPacketSize back to us. Given that
555 wMaxPacketSize is 64 for these readers we set the IFSD to a value
556 lower than that:
557 64 - 10 CCID header - 4 T1frame - 2 reserved = 48
558 Product Ids:
559 0xe001 - SCR 331
560 0x5111 - SCR 331-DI
561 0x5115 - SCR 335
562 0xe003 - SPR 532
564 if (handle->id_vendor == VENDOR_SCM
565 && handle->max_ifsd > 48
566 && ( (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
567 ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
568 ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
569 ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
572 DEBUGOUT ("enabling workaround for buggy SCM readers\n");
573 handle->max_ifsd = 48;
577 return 0;
581 static char *
582 get_escaped_usb_string (usb_dev_handle *idev, int idx,
583 const char *prefix, const char *suffix)
585 int rc;
586 unsigned char buf[280];
587 unsigned char *s;
588 unsigned int langid;
589 size_t i, n, len;
590 char *result;
592 if (!idx)
593 return NULL;
595 /* Fixme: The next line is for the current Valgrid without support
596 for USB IOCTLs. */
597 memset (buf, 0, sizeof buf);
599 /* First get the list of supported languages and use the first one.
600 If we do don't find it we try to use English. Note that this is
601 all in a 2 bute Unicode encoding using little endian. */
602 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
603 (USB_DT_STRING << 8), 0,
604 (char*)buf, sizeof buf, 1000 /* ms timeout */);
605 if (rc < 4)
606 langid = 0x0409; /* English. */
607 else
608 langid = (buf[3] << 8) | buf[2];
610 rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
611 (USB_DT_STRING << 8) + idx, langid,
612 (char*)buf, sizeof buf, 1000 /* ms timeout */);
613 if (rc < 2 || buf[1] != USB_DT_STRING)
614 return NULL; /* Error or not a string. */
615 len = buf[0];
616 if (len > rc)
617 return NULL; /* Larger than our buffer. */
619 for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
621 if (s[1])
622 n++; /* High byte set. */
623 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
624 n += 3 ;
625 else
626 n++;
629 result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
630 if (!result)
631 return NULL;
633 strcpy (result, prefix);
634 n = strlen (prefix);
635 for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
637 if (s[1])
638 result[n++] = '\xff'; /* High byte set. */
639 else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
641 sprintf (result+n, "%%%02X", *s);
642 n += 3;
644 else
645 result[n++] = *s;
647 strcpy (result+n, suffix);
649 return result;
652 /* This function creates an reader id to be used to find the same
653 physical reader after a reset. It returns an allocated and possibly
654 percent escaped string or NULL if not enough memory is available. */
655 static char *
656 make_reader_id (usb_dev_handle *idev,
657 unsigned int vendor, unsigned int product,
658 unsigned char serialno_index)
660 char *rid;
661 char prefix[20];
663 sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
664 rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
665 if (!rid)
667 rid = malloc (strlen (prefix) + 3 + 1);
668 if (!rid)
669 return NULL;
670 strcpy (rid, prefix);
671 strcat (rid, "X:0");
673 return rid;
677 /* Helper to find the endpoint from an interface descriptor. */
678 static int
679 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
681 int no;
682 int want_bulk_in = 0;
684 if (mode == 1)
685 want_bulk_in = 0x80;
686 for (no=0; no < ifcdesc->bNumEndpoints; no++)
688 struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
689 if (ep->bDescriptorType != USB_DT_ENDPOINT)
691 else if (mode == 2
692 && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
693 == USB_ENDPOINT_TYPE_INTERRUPT)
694 && (ep->bEndpointAddress & 0x80))
695 return (ep->bEndpointAddress & 0x0f);
696 else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
697 == USB_ENDPOINT_TYPE_BULK)
698 && (ep->bEndpointAddress & 0x80) == want_bulk_in)
699 return (ep->bEndpointAddress & 0x0f);
701 /* Should never happen. */
702 return mode == 2? 0x83 : mode == 1? 0x82 :1;
706 /* Helper for scan_or_find_devices. This function returns true if a
707 requested device has been found or the caller should stop scanning
708 for other reasons. */
709 static int
710 scan_or_find_usb_device (int scan_mode,
711 int *readerno, int *count, char **rid_list,
712 const char *readerid,
713 struct usb_device *dev,
714 char **r_rid,
715 struct usb_device **r_dev,
716 usb_dev_handle **r_idev,
717 unsigned char **ifcdesc_extra,
718 size_t *ifcdesc_extra_len,
719 int *interface_number,
720 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
722 int cfg_no;
723 int ifc_no;
724 int set_no;
725 struct usb_config_descriptor *config;
726 struct usb_interface *interface;
727 struct usb_interface_descriptor *ifcdesc;
728 char *rid;
729 usb_dev_handle *idev;
731 *r_idev = NULL;
733 for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
735 config = dev->config + cfg_no;
736 if(!config)
737 continue;
739 for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
741 interface = config->interface + ifc_no;
742 if (!interface)
743 continue;
745 for (set_no=0; set_no < interface->num_altsetting; set_no++)
747 ifcdesc = (interface->altsetting + set_no);
748 /* The second condition is for older SCM SPR 532 who did
749 not know about the assigned CCID class. Instead of
750 trying to interpret the strings we simply check the
751 product ID. */
752 if (ifcdesc && ifcdesc->extra
753 && ((ifcdesc->bInterfaceClass == 11
754 && ifcdesc->bInterfaceSubClass == 0
755 && ifcdesc->bInterfaceProtocol == 0)
756 || (ifcdesc->bInterfaceClass == 255
757 && dev->descriptor.idVendor == VENDOR_SCM
758 && dev->descriptor.idProduct == 0xe003)))
760 idev = usb_open (dev);
761 if (!idev)
763 DEBUGOUT_1 ("usb_open failed: %s\n",
764 strerror (errno));
765 continue; /* with next setting. */
768 rid = make_reader_id (idev,
769 dev->descriptor.idVendor,
770 dev->descriptor.idProduct,
771 dev->descriptor.iSerialNumber);
772 if (rid)
774 if (scan_mode)
776 char *p;
778 /* We are collecting infos about all
779 available CCID readers. Store them and
780 continue. */
781 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
782 *count, rid );
783 p = malloc ((*rid_list? strlen (*rid_list):0) + 1
784 + strlen (rid) + 1);
785 if (p)
787 *p = 0;
788 if (*rid_list)
790 strcat (p, *rid_list);
791 free (*rid_list);
793 strcat (p, rid);
794 strcat (p, "\n");
795 *rid_list = p;
797 else /* Out of memory. */
798 free (rid);
800 rid = NULL;
801 ++*count;
803 else if (!*readerno
804 || (*readerno < 0
805 && readerid
806 && !strcmp (readerid, rid)))
808 /* We found the requested reader. */
809 if (ifcdesc_extra && ifcdesc_extra_len)
811 *ifcdesc_extra = malloc (ifcdesc
812 ->extralen);
813 if (!*ifcdesc_extra)
815 usb_close (idev);
816 free (rid);
817 return 1; /* Out of core. */
819 memcpy (*ifcdesc_extra, ifcdesc->extra,
820 ifcdesc->extralen);
821 *ifcdesc_extra_len = ifcdesc->extralen;
824 if (interface_number)
825 *interface_number = (ifcdesc->bInterfaceNumber);
827 if (ep_bulk_out)
828 *ep_bulk_out = find_endpoint (ifcdesc, 0);
829 if (ep_bulk_in)
830 *ep_bulk_in = find_endpoint (ifcdesc, 1);
831 if (ep_intr)
832 *ep_intr = find_endpoint (ifcdesc, 2);
834 if (r_dev)
835 *r_dev = dev;
836 if (r_rid)
838 *r_rid = rid;
839 rid = NULL;
841 else
842 free (rid);
844 *r_idev = idev;
845 return 1; /* Found requested device. */
847 else
849 /* This is not yet the reader we want.
850 fixme: We should avoid the extra usb_open
851 in this case. */
852 if (*readerno >= 0)
853 --*readerno;
855 free (rid);
858 usb_close (idev);
859 idev = NULL;
860 return 0;
866 return 0;
869 /* Combination function to either scan all CCID devices or to find and
870 open one specific device.
872 The function returns 0 if a reader has been found or when a scan
873 returned without error.
875 With READERNO = -1 and READERID is NULL, scan mode is used and
876 R_RID should be the address where to store the list of reader_ids
877 we found. If on return this list is empty, no CCID device has been
878 found; otherwise it points to an allocated linked list of reader
879 IDs. Note that in this mode the function always returns NULL.
881 With READERNO >= 0 or READERID is not NULL find mode is used. This
882 uses the same algorithm as the scan mode but stops and returns at
883 the entry number READERNO and return the handle for the the opened
884 USB device. If R_RID is not NULL it will receive the reader ID of
885 that device. If R_DEV is not NULL it will the device pointer of
886 that device. If IFCDESC_EXTRA is NOT NULL it will receive a
887 malloced copy of the interfaces "extra: data filed;
888 IFCDESC_EXTRA_LEN receive the length of this field. If there is
889 no reader with number READERNO or that reader is not usable by our
890 implementation NULL will be returned. The caller must close a
891 returned USB device handle and free (if not passed as NULL) the
892 returned reader ID info as well as the IFCDESC_EXTRA. On error
893 NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
894 IFCDESC_EXTRA_LEN. With READERID being -1 the function stops if
895 the READERID was found.
897 If R_FD is not -1 on return the device is not using USB for
898 transport but the device associated with that file descriptor. In
899 this case INTERFACE will receive the transport type and the other
900 USB specific return values are not used; the return value is
901 (void*)(1).
903 Note that the first entry of the returned reader ID list in scan mode
904 corresponds with a READERNO of 0 in find mode.
906 static int
907 scan_or_find_devices (int readerno, const char *readerid,
908 char **r_rid,
909 struct usb_device **r_dev,
910 unsigned char **ifcdesc_extra,
911 size_t *ifcdesc_extra_len,
912 int *interface_number,
913 int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
914 usb_dev_handle **r_idev,
915 int *r_fd)
917 char *rid_list = NULL;
918 int count = 0;
919 struct usb_bus *busses, *bus;
920 struct usb_device *dev = NULL;
921 usb_dev_handle *idev = NULL;
922 int scan_mode = (readerno == -1 && !readerid);
923 int i;
925 /* Set return values to a default. */
926 if (r_rid)
927 *r_rid = NULL;
928 if (r_dev)
929 *r_dev = NULL;
930 if (ifcdesc_extra)
931 *ifcdesc_extra = NULL;
932 if (ifcdesc_extra_len)
933 *ifcdesc_extra_len = 0;
934 if (interface_number)
935 *interface_number = 0;
936 if (r_idev)
937 *r_idev = NULL;
938 if (r_fd)
939 *r_fd = -1;
941 /* See whether we want scan or find mode. */
942 if (scan_mode)
944 assert (r_rid);
947 usb_find_busses();
948 usb_find_devices();
950 #ifdef HAVE_USB_GET_BUSSES
951 busses = usb_get_busses();
952 #else
953 busses = usb_busses;
954 #endif
956 for (bus = busses; bus; bus = bus->next)
958 for (dev = bus->devices; dev; dev = dev->next)
960 if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
961 readerid,
962 dev,
963 r_rid,
964 r_dev,
965 &idev,
966 ifcdesc_extra,
967 ifcdesc_extra_len,
968 interface_number,
969 ep_bulk_out, ep_bulk_in, ep_intr))
971 /* Found requested device or out of core. */
972 if (!idev)
974 free (rid_list);
975 return -1; /* error */
977 *r_idev = idev;
978 return 0;
983 /* Now check whether there are any devices with special transport types. */
984 for (i=0; transports[i].name; i++)
986 int fd;
987 char *rid, *p;
989 fd = open (transports[i].name, O_RDWR);
990 if (fd == -1 && scan_mode && errno == EBUSY)
992 /* Ignore this error in scan mode because it indicates that
993 the device exists but is already open (most likely by us)
994 and thus in general suitable as a reader. */
996 else if (fd == -1)
998 DEBUGOUT_2 ("failed to open `%s': %s\n",
999 transports[i].name, strerror (errno));
1000 continue;
1003 rid = malloc (strlen (transports[i].name) + 30 + 10);
1004 if (!rid)
1006 if (fd != -1)
1007 close (fd);
1008 free (rid_list);
1009 return -1; /* Error. */
1011 sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1012 if (scan_mode)
1014 DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1015 p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1016 if (!p)
1018 if (fd != -1)
1019 close (fd);
1020 free (rid_list);
1021 free (rid);
1022 return -1; /* Error. */
1024 *p = 0;
1025 if (rid_list)
1027 strcat (p, rid_list);
1028 free (rid_list);
1030 strcat (p, rid);
1031 strcat (p, "\n");
1032 rid_list = p;
1033 ++count;
1035 else if (!readerno ||
1036 (readerno < 0 && readerid && !strcmp (readerid, rid)))
1038 /* Found requested device. */
1039 if (interface_number)
1040 *interface_number = transports[i].type;
1041 if (r_rid)
1042 *r_rid = rid;
1043 else
1044 free (rid);
1045 if (r_fd)
1046 *r_fd = fd;
1047 return 0; /* Okay, found device */
1049 else /* This is not yet the reader we want. */
1051 if (readerno >= 0)
1052 --readerno;
1054 free (rid);
1055 if (fd != -1)
1056 close (fd);
1059 if (scan_mode)
1061 *r_rid = rid_list;
1062 return 0;
1064 else
1065 return -1;
1069 /* Set the level of debugging to LEVEL and return the old level. -1
1070 just returns the old level. A level of 0 disables debugging, 1
1071 enables debugging, 2 enables additional tracing of the T=1
1072 protocol, other values are not yet defined. */
1074 ccid_set_debug_level (int level)
1076 int old = debug_level;
1077 if (level != -1)
1078 debug_level = level;
1079 return old;
1083 char *
1084 ccid_get_reader_list (void)
1086 char *reader_list;
1088 if (!initialized_usb)
1090 usb_init ();
1091 initialized_usb = 1;
1094 if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1095 NULL, NULL, NULL, NULL, NULL))
1096 return NULL; /* Error. */
1097 return reader_list;
1101 /* Open the reader with the internal number READERNO and return a
1102 pointer to be used as handle in HANDLE. Returns 0 on success. */
1103 int
1104 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1106 int rc = 0;
1107 struct usb_device *dev = NULL;
1108 usb_dev_handle *idev = NULL;
1109 int dev_fd = -1;
1110 char *rid = NULL;
1111 unsigned char *ifcdesc_extra = NULL;
1112 size_t ifcdesc_extra_len;
1113 int readerno;
1114 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1116 *handle = NULL;
1118 if (!initialized_usb)
1120 usb_init ();
1121 initialized_usb = 1;
1124 /* See whether we want to use the reader ID string or a reader
1125 number. A readerno of -1 indicates that the reader ID string is
1126 to be used. */
1127 if (readerid && strchr (readerid, ':'))
1128 readerno = -1; /* We want to use the readerid. */
1129 else if (readerid)
1131 readerno = atoi (readerid);
1132 if (readerno < 0)
1134 DEBUGOUT ("no CCID readers found\n");
1135 rc = CCID_DRIVER_ERR_NO_READER;
1136 goto leave;
1139 else
1140 readerno = 0; /* Default. */
1142 if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1143 &ifcdesc_extra, &ifcdesc_extra_len,
1144 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1145 &idev, &dev_fd) )
1147 if (readerno == -1)
1148 DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1149 else
1150 DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1151 rc = CCID_DRIVER_ERR_NO_READER;
1152 goto leave;
1155 /* Okay, this is a CCID reader. */
1156 *handle = calloc (1, sizeof **handle);
1157 if (!*handle)
1159 DEBUGOUT ("out of memory\n");
1160 rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1161 goto leave;
1163 (*handle)->rid = rid;
1164 if (idev) /* Regular USB transport. */
1166 (*handle)->idev = idev;
1167 (*handle)->dev_fd = -1;
1168 (*handle)->id_vendor = dev->descriptor.idVendor;
1169 (*handle)->id_product = dev->descriptor.idProduct;
1170 (*handle)->bcd_device = dev->descriptor.bcdDevice;
1171 (*handle)->ifc_no = ifc_no;
1172 (*handle)->ep_bulk_out = ep_bulk_out;
1173 (*handle)->ep_bulk_in = ep_bulk_in;
1174 (*handle)->ep_intr = ep_intr;
1176 else if (dev_fd != -1) /* Device transport. */
1178 (*handle)->idev = NULL;
1179 (*handle)->dev_fd = dev_fd;
1180 (*handle)->id_vendor = 0; /* Magic vendor for special transport. */
1181 (*handle)->id_product = ifc_no; /* Transport type */
1182 prepare_special_transport (*handle);
1184 else
1186 assert (!"no transport"); /* Bug. */
1189 DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n", readerno, rid );
1191 if (idev)
1193 if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1195 DEBUGOUT ("device not supported\n");
1196 rc = CCID_DRIVER_ERR_NO_READER;
1197 goto leave;
1200 rc = usb_claim_interface (idev, ifc_no);
1201 if (rc)
1203 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1204 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1205 goto leave;
1209 leave:
1210 free (ifcdesc_extra);
1211 if (rc)
1213 free (rid);
1214 if (idev)
1215 usb_close (idev);
1216 if (dev_fd != -1)
1217 close (dev_fd);
1218 free (*handle);
1219 *handle = NULL;
1222 return rc;
1226 static void
1227 do_close_reader (ccid_driver_t handle)
1229 int rc;
1230 unsigned char msg[100];
1231 size_t msglen;
1232 unsigned char seqno;
1234 if (!handle->powered_off)
1236 msg[0] = PC_to_RDR_IccPowerOff;
1237 msg[5] = 0; /* slot */
1238 msg[6] = seqno = handle->seqno++;
1239 msg[7] = 0; /* RFU */
1240 msg[8] = 0; /* RFU */
1241 msg[9] = 0; /* RFU */
1242 set_msg_len (msg, 0);
1243 msglen = 10;
1245 rc = bulk_out (handle, msg, msglen);
1246 if (!rc)
1247 bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1248 seqno, 2000, 0);
1249 handle->powered_off = 1;
1251 if (handle->idev)
1253 usb_release_interface (handle->idev, handle->ifc_no);
1254 usb_close (handle->idev);
1255 handle->idev = NULL;
1257 if (handle->dev_fd != -1)
1259 close (handle->dev_fd);
1260 handle->dev_fd = -1;
1265 /* Reset a reader on HANDLE. This is useful in case a reader has been
1266 plugged of and inserted at a different port. By resetting the
1267 handle, the same reader will be get used. Note, that on error the
1268 handle won't get released.
1270 This does not return an ATR, so ccid_get_atr should be called right
1271 after this one.
1273 int
1274 ccid_shutdown_reader (ccid_driver_t handle)
1276 int rc = 0;
1277 struct usb_device *dev = NULL;
1278 usb_dev_handle *idev = NULL;
1279 unsigned char *ifcdesc_extra = NULL;
1280 size_t ifcdesc_extra_len;
1281 int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1283 if (!handle || !handle->rid)
1284 return CCID_DRIVER_ERR_INV_VALUE;
1286 do_close_reader (handle);
1288 if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1289 &ifcdesc_extra, &ifcdesc_extra_len,
1290 &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1291 &idev, NULL) || !idev)
1293 DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1294 return CCID_DRIVER_ERR_NO_READER;
1297 if (idev)
1299 handle->idev = idev;
1300 handle->ifc_no = ifc_no;
1301 handle->ep_bulk_out = ep_bulk_out;
1302 handle->ep_bulk_in = ep_bulk_in;
1303 handle->ep_intr = ep_intr;
1305 if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1307 DEBUGOUT ("device not supported\n");
1308 rc = CCID_DRIVER_ERR_NO_READER;
1309 goto leave;
1312 rc = usb_claim_interface (idev, ifc_no);
1313 if (rc)
1315 DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1316 rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1317 goto leave;
1321 leave:
1322 free (ifcdesc_extra);
1323 if (rc)
1325 if (handle->idev)
1326 usb_close (handle->idev);
1327 handle->idev = NULL;
1328 if (handle->dev_fd != -1)
1329 close (handle->dev_fd);
1330 handle->dev_fd = -1;
1333 return rc;
1338 /* Close the reader HANDLE. */
1339 int
1340 ccid_close_reader (ccid_driver_t handle)
1342 if (!handle || (!handle->idev && handle->dev_fd == -1))
1343 return 0;
1345 do_close_reader (handle);
1346 free (handle->rid);
1347 free (handle);
1348 return 0;
1352 /* Return False if a card is present and powered. */
1354 ccid_check_card_presence (ccid_driver_t handle)
1357 return -1;
1361 /* Write NBYTES of BUF to file descriptor FD. */
1362 static int
1363 writen (int fd, const void *buf, size_t nbytes)
1365 size_t nleft = nbytes;
1366 int nwritten;
1368 while (nleft > 0)
1370 nwritten = write (fd, buf, nleft);
1371 if (nwritten < 0)
1373 if (errno == EINTR)
1374 nwritten = 0;
1375 else
1376 return -1;
1378 nleft -= nwritten;
1379 buf = (const char*)buf + nwritten;
1382 return 0;
1386 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1387 Returns 0 on success. */
1388 static int
1389 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen)
1391 int rc;
1393 if (handle->idev)
1395 rc = usb_bulk_write (handle->idev,
1396 handle->ep_bulk_out,
1397 (char*)msg, msglen,
1398 1000 /* ms timeout */);
1399 if (rc == msglen)
1400 return 0;
1401 if (rc == -1)
1402 DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1403 else
1404 DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1406 else
1408 rc = writen (handle->dev_fd, msg, msglen);
1409 if (!rc)
1410 return 0;
1411 DEBUGOUT_2 ("writen to %d failed: %s\n",
1412 handle->dev_fd, strerror (errno));
1415 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1419 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1420 BUFFER and return the actual read number if bytes in NREAD. SEQNO
1421 is the sequence number used to send the request and EXPECTED_TYPE
1422 the type of message we expect. Does checks on the ccid
1423 header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1424 avoid debug messages in case of no error. Returns 0 on success. */
1425 static int
1426 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1427 size_t *nread, int expected_type, int seqno, int timeout,
1428 int no_debug)
1430 int i, rc;
1431 size_t msglen;
1433 /* Fixme: The next line for the current Valgrind without support
1434 for USB IOCTLs. */
1435 memset (buffer, 0, length);
1436 retry:
1437 if (handle->idev)
1439 rc = usb_bulk_read (handle->idev,
1440 handle->ep_bulk_in,
1441 (char*)buffer, length,
1442 timeout);
1443 if (rc < 0)
1445 DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (errno));
1446 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1448 *nread = msglen = rc;
1450 else
1452 rc = read (handle->dev_fd, buffer, length);
1453 if (rc < 0)
1455 DEBUGOUT_2 ("read from %d failed: %s\n",
1456 handle->dev_fd, strerror (errno));
1457 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1459 *nread = msglen = rc;
1463 if (msglen < 10)
1465 DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1466 return CCID_DRIVER_ERR_INV_VALUE;
1468 if (buffer[5] != 0)
1470 DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1471 return CCID_DRIVER_ERR_INV_VALUE;
1473 if (buffer[6] != seqno)
1475 DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1476 seqno, buffer[6]);
1477 return CCID_DRIVER_ERR_INV_VALUE;
1480 /* We need to handle the time extension request before we check that
1481 we go the expected message type. This is in particular required
1482 for the Cherry keyboard which sends a time extension request for
1483 each key hit. */
1484 if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1486 /* Card present and active, time extension requested. */
1487 DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1488 buffer[7], buffer[8]);
1489 goto retry;
1492 if (buffer[0] != expected_type)
1494 DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1495 return CCID_DRIVER_ERR_INV_VALUE;
1499 if (!no_debug)
1501 DEBUGOUT_3 ("status: %02X error: %02X octet[9]: %02X\n"
1502 " data:", buffer[7], buffer[8], buffer[9] );
1503 for (i=10; i < msglen; i++)
1504 DEBUGOUT_CONT_1 (" %02X", buffer[i]);
1505 DEBUGOUT_LF ();
1507 if (CCID_COMMAND_FAILED (buffer))
1508 print_command_failed (buffer);
1510 /* Check whether a card is at all available. Note: If you add new
1511 error codes here, check whether they need to be ignored in
1512 send_escape_cmd. */
1513 switch ((buffer[7] & 0x03))
1515 case 0: /* no error */ break;
1516 case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1517 case 2: return CCID_DRIVER_ERR_NO_CARD;
1518 case 3: /* RFU */ break;
1520 return 0;
1524 /* Note that this function won't return the error codes NO_CARD or
1525 CARD_INACTIVE. IF RESULT is not NULL, the result from the
1526 operation will get returned in RESULT and its length in RESULTLEN.
1527 If the response is larger than RESULTMAX, an error is returned and
1528 the required buffer length returned in RESULTLEN. */
1529 static int
1530 send_escape_cmd (ccid_driver_t handle,
1531 const unsigned char *data, size_t datalen,
1532 unsigned char *result, size_t resultmax, size_t *resultlen)
1534 int i, rc;
1535 unsigned char msg[100];
1536 size_t msglen;
1537 unsigned char seqno;
1539 if (resultlen)
1540 *resultlen = 0;
1542 if (datalen > sizeof msg - 10)
1543 return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large. */
1545 msg[0] = PC_to_RDR_Escape;
1546 msg[5] = 0; /* slot */
1547 msg[6] = seqno = handle->seqno++;
1548 msg[7] = 0; /* RFU */
1549 msg[8] = 0; /* RFU */
1550 msg[9] = 0; /* RFU */
1551 memcpy (msg+10, data, datalen);
1552 msglen = 10 + datalen;
1553 set_msg_len (msg, datalen);
1555 DEBUGOUT ("sending");
1556 for (i=0; i < msglen; i++)
1557 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1558 DEBUGOUT_LF ();
1559 rc = bulk_out (handle, msg, msglen);
1560 if (rc)
1561 return rc;
1562 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
1563 seqno, 5000, 0);
1564 if (result)
1565 switch (rc)
1567 /* We need to ignore certain errorcode here. */
1568 case 0:
1569 case CCID_DRIVER_ERR_CARD_INACTIVE:
1570 case CCID_DRIVER_ERR_NO_CARD:
1572 if (msglen > resultmax)
1573 rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
1574 else
1576 memcpy (result, msg, msglen);
1577 *resultlen = msglen;
1579 rc = 0;
1581 break;
1582 default:
1583 break;
1586 return rc;
1591 ccid_transceive_escape (ccid_driver_t handle,
1592 const unsigned char *data, size_t datalen,
1593 unsigned char *resp, size_t maxresplen, size_t *nresp)
1595 return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
1600 /* experimental */
1602 ccid_poll (ccid_driver_t handle)
1604 int rc;
1605 unsigned char msg[10];
1606 size_t msglen;
1607 int i, j;
1609 if (handle->idev)
1611 rc = usb_bulk_read (handle->idev,
1612 handle->ep_intr,
1613 (char*)msg, sizeof msg,
1614 0 /* ms timeout */ );
1615 if (rc < 0 && errno == ETIMEDOUT)
1616 return 0;
1618 else
1619 return 0;
1621 if (rc < 0)
1623 DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
1624 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1627 msglen = rc;
1628 rc = 0;
1630 if (msglen < 1)
1632 DEBUGOUT ("intr-in msg too short\n");
1633 return CCID_DRIVER_ERR_INV_VALUE;
1636 if (msg[0] == RDR_to_PC_NotifySlotChange)
1638 DEBUGOUT ("notify slot change:");
1639 for (i=1; i < msglen; i++)
1640 for (j=0; j < 4; j++)
1641 DEBUGOUT_CONT_3 (" %d:%c%c",
1642 (i-1)*4+j,
1643 (msg[i] & (1<<(j*2)))? 'p':'-',
1644 (msg[i] & (2<<(j*2)))? '*':' ');
1645 DEBUGOUT_LF ();
1647 else if (msg[0] == RDR_to_PC_HardwareError)
1649 DEBUGOUT ("hardware error occured\n");
1651 else
1653 DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
1656 return 0;
1660 /* Note that this fucntion won't return the error codes NO_CARD or
1661 CARD_INACTIVE */
1662 int
1663 ccid_slot_status (ccid_driver_t handle, int *statusbits)
1665 int rc;
1666 unsigned char msg[100];
1667 size_t msglen;
1668 unsigned char seqno;
1669 int retries = 0;
1671 retry:
1672 msg[0] = PC_to_RDR_GetSlotStatus;
1673 msg[5] = 0; /* slot */
1674 msg[6] = seqno = handle->seqno++;
1675 msg[7] = 0; /* RFU */
1676 msg[8] = 0; /* RFU */
1677 msg[9] = 0; /* RFU */
1678 set_msg_len (msg, 0);
1680 rc = bulk_out (handle, msg, 10);
1681 if (rc)
1682 return rc;
1683 /* Note that we set the NO_DEBUG flag here, so that the logs won't
1684 get cluttered up by a ticker function checking for the slot
1685 status and debugging enabled. */
1686 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1687 seqno, retries? 1000 : 200, 1);
1688 if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
1690 if (!retries)
1692 DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
1693 usb_clear_halt (handle->idev, handle->ep_bulk_in);
1694 usb_clear_halt (handle->idev, handle->ep_bulk_out);
1696 else
1697 DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
1698 retries++;
1699 goto retry;
1701 if (rc && rc != CCID_DRIVER_ERR_NO_CARD
1702 && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
1703 return rc;
1704 *statusbits = (msg[7] & 3);
1706 return 0;
1710 int
1711 ccid_get_atr (ccid_driver_t handle,
1712 unsigned char *atr, size_t maxatrlen, size_t *atrlen)
1714 int rc;
1715 int statusbits;
1716 unsigned char msg[100];
1717 unsigned char *tpdu;
1718 size_t msglen, tpdulen;
1719 unsigned char seqno;
1720 int use_crc = 0;
1721 unsigned int edc;
1722 int i;
1723 int tried_iso = 0;
1724 int got_param;
1726 /* First check whether a card is available. */
1727 rc = ccid_slot_status (handle, &statusbits);
1728 if (rc)
1729 return rc;
1730 if (statusbits == 2)
1731 return CCID_DRIVER_ERR_NO_CARD;
1734 /* For an inactive and also for an active card, issue the PowerOn
1735 command to get the ATR. */
1736 again:
1737 msg[0] = PC_to_RDR_IccPowerOn;
1738 msg[5] = 0; /* slot */
1739 msg[6] = seqno = handle->seqno++;
1740 msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
1741 msg[8] = 0; /* RFU */
1742 msg[9] = 0; /* RFU */
1743 set_msg_len (msg, 0);
1744 msglen = 10;
1746 rc = bulk_out (handle, msg, msglen);
1747 if (rc)
1748 return rc;
1749 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
1750 seqno, 5000, 0);
1751 if (rc)
1752 return rc;
1753 if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
1754 && ((handle->id_vendor == VENDOR_CHERRY
1755 && handle->id_product == 0x0005)
1756 || (handle->id_vendor == VENDOR_GEMPC
1757 && handle->id_product == 0x4433)
1760 tried_iso = 1;
1761 /* Try switching to ISO mode. */
1762 if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
1763 NULL, 0, NULL))
1764 goto again;
1766 else if (CCID_COMMAND_FAILED (msg))
1767 return CCID_DRIVER_ERR_CARD_IO_ERROR;
1770 handle->powered_off = 0;
1772 if (atr)
1774 size_t n = msglen - 10;
1776 if (n > maxatrlen)
1777 n = maxatrlen;
1778 memcpy (atr, msg+10, n);
1779 *atrlen = n;
1782 got_param = 0;
1783 msg[0] = PC_to_RDR_GetParameters;
1784 msg[5] = 0; /* slot */
1785 msg[6] = seqno = handle->seqno++;
1786 msg[7] = 0; /* RFU */
1787 msg[8] = 0; /* RFU */
1788 msg[9] = 0; /* RFU */
1789 set_msg_len (msg, 0);
1790 msglen = 10;
1791 rc = bulk_out (handle, msg, msglen);
1792 if (!rc)
1793 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
1794 seqno, 2000, 0);
1795 if (rc)
1796 DEBUGOUT ("GetParameters failed\n");
1797 else
1799 DEBUGOUT ("GetParametes returned");
1800 for (i=0; i < msglen; i++)
1801 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1802 DEBUGOUT_LF ();
1803 if (msglen >= 10)
1805 DEBUGOUT_1 (" protocol ..........: T=%d\n", msg[9]);
1806 if (msglen == 17 && msg[9] == 1)
1808 DEBUGOUT_1 (" bmFindexDindex ....: %02X\n", msg[10]);
1809 DEBUGOUT_1 (" bmTCCKST1 .........: %02X\n", msg[11]);
1810 DEBUGOUT_1 (" bGuardTimeT1 ......: %02X\n", msg[12]);
1811 DEBUGOUT_1 (" bmWaitingIntegersT1: %02X\n", msg[13]);
1812 DEBUGOUT_1 (" bClockStop ........: %02X\n", msg[14]);
1813 DEBUGOUT_1 (" bIFSC .............: %d\n", msg[15]);
1814 DEBUGOUT_1 (" bNadValue .........: %d\n", msg[16]);
1815 got_param = 1;
1820 /* Setup parameters to select T=1. */
1821 msg[0] = PC_to_RDR_SetParameters;
1822 msg[5] = 0; /* slot */
1823 msg[6] = seqno = handle->seqno++;
1824 msg[7] = 1; /* Select T=1. */
1825 msg[8] = 0; /* RFU */
1826 msg[9] = 0; /* RFU */
1828 if (!got_param)
1830 /* FIXME: Get those values from the ATR. */
1831 msg[10]= 0x01; /* Fi/Di */
1832 msg[11]= 0x10; /* LRC, direct convention. */
1833 msg[12]= 0; /* Extra guardtime. */
1834 msg[13]= 0x41; /* BWI/CWI */
1835 msg[14]= 0; /* No clock stoppping. */
1836 msg[15]= 254; /* IFSC */
1837 msg[16]= 0; /* Does not support non default NAD values. */
1839 set_msg_len (msg, 7);
1840 msglen = 10 + 7;
1842 DEBUGOUT ("sending");
1843 for (i=0; i < msglen; i++)
1844 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1845 DEBUGOUT_LF ();
1847 rc = bulk_out (handle, msg, msglen);
1848 if (rc)
1849 return rc;
1850 rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
1851 seqno, 5000, 0);
1852 if (rc)
1853 DEBUGOUT ("SetParameters failed (ignored)\n");
1855 handle->t1_ns = 0;
1856 handle->t1_nr = 0;
1858 /* Send an S-Block with our maximum IFSD to the CCID. */
1859 if (!handle->apdu_level && !handle->auto_ifsd)
1861 tpdu = msg+10;
1862 /* NAD: DAD=1, SAD=0 */
1863 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1864 tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
1865 tpdu[2] = 1;
1866 tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
1867 tpdulen = 4;
1868 edc = compute_edc (tpdu, tpdulen, use_crc);
1869 if (use_crc)
1870 tpdu[tpdulen++] = (edc >> 8);
1871 tpdu[tpdulen++] = edc;
1873 msg[0] = PC_to_RDR_XfrBlock;
1874 msg[5] = 0; /* slot */
1875 msg[6] = seqno = handle->seqno++;
1876 msg[7] = 0;
1877 msg[8] = 0; /* RFU */
1878 msg[9] = 0; /* RFU */
1879 set_msg_len (msg, tpdulen);
1880 msglen = 10 + tpdulen;
1882 DEBUGOUT ("sending");
1883 for (i=0; i < msglen; i++)
1884 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1885 DEBUGOUT_LF ();
1887 if (debug_level > 1)
1888 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1889 ((msg[11] & 0xc0) == 0x80)? 'R' :
1890 (msg[11] & 0x80)? 'S' : 'I',
1891 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1892 : !!(msg[11] & 0x40)),
1893 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1895 rc = bulk_out (handle, msg, msglen);
1896 if (rc)
1897 return rc;
1900 rc = bulk_in (handle, msg, sizeof msg, &msglen,
1901 RDR_to_PC_DataBlock, seqno, 5000, 0);
1902 if (rc)
1903 return rc;
1905 tpdu = msg + 10;
1906 tpdulen = msglen - 10;
1908 if (tpdulen < 4)
1909 return CCID_DRIVER_ERR_ABORTED;
1911 if (debug_level > 1)
1912 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1913 ((msg[11] & 0xc0) == 0x80)? 'R' :
1914 (msg[11] & 0x80)? 'S' : 'I',
1915 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1916 : !!(msg[11] & 0x40)),
1917 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1918 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1920 if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
1922 DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
1923 return -1;
1925 DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
1928 return 0;
1934 static unsigned int
1935 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
1937 if (use_crc)
1939 return 0x42; /* Not yet implemented. */
1941 else
1943 unsigned char crc = 0;
1945 for (; datalen; datalen--)
1946 crc ^= *data++;
1947 return crc;
1952 /* Helper for ccid_transceive used for APDU level exchanges. */
1953 static int
1954 ccid_transceive_apdu_level (ccid_driver_t handle,
1955 const unsigned char *apdu_buf, size_t apdu_buflen,
1956 unsigned char *resp, size_t maxresplen,
1957 size_t *nresp)
1959 int rc;
1960 unsigned char send_buffer[10+259], recv_buffer[10+259];
1961 const unsigned char *apdu;
1962 size_t apdulen;
1963 unsigned char *msg;
1964 size_t msglen;
1965 unsigned char seqno;
1966 int i;
1968 msg = send_buffer;
1970 apdu = apdu_buf;
1971 apdulen = apdu_buflen;
1972 assert (apdulen);
1974 if (apdulen > 254)
1975 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1977 msg[0] = PC_to_RDR_XfrBlock;
1978 msg[5] = 0; /* slot */
1979 msg[6] = seqno = handle->seqno++;
1980 msg[7] = 4; /* bBWI */
1981 msg[8] = 0; /* RFU */
1982 msg[9] = 0; /* RFU */
1983 memcpy (msg+10, apdu, apdulen);
1984 set_msg_len (msg, apdulen);
1985 msglen = 10 + apdulen;
1987 DEBUGOUT ("sending");
1988 for (i=0; i < msglen; i++)
1989 DEBUGOUT_CONT_1 (" %02X", msg[i]);
1990 DEBUGOUT_LF ();
1992 rc = bulk_out (handle, msg, msglen);
1993 if (rc)
1994 return rc;
1996 msg = recv_buffer;
1997 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1998 RDR_to_PC_DataBlock, seqno, 5000, 0);
1999 if (rc)
2000 return rc;
2002 apdu = msg + 10;
2003 apdulen = msglen - 10;
2005 if (resp)
2007 if (apdulen > maxresplen)
2009 DEBUGOUT_2 ("provided buffer too short for received data "
2010 "(%u/%u)\n",
2011 (unsigned int)apdulen, (unsigned int)maxresplen);
2012 return CCID_DRIVER_ERR_INV_VALUE;
2015 memcpy (resp, apdu, apdulen);
2016 *nresp = apdulen;
2019 return 0;
2025 Protocol T=1 overview
2027 Block Structure:
2028 Prologue Field:
2029 1 byte Node Address (NAD)
2030 1 byte Protocol Control Byte (PCB)
2031 1 byte Length (LEN)
2032 Information Field:
2033 0-254 byte APDU or Control Information (INF)
2034 Epilogue Field:
2035 1 byte Error Detection Code (EDC)
2037 NAD:
2038 bit 7 unused
2039 bit 4..6 Destination Node Address (DAD)
2040 bit 3 unused
2041 bit 2..0 Source Node Address (SAD)
2043 If node adresses are not used, SAD and DAD should be set to 0 on
2044 the first block sent to the card. If they are used they should
2045 have different values (0 for one is okay); that first block sets up
2046 the addresses of the nodes.
2048 PCB:
2049 Information Block (I-Block):
2050 bit 7 0
2051 bit 6 Sequence number (yep, that is modulo 2)
2052 bit 5 Chaining flag
2053 bit 4..0 reserved
2054 Received-Ready Block (R-Block):
2055 bit 7 1
2056 bit 6 0
2057 bit 5 0
2058 bit 4 Sequence number
2059 bit 3..0 0 = no error
2060 1 = EDC or parity error
2061 2 = other error
2062 other values are reserved
2063 Supervisory Block (S-Block):
2064 bit 7 1
2065 bit 6 1
2066 bit 5 clear=request,set=response
2067 bit 4..0 0 = resyncronisation request
2068 1 = information field size request
2069 2 = abort request
2070 3 = extension of BWT request
2071 4 = VPP error
2072 other values are reserved
2077 ccid_transceive (ccid_driver_t handle,
2078 const unsigned char *apdu_buf, size_t apdu_buflen,
2079 unsigned char *resp, size_t maxresplen, size_t *nresp)
2081 int rc;
2082 unsigned char send_buffer[10+259], recv_buffer[10+259];
2083 const unsigned char *apdu;
2084 size_t apdulen;
2085 unsigned char *msg, *tpdu, *p;
2086 size_t msglen, tpdulen, last_tpdulen, n;
2087 unsigned char seqno;
2088 int i;
2089 unsigned int edc;
2090 int use_crc = 0;
2091 size_t dummy_nresp;
2092 int next_chunk = 1;
2093 int sending = 1;
2094 int retries = 0;
2096 if (!nresp)
2097 nresp = &dummy_nresp;
2098 *nresp = 0;
2100 /* Smarter readers allow to send APDUs directly; divert here. */
2101 if (handle->apdu_level)
2102 return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
2103 resp, maxresplen, nresp);
2105 /* The other readers we support require sending TPDUs. */
2107 tpdulen = 0; /* Avoid compiler warning about no initialization. */
2108 msg = send_buffer;
2109 for (;;)
2111 if (next_chunk)
2113 next_chunk = 0;
2115 apdu = apdu_buf;
2116 apdulen = apdu_buflen;
2117 assert (apdulen);
2119 /* Construct an I-Block. */
2120 if (apdulen > 254)
2121 return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2123 tpdu = msg+10;
2124 /* NAD: DAD=1, SAD=0 */
2125 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2126 tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
2127 if (apdulen > 128 /* fixme: replace by ifsc */)
2129 apdulen = 128;
2130 apdu_buf += 128;
2131 apdu_buflen -= 128;
2132 tpdu[1] |= (1 << 5); /* Set more bit. */
2134 tpdu[2] = apdulen;
2135 memcpy (tpdu+3, apdu, apdulen);
2136 tpdulen = 3 + apdulen;
2137 edc = compute_edc (tpdu, tpdulen, use_crc);
2138 if (use_crc)
2139 tpdu[tpdulen++] = (edc >> 8);
2140 tpdu[tpdulen++] = edc;
2143 msg[0] = PC_to_RDR_XfrBlock;
2144 msg[5] = 0; /* slot */
2145 msg[6] = seqno = handle->seqno++;
2146 msg[7] = 4; /* bBWI */
2147 msg[8] = 0; /* RFU */
2148 msg[9] = 0; /* RFU */
2149 set_msg_len (msg, tpdulen);
2150 msglen = 10 + tpdulen;
2151 last_tpdulen = tpdulen;
2153 DEBUGOUT ("sending");
2154 for (i=0; i < msglen; i++)
2155 DEBUGOUT_CONT_1 (" %02X", msg[i]);
2156 DEBUGOUT_LF ();
2158 if (debug_level > 1)
2159 DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2160 ((msg[11] & 0xc0) == 0x80)? 'R' :
2161 (msg[11] & 0x80)? 'S' : 'I',
2162 ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2163 : !!(msg[11] & 0x40)),
2164 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2166 rc = bulk_out (handle, msg, msglen);
2167 if (rc)
2168 return rc;
2170 msg = recv_buffer;
2171 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2172 RDR_to_PC_DataBlock, seqno, 5000, 0);
2173 if (rc)
2174 return rc;
2176 tpdu = msg + 10;
2177 tpdulen = msglen - 10;
2179 if (tpdulen < 4)
2181 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2182 return CCID_DRIVER_ERR_ABORTED;
2185 if (debug_level > 1)
2186 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2187 ((msg[11] & 0xc0) == 0x80)? 'R' :
2188 (msg[11] & 0x80)? 'S' : 'I',
2189 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2190 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2191 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2193 if (!(tpdu[1] & 0x80))
2194 { /* This is an I-block. */
2195 retries = 0;
2196 if (sending)
2197 { /* last block sent was successful. */
2198 handle->t1_ns ^= 1;
2199 sending = 0;
2202 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2203 { /* Reponse does not match our sequence number. */
2204 msg = send_buffer;
2205 tpdu = msg+10;
2206 /* NAD: DAD=1, SAD=0 */
2207 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2208 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
2209 tpdu[2] = 0;
2210 tpdulen = 3;
2211 edc = compute_edc (tpdu, tpdulen, use_crc);
2212 if (use_crc)
2213 tpdu[tpdulen++] = (edc >> 8);
2214 tpdu[tpdulen++] = edc;
2216 continue;
2219 handle->t1_nr ^= 1;
2221 p = tpdu + 3; /* Skip the prologue field. */
2222 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2223 /* fixme: verify the checksum. */
2224 if (resp)
2226 if (n > maxresplen)
2228 DEBUGOUT_2 ("provided buffer too short for received data "
2229 "(%u/%u)\n",
2230 (unsigned int)n, (unsigned int)maxresplen);
2231 return CCID_DRIVER_ERR_INV_VALUE;
2234 memcpy (resp, p, n);
2235 resp += n;
2236 *nresp += n;
2237 maxresplen -= n;
2240 if (!(tpdu[1] & 0x20))
2241 return 0; /* No chaining requested - ready. */
2243 msg = send_buffer;
2244 tpdu = msg+10;
2245 /* NAD: DAD=1, SAD=0 */
2246 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2247 tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
2248 tpdu[2] = 0;
2249 tpdulen = 3;
2250 edc = compute_edc (tpdu, tpdulen, use_crc);
2251 if (use_crc)
2252 tpdu[tpdulen++] = (edc >> 8);
2253 tpdu[tpdulen++] = edc;
2255 else if ((tpdu[1] & 0xc0) == 0x80)
2256 { /* This is a R-block. */
2257 if ( (tpdu[1] & 0x0f))
2258 { /* Error: repeat last block */
2259 if (++retries > 3)
2261 DEBUGOUT ("3 failed retries\n");
2262 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2264 msg = send_buffer;
2265 tpdulen = last_tpdulen;
2267 else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
2268 { /* Response does not match our sequence number. */
2269 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2270 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2272 else if (sending)
2273 { /* Send next chunk. */
2274 retries = 0;
2275 msg = send_buffer;
2276 next_chunk = 1;
2277 handle->t1_ns ^= 1;
2279 else
2281 DEBUGOUT ("unexpected ACK R-block received\n");
2282 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2285 else
2286 { /* This is a S-block. */
2287 retries = 0;
2288 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d\n",
2289 (tpdu[1] & 0x20)? "response": "request",
2290 (tpdu[1] & 0x1f));
2291 if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
2292 { /* Wait time extension request. */
2293 unsigned char bwi = tpdu[3];
2294 msg = send_buffer;
2295 tpdu = msg+10;
2296 /* NAD: DAD=1, SAD=0 */
2297 tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2298 tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
2299 tpdu[2] = 1;
2300 tpdu[3] = bwi;
2301 tpdulen = 4;
2302 edc = compute_edc (tpdu, tpdulen, use_crc);
2303 if (use_crc)
2304 tpdu[tpdulen++] = (edc >> 8);
2305 tpdu[tpdulen++] = edc;
2306 DEBUGOUT_1 ("T=1 waittime extension of bwi=%d\n", bwi);
2308 else
2309 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2311 } /* end T=1 protocol loop. */
2313 return 0;
2317 /* Send the CCID Secure command to the reader. APDU_BUF should
2318 contain the APDU template. PIN_MODE defines how the pin gets
2319 formatted:
2321 1 := The PIN is ASCII encoded and of variable length. The
2322 length of the PIN entered will be put into Lc by the reader.
2323 The APDU should me made up of 4 bytes without Lc.
2325 PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2326 may be used t enable reasonable defaults. PIN_PADLEN should be 0.
2328 When called with RESP and NRESP set to NULL, the function will
2329 merely check whether the reader supports the secure command for the
2330 given APDU and PIN_MODE. */
2332 ccid_transceive_secure (ccid_driver_t handle,
2333 const unsigned char *apdu_buf, size_t apdu_buflen,
2334 int pin_mode, int pinlen_min, int pinlen_max,
2335 int pin_padlen,
2336 unsigned char *resp, size_t maxresplen, size_t *nresp)
2338 int rc;
2339 unsigned char send_buffer[10+259], recv_buffer[10+259];
2340 unsigned char *msg, *tpdu, *p;
2341 size_t msglen, tpdulen, n;
2342 unsigned char seqno;
2343 int i;
2344 size_t dummy_nresp;
2345 int testmode;
2346 int cherry_mode = 0;
2348 testmode = !resp && !nresp;
2350 if (!nresp)
2351 nresp = &dummy_nresp;
2352 *nresp = 0;
2354 if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2356 else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2357 return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2358 else
2359 return CCID_DRIVER_ERR_NO_KEYPAD;
2361 if (pin_mode != 1)
2362 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2364 if (pin_padlen != 0)
2365 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2367 if (!pinlen_min)
2368 pinlen_min = 1;
2369 if (!pinlen_max)
2370 pinlen_max = 25;
2372 /* Note that the 25 is the maximum value the SPR532 allows. */
2373 if (pinlen_min < 1 || pinlen_min > 25
2374 || pinlen_max < 1 || pinlen_max > 25
2375 || pinlen_min > pinlen_max)
2376 return CCID_DRIVER_ERR_INV_VALUE;
2378 /* We have only tested a few readers so better don't risk anything
2379 and do not allow the use with other readers. */
2380 switch (handle->id_vendor)
2382 case VENDOR_SCM: /* Tested with SPR 532. */
2383 case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
2384 break;
2385 case VENDOR_CHERRY:
2386 /* The CHERRY XX44 keyboard echos an asterisk for each entered
2387 character on the keyboard channel. We use a special variant
2388 of PC_to_RDR_Secure which directs these characters to the
2389 smart card's bulk-in channel. We also need to append a zero
2390 Lc byte to the APDU. It seems that it will be replaced with
2391 the actual length instead of being appended before the APDU
2392 is send to the card. */
2393 cherry_mode = 1;
2394 break;
2395 default:
2396 return CCID_DRIVER_ERR_NOT_SUPPORTED;
2399 if (testmode)
2400 return 0; /* Success */
2402 msg = send_buffer;
2403 if (handle->id_vendor == VENDOR_SCM)
2405 DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
2406 rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
2407 NULL, 0, NULL);
2408 if (rc)
2409 return rc;
2412 msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
2413 msg[5] = 0; /* slot */
2414 msg[6] = seqno = handle->seqno++;
2415 msg[7] = 0; /* bBWI */
2416 msg[8] = 0; /* RFU */
2417 msg[9] = 0; /* RFU */
2418 msg[10] = 0; /* Perform PIN verification. */
2419 msg[11] = 0; /* Timeout in seconds. */
2420 msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2421 if (handle->id_vendor == VENDOR_SCM)
2423 /* For the SPR532 the next 2 bytes need to be zero. We do this
2424 for all SCM products. Kudos to Martin Paljak for this
2425 hint. */
2426 msg[13] = msg[14] = 0;
2428 else
2430 msg[13] = 0x00; /* bmPINBlockString:
2431 0 bits of pin length to insert.
2432 0 bytes of PIN block size. */
2433 msg[14] = 0x00; /* bmPINLengthFormat:
2434 Units are bytes, position is 0. */
2437 /* The following is a little endian word. */
2438 msg[15] = pinlen_max; /* wPINMaxExtraDigit-Maximum. */
2439 msg[16] = pinlen_min; /* wPINMaxExtraDigit-Minimum. */
2441 msg[17] = 0x02; /* bEntryValidationCondition:
2442 Validation key pressed */
2443 if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
2444 msg[17] |= 0x01; /* Max size reached. */
2445 msg[18] = 0xff; /* bNumberMessage: Default. */
2446 msg[19] = 0x04; /* wLangId-High. */
2447 msg[20] = 0x09; /* wLangId-Low: English FIXME: use the first entry. */
2448 msg[21] = 0; /* bMsgIndex. */
2449 /* bTeoProlog follows: */
2450 msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2451 msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
2452 msg[24] = 0; /* The apdulen will be filled in by the reader. */
2453 /* APDU follows: */
2454 msg[25] = apdu_buf[0]; /* CLA */
2455 msg[26] = apdu_buf[1]; /* INS */
2456 msg[27] = apdu_buf[2]; /* P1 */
2457 msg[28] = apdu_buf[3]; /* P2 */
2458 msglen = 29;
2459 if (cherry_mode)
2460 msg[msglen++] = 0;
2461 /* An EDC is not required. */
2462 set_msg_len (msg, msglen - 10);
2464 DEBUGOUT ("sending");
2465 for (i=0; i < msglen; i++)
2466 DEBUGOUT_CONT_1 (" %02X", msg[i]);
2467 DEBUGOUT_LF ();
2469 rc = bulk_out (handle, msg, msglen);
2470 if (rc)
2471 return rc;
2473 msg = recv_buffer;
2474 rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2475 RDR_to_PC_DataBlock, seqno, 30000, 0);
2476 if (rc)
2477 return rc;
2479 tpdu = msg + 10;
2480 tpdulen = msglen - 10;
2482 if (handle->apdu_level)
2484 if (resp)
2486 if (tpdulen > maxresplen)
2488 DEBUGOUT_2 ("provided buffer too short for received data "
2489 "(%u/%u)\n",
2490 (unsigned int)tpdulen, (unsigned int)maxresplen);
2491 return CCID_DRIVER_ERR_INV_VALUE;
2494 memcpy (resp, tpdu, tpdulen);
2495 *nresp = tpdulen;
2497 return 0;
2500 if (tpdulen < 4)
2502 usb_clear_halt (handle->idev, handle->ep_bulk_in);
2503 return CCID_DRIVER_ERR_ABORTED;
2505 if (debug_level > 1)
2506 DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2507 ((msg[11] & 0xc0) == 0x80)? 'R' :
2508 (msg[11] & 0x80)? 'S' : 'I',
2509 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2510 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2511 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2513 if (!(tpdu[1] & 0x80))
2514 { /* This is an I-block. */
2515 /* Last block sent was successful. */
2516 handle->t1_ns ^= 1;
2518 if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2519 { /* Reponse does not match our sequence number. */
2520 DEBUGOUT ("I-block with wrong seqno received\n");
2521 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2524 handle->t1_nr ^= 1;
2526 p = tpdu + 3; /* Skip the prologue field. */
2527 n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2528 /* fixme: verify the checksum. */
2529 if (resp)
2531 if (n > maxresplen)
2533 DEBUGOUT_2 ("provided buffer too short for received data "
2534 "(%u/%u)\n",
2535 (unsigned int)n, (unsigned int)maxresplen);
2536 return CCID_DRIVER_ERR_INV_VALUE;
2539 memcpy (resp, p, n);
2540 resp += n;
2541 *nresp += n;
2542 maxresplen -= n;
2545 if (!(tpdu[1] & 0x20))
2546 return 0; /* No chaining requested - ready. */
2548 DEBUGOUT ("chaining requested but not supported for Secure operation\n");
2549 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2551 else if ((tpdu[1] & 0xc0) == 0x80)
2552 { /* This is a R-block. */
2553 if ( (tpdu[1] & 0x0f))
2554 { /* Error: repeat last block */
2555 DEBUGOUT ("No retries supported for Secure operation\n");
2556 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2558 else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
2559 { /* Reponse does not match our sequence number. */
2560 DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2561 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2563 else
2564 { /* Send next chunk. */
2565 DEBUGOUT ("chaining not supported on Secure operation\n");
2566 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2569 else
2570 { /* This is a S-block. */
2571 DEBUGOUT_2 ("T=1 S-block %s received cmd=%d for Secure operation\n",
2572 (tpdu[1] & 0x20)? "response": "request",
2573 (tpdu[1] & 0x1f));
2574 return CCID_DRIVER_ERR_CARD_IO_ERROR;
2577 return 0;
2583 #ifdef TEST
2586 static void
2587 print_error (int err)
2589 const char *p;
2590 char buf[50];
2592 switch (err)
2594 case 0: p = "success";
2595 case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
2596 case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
2597 case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
2598 case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
2599 case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
2600 case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
2601 case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
2602 case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
2603 case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
2604 case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
2605 case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
2606 case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
2607 default: sprintf (buf, "0x%05x", err); p = buf; break;
2609 fprintf (stderr, "operation failed: %s\n", p);
2612 static void
2613 print_data (const unsigned char *data, size_t length)
2615 if (length >= 2)
2617 fprintf (stderr, "operation status: %02X%02X\n",
2618 data[length-2], data[length-1]);
2619 length -= 2;
2621 if (length)
2623 fputs (" returned data:", stderr);
2624 for (; length; length--, data++)
2625 fprintf (stderr, " %02X", *data);
2626 putc ('\n', stderr);
2630 static void
2631 print_result (int rc, const unsigned char *data, size_t length)
2633 if (rc)
2634 print_error (rc);
2635 else if (data)
2636 print_data (data, length);
2640 main (int argc, char **argv)
2642 int rc;
2643 ccid_driver_t ccid;
2644 int slotstat;
2645 unsigned char result[512];
2646 size_t resultlen;
2647 int no_pinpad = 0;
2648 int verify_123456 = 0;
2649 int did_verify = 0;
2650 int no_poll = 0;
2652 if (argc)
2654 argc--;
2655 argv++;
2658 while (argc)
2660 if ( !strcmp (*argv, "--list"))
2662 char *p;
2663 p = ccid_get_reader_list ();
2664 if (!p)
2665 return 1;
2666 fputs (p, stderr);
2667 free (p);
2668 return 0;
2670 else if ( !strcmp (*argv, "--debug"))
2672 ccid_set_debug_level (ccid_set_debug_level (-1)+1);
2673 argc--; argv++;
2675 else if ( !strcmp (*argv, "--no-poll"))
2677 no_poll = 1;
2678 argc--; argv++;
2680 else if ( !strcmp (*argv, "--no-pinpad"))
2682 no_pinpad = 1;
2683 argc--; argv++;
2685 else if ( !strcmp (*argv, "--verify-123456"))
2687 verify_123456 = 1;
2688 argc--; argv++;
2690 else
2691 break;
2694 rc = ccid_open_reader (&ccid, argc? *argv:NULL);
2695 if (rc)
2696 return 1;
2698 if (!no_poll)
2699 ccid_poll (ccid);
2700 fputs ("getting ATR ...\n", stderr);
2701 rc = ccid_get_atr (ccid, NULL, 0, NULL);
2702 if (rc)
2704 print_error (rc);
2705 return 1;
2708 if (!no_poll)
2709 ccid_poll (ccid);
2710 fputs ("getting slot status ...\n", stderr);
2711 rc = ccid_slot_status (ccid, &slotstat);
2712 if (rc)
2714 print_error (rc);
2715 return 1;
2718 if (!no_poll)
2719 ccid_poll (ccid);
2721 fputs ("selecting application OpenPGP ....\n", stderr);
2723 static unsigned char apdu[] = {
2724 0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
2725 rc = ccid_transceive (ccid,
2726 apdu, sizeof apdu,
2727 result, sizeof result, &resultlen);
2728 print_result (rc, result, resultlen);
2732 if (!no_poll)
2733 ccid_poll (ccid);
2735 fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
2737 static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
2738 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2739 result, sizeof result, &resultlen);
2740 print_result (rc, result, resultlen);
2743 if (!no_pinpad)
2747 if (!no_pinpad)
2749 static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
2752 if (ccid_transceive_secure (ccid,
2753 apdu, sizeof apdu,
2754 1, 0, 0, 0,
2755 NULL, 0, NULL))
2756 fputs ("can't verify using a PIN-Pad reader\n", stderr);
2757 else
2759 fputs ("verifying CHV1 using the PINPad ....\n", stderr);
2761 rc = ccid_transceive_secure (ccid,
2762 apdu, sizeof apdu,
2763 1, 0, 0, 0,
2764 result, sizeof result, &resultlen);
2765 print_result (rc, result, resultlen);
2766 did_verify = 1;
2770 if (verify_123456 && !did_verify)
2772 fputs ("verifying that CHV1 is 123456....\n", stderr);
2774 static unsigned char apdu[] = {0, 0x20, 0, 0x81,
2775 6, '1','2','3','4','5','6'};
2776 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2777 result, sizeof result, &resultlen);
2778 print_result (rc, result, resultlen);
2782 if (!rc)
2784 fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
2786 static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
2787 rc = ccid_transceive (ccid, apdu, sizeof apdu,
2788 result, sizeof result, &resultlen);
2789 print_result (rc, result, resultlen);
2793 ccid_close_reader (ccid);
2795 return 0;
2799 * Local Variables:
2800 * compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
2801 * End:
2803 #endif /*TEST*/
2804 #endif /*HAVE_LIBUSB*/