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