remove autogenerated file
[librfid] / src / ccid / ccid-driver.c
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2  *      Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
3  *      Written by Werner Koch.
4  *
5  * This file is part of GnuPG.
6  *
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 2 of the License, or
10  * (at your option) any later version.
11  *
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.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20  * USA.
21  *
22  * ALTERNATIVELY, this file may be distributed under the terms of the
23  * following license, in which case the provisions of this license are
24  * required INSTEAD OF the GNU General Public License. If you wish to
25  * allow use of your version of this file only under the terms of the
26  * GNU General Public License, and not to allow others to use your
27  * version of this file under the terms of the following license,
28  * indicate your decision by deleting this paragraph and the license
29  * below.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, and the entire permission notice in its entirety,
36  *    including the disclaimer of warranties.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. The name of the author may not be used to endorse or promote
41  *    products derived from this software without specific prior
42  *    written permission.
43  *
44  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
45  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
46  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
48  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54  * OF THE POSSIBILITY OF SUCH DAMAGE.
55  *
56  * $Date: 2005-09-09 13:18:08 +0200 (Fri, 09 Sep 2005) $
57  */
58
59
60 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
61    smartcard via a reader connected to the USB.  
62
63    This is a limited driver allowing to use some CCID drivers directly
64    without any other specila drivers. This is a fallback driver to be
65    used when nothing else works or the system should be kept minimal
66    for security reasons.  It makes use of the libusb library to gain
67    portable access to USB.
68
69    This driver has been tested with the SCM SCR335 and SPR532
70    smartcard readers and requires that a reader implements the TPDU
71    level exchange and does fully automatic initialization.
72 */
73
74 #include <librfid/rfid.h>
75
76 #ifndef LIBRFID_FIRMWARE
77
78 #ifdef HAVE_CONFIG_H
79 # include <config.h>
80 #endif
81
82 #if defined(HAVE_LIBUSB) || defined(TEST)
83
84 #include <errno.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <assert.h>
89
90 #include <usb.h>
91
92 #include "ccid-driver.h"
93
94 #define DRVNAME "ccid-driver: "
95
96
97 /* Depending on how this source is used we either define our error
98    output to go to stderr or to the jnlib based logging functions.  We
99    use the latter when GNUPG_MAJOR_VERSION is defines or when both,
100    GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
101 */
102 #if defined(GNUPG_MAJOR_VERSION) \
103     || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
104
105 #if defined(GNUPG_SCD_MAIN_HEADER)
106 #  include GNUPG_SCD_MAIN_HEADER
107 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
108 #  include "options.h"
109 #  include "util.h"
110 #  include "memory.h"
111 #  include "cardglue.h"
112 # else /* This is the modularized GnuPG 1.9 or later. */
113 #  include "scdaemon.h"
114 #endif
115
116
117 # define DEBUGOUT(t)         do { if (debug_level) \
118                                   log_debug (DRVNAME t); } while (0)
119 # define DEBUGOUT_1(t,a)     do { if (debug_level) \
120                                   log_debug (DRVNAME t,(a)); } while (0)
121 # define DEBUGOUT_2(t,a,b)   do { if (debug_level) \
122                                   log_debug (DRVNAME t,(a),(b)); } while (0)
123 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
124                                   log_debug (DRVNAME t,(a),(b),(c));} while (0)
125 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
126                               log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
127 # define DEBUGOUT_CONT(t)    do { if (debug_level) \
128                                   log_printf (t); } while (0)
129 # define DEBUGOUT_CONT_1(t,a)  do { if (debug_level) \
130                                   log_printf (t,(a)); } while (0)
131 # define DEBUGOUT_CONT_2(t,a,b)   do { if (debug_level) \
132                                   log_printf (t,(a),(b)); } while (0)
133 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
134                                   log_printf (t,(a),(b),(c)); } while (0)
135 # define DEBUGOUT_LF()       do { if (debug_level) \
136                                   log_printf ("\n"); } while (0)
137
138 #else /* Other usage of this source - don't use gnupg specifics. */
139
140 # define DEBUGOUT(t)          do { if (debug_level) \
141                      fprintf (stderr, DRVNAME t); } while (0)
142 # define DEBUGOUT_1(t,a)      do { if (debug_level) \
143                      fprintf (stderr, DRVNAME t, (a)); } while (0)
144 # define DEBUGOUT_2(t,a,b)    do { if (debug_level) \
145                      fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
146 # define DEBUGOUT_3(t,a,b,c)  do { if (debug_level) \
147                      fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
148 # define DEBUGOUT_4(t,a,b,c,d)  do { if (debug_level) \
149                      fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
150 # define DEBUGOUT_CONT(t)     do { if (debug_level) \
151                      fprintf (stderr, t); } while (0)
152 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
153                      fprintf (stderr, t, (a)); } while (0)
154 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
155                      fprintf (stderr, t, (a), (b)); } while (0)
156 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
157                      fprintf (stderr, t, (a), (b), (c)); } while (0)
158 # define DEBUGOUT_LF()        do { if (debug_level) \
159                      putc ('\n', stderr); } while (0)
160
161 #endif /* This source not used by scdaemon. */
162
163
164
165 enum {
166   RDR_to_PC_NotifySlotChange= 0x50,
167   RDR_to_PC_HardwareError   = 0x51,
168
169   PC_to_RDR_SetParameters   = 0x61,
170   PC_to_RDR_IccPowerOn      = 0x62,
171   PC_to_RDR_IccPowerOff     = 0x63,
172   PC_to_RDR_GetSlotStatus   = 0x65,
173   PC_to_RDR_Secure          = 0x69,
174   PC_to_RDR_T0APDU          = 0x6a,
175   PC_to_RDR_Escape          = 0x6b,
176   PC_to_RDR_GetParameters   = 0x6c,
177   PC_to_RDR_ResetParameters = 0x6d,
178   PC_to_RDR_IccClock        = 0x6e,
179   PC_to_RDR_XfrBlock        = 0x6f,
180   PC_to_RDR_Mechanical      = 0x71,
181   PC_to_RDR_Abort           = 0x72,
182   PC_to_RDR_SetDataRate     = 0x73,
183
184   RDR_to_PC_DataBlock       = 0x80,
185   RDR_to_PC_SlotStatus      = 0x81,
186   RDR_to_PC_Parameters      = 0x82,
187   RDR_to_PC_Escape          = 0x83,
188   RDR_to_PC_DataRate        = 0x84
189 };
190
191
192 /* Two macro to detect whether a CCID command has failed and to get
193    the error code.  These macros assume that we can access the
194    mandatory first 10 bytes of a CCID message in BUF. */
195 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
196 #define CCID_ERROR_CODE(buf)     (((unsigned char *)(buf))[8])
197
198
199 /* We need to know the vendor to do some hacks. */
200 enum {
201   VENDOR_SCM    = 0x04e6,
202   VENDOR_CHERRY = 0x046a,
203   VENDOR_OMNIKEY= 0x076b,
204   VENDOR_GEMPC  = 0x08e6
205 };
206
207
208 /* Store information on the driver's state.  A pointer to such a
209    structure is used as handle for most functions. */
210 struct ccid_driver_s 
211 {
212   usb_dev_handle *idev;
213   char *rid;
214   unsigned short id_vendor;
215   unsigned short id_product;
216   unsigned short bcd_device;
217   int ifc_no;
218   int ep_bulk_out;
219   int ep_bulk_in;
220   int ep_intr;
221   int seqno;
222   unsigned char t1_ns;
223   unsigned char t1_nr;
224   int nonnull_nad;
225   int auto_ifsd;
226   int max_ifsd;
227   int ifsd;
228   int powered_off;
229   int has_pinpad;
230   int apdu_level;     /* Reader supports short APDU level exchange.  */
231 };
232
233
234 static int initialized_usb; /* Tracks whether USB has been initialized. */
235 static int debug_level;     /* Flag to control the debug output. 
236                                0 = No debugging
237                                1 = USB I/O info
238                                2 = T=1 protocol tracing
239                               */
240
241
242 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
243                                  int use_crc);
244 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen);
245 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
246                     size_t *nread, int expected_type, int seqno, int timeout,
247                     int no_debug);
248
249 /* Convert a little endian stored 4 byte value into an unsigned
250    integer. */
251 static unsigned int 
252 convert_le_u32 (const unsigned char *buf)
253 {
254   return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24); 
255 }
256
257 static void
258 set_msg_len (unsigned char *msg, unsigned int length)
259 {
260   msg[1] = length;
261   msg[2] = length >> 8;
262   msg[3] = length >> 16;
263   msg[4] = length >> 24;
264 }
265
266
267 /* Pint an error message for a failed CCID command including a textual
268    error code.  MSG is shall be the CCID message of at least 10 bytes. */
269 static void
270 print_command_failed (const unsigned char *msg)
271 {
272   const char *t;
273   char buffer[100];
274   int ec;
275
276   if (!debug_level)
277     return;
278
279   ec = CCID_ERROR_CODE (msg);
280   switch (ec)
281     {
282     case 0x00: t = "Command not supported"; break;
283     
284     case 0xE0: t = "Slot busy"; break;
285     case 0xEF: t = "PIN cancelled"; break;
286     case 0xF0: t = "PIN timeout"; break;
287
288     case 0xF2: t = "Automatic sequence ongoing"; break;
289     case 0xF3: t = "Deactivated Protocol"; break;
290     case 0xF4: t = "Procedure byte conflict"; break;
291     case 0xF5: t = "ICC class not supported"; break;
292     case 0xF6: t = "ICC protocol not supported"; break;
293     case 0xF7: t = "Bad checksum in ATR"; break;
294     case 0xF8: t = "Bad TS in ATR"; break;
295
296     case 0xFB: t = "An all inclusive hardware error occurred"; break;
297     case 0xFC: t = "Overrun error while talking to the ICC"; break;
298     case 0xFD: t = "Parity error while talking to the ICC"; break;
299     case 0xFE: t = "CCID timed out while talking to the ICC"; break;
300     case 0xFF: t = "Host aborted the current activity"; break;
301
302     default:
303       if (ec > 0 && ec < 128)
304         sprintf (buffer, "Parameter error at offset %d", ec);
305       else
306         sprintf (buffer, "Error code %02X", ec);
307       t = buffer;
308       break;
309     }
310   DEBUGOUT_1 ("CCID command failed: %s\n", t);
311 }
312   
313
314
315
316 /* Parse a CCID descriptor, optionally print all available features
317    and test whether this reader is usable by this driver.  Returns 0
318    if it is usable.
319
320    Note, that this code is based on the one in lsusb.c of the
321    usb-utils package, I wrote on 2003-09-01. -wk. */
322 static int
323 parse_ccid_descriptor (ccid_driver_t handle,
324                        const unsigned char *buf, size_t buflen)
325 {
326   unsigned int i;
327   unsigned int us;
328   int have_t1 = 0, have_tpdu=0, have_auto_conf = 0;
329
330
331   handle->nonnull_nad = 0;
332   handle->auto_ifsd = 0;
333   handle->max_ifsd = 32;
334   handle->ifsd = 0;
335   handle->has_pinpad = 0;
336   handle->apdu_level = 0;
337   DEBUGOUT_3 ("idVendor: %04X  idProduct: %04X  bcdDevice: %04X\n",
338               handle->id_vendor, handle->id_product, handle->bcd_device);
339   if (buflen < 54 || buf[0] < 54)
340     {
341       DEBUGOUT ("CCID device descriptor is too short\n");
342       return -1;
343     }
344
345   DEBUGOUT   ("ChipCard Interface Descriptor:\n");
346   DEBUGOUT_1 ("  bLength             %5u\n", buf[0]);
347   DEBUGOUT_1 ("  bDescriptorType     %5u\n", buf[1]);
348   DEBUGOUT_2 ("  bcdCCID             %2x.%02x", buf[3], buf[2]);
349     if (buf[3] != 1 || buf[2] != 0) 
350       DEBUGOUT_CONT("  (Warning: Only accurate for version 1.0)");
351   DEBUGOUT_LF ();
352
353   DEBUGOUT_1 ("  nMaxSlotIndex       %5u\n", buf[4]);
354   DEBUGOUT_2 ("  bVoltageSupport     %5u  %s\n",
355               buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
356                        : buf[5] == 3? "1.8V":"?"));
357
358   us = convert_le_u32 (buf+6);
359   DEBUGOUT_1 ("  dwProtocols         %5u ", us);
360   if ((us & 1))
361     DEBUGOUT_CONT (" T=0");
362   if ((us & 2))
363     {
364       DEBUGOUT_CONT (" T=1");
365       have_t1 = 1;
366     }
367   if ((us & ~3))
368     DEBUGOUT_CONT (" (Invalid values detected)");
369   DEBUGOUT_LF ();
370
371   us = convert_le_u32(buf+10);
372   DEBUGOUT_1 ("  dwDefaultClock      %5u\n", us);
373   us = convert_le_u32(buf+14);
374   DEBUGOUT_1 ("  dwMaxiumumClock     %5u\n", us);
375   DEBUGOUT_1 ("  bNumClockSupported  %5u\n", buf[18]);
376   us = convert_le_u32(buf+19);
377   DEBUGOUT_1 ("  dwDataRate        %7u bps\n", us);
378   us = convert_le_u32(buf+23);
379   DEBUGOUT_1 ("  dwMaxDataRate     %7u bps\n", us);
380   DEBUGOUT_1 ("  bNumDataRatesSupp.  %5u\n", buf[27]);
381         
382   us = convert_le_u32(buf+28);
383   DEBUGOUT_1 ("  dwMaxIFSD           %5u\n", us);
384   handle->max_ifsd = us;
385
386   us = convert_le_u32(buf+32);
387   DEBUGOUT_1 ("  dwSyncProtocols  %08X ", us);
388   if ((us&1))
389     DEBUGOUT_CONT ( " 2-wire");
390   if ((us&2))
391     DEBUGOUT_CONT ( " 3-wire");
392   if ((us&4))
393     DEBUGOUT_CONT ( " I2C");
394   DEBUGOUT_LF ();
395
396   us = convert_le_u32(buf+36);
397   DEBUGOUT_1 ("  dwMechanical     %08X ", us);
398   if ((us & 1))
399     DEBUGOUT_CONT (" accept");
400   if ((us & 2))
401     DEBUGOUT_CONT (" eject");
402   if ((us & 4))
403     DEBUGOUT_CONT (" capture");
404   if ((us & 8))
405     DEBUGOUT_CONT (" lock");
406   DEBUGOUT_LF ();
407
408   us = convert_le_u32(buf+40);
409   DEBUGOUT_1 ("  dwFeatures       %08X\n", us);
410   if ((us & 0x0002))
411     {
412       DEBUGOUT ("    Auto configuration based on ATR\n");
413       have_auto_conf = 1;
414     }
415   if ((us & 0x0004))
416     DEBUGOUT ("    Auto activation on insert\n");
417   if ((us & 0x0008))
418     DEBUGOUT ("    Auto voltage selection\n");
419   if ((us & 0x0010))
420     DEBUGOUT ("    Auto clock change\n");
421   if ((us & 0x0020))
422     DEBUGOUT ("    Auto baud rate change\n");
423   if ((us & 0x0040))
424     DEBUGOUT ("    Auto parameter negotation made by CCID\n");
425   else if ((us & 0x0080))
426     DEBUGOUT ("    Auto PPS made by CCID\n");
427   else if ((us & (0x0040 | 0x0080)))
428     DEBUGOUT ("    WARNING: conflicting negotation features\n");
429
430   if ((us & 0x0100))
431     DEBUGOUT ("    CCID can set ICC in clock stop mode\n");
432   if ((us & 0x0200))
433     {
434       DEBUGOUT ("    NAD value other than 0x00 accepted\n");
435       handle->nonnull_nad = 1;
436     }
437   if ((us & 0x0400))
438     {
439       DEBUGOUT ("    Auto IFSD exchange\n");
440       handle->auto_ifsd = 1;
441     }
442
443   if ((us & 0x00010000))
444     {
445       DEBUGOUT ("    TPDU level exchange\n");
446       have_tpdu = 1;
447     } 
448   else if ((us & 0x00020000))
449     {
450       DEBUGOUT ("    Short APDU level exchange\n");
451       handle->apdu_level = 1;
452     }
453   else if ((us & 0x00040000))
454     {
455       DEBUGOUT ("    Short and extended APDU level exchange\n");
456       handle->apdu_level = 1;
457     }
458   else if ((us & 0x00070000))
459     DEBUGOUT ("    WARNING: conflicting exchange levels\n");
460
461   us = convert_le_u32(buf+44);
462   DEBUGOUT_1 ("  dwMaxCCIDMsgLen     %5u\n", us);
463
464   DEBUGOUT (  "  bClassGetResponse    ");
465   if (buf[48] == 0xff)
466     DEBUGOUT_CONT ("echo\n");
467   else
468     DEBUGOUT_CONT_1 ("  %02X\n", buf[48]);
469
470   DEBUGOUT (  "  bClassEnvelope       ");
471   if (buf[49] == 0xff)
472     DEBUGOUT_CONT ("echo\n");
473   else
474     DEBUGOUT_CONT_1 ("  %02X\n", buf[48]);
475
476   DEBUGOUT (  "  wlcdLayout           ");
477   if (!buf[50] && !buf[51])
478     DEBUGOUT_CONT ("none\n");
479   else
480     DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
481         
482   DEBUGOUT_1 ("  bPINSupport         %5u ", buf[52]);
483   if ((buf[52] & 1))
484     {
485       DEBUGOUT_CONT ( " verification");
486       handle->has_pinpad |= 1;
487     }
488   if ((buf[52] & 2))
489     {
490       DEBUGOUT_CONT ( " modification");
491       handle->has_pinpad |= 2;
492     }
493   DEBUGOUT_LF ();
494         
495   DEBUGOUT_1 ("  bMaxCCIDBusySlots   %5u\n", buf[53]);
496
497   if (buf[0] > 54) {
498     DEBUGOUT ("  junk             ");
499     for (i=54; i < buf[0]-54; i++)
500       DEBUGOUT_CONT_1 (" %02X", buf[i]);
501     DEBUGOUT_LF ();
502   }
503
504   if (!have_t1 || !(have_tpdu  || handle->apdu_level) || !have_auto_conf)
505     {
506       DEBUGOUT ("this drivers requires that the reader supports T=1, "
507                 "TPDU or APDU level exchange and auto configuration - "
508                 "this is not available\n");
509 //      return -1; // XXX dpavlin - fix for 5312 v2
510     }
511
512
513   /* SCM drivers get stuck in their internal USB stack if they try to
514      send a frame of n*wMaxPacketSize back to us.  Given that
515      wMaxPacketSize is 64 for these readers we set the IFSD to a value
516      lower than that:
517         64 - 10 CCID header -  4 T1frame - 2 reserved = 48
518      Product Ids:
519          0xe001 - SCR 331 
520          0x5111 - SCR 331-DI 
521          0x5115 - SCR 335 
522          0xe003 - SPR 532 
523   */
524   if (handle->id_vendor == VENDOR_SCM
525       && handle->max_ifsd > 48      
526       && (  (handle->id_product == 0xe001 && handle->bcd_device < 0x0516)
527           ||(handle->id_product == 0x5111 && handle->bcd_device < 0x0620)
528           ||(handle->id_product == 0x5115 && handle->bcd_device < 0x0514)
529           ||(handle->id_product == 0xe003 && handle->bcd_device < 0x0504)
530           ))
531     {
532       DEBUGOUT ("enabling workaround for buggy SCM readers\n");
533       handle->max_ifsd = 48;
534     }
535
536
537   return 0;
538 }
539
540
541 static char *
542 get_escaped_usb_string (usb_dev_handle *idev, int idx,
543                         const char *prefix, const char *suffix)
544 {
545   int rc;
546   unsigned char buf[280];
547   unsigned char *s;
548   unsigned int langid;
549   size_t i, n, len;
550   char *result;
551
552   if (!idx)
553     return NULL;
554
555   /* Fixme: The next line is for the current Valgrid without support
556      for USB IOCTLs. */
557   memset (buf, 0, sizeof buf);
558
559   /* First get the list of supported languages and use the first one.
560      If we do don't find it we try to use English.  Note that this is
561      all in a 2 bute Unicode encoding using little endian. */
562   rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
563                         (USB_DT_STRING << 8), 0, 
564                         (char*)buf, sizeof buf, 1000 /* ms timeout */);
565   if (rc < 4)
566     langid = 0x0409; /* English.  */
567   else
568     langid = (buf[3] << 8) | buf[2];
569
570   rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
571                         (USB_DT_STRING << 8) + idx, langid,
572                         (char*)buf, sizeof buf, 1000 /* ms timeout */);
573   if (rc < 2 || buf[1] != USB_DT_STRING)
574     return NULL; /* Error or not a string. */
575   len = buf[0];
576   if (len > rc)
577     return NULL; /* Larger than our buffer. */
578
579   for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
580     {
581       if (s[1])
582         n++; /* High byte set. */
583       else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
584         n += 3 ;
585       else 
586         n++;
587     }
588
589   result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
590   if (!result)
591     return NULL;
592
593   strcpy (result, prefix);
594   n = strlen (prefix);
595   for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
596     {
597       if (s[1])
598         result[n++] = '\xff'; /* High byte set. */
599       else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
600         {
601           sprintf (result+n, "%%%02X", *s);
602           n += 3;
603         }
604       else 
605         result[n++] = *s;
606     }
607   strcpy (result+n, suffix);
608
609   return result;
610 }
611
612 /* This function creates an reader id to be used to find the same
613    physical reader after a reset.  It returns an allocated and possibly
614    percent escaped string or NULL if not enough memory is available. */
615 static char *
616 make_reader_id (usb_dev_handle *idev,
617                 unsigned int vendor, unsigned int product,
618                 unsigned char serialno_index)
619 {
620   char *rid;
621   char prefix[20];
622
623   sprintf (prefix, "%04X:%04X:", (vendor & 0xfff), (product & 0xffff));
624   rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
625   if (!rid)
626     {
627       rid = malloc (strlen (prefix) + 3 + 1);
628       if (!rid)
629         return NULL;
630       strcpy (rid, prefix);
631       strcat (rid, "X:0");
632     }
633   return rid;
634 }
635
636
637 /* Helper to find the endpoint from an interface descriptor.  */
638 static int
639 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
640 {
641   int no;
642   int want_bulk_in = 0;
643
644   if (mode == 1)
645     want_bulk_in = 0x80;
646   for (no=0; no < ifcdesc->bNumEndpoints; no++)
647     {
648       struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
649       if (ep->bDescriptorType != USB_DT_ENDPOINT)
650         ;
651       else if (mode == 2
652           && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
653               == USB_ENDPOINT_TYPE_INTERRUPT)
654           && (ep->bEndpointAddress & 0x80))
655         return (ep->bEndpointAddress & 0x0f);
656       else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
657                 == USB_ENDPOINT_TYPE_BULK)
658                && (ep->bEndpointAddress & 0x80) == want_bulk_in)
659         return (ep->bEndpointAddress & 0x0f);
660     }
661   /* Should never happen.  */
662   return mode == 2? 0x83 : mode == 1? 0x82 :1;
663 }
664
665
666
667 /* Combination function to either scan all CCID devices or to find and
668    open one specific device. 
669
670    With READERNO = -1 and READERID is NULL, scan mode is used and
671    R_RID should be the address where to store the list of reader_ids
672    we found.  If on return this list is empty, no CCID device has been
673    found; otherwise it points to an allocated linked list of reader
674    IDs.  Note that in this mode the function always returns NULL.
675
676    With READERNO >= 0 or READERID is not NULL find mode is used.  This
677    uses the same algorithm as the scan mode but stops and returns at
678    the entry number READERNO and return the handle for the the opened
679    USB device. If R_ID is not NULL it will receive the reader ID of
680    that device.  If R_DEV is not NULL it will the device pointer of
681    that device.  If IFCDESC_EXTRA is NOT NULL it will receive a
682    malloced copy of the interfaces "extra: data filed;
683    IFCDESC_EXTRA_LEN receive the lengtyh of this field.  If there is
684    no reader with number READERNO or that reader is not usable by our
685    implementation NULL will be returned.  The caller must close a
686    returned USB device handle and free (if not passed as NULL) the
687    returned reader ID info as well as the IFCDESC_EXTRA.  On error
688    NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
689    IFCDESC_EXTRA_LEN.  With READERID being -1 the function stops if
690    the READERID was found.
691
692    Note that the first entry of the returned reader ID list in scan mode
693    corresponds with a READERNO of 0 in find mode.
694 */
695 static usb_dev_handle *
696 scan_or_find_devices (int readerno, const char *readerid,
697                       char **r_rid,
698                       struct usb_device **r_dev,
699                       unsigned char **ifcdesc_extra,
700                       size_t *ifcdesc_extra_len,
701                       int *interface_number,
702                       int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
703 {
704   char *rid_list = NULL;
705   int count = 0;
706   struct usb_bus *busses, *bus;
707   struct usb_device *dev = NULL;
708   usb_dev_handle *idev = NULL;
709   int scan_mode = (readerno == -1 && !readerid);
710
711    /* Set return values to a default. */
712   if (r_rid)
713     *r_rid = NULL;
714   if (r_dev)
715     *r_dev = NULL; 
716   if (ifcdesc_extra)
717     *ifcdesc_extra = NULL;
718   if (ifcdesc_extra_len)
719     *ifcdesc_extra_len = 0;
720   if (interface_number)
721     *interface_number = 0;
722
723   /* See whether we want scan or find mode. */
724   if (scan_mode) 
725     {
726       assert (r_rid);
727     }
728
729   usb_find_busses();
730   usb_find_devices();
731
732 #ifdef HAVE_USB_GET_BUSSES
733   busses = usb_get_busses();
734 #else
735   busses = usb_busses;
736 #endif
737
738   for (bus = busses; bus; bus = bus->next) 
739     {
740       for (dev = bus->devices; dev; dev = dev->next)
741         {
742           int cfg_no;
743           
744           for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
745             {
746               struct usb_config_descriptor *config = dev->config + cfg_no;
747               int ifc_no;
748
749               if(!config)
750                 continue;
751
752               for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
753                 {
754                   struct usb_interface *interface
755                     = config->interface + ifc_no;
756                   int set_no;
757                   
758                   if (!interface)
759                     continue;
760                   
761                   for (set_no=0; set_no < interface->num_altsetting; set_no++)
762                     {
763                       struct usb_interface_descriptor *ifcdesc
764                         = interface->altsetting + set_no;
765                       char *rid;
766                       
767                       /* The second condition is for some SCM Micro
768                          SPR 532 which does not know about the
769                          assigned CCID class. Instead of trying to
770                          interpret the strings we simply look at the
771                          product ID. */
772                       if (ifcdesc && ifcdesc->extra
773                           && (   (ifcdesc->bInterfaceClass == 11
774                                   && ifcdesc->bInterfaceSubClass == 0
775                                   && ifcdesc->bInterfaceProtocol == 0)
776                               || (ifcdesc->bInterfaceClass == 255
777                                   && dev->descriptor.idVendor == 0x04e6
778                                   && dev->descriptor.idProduct == 0xe003)))
779                         {
780                           idev = usb_open (dev);
781                           if (!idev)
782                             {
783                               DEBUGOUT_1 ("usb_open failed: %s\n",
784                                           strerror (errno));
785                               continue;
786                             }
787                               
788                           rid = make_reader_id (idev,
789                                                 dev->descriptor.idVendor,
790                                                 dev->descriptor.idProduct,
791                                                 dev->descriptor.iSerialNumber);
792                           if (rid)
793                             {
794                               if (scan_mode)
795                                 {
796                                   char *p;
797
798                                   /* We are collecting infos about all
799                                      available CCID readers.  Store
800                                      them and continue. */
801                                   DEBUGOUT_2 ("found CCID reader %d "
802                                               "(ID=%s)\n",
803                                               count, rid );
804                                   if ((p = malloc ((rid_list?
805                                                     strlen (rid_list):0)
806                                                    + 1 + strlen (rid)
807                                                    + 1)))
808                                     {
809                                       *p = 0;
810                                       if (rid_list)
811                                         {
812                                           strcat (p, rid_list);
813                                           free (rid_list);
814                                         }
815                                       strcat (p, rid);
816                                       strcat (p, "\n");
817                                       rid_list = p;
818                                     }
819                                   else /* Out of memory. */
820                                     free (rid);
821                                   rid = NULL;
822                                   count++;
823                                 }
824                               else if (!readerno
825                                        || (readerno < 0
826                                            && readerid
827                                            && !strcmp (readerid, rid)))
828                                 {
829                                   /* We found the requested reader. */
830                                   if (ifcdesc_extra && ifcdesc_extra_len)
831                                     {
832                                       *ifcdesc_extra = malloc (ifcdesc
833                                                                ->extralen);
834                                       if (!*ifcdesc_extra)
835                                         {
836                                           usb_close (idev);
837                                           free (rid);
838                                           return NULL; /* Out of core. */
839                                         }
840                                       memcpy (*ifcdesc_extra, ifcdesc->extra,
841                                               ifcdesc->extralen);
842                                       *ifcdesc_extra_len = ifcdesc->extralen;
843                                     }
844                                   if (interface_number)
845                                     *interface_number = (ifcdesc->
846                                                          bInterfaceNumber);
847                                   if (ep_bulk_out)
848                                     *ep_bulk_out = find_endpoint (ifcdesc, 0);
849                                   if (ep_bulk_in)
850                                     *ep_bulk_in = find_endpoint (ifcdesc, 1);
851                                   if (ep_intr)
852                                     *ep_intr = find_endpoint (ifcdesc, 2);
853
854
855                                   if (r_dev)
856                                     *r_dev = dev;
857                                   if (r_rid)
858                                     {
859                                       *r_rid = rid;
860                                       rid = NULL;
861                                     }
862                                   else
863                                     free (rid);
864                                   return idev; /* READY. */
865                                 }
866                               else
867                                 {
868                                   /* This is not yet the reader we
869                                      want.  fixme: We could avoid the
870                                      extra usb_open in this case. */
871                                   if (readerno >= 0)
872                                     readerno--;
873                                 }
874                               free (rid);
875                             }
876                           
877                           usb_close (idev);
878                           idev = NULL;
879                           goto next_device;
880                         }
881                     }
882                 }
883             }
884         next_device:
885           ;
886         }
887     }
888
889   if (scan_mode)
890     *r_rid = rid_list;
891
892   return NULL;
893 }
894
895
896 /* Set the level of debugging to to usea dn return the old level.  -1
897    just returns the old level.  A level of 0 disables debugging, 1
898    enables debugging, 2 enables additional tracing of the T=1
899    protocol, other values are not yet defined. */
900 int
901 ccid_set_debug_level (int level)
902 {
903   int old = debug_level;
904   if (level != -1)
905     debug_level = level;
906   return old;
907 }
908
909
910 char *
911 ccid_get_reader_list (void)
912 {
913   char *reader_list;
914
915   if (!initialized_usb)
916     {
917       usb_init ();
918       initialized_usb = 1;
919     }
920
921   scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
922                         NULL, NULL, NULL);
923   return reader_list;
924 }
925
926
927 /* Open the reader with the internal number READERNO and return a 
928    pointer to be used as handle in HANDLE.  Returns 0 on success. */
929 int 
930 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
931 {
932   int rc = 0;
933   struct usb_device *dev = NULL;
934   usb_dev_handle *idev = NULL;
935   char *rid = NULL;
936   unsigned char *ifcdesc_extra = NULL;
937   size_t ifcdesc_extra_len;
938   int readerno;
939   int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
940
941   *handle = NULL;
942
943   if (!initialized_usb)
944     {
945       usb_init ();
946       initialized_usb = 1;
947     }
948
949   /* See whether we want to use the reader ID string or a reader
950      number. A readerno of -1 indicates that the reader ID string is
951      to be used. */
952   if (readerid && strchr (readerid, ':'))
953     readerno = -1; /* We want to use the readerid.  */
954   else if (readerid)
955     {
956       readerno = atoi (readerid);
957       if (readerno < 0)
958         {
959           DEBUGOUT ("no CCID readers found\n");
960           rc = CCID_DRIVER_ERR_NO_READER;
961           goto leave;
962         }
963     }
964   else
965     readerno = 0;  /* Default. */
966
967   idev = scan_or_find_devices (readerno, readerid, &rid, &dev,
968                                &ifcdesc_extra, &ifcdesc_extra_len,
969                                &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr);
970   if (!idev)
971     {
972       if (readerno == -1)
973         DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
974       else
975         DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
976       rc = CCID_DRIVER_ERR_NO_READER;
977       goto leave;
978     }
979
980   /* Okay, this is a CCID reader. */
981   *handle = calloc (1, sizeof **handle);
982   if (!*handle)
983     {
984       DEBUGOUT ("out of memory\n");
985       rc = CCID_DRIVER_ERR_OUT_OF_CORE;
986       goto leave;
987     }
988   (*handle)->idev = idev;
989   (*handle)->rid = rid;
990   (*handle)->id_vendor = dev->descriptor.idVendor;
991   (*handle)->id_product = dev->descriptor.idProduct;
992   (*handle)->bcd_device = dev->descriptor.bcdDevice;
993   (*handle)->ifc_no = ifc_no;
994   (*handle)->ep_bulk_out = ep_bulk_out;
995   (*handle)->ep_bulk_in = ep_bulk_in;
996   (*handle)->ep_intr = ep_intr;
997
998   DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n",  readerno, rid );
999
1000
1001   if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1002     {
1003       DEBUGOUT ("device not supported\n");
1004       rc = CCID_DRIVER_ERR_NO_READER;
1005       goto leave;
1006     }
1007   
1008   rc = usb_claim_interface (idev, ifc_no);
1009   if (rc)
1010     {
1011       DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1012       rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1013       goto leave;
1014     }
1015   
1016  leave:
1017   free (ifcdesc_extra);
1018   if (rc)
1019     {
1020       free (rid);
1021       if (idev)
1022         usb_close (idev);
1023       free (*handle);
1024       *handle = NULL;
1025     }
1026
1027   return rc;
1028 }
1029
1030
1031 static void
1032 do_close_reader (ccid_driver_t handle)
1033 {
1034   int rc;
1035   unsigned char msg[100];
1036   size_t msglen;
1037   unsigned char seqno;
1038   
1039   if (!handle->powered_off)
1040     {
1041       msg[0] = PC_to_RDR_IccPowerOff;
1042       msg[5] = 0; /* slot */
1043       msg[6] = seqno = handle->seqno++;
1044       msg[7] = 0; /* RFU */
1045       msg[8] = 0; /* RFU */
1046       msg[9] = 0; /* RFU */
1047       set_msg_len (msg, 0);
1048       msglen = 10;
1049       
1050       rc = bulk_out (handle, msg, msglen);
1051       if (!rc)
1052         bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1053                  seqno, 2000, 0);
1054       handle->powered_off = 1;
1055     }
1056   if (handle->idev)
1057     {
1058       usb_release_interface (handle->idev, handle->ifc_no);
1059       usb_close (handle->idev);
1060       handle->idev = NULL;
1061     }
1062 }
1063
1064
1065 /* Reset a reader on HANDLE.  This is useful in case a reader has been
1066    plugged of and inserted at a different port.  By resetting the
1067    handle, the same reader will be get used.  Note, that on error the
1068    handle won't get released. 
1069
1070    This does not return an ATR, so ccid_get_atr should be called right
1071    after this one.
1072 */
1073 int 
1074 ccid_shutdown_reader (ccid_driver_t handle)
1075 {
1076   int rc = 0;
1077   struct usb_device *dev = NULL;
1078   usb_dev_handle *idev = NULL;
1079   unsigned char *ifcdesc_extra = NULL;
1080   size_t ifcdesc_extra_len;
1081   int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1082
1083   if (!handle || !handle->rid)
1084     return CCID_DRIVER_ERR_INV_VALUE;
1085
1086   do_close_reader (handle);
1087
1088   idev = scan_or_find_devices (-1, handle->rid, NULL, &dev,
1089                                &ifcdesc_extra, &ifcdesc_extra_len,
1090                                &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr);
1091   if (!idev)
1092     {
1093       DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1094       return CCID_DRIVER_ERR_NO_READER;
1095     }
1096
1097
1098   handle->idev = idev;
1099   handle->ifc_no = ifc_no;
1100   handle->ep_bulk_out = ep_bulk_out;
1101   handle->ep_bulk_in = ep_bulk_in;
1102   handle->ep_intr = ep_intr;
1103
1104   if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1105     {
1106       DEBUGOUT ("device not supported\n");
1107       rc = CCID_DRIVER_ERR_NO_READER;
1108       goto leave;
1109     }
1110   
1111   rc = usb_claim_interface (idev, ifc_no);
1112   if (rc)
1113     {
1114       DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1115       rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1116       goto leave;
1117     }
1118   
1119  leave:
1120   free (ifcdesc_extra);
1121   if (rc)
1122     {
1123       usb_close (handle->idev);
1124       handle->idev = NULL;
1125     }
1126
1127   return rc;
1128
1129 }
1130
1131
1132 /* Close the reader HANDLE. */
1133 int 
1134 ccid_close_reader (ccid_driver_t handle)
1135 {
1136   if (!handle || !handle->idev)
1137     return 0;
1138
1139   do_close_reader (handle);
1140   free (handle->rid);
1141   free (handle);
1142   return 0;
1143 }
1144
1145
1146 /* Return False if a card is present and powered. */
1147 int
1148 ccid_check_card_presence (ccid_driver_t handle)
1149 {
1150
1151   return -1;
1152 }
1153
1154
1155 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1156    Returns 0 on success. */
1157 static int
1158 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen)
1159 {
1160   int rc;
1161
1162   rc = usb_bulk_write (handle->idev, 
1163                        handle->ep_bulk_out,
1164                        (char*)msg, msglen,
1165                        1000 /* ms timeout */);
1166   if (rc == msglen)
1167     return 0;
1168
1169   if (rc == -1)
1170     DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1171   else
1172     DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1173   return CCID_DRIVER_ERR_CARD_IO_ERROR;
1174 }
1175
1176
1177 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1178    BUFFER and return the actual read number if bytes in NREAD. SEQNO
1179    is the sequence number used to send the request and EXPECTED_TYPE
1180    the type of message we expect. Does checks on the ccid
1181    header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1182    avoid debug messages in case of no error. Returns 0 on success. */
1183 static int
1184 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1185          size_t *nread, int expected_type, int seqno, int timeout,
1186          int no_debug)
1187 {
1188   int i, rc;
1189   size_t msglen;
1190
1191   /* Fixme: The next line for the current Valgrind without support
1192      for USB IOCTLs. */
1193   memset (buffer, 0, length);
1194  retry:
1195   rc = usb_bulk_read (handle->idev, 
1196                       handle->ep_bulk_in,
1197                       (char*)buffer, length,
1198                       timeout);
1199   if (rc < 0)
1200     {
1201       DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (errno));
1202       return CCID_DRIVER_ERR_CARD_IO_ERROR;
1203     }
1204
1205   *nread = msglen = rc;
1206
1207   if (msglen < 10)
1208     {
1209       DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
1210       return CCID_DRIVER_ERR_INV_VALUE;
1211     }
1212   if (buffer[0] != expected_type)
1213     {
1214       DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
1215       return CCID_DRIVER_ERR_INV_VALUE;
1216     }
1217   if (buffer[5] != 0)    
1218     {
1219       DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
1220       return CCID_DRIVER_ERR_INV_VALUE;
1221     }
1222   if (buffer[6] != seqno)    
1223     {
1224       DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
1225                   seqno, buffer[6]);
1226       return CCID_DRIVER_ERR_INV_VALUE;
1227     }
1228
1229   if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
1230     { 
1231       /* Card present and active, time extension requested. */
1232       DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
1233                   buffer[7], buffer[8]);
1234       goto retry;
1235     }
1236
1237   if (!no_debug)
1238     {
1239       DEBUGOUT_3 ("status: %02X  error: %02X  octet[9]: %02X\n"
1240                   "               data:",  buffer[7], buffer[8], buffer[9] );
1241       for (i=10; i < msglen; i++)
1242         DEBUGOUT_CONT_1 (" %02X", buffer[i]);
1243       DEBUGOUT_LF ();
1244     }
1245   if (CCID_COMMAND_FAILED (buffer))
1246     print_command_failed (buffer);
1247
1248   /* Check whether a card is at all available.  Note: If you add new
1249      error codes here, check whether they need to be ignored in
1250      send_escape_cmd. */
1251   switch ((buffer[7] & 0x03))
1252     {
1253     case 0: /* no error */ break;
1254     case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
1255     case 2: return CCID_DRIVER_ERR_NO_CARD;
1256     case 3: /* RFU */ break;
1257     }
1258   return 0;
1259 }
1260
1261
1262 /* Note that this function won't return the error codes NO_CARD or
1263    CARD_INACTIVE.  IF RESULT is not NULL, the result from the
1264    operation will get returned in RESULT and its length in RESULTLEN.
1265    If the response is larger than RESULTMAX, an error is returned and
1266    the required buffer length returned in RESULTLEN.  */
1267 static int 
1268 send_escape_cmd (ccid_driver_t handle,
1269                  const unsigned char *data, size_t datalen,
1270                  unsigned char *result, size_t resultmax, size_t *resultlen)
1271 {
1272   int i, rc;
1273   unsigned char msg[100];
1274   size_t msglen;
1275   unsigned char seqno;
1276
1277   if (resultlen)
1278     *resultlen = 0;
1279
1280   if (datalen > sizeof msg - 10)
1281     return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large.  */
1282
1283   msg[0] = PC_to_RDR_Escape;
1284   msg[5] = 0; /* slot */
1285   msg[6] = seqno = handle->seqno++;
1286   msg[7] = 0; /* RFU */
1287   msg[8] = 0; /* RFU */
1288   msg[9] = 0; /* RFU */
1289   memcpy (msg+10, data, datalen);
1290   msglen = 10 + datalen;
1291   set_msg_len (msg, datalen);
1292
1293   DEBUGOUT ("sending");
1294   for (i=0; i < msglen; i++)
1295     DEBUGOUT_CONT_1 (" %02X", msg[i]);
1296   DEBUGOUT_LF ();
1297   rc = bulk_out (handle, msg, msglen);
1298   if (rc)
1299     return rc;
1300   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
1301                 seqno, 5000, 0);
1302   if (result)
1303     switch (rc)
1304       {
1305         /* We need to ignore certain errorcode here. */
1306       case 0:
1307       case CCID_DRIVER_ERR_CARD_INACTIVE:
1308       case CCID_DRIVER_ERR_NO_CARD:
1309         {
1310           if (msglen < 10 || (msglen-10) > resultmax )
1311             rc = CCID_DRIVER_ERR_INV_VALUE; /* Invalid length of response. */
1312           else
1313             {
1314               memcpy (result, msg+10, msglen-10);
1315               *resultlen = msglen-10;
1316             }
1317           rc = 0;
1318         }
1319         break;
1320       default:
1321         break;
1322       }
1323   
1324   return rc;
1325 }
1326
1327
1328 int
1329 ccid_transceive_escape (ccid_driver_t handle,
1330                         const unsigned char *data, size_t datalen,
1331                         unsigned char *resp, size_t maxresplen, size_t *nresp)
1332 {
1333   return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
1334 }
1335
1336
1337
1338 /* experimental */
1339 int
1340 ccid_poll (ccid_driver_t handle)
1341 {
1342   int rc;
1343   unsigned char msg[10];
1344   size_t msglen;
1345   int i, j;
1346
1347   rc = usb_bulk_read (handle->idev, 
1348                       handle->ep_intr,
1349                       (char*)msg, sizeof msg,
1350                       0 /* ms timeout */ );
1351   if (rc < 0 && errno == ETIMEDOUT)
1352     return 0;
1353
1354   if (rc < 0)
1355     {
1356       DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
1357       return CCID_DRIVER_ERR_CARD_IO_ERROR;
1358     }
1359
1360   msglen = rc;
1361   rc = 0;
1362
1363   if (msglen < 1)
1364     {
1365       DEBUGOUT ("intr-in msg too short\n");
1366       return CCID_DRIVER_ERR_INV_VALUE;
1367     }
1368
1369   if (msg[0] == RDR_to_PC_NotifySlotChange)
1370     {
1371       DEBUGOUT ("notify slot change:");
1372       for (i=1; i < msglen; i++)
1373         for (j=0; j < 4; j++)
1374           DEBUGOUT_CONT_3 (" %d:%c%c",
1375                            (i-1)*4+j, 
1376                            (msg[i] & (1<<(j*2)))? 'p':'-',
1377                            (msg[i] & (2<<(j*2)))? '*':' ');
1378       DEBUGOUT_LF ();
1379     }
1380   else if (msg[0] == RDR_to_PC_HardwareError)    
1381     {
1382       DEBUGOUT ("hardware error occured\n");
1383     }
1384   else
1385     {
1386       DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
1387     }
1388
1389   return 0;
1390 }
1391
1392
1393 /* Note that this fucntion won't return the error codes NO_CARD or
1394    CARD_INACTIVE */
1395 int 
1396 ccid_slot_status (ccid_driver_t handle, int *statusbits)
1397 {
1398   int rc;
1399   unsigned char msg[100];
1400   size_t msglen;
1401   unsigned char seqno;
1402   int retries = 0;
1403
1404  retry:
1405   msg[0] = PC_to_RDR_GetSlotStatus;
1406   msg[5] = 0; /* slot */
1407   msg[6] = seqno = handle->seqno++;
1408   msg[7] = 0; /* RFU */
1409   msg[8] = 0; /* RFU */
1410   msg[9] = 0; /* RFU */
1411   set_msg_len (msg, 0);
1412
1413   rc = bulk_out (handle, msg, 10);
1414   if (rc)
1415     return rc;
1416   /* Note that we set the NO_DEBUG flag here, so that the logs won't
1417      get cluttered up by a ticker function checking for the slot
1418      status and debugging enabled. */
1419   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1420                 seqno, retries? 1000 : 200, 1);
1421   if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
1422     {
1423       if (!retries)
1424         {
1425           DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
1426           usb_clear_halt (handle->idev, handle->ep_bulk_in);
1427           usb_clear_halt (handle->idev, handle->ep_bulk_out);
1428         }
1429       else
1430           DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
1431       retries++;
1432       goto retry;
1433     }
1434   if (rc && rc != CCID_DRIVER_ERR_NO_CARD
1435       && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
1436     return rc;
1437   *statusbits = (msg[7] & 3);
1438
1439   return 0;
1440 }
1441
1442
1443 int 
1444 ccid_get_atr (ccid_driver_t handle,
1445               unsigned char *atr, size_t maxatrlen, size_t *atrlen)
1446 {
1447   int rc;
1448   int statusbits;
1449   unsigned char msg[100];
1450   unsigned char *tpdu;
1451   size_t msglen, tpdulen;
1452   unsigned char seqno;
1453   int use_crc = 0;
1454   unsigned int edc;
1455   int i;
1456   int tried_iso = 0;
1457
1458   /* First check whether a card is available.  */
1459   rc = ccid_slot_status (handle, &statusbits);
1460   if (rc)
1461     return rc;
1462   if (statusbits == 2)
1463     return CCID_DRIVER_ERR_NO_CARD;
1464
1465   /* For an inactive and also for an active card, issue the PowerOn
1466      command to get the ATR.  */
1467  again:
1468   msg[0] = PC_to_RDR_IccPowerOn;
1469   msg[5] = 0; /* slot */
1470   msg[6] = seqno = handle->seqno++;
1471   msg[7] = 0; /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
1472   msg[8] = 0; /* RFU */
1473   msg[9] = 0; /* RFU */
1474   set_msg_len (msg, 0);
1475   msglen = 10;
1476
1477   rc = bulk_out (handle, msg, msglen);
1478   if (rc)
1479     return rc;
1480   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
1481                 seqno, 5000, 0);
1482   if (rc)
1483     return rc;
1484   if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
1485       && ((handle->id_vendor == VENDOR_CHERRY
1486            && handle->id_product == 0x0005)
1487           || (handle->id_vendor == VENDOR_GEMPC
1488               && handle->id_product == 0x4433)
1489           ))
1490     {
1491       tried_iso = 1;
1492       /* Try switching to ISO mode. */
1493       if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
1494                             NULL, 0, NULL))
1495         goto again;
1496     }
1497   else if (CCID_COMMAND_FAILED (msg))
1498     return CCID_DRIVER_ERR_CARD_IO_ERROR;
1499
1500
1501   handle->powered_off = 0;
1502   
1503   if (atr)
1504     {
1505       size_t n = msglen - 10;
1506
1507       if (n > maxatrlen)
1508         n = maxatrlen;
1509       memcpy (atr, msg+10, n);
1510       *atrlen = n;
1511     }
1512
1513   /* Setup parameters to select T=1. */
1514   msg[0] = PC_to_RDR_SetParameters;
1515   msg[5] = 0; /* slot */
1516   msg[6] = seqno = handle->seqno++;
1517   msg[7] = 1; /* Select T=1. */
1518   msg[8] = 0; /* RFU */
1519   msg[9] = 0; /* RFU */
1520
1521   /* FIXME: Get those values from the ATR. */
1522   msg[10]= 0x01; /* Fi/Di */
1523   msg[11]= 0x10; /* LRC, direct convention. */
1524   msg[12]= 0;    /* Extra guardtime. */
1525   msg[13]= 0x41; /* BWI/CWI */
1526   msg[14]= 0;    /* No clock stoppping. */
1527   msg[15]= 254;  /* IFSC */
1528   msg[16]= 0;    /* Does not support non default NAD values. */
1529   set_msg_len (msg, 7);
1530   msglen = 10 + 7;
1531
1532   DEBUGOUT ("sending");
1533   for (i=0; i < msglen; i++)
1534     DEBUGOUT_CONT_1 (" %02X", msg[i]);
1535   DEBUGOUT_LF ();
1536
1537   rc = bulk_out (handle, msg, msglen);
1538   if (rc)
1539     return rc;
1540   /* Note that we ignore the error code on purpose. */
1541   bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
1542            seqno, 5000, 0);
1543
1544   handle->t1_ns = 0;
1545   handle->t1_nr = 0;
1546
1547   /* Send an S-Block with our maximun IFSD to the CCID.  */
1548   if (!handle->auto_ifsd)
1549     {
1550       tpdu = msg+10;
1551       /* NAD: DAD=1, SAD=0 */
1552       tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1553       tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
1554       tpdu[2] = 1;
1555       tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32; 
1556       tpdulen = 4;
1557       edc = compute_edc (tpdu, tpdulen, use_crc);
1558       if (use_crc)
1559         tpdu[tpdulen++] = (edc >> 8);
1560       tpdu[tpdulen++] = edc;
1561
1562       msg[0] = PC_to_RDR_XfrBlock;
1563       msg[5] = 0; /* slot */
1564       msg[6] = seqno = handle->seqno++;
1565       msg[7] = 0; 
1566       msg[8] = 0; /* RFU */
1567       msg[9] = 0; /* RFU */
1568       set_msg_len (msg, tpdulen);
1569       msglen = 10 + tpdulen;
1570
1571       DEBUGOUT ("sending");
1572       for (i=0; i < msglen; i++)
1573         DEBUGOUT_CONT_1 (" %02X", msg[i]);
1574       DEBUGOUT_LF ();
1575
1576       if (debug_level > 1)
1577         DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1578                       ((msg[11] & 0xc0) == 0x80)? 'R' :
1579                                 (msg[11] & 0x80)? 'S' : 'I',
1580                       ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1581                                        : !!(msg[11] & 0x40)),
1582                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1583
1584       rc = bulk_out (handle, msg, msglen);
1585       if (rc)
1586         return rc;
1587
1588
1589       rc = bulk_in (handle, msg, sizeof msg, &msglen,
1590                     RDR_to_PC_DataBlock, seqno, 5000, 0);
1591       if (rc)
1592         return rc;
1593       
1594       tpdu = msg + 10;
1595       tpdulen = msglen - 10;
1596       
1597       if (tpdulen < 4) 
1598         return CCID_DRIVER_ERR_ABORTED; 
1599
1600       if (debug_level > 1)
1601         DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1602                     ((msg[11] & 0xc0) == 0x80)? 'R' :
1603                               (msg[11] & 0x80)? 'S' : 'I',
1604                     ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1605                                      : !!(msg[11] & 0x40)),
1606                     ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1607                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1608
1609       if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
1610         {
1611           DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
1612           return -1;
1613         }
1614       DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
1615     }
1616
1617   return 0;
1618 }
1619
1620
1621
1622
1623 static unsigned int 
1624 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
1625 {
1626   if (use_crc)
1627     {
1628       return 0x42; /* Not yet implemented. */
1629     }
1630   else
1631     {
1632       unsigned char crc = 0;
1633       
1634       for (; datalen; datalen--)
1635         crc ^= *data++;
1636       return crc;
1637     }
1638 }
1639
1640
1641 /* Helper for ccid_transceive used for APDU level exchanges.  */
1642 static int
1643 ccid_transceive_apdu_level (ccid_driver_t handle,
1644                             const unsigned char *apdu_buf, size_t apdu_buflen,
1645                             unsigned char *resp, size_t maxresplen,
1646                             size_t *nresp)
1647 {
1648   int rc;
1649   unsigned char send_buffer[10+259], recv_buffer[10+259];
1650   const unsigned char *apdu;
1651   size_t apdulen;
1652   unsigned char *msg;
1653   size_t msglen;
1654   unsigned char seqno;
1655   int i;
1656
1657   msg = send_buffer;
1658
1659   apdu = apdu_buf;
1660   apdulen = apdu_buflen;
1661   assert (apdulen);
1662
1663   if (apdulen > 254)
1664     return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1665
1666   msg[0] = PC_to_RDR_XfrBlock;
1667   msg[5] = 0; /* slot */
1668   msg[6] = seqno = handle->seqno++;
1669   msg[7] = 4; /* bBWI */
1670   msg[8] = 0; /* RFU */
1671   msg[9] = 0; /* RFU */
1672   memcpy (msg+10, apdu, apdulen);
1673   set_msg_len (msg, apdulen);
1674   msglen = 10 + apdulen;
1675
1676   DEBUGOUT ("sending");
1677   for (i=0; i < msglen; i++)
1678     DEBUGOUT_CONT_1 (" %02X", msg[i]);
1679   DEBUGOUT_LF ();
1680   
1681   rc = bulk_out (handle, msg, msglen);
1682   if (rc)
1683     return rc;
1684
1685   msg = recv_buffer;
1686   rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1687                 RDR_to_PC_DataBlock, seqno, 5000, 0);
1688   if (rc)
1689     return rc;
1690       
1691   apdu = msg + 10;
1692   apdulen = msglen - 10;
1693       
1694   if (resp)
1695     {
1696       if (apdulen > maxresplen)
1697         {
1698           DEBUGOUT_2 ("provided buffer too short for received data "
1699                       "(%u/%u)\n",
1700                       (unsigned int)apdulen, (unsigned int)maxresplen);
1701           return CCID_DRIVER_ERR_INV_VALUE;
1702         }
1703       
1704       memcpy (resp, apdu, apdulen); 
1705       *nresp = apdulen;
1706     }
1707           
1708   return 0;
1709 }
1710
1711
1712
1713 /*
1714   Protocol T=1 overview
1715
1716   Block Structure:
1717            Prologue Field:
1718    1 byte     Node Address (NAD) 
1719    1 byte     Protocol Control Byte (PCB)
1720    1 byte     Length (LEN) 
1721            Information Field:
1722    0-254 byte APDU or Control Information (INF)
1723            Epilogue Field:
1724    1 byte     Error Detection Code (EDC)
1725
1726   NAD:  
1727    bit 7     unused
1728    bit 4..6  Destination Node Address (DAD)
1729    bit 3     unused
1730    bit 2..0  Source Node Address (SAD)
1731
1732    If node adresses are not used, SAD and DAD should be set to 0 on
1733    the first block sent to the card.  If they are used they should
1734    have different values (0 for one is okay); that first block sets up
1735    the addresses of the nodes.
1736
1737   PCB:
1738    Information Block (I-Block):
1739       bit 7    0
1740       bit 6    Sequence number (yep, that is modulo 2)
1741       bit 5    Chaining flag 
1742       bit 4..0 reserved
1743    Received-Ready Block (R-Block):
1744       bit 7    1
1745       bit 6    0
1746       bit 5    0
1747       bit 4    Sequence number
1748       bit 3..0  0 = no error
1749                 1 = EDC or parity error
1750                 2 = other error
1751                 other values are reserved
1752    Supervisory Block (S-Block):
1753       bit 7    1
1754       bit 6    1
1755       bit 5    clear=request,set=response
1756       bit 4..0  0 = resyncronisation request
1757                 1 = information field size request
1758                 2 = abort request
1759                 3 = extension of BWT request
1760                 4 = VPP error
1761                 other values are reserved
1762
1763 */
1764
1765 int
1766 ccid_transceive (ccid_driver_t handle,
1767                  const unsigned char *apdu_buf, size_t apdu_buflen,
1768                  unsigned char *resp, size_t maxresplen, size_t *nresp)
1769 {
1770   int rc;
1771   unsigned char send_buffer[10+259], recv_buffer[10+259];
1772   const unsigned char *apdu;
1773   size_t apdulen;
1774   unsigned char *msg, *tpdu, *p;
1775   size_t msglen, tpdulen, last_tpdulen, n;
1776   unsigned char seqno;
1777   int i;
1778   unsigned int edc;
1779   int use_crc = 0;
1780   size_t dummy_nresp;
1781   int next_chunk = 1;
1782   int sending = 1;
1783   int retries = 0;
1784
1785   if (!nresp)
1786     nresp = &dummy_nresp;
1787   *nresp = 0;
1788
1789   /* Smarter readers allow to send APDUs directly; divert here. */
1790   if (handle->apdu_level)
1791     return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
1792                                        resp, maxresplen, nresp);
1793
1794   /* The other readers we support require sending TPDUs.  */
1795
1796   tpdulen = 0; /* Avoid compiler warning about no initialization. */
1797   msg = send_buffer;
1798   for (;;)
1799     {
1800       if (next_chunk)
1801         {
1802           next_chunk = 0;
1803
1804           apdu = apdu_buf;
1805           apdulen = apdu_buflen;
1806           assert (apdulen);
1807
1808           /* Construct an I-Block. */
1809           if (apdulen > 254)
1810             return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
1811
1812           tpdu = msg+10;
1813           /* NAD: DAD=1, SAD=0 */
1814           tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1815           tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
1816           if (apdulen > 128 /* fixme: replace by ifsc */)
1817             {
1818               apdulen = 128;
1819               apdu_buf += 128;  
1820               apdu_buflen -= 128;
1821               tpdu[1] |= (1 << 5); /* Set more bit. */
1822             }
1823           tpdu[2] = apdulen;
1824           memcpy (tpdu+3, apdu, apdulen);
1825           tpdulen = 3 + apdulen;
1826           edc = compute_edc (tpdu, tpdulen, use_crc);
1827           if (use_crc)
1828             tpdu[tpdulen++] = (edc >> 8);
1829           tpdu[tpdulen++] = edc;
1830         }
1831
1832       msg[0] = PC_to_RDR_XfrBlock;
1833       msg[5] = 0; /* slot */
1834       msg[6] = seqno = handle->seqno++;
1835       msg[7] = 4; /* bBWI */
1836       msg[8] = 0; /* RFU */
1837       msg[9] = 0; /* RFU */
1838       set_msg_len (msg, tpdulen);
1839       msglen = 10 + tpdulen;
1840       last_tpdulen = tpdulen;
1841
1842       DEBUGOUT ("sending");
1843       for (i=0; i < msglen; i++)
1844         DEBUGOUT_CONT_1 (" %02X", msg[i]);
1845       DEBUGOUT_LF ();
1846
1847       if (debug_level > 1)
1848           DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
1849                       ((msg[11] & 0xc0) == 0x80)? 'R' :
1850                                 (msg[11] & 0x80)? 'S' : 'I',
1851                       ((msg[11] & 0x80)? !!(msg[11]& 0x10)
1852                                        : !!(msg[11] & 0x40)),
1853                       (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1854
1855       rc = bulk_out (handle, msg, msglen);
1856       if (rc)
1857         return rc;
1858
1859       msg = recv_buffer;
1860       rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
1861                     RDR_to_PC_DataBlock, seqno, 5000, 0);
1862       if (rc)
1863         return rc;
1864       
1865       tpdu = msg + 10;
1866       tpdulen = msglen - 10;
1867       
1868       if (tpdulen < 4) 
1869         {
1870           usb_clear_halt (handle->idev, handle->ep_bulk_in);
1871           return CCID_DRIVER_ERR_ABORTED; 
1872         }
1873
1874       if (debug_level > 1)
1875         DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
1876                     ((msg[11] & 0xc0) == 0x80)? 'R' :
1877                               (msg[11] & 0x80)? 'S' : 'I',
1878                     ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
1879                     ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
1880                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
1881
1882       if (!(tpdu[1] & 0x80))
1883         { /* This is an I-block. */
1884           retries = 0;
1885           if (sending)
1886             { /* last block sent was successful. */
1887               handle->t1_ns ^= 1;
1888               sending = 0;
1889             }
1890
1891           if (!!(tpdu[1] & 0x40) != handle->t1_nr)
1892             { /* Reponse does not match our sequence number. */
1893               msg = send_buffer;
1894               tpdu = msg+10;
1895               /* NAD: DAD=1, SAD=0 */
1896               tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1897               tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
1898               tpdu[2] = 0;
1899               tpdulen = 3;
1900               edc = compute_edc (tpdu, tpdulen, use_crc);
1901               if (use_crc)
1902                 tpdu[tpdulen++] = (edc >> 8);
1903               tpdu[tpdulen++] = edc;
1904
1905               continue;
1906             }
1907
1908           handle->t1_nr ^= 1;
1909
1910           p = tpdu + 3; /* Skip the prologue field. */
1911           n = tpdulen - 3 - 1; /* Strip the epilogue field. */
1912           /* fixme: verify the checksum. */
1913           if (resp)
1914             {
1915               if (n > maxresplen)
1916                 {
1917                   DEBUGOUT_2 ("provided buffer too short for received data "
1918                               "(%u/%u)\n",
1919                               (unsigned int)n, (unsigned int)maxresplen);
1920                   return CCID_DRIVER_ERR_INV_VALUE;
1921                 }
1922               
1923               memcpy (resp, p, n); 
1924               resp += n;
1925               *nresp += n;
1926               maxresplen -= n;
1927             }
1928           
1929           if (!(tpdu[1] & 0x20))
1930             return 0; /* No chaining requested - ready. */
1931           
1932           msg = send_buffer;
1933           tpdu = msg+10;
1934           /* NAD: DAD=1, SAD=0 */
1935           tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1936           tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
1937           tpdu[2] = 0;
1938           tpdulen = 3;
1939           edc = compute_edc (tpdu, tpdulen, use_crc);
1940           if (use_crc)
1941             tpdu[tpdulen++] = (edc >> 8);
1942           tpdu[tpdulen++] = edc;
1943         }
1944       else if ((tpdu[1] & 0xc0) == 0x80)
1945         { /* This is a R-block. */
1946           if ( (tpdu[1] & 0x0f)) 
1947             { /* Error: repeat last block */
1948               if (++retries > 3)
1949                 {
1950                   DEBUGOUT ("3 failed retries\n");
1951                   return CCID_DRIVER_ERR_CARD_IO_ERROR;
1952                 }
1953               msg = send_buffer;
1954               tpdulen = last_tpdulen;
1955             }
1956           else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
1957             { /* Response does not match our sequence number. */
1958               DEBUGOUT ("R-block with wrong seqno received on more bit\n");
1959               return CCID_DRIVER_ERR_CARD_IO_ERROR;
1960             }
1961           else if (sending)
1962             { /* Send next chunk. */
1963               retries = 0;
1964               msg = send_buffer;
1965               next_chunk = 1;
1966               handle->t1_ns ^= 1;
1967             }
1968           else
1969             {
1970               DEBUGOUT ("unexpected ACK R-block received\n");
1971               return CCID_DRIVER_ERR_CARD_IO_ERROR;
1972             }
1973         }
1974       else 
1975         { /* This is a S-block. */
1976           retries = 0;
1977           DEBUGOUT_2 ("T=1 S-block %s received cmd=%d\n",
1978                       (tpdu[1] & 0x20)? "response": "request",
1979                       (tpdu[1] & 0x1f));
1980           if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
1981             { /* Wait time extension request. */
1982               unsigned char bwi = tpdu[3];
1983               msg = send_buffer;
1984               tpdu = msg+10;
1985               /* NAD: DAD=1, SAD=0 */
1986               tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
1987               tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
1988               tpdu[2] = 1;
1989               tpdu[3] = bwi;
1990               tpdulen = 4;
1991               edc = compute_edc (tpdu, tpdulen, use_crc);
1992               if (use_crc)
1993                 tpdu[tpdulen++] = (edc >> 8);
1994               tpdu[tpdulen++] = edc;
1995               DEBUGOUT_1 ("T=1 waittime extension of bwi=%d\n", bwi);
1996             }
1997           else
1998             return CCID_DRIVER_ERR_CARD_IO_ERROR;
1999         }
2000     } /* end T=1 protocol loop. */
2001
2002   return 0;
2003 }
2004
2005
2006 /* Send the CCID Secure command to the reader.  APDU_BUF should
2007    contain the APDU template.  PIN_MODE defines how the pin gets
2008    formatted:
2009    
2010      1 := The PIN is ASCII encoded and of variable length.  The
2011           length of the PIN entered will be put into Lc by the reader.
2012           The APDU should me made up of 4 bytes without Lc.
2013
2014    PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
2015    may be used t enable reasonable defaults.  PIN_PADLEN should be 0.
2016    
2017    When called with RESP and NRESP set to NULL, the function will
2018    merely check whether the reader supports the secure command for the
2019    given APDU and PIN_MODE. */
2020 int
2021 ccid_transceive_secure (ccid_driver_t handle,
2022                         const unsigned char *apdu_buf, size_t apdu_buflen,
2023                         int pin_mode, int pinlen_min, int pinlen_max,
2024                         int pin_padlen, 
2025                         unsigned char *resp, size_t maxresplen, size_t *nresp)
2026 {
2027   int rc;
2028   unsigned char send_buffer[10+259], recv_buffer[10+259];
2029   unsigned char *msg, *tpdu, *p;
2030   size_t msglen, tpdulen, n;
2031   unsigned char seqno;
2032   int i;
2033   size_t dummy_nresp;
2034   int testmode;
2035
2036   testmode = !resp && !nresp;
2037
2038   if (!nresp)
2039     nresp = &dummy_nresp;
2040   *nresp = 0;
2041
2042   if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
2043     ;
2044   else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
2045     return CCID_DRIVER_ERR_NOT_SUPPORTED; /* Not yet by our code. */
2046   else
2047     return CCID_DRIVER_ERR_NO_KEYPAD;
2048     
2049   if (pin_mode != 1)
2050     return CCID_DRIVER_ERR_NOT_SUPPORTED;
2051
2052   if (pin_padlen != 0)
2053     return CCID_DRIVER_ERR_NOT_SUPPORTED;
2054
2055   if (!pinlen_min)
2056     pinlen_min = 1;
2057   if (!pinlen_max)
2058     pinlen_max = 25;
2059
2060   /* Note that the 25 is the maximum value the SPR532 allows.  */
2061   if (pinlen_min < 1 || pinlen_min > 25
2062       || pinlen_max < 1 || pinlen_max > 25 
2063       || pinlen_min > pinlen_max)
2064     return CCID_DRIVER_ERR_INV_VALUE;
2065
2066   /* We have only tested this with an SCM reader so better don't risk
2067      anything and do not allow the use with other readers. */
2068   if (handle->id_vendor != VENDOR_SCM)
2069     return CCID_DRIVER_ERR_NOT_SUPPORTED;
2070
2071   if (testmode)
2072     return 0; /* Success */
2073     
2074   msg = send_buffer;
2075   if (handle->id_vendor == VENDOR_SCM)
2076     {
2077       DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
2078       rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
2079                             NULL, 0, NULL);
2080       if (rc)
2081         return rc;
2082     }
2083
2084   msg[0] = PC_to_RDR_Secure;
2085   msg[5] = 0; /* slot */
2086   msg[6] = seqno = handle->seqno++;
2087   msg[7] = 4; /* bBWI */
2088   msg[8] = 0; /* RFU */
2089   msg[9] = 0; /* RFU */
2090   msg[10] = 0; /* Perform PIN verification. */
2091   msg[11] = 0; /* Timeout in seconds. */
2092   msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2093   if (handle->id_vendor == VENDOR_SCM)
2094     {
2095       /* For the SPR532 the next 2 bytes need to be zero.  We do this
2096          for all SCM product. Kudos to Martin Paljak for this
2097          hint.  */
2098       msg[13] = msg[14] = 0;
2099     }
2100   else
2101     {
2102       msg[13] = 0x00; /* bmPINBlockString:
2103                          0 bits of pin length to insert. 
2104                          0 bytes of PIN block size.  */
2105       msg[14] = 0x00; /* bmPINLengthFormat:
2106                          Units are bytes, position is 0. */
2107     }
2108   msg[15] = pinlen_min;   /* wPINMaxExtraDigit-Minimum.  */
2109   msg[16] = pinlen_max;   /* wPINMaxExtraDigit-Maximum.  */
2110   msg[17] = 0x02; /* bEntryValidationCondition:
2111                      Validation key pressed */
2112   if (pinlen_min && pinlen_max && pinlen_min == pinlen_max)
2113     msg[17] |= 0x01; /* Max size reached.  */
2114   msg[18] = 0xff; /* bNumberMessage: Default. */
2115   msg[19] = 0x04; /* wLangId-High. */
2116   msg[20] = 0x09; /* wLangId-Low:  English FIXME: use the first entry. */
2117   msg[21] = 0;    /* bMsgIndex. */
2118   /* bTeoProlog follows: */
2119   msg[22] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2120   msg[23] = ((handle->t1_ns & 1) << 6); /* I-block */
2121   msg[24] = 4; /* apdulen.  */
2122   /* APDU follows:  */
2123   msg[25] = apdu_buf[0]; /* CLA */
2124   msg[26] = apdu_buf[1]; /* INS */
2125   msg[27] = apdu_buf[2]; /* P1 */
2126   msg[28] = apdu_buf[3]; /* P2 */
2127   msglen = 29;
2128   set_msg_len (msg, msglen - 10);
2129
2130   DEBUGOUT ("sending");
2131   for (i=0; i < msglen; i++)
2132     DEBUGOUT_CONT_1 (" %02X", msg[i]);
2133   DEBUGOUT_LF ();
2134   
2135   rc = bulk_out (handle, msg, msglen);
2136   if (rc)
2137     return rc;
2138   
2139   msg = recv_buffer;
2140   rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2141                 RDR_to_PC_DataBlock, seqno, 5000, 0);
2142   if (rc)
2143     return rc;
2144   
2145   tpdu = msg + 10;
2146   tpdulen = msglen - 10;
2147   
2148   if (tpdulen < 4) 
2149     {
2150       usb_clear_halt (handle->idev, handle->ep_bulk_in);
2151       return CCID_DRIVER_ERR_ABORTED; 
2152     }
2153   if (debug_level > 1)
2154     DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2155                 ((msg[11] & 0xc0) == 0x80)? 'R' :
2156                           (msg[11] & 0x80)? 'S' : 'I',
2157                 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
2158                 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2159                 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2160
2161   if (!(tpdu[1] & 0x80))
2162     { /* This is an I-block. */
2163       /* Last block sent was successful. */
2164       handle->t1_ns ^= 1;
2165
2166       if (!!(tpdu[1] & 0x40) != handle->t1_nr)
2167         { /* Reponse does not match our sequence number. */
2168           DEBUGOUT ("I-block with wrong seqno received\n");
2169           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2170         }
2171
2172       handle->t1_nr ^= 1;
2173
2174       p = tpdu + 3; /* Skip the prologue field. */
2175       n = tpdulen - 3 - 1; /* Strip the epilogue field. */
2176       /* fixme: verify the checksum. */
2177       if (resp)
2178         {
2179           if (n > maxresplen)
2180             {
2181               DEBUGOUT_2 ("provided buffer too short for received data "
2182                           "(%u/%u)\n",
2183                           (unsigned int)n, (unsigned int)maxresplen);
2184               return CCID_DRIVER_ERR_INV_VALUE;
2185             }
2186               
2187           memcpy (resp, p, n); 
2188           resp += n;
2189           *nresp += n;
2190           maxresplen -= n;
2191         }
2192           
2193       if (!(tpdu[1] & 0x20))
2194         return 0; /* No chaining requested - ready. */
2195       
2196       DEBUGOUT ("chaining requested but not supported for Secure operation\n");
2197       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2198     }
2199   else if ((tpdu[1] & 0xc0) == 0x80)
2200     { /* This is a R-block. */
2201       if ( (tpdu[1] & 0x0f)) 
2202         { /* Error: repeat last block */
2203           DEBUGOUT ("No retries supported for Secure operation\n");
2204           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2205         }
2206       else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
2207         { /* Reponse does not match our sequence number. */
2208           DEBUGOUT ("R-block with wrong seqno received on more bit\n");
2209           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2210         }
2211       else
2212         { /* Send next chunk. */
2213           DEBUGOUT ("chaining not supported on Secure operation\n");
2214           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2215         }
2216     }
2217   else 
2218     { /* This is a S-block. */
2219       DEBUGOUT_2 ("T=1 S-block %s received cmd=%d for Secure operation\n",
2220                   (tpdu[1] & 0x20)? "response": "request",
2221                   (tpdu[1] & 0x1f));
2222       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2223     } 
2224
2225   return 0;
2226 }
2227
2228
2229
2230
2231 #ifdef TEST
2232
2233
2234 static void
2235 print_error (int err)
2236 {
2237   const char *p;
2238   char buf[50];
2239
2240   switch (err)
2241     {
2242     case 0: p = "success";
2243     case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
2244     case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
2245     case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
2246     case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
2247     case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
2248     case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
2249     case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
2250     case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
2251     case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
2252     case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
2253     case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
2254     case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
2255     default: sprintf (buf, "0x%05x", err); p = buf; break;
2256     }
2257   fprintf (stderr, "operation failed: %s\n", p);
2258 }
2259
2260 static void
2261 print_data (const unsigned char *data, size_t length)
2262 {
2263   if (length >= 2)
2264     {
2265       fprintf (stderr, "operation status: %02X%02X\n",
2266                data[length-2], data[length-1]);
2267       length -= 2;
2268     }
2269   if (length)
2270     {
2271         fputs ("   returned data:", stderr);
2272         for (; length; length--, data++)
2273           fprintf (stderr, " %02X", *data);
2274         putc ('\n', stderr);
2275     }
2276 }
2277
2278 static void
2279 print_result (int rc, const unsigned char *data, size_t length)
2280 {
2281   if (rc)
2282     print_error (rc);
2283   else if (data)
2284     print_data (data, length);
2285 }
2286
2287 int
2288 main (int argc, char **argv)
2289 {
2290   int rc;
2291   ccid_driver_t ccid;
2292   unsigned int slotstat;
2293   unsigned char result[512];
2294   size_t resultlen;
2295   int no_pinpad = 0;
2296   int verify_123456 = 0;
2297   int did_verify = 0;
2298   int no_poll = 0;
2299
2300   if (argc)
2301     {
2302       argc--;
2303       argv++;
2304     }
2305
2306   while (argc)
2307     {
2308       if ( !strcmp (*argv, "--list"))
2309         {
2310           char *p;
2311           p = ccid_get_reader_list ();
2312           if (!p)
2313             return 1;
2314           fputs (p, stderr);
2315           free (p);
2316           return 0;
2317         }
2318       else if ( !strcmp (*argv, "--debug"))
2319         {
2320           ccid_set_debug_level (1);
2321           argc--; argv++;
2322         }
2323       else if ( !strcmp (*argv, "--no-poll"))
2324         {
2325           no_poll = 1;
2326           argc--; argv++;
2327         }
2328       else if ( !strcmp (*argv, "--no-pinpad"))
2329         {
2330           no_pinpad = 1;
2331           argc--; argv++;
2332         }
2333       else if ( !strcmp (*argv, "--verify-123456"))
2334         {
2335           verify_123456 = 1;
2336           argc--; argv++;
2337         }
2338       else
2339         break;
2340     }
2341
2342   rc = ccid_open_reader (&ccid, argc? *argv:NULL);
2343   if (rc)
2344     return 1;
2345
2346   if (!no_poll)
2347     ccid_poll (ccid);
2348   fputs ("getting ATR ...\n", stderr);
2349   rc = ccid_get_atr (ccid, NULL, 0, NULL);
2350   if (rc)
2351     {
2352       print_error (rc);
2353       return 1;
2354     }
2355
2356   if (!no_poll)
2357     ccid_poll (ccid);
2358   fputs ("getting slot status ...\n", stderr);
2359   rc = ccid_slot_status (ccid, &slotstat);
2360   if (rc)
2361     {
2362       print_error (rc);
2363       return 1;
2364     }
2365
2366   if (!no_poll)
2367     ccid_poll (ccid);
2368
2369   fputs ("selecting application OpenPGP ....\n", stderr);
2370   {
2371     static unsigned char apdu[] = {
2372       0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
2373     rc = ccid_transceive (ccid,
2374                           apdu, sizeof apdu,
2375                           result, sizeof result, &resultlen);
2376     print_result (rc, result, resultlen);
2377   }
2378   
2379
2380   if (!no_poll)
2381     ccid_poll (ccid);
2382
2383   fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
2384   {
2385     static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
2386     rc = ccid_transceive (ccid, apdu, sizeof apdu,
2387                           result, sizeof result, &resultlen);
2388     print_result (rc, result, resultlen);
2389   }
2390
2391   if (!no_pinpad)
2392     {
2393     }
2394
2395   if (!no_pinpad)
2396     {
2397       static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
2398
2399       
2400       if (ccid_transceive_secure (ccid,
2401                                   apdu, sizeof apdu,
2402                                   1, 0, 0, 0,
2403                                   NULL, 0, NULL))
2404         fputs ("can't verify using a PIN-Pad reader\n", stderr);
2405       else
2406         {
2407           fputs ("verifying CHV1 using the PINPad ....\n", stderr);
2408           
2409           rc = ccid_transceive_secure (ccid,
2410                                        apdu, sizeof apdu,
2411                                        1, 0, 0, 0,
2412                                        result, sizeof result, &resultlen);
2413           print_result (rc, result, resultlen);
2414           did_verify = 1;
2415         }
2416     }
2417   
2418   if (verify_123456 && !did_verify)
2419     {
2420       fputs ("verifying that CHV1 is 123456....\n", stderr);
2421       {
2422         static unsigned char apdu[] = {0, 0x20, 0, 0x81,
2423                                        6, '1','2','3','4','5','6'};
2424         rc = ccid_transceive (ccid, apdu, sizeof apdu,
2425                               result, sizeof result, &resultlen);
2426         print_result (rc, result, resultlen);
2427       }
2428     }
2429
2430   if (!rc)
2431     {
2432       fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
2433       {
2434         static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
2435         rc = ccid_transceive (ccid, apdu, sizeof apdu,
2436                               result, sizeof result, &resultlen);
2437         print_result (rc, result, resultlen);
2438       }
2439     }
2440
2441   ccid_close_reader (ccid);
2442
2443   return 0;
2444 }
2445
2446 /*
2447  * Local Variables:
2448  *  compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
2449  * End:
2450  */
2451 #endif /*TEST*/
2452 #endif /*HAVE_LIBUSB*/
2453
2454 #endif /* LIBRFID_FIRMWARE */