Imported Upstream version 2.0.26
[platform/upstream/gpg2.git] / scd / ccid-driver.c
1 /* ccid-driver.c - USB ChipCardInterfaceDevices driver
2  * Copyright (C) 2003, 2004, 2005, 2006, 2007
3  *               2008, 2009, 2013  Free Software Foundation, Inc.
4  * Written by Werner Koch.
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <http://www.gnu.org/licenses/>.
20  *
21  * ALTERNATIVELY, this file may be distributed under the terms of the
22  * following license, in which case the provisions of this license are
23  * required INSTEAD OF the GNU General Public License. If you wish to
24  * allow use of your version of this file only under the terms of the
25  * GNU General Public License, and not to allow others to use your
26  * version of this file under the terms of the following license,
27  * indicate your decision by deleting this paragraph and the license
28  * below.
29  *
30  * Redistribution and use in source and binary forms, with or without
31  * modification, are permitted provided that the following conditions
32  * are met:
33  * 1. Redistributions of source code must retain the above copyright
34  *    notice, and the entire permission notice in its entirety,
35  *    including the disclaimer of warranties.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 3. The name of the author may not be used to endorse or promote
40  *    products derived from this software without specific prior
41  *    written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
44  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53  * OF THE POSSIBILITY OF SUCH DAMAGE.
54  *
55  * $Date$
56  */
57
58
59 /* CCID (ChipCardInterfaceDevices) is a specification for accessing
60    smartcard via a reader connected to the USB.
61
62    This is a limited driver allowing to use some CCID drivers directly
63    without any other specila drivers. This is a fallback driver to be
64    used when nothing else works or the system should be kept minimal
65    for security reasons.  It makes use of the libusb library to gain
66    portable access to USB.
67
68    This driver has been tested with the SCM SCR335 and SPR532
69    smartcard readers and requires that a reader implements APDU or
70    TPDU level exchange and does fully automatic initialization.
71 */
72
73 #ifdef HAVE_CONFIG_H
74 # include <config.h>
75 #endif
76
77 #if defined(HAVE_LIBUSB) || defined(TEST)
78
79 #include <errno.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <assert.h>
84 #include <sys/types.h>
85 #include <sys/stat.h>
86 #include <fcntl.h>
87 #include <time.h>
88 #ifdef HAVE_PTH
89 # include <pth.h>
90 #endif /*HAVE_PTH*/
91
92 #include <usb.h>
93
94 #include "scdaemon.h"
95 #include "iso7816.h"
96 #include "ccid-driver.h"
97
98 #define DRVNAME "ccid-driver: "
99
100
101 /* Depending on how this source is used we either define our error
102    output to go to stderr or to the jnlib based logging functions.  We
103    use the latter when GNUPG_MAJOR_VERSION is defines or when both,
104    GNUPG_SCD_MAIN_HEADER and HAVE_JNLIB_LOGGING are defined.
105 */
106 #if defined(GNUPG_MAJOR_VERSION) \
107     || (defined(GNUPG_SCD_MAIN_HEADER) && defined(HAVE_JNLIB_LOGGING))
108
109 #if defined(GNUPG_SCD_MAIN_HEADER)
110 #  include GNUPG_SCD_MAIN_HEADER
111 #elif GNUPG_MAJOR_VERSION == 1 /* GnuPG Version is < 1.9. */
112 #  include "options.h"
113 #  include "util.h"
114 #  include "memory.h"
115 #  include "cardglue.h"
116 # else /* This is the modularized GnuPG 1.9 or later. */
117 #  include "scdaemon.h"
118 #endif
119
120
121 # define DEBUGOUT(t)         do { if (debug_level) \
122                                   log_debug (DRVNAME t); } while (0)
123 # define DEBUGOUT_1(t,a)     do { if (debug_level) \
124                                   log_debug (DRVNAME t,(a)); } while (0)
125 # define DEBUGOUT_2(t,a,b)   do { if (debug_level) \
126                                   log_debug (DRVNAME t,(a),(b)); } while (0)
127 # define DEBUGOUT_3(t,a,b,c) do { if (debug_level) \
128                                   log_debug (DRVNAME t,(a),(b),(c));} while (0)
129 # define DEBUGOUT_4(t,a,b,c,d) do { if (debug_level) \
130                               log_debug (DRVNAME t,(a),(b),(c),(d));} while (0)
131 # define DEBUGOUT_CONT(t)    do { if (debug_level) \
132                                   log_printf (t); } while (0)
133 # define DEBUGOUT_CONT_1(t,a)  do { if (debug_level) \
134                                   log_printf (t,(a)); } while (0)
135 # define DEBUGOUT_CONT_2(t,a,b)   do { if (debug_level) \
136                                   log_printf (t,(a),(b)); } while (0)
137 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
138                                   log_printf (t,(a),(b),(c)); } while (0)
139 # define DEBUGOUT_LF()       do { if (debug_level) \
140                                   log_printf ("\n"); } while (0)
141
142 #else /* Other usage of this source - don't use gnupg specifics. */
143
144 # define DEBUGOUT(t)          do { if (debug_level) \
145                      fprintf (stderr, DRVNAME t); } while (0)
146 # define DEBUGOUT_1(t,a)      do { if (debug_level) \
147                      fprintf (stderr, DRVNAME t, (a)); } while (0)
148 # define DEBUGOUT_2(t,a,b)    do { if (debug_level) \
149                      fprintf (stderr, DRVNAME t, (a), (b)); } while (0)
150 # define DEBUGOUT_3(t,a,b,c)  do { if (debug_level) \
151                      fprintf (stderr, DRVNAME t, (a), (b), (c)); } while (0)
152 # define DEBUGOUT_4(t,a,b,c,d)  do { if (debug_level) \
153                      fprintf (stderr, DRVNAME t, (a), (b), (c), (d));} while(0)
154 # define DEBUGOUT_CONT(t)     do { if (debug_level) \
155                      fprintf (stderr, t); } while (0)
156 # define DEBUGOUT_CONT_1(t,a) do { if (debug_level) \
157                      fprintf (stderr, t, (a)); } while (0)
158 # define DEBUGOUT_CONT_2(t,a,b) do { if (debug_level) \
159                      fprintf (stderr, t, (a), (b)); } while (0)
160 # define DEBUGOUT_CONT_3(t,a,b,c) do { if (debug_level) \
161                      fprintf (stderr, t, (a), (b), (c)); } while (0)
162 # define DEBUGOUT_LF()        do { if (debug_level) \
163                      putc ('\n', stderr); } while (0)
164
165 #endif /* This source not used by scdaemon. */
166
167
168 #ifndef EAGAIN
169 #define EAGAIN  EWOULDBLOCK
170 #endif
171
172
173
174 enum {
175   RDR_to_PC_NotifySlotChange= 0x50,
176   RDR_to_PC_HardwareError   = 0x51,
177
178   PC_to_RDR_SetParameters   = 0x61,
179   PC_to_RDR_IccPowerOn      = 0x62,
180   PC_to_RDR_IccPowerOff     = 0x63,
181   PC_to_RDR_GetSlotStatus   = 0x65,
182   PC_to_RDR_Secure          = 0x69,
183   PC_to_RDR_T0APDU          = 0x6a,
184   PC_to_RDR_Escape          = 0x6b,
185   PC_to_RDR_GetParameters   = 0x6c,
186   PC_to_RDR_ResetParameters = 0x6d,
187   PC_to_RDR_IccClock        = 0x6e,
188   PC_to_RDR_XfrBlock        = 0x6f,
189   PC_to_RDR_Mechanical      = 0x71,
190   PC_to_RDR_Abort           = 0x72,
191   PC_to_RDR_SetDataRate     = 0x73,
192
193   RDR_to_PC_DataBlock       = 0x80,
194   RDR_to_PC_SlotStatus      = 0x81,
195   RDR_to_PC_Parameters      = 0x82,
196   RDR_to_PC_Escape          = 0x83,
197   RDR_to_PC_DataRate        = 0x84
198 };
199
200
201 /* Two macro to detect whether a CCID command has failed and to get
202    the error code.  These macros assume that we can access the
203    mandatory first 10 bytes of a CCID message in BUF. */
204 #define CCID_COMMAND_FAILED(buf) ((buf)[7] & 0x40)
205 #define CCID_ERROR_CODE(buf)     (((unsigned char *)(buf))[8])
206
207
208 /* We need to know the vendor to do some hacks. */
209 enum {
210   VENDOR_CHERRY = 0x046a,
211   VENDOR_SCM    = 0x04e6,
212   VENDOR_OMNIKEY= 0x076b,
213   VENDOR_GEMPC  = 0x08e6,
214   VENDOR_VEGA   = 0x0982,
215   VENDOR_REINER = 0x0c4b,
216   VENDOR_KAAN   = 0x0d46,
217   VENDOR_VASCO  = 0x1a44,
218   VENDOR_FSIJ   = 0x234b,
219 };
220
221 /* Some product ids.  */
222 #define SCM_SCR331      0xe001
223 #define SCM_SCR331DI    0x5111
224 #define SCM_SCR335      0x5115
225 #define SCM_SCR3320     0x5117
226 #define SCM_SPR532      0xe003
227 #define CHERRY_ST2000   0x003e
228 #define VASCO_920       0x0920
229 #define GEMPC_PINPAD    0x3478
230 #define GEMPC_CT30      0x3437
231 #define VEGA_ALPHA      0x0008
232 #define CYBERJACK_GO    0x0504
233
234 /* A list and a table with special transport descriptions. */
235 enum {
236   TRANSPORT_USB    = 0, /* Standard USB transport. */
237   TRANSPORT_CM4040 = 1  /* As used by the Cardman 4040. */
238 };
239
240 static struct
241 {
242   char *name;  /* Device name. */
243   int  type;
244
245 } transports[] = {
246   { "/dev/cmx0", TRANSPORT_CM4040 },
247   { "/dev/cmx1", TRANSPORT_CM4040 },
248   { NULL },
249 };
250
251
252 /* Store information on the driver's state.  A pointer to such a
253    structure is used as handle for most functions. */
254 struct ccid_driver_s
255 {
256   usb_dev_handle *idev;
257   char *rid;
258   int dev_fd;  /* -1 for USB transport or file descriptor of the
259                    transport device. */
260   unsigned short id_vendor;
261   unsigned short id_product;
262   unsigned short bcd_device;
263   int ifc_no;
264   int ep_bulk_out;
265   int ep_bulk_in;
266   int ep_intr;
267   int seqno;
268   unsigned char t1_ns;
269   unsigned char t1_nr;
270   unsigned char nonnull_nad;
271   int max_ifsd;
272   int ifsd;
273   int ifsc;
274   unsigned char apdu_level:2;     /* Reader supports short APDU level
275                                      exchange.  With a value of 2 short
276                                      and extended level is supported.*/
277   unsigned int auto_voltage:1;
278   unsigned int auto_param:1;
279   unsigned int auto_pps:1;
280   unsigned int auto_ifsd:1;
281   unsigned int powered_off:1;
282   unsigned int has_pinpad:2;
283   unsigned int enodev_seen:1;
284
285   time_t last_progress; /* Last time we sent progress line.  */
286
287   /* The progress callback and its first arg as supplied to
288      ccid_set_progress_cb.  */
289   void (*progress_cb)(void *, const char *, int, int, int);
290   void *progress_cb_arg;
291 };
292
293
294 static int initialized_usb; /* Tracks whether USB has been initialized. */
295 static int debug_level;     /* Flag to control the debug output.
296                                0 = No debugging
297                                1 = USB I/O info
298                                2 = Level 1 + T=1 protocol tracing
299                                3 = Level 2 + USB/I/O tracing of SlotStatus.
300                               */
301
302
303 static unsigned int compute_edc (const unsigned char *data, size_t datalen,
304                                  int use_crc);
305 static int bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
306                      int no_debug);
307 static int bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
308                     size_t *nread, int expected_type, int seqno, int timeout,
309                     int no_debug);
310 static int abort_cmd (ccid_driver_t handle, int seqno);
311 static int send_escape_cmd (ccid_driver_t handle, const unsigned char *data,
312                             size_t datalen, unsigned char *result,
313                             size_t resultmax, size_t *resultlen);
314
315 /* Convert a little endian stored 4 byte value into an unsigned
316    integer. */
317 static unsigned int
318 convert_le_u32 (const unsigned char *buf)
319 {
320   return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
321 }
322
323
324 /* Convert a little endian stored 2 byte value into an unsigned
325    integer. */
326 static unsigned int
327 convert_le_u16 (const unsigned char *buf)
328 {
329   return buf[0] | (buf[1] << 8);
330 }
331
332 static void
333 set_msg_len (unsigned char *msg, unsigned int length)
334 {
335   msg[1] = length;
336   msg[2] = length >> 8;
337   msg[3] = length >> 16;
338   msg[4] = length >> 24;
339 }
340
341
342 static void
343 my_sleep (int seconds)
344 {
345 #ifdef HAVE_PTH
346   /* With Pth we also call the standard sleep(0) so that the process
347      may give up its timeslot.  */
348   if (!seconds)
349     {
350 # ifdef HAVE_W32_SYSTEM
351       Sleep (0);
352 # else
353       sleep (0);
354 # endif
355     }
356   pth_sleep (seconds);
357 #else
358 # ifdef HAVE_W32_SYSTEM
359   Sleep (seconds*1000);
360 # else
361   sleep (seconds);
362 # endif
363 #endif
364 }
365
366 static void
367 print_progress (ccid_driver_t handle)
368 {
369   time_t ct = time (NULL);
370
371   /* We don't want to print progress lines too often. */
372   if (ct == handle->last_progress)
373     return;
374
375   if (handle->progress_cb)
376     handle->progress_cb (handle->progress_cb_arg, "card_busy", 'w', 0, 0);
377
378   handle->last_progress = ct;
379 }
380
381
382
383 /* Pint an error message for a failed CCID command including a textual
384    error code.  MSG shall be the CCID message at a minimum of 10 bytes. */
385 static void
386 print_command_failed (const unsigned char *msg)
387 {
388   const char *t;
389   char buffer[100];
390   int ec;
391
392   if (!debug_level)
393     return;
394
395   ec = CCID_ERROR_CODE (msg);
396   switch (ec)
397     {
398     case 0x00: t = "Command not supported"; break;
399
400     case 0xE0: t = "Slot busy"; break;
401     case 0xEF: t = "PIN cancelled"; break;
402     case 0xF0: t = "PIN timeout"; break;
403
404     case 0xF2: t = "Automatic sequence ongoing"; break;
405     case 0xF3: t = "Deactivated Protocol"; break;
406     case 0xF4: t = "Procedure byte conflict"; break;
407     case 0xF5: t = "ICC class not supported"; break;
408     case 0xF6: t = "ICC protocol not supported"; break;
409     case 0xF7: t = "Bad checksum in ATR"; break;
410     case 0xF8: t = "Bad TS in ATR"; break;
411
412     case 0xFB: t = "An all inclusive hardware error occurred"; break;
413     case 0xFC: t = "Overrun error while talking to the ICC"; break;
414     case 0xFD: t = "Parity error while talking to the ICC"; break;
415     case 0xFE: t = "CCID timed out while talking to the ICC"; break;
416     case 0xFF: t = "Host aborted the current activity"; break;
417
418     default:
419       if (ec > 0 && ec < 128)
420         sprintf (buffer, "Parameter error at offset %d", ec);
421       else
422         sprintf (buffer, "Error code %02X", ec);
423       t = buffer;
424       break;
425     }
426   DEBUGOUT_1 ("CCID command failed: %s\n", t);
427 }
428
429
430 static void
431 print_pr_data (const unsigned char *data, size_t datalen, size_t off)
432 {
433   int any = 0;
434
435   for (; off < datalen; off++)
436     {
437       if (!any || !(off % 16))
438         {
439           if (any)
440             DEBUGOUT_LF ();
441           DEBUGOUT_1 ("  [%04lu] ", (unsigned long) off);
442         }
443       DEBUGOUT_CONT_1 (" %02X", data[off]);
444       any = 1;
445     }
446   if (any && (off % 16))
447     DEBUGOUT_LF ();
448 }
449
450
451 static void
452 print_p2r_header (const char *name, const unsigned char *msg, size_t msglen)
453 {
454   DEBUGOUT_1 ("%s:\n", name);
455   if (msglen < 7)
456     return;
457   DEBUGOUT_1 ("  dwLength ..........: %u\n", convert_le_u32 (msg+1));
458   DEBUGOUT_1 ("  bSlot .............: %u\n", msg[5]);
459   DEBUGOUT_1 ("  bSeq ..............: %u\n", msg[6]);
460 }
461
462
463 static void
464 print_p2r_iccpoweron (const unsigned char *msg, size_t msglen)
465 {
466   print_p2r_header ("PC_to_RDR_IccPowerOn", msg, msglen);
467   if (msglen < 10)
468     return;
469   DEBUGOUT_2 ("  bPowerSelect ......: 0x%02x (%s)\n", msg[7],
470               msg[7] == 0? "auto":
471               msg[7] == 1? "5.0 V":
472               msg[7] == 2? "3.0 V":
473               msg[7] == 3? "1.8 V":"");
474   print_pr_data (msg, msglen, 8);
475 }
476
477
478 static void
479 print_p2r_iccpoweroff (const unsigned char *msg, size_t msglen)
480 {
481   print_p2r_header ("PC_to_RDR_IccPowerOff", msg, msglen);
482   print_pr_data (msg, msglen, 7);
483 }
484
485
486 static void
487 print_p2r_getslotstatus (const unsigned char *msg, size_t msglen)
488 {
489   print_p2r_header ("PC_to_RDR_GetSlotStatus", msg, msglen);
490   print_pr_data (msg, msglen, 7);
491 }
492
493
494 static void
495 print_p2r_xfrblock (const unsigned char *msg, size_t msglen)
496 {
497   unsigned int val;
498
499   print_p2r_header ("PC_to_RDR_XfrBlock", msg, msglen);
500   if (msglen < 10)
501     return;
502   DEBUGOUT_1 ("  bBWI ..............: 0x%02x\n", msg[7]);
503   val = convert_le_u16 (msg+8);
504   DEBUGOUT_2 ("  wLevelParameter ...: 0x%04x%s\n", val,
505               val == 1? " (continued)":
506               val == 2? " (continues+ends)":
507               val == 3? " (continues+continued)":
508               val == 16? " (DataBlock-expected)":"");
509   print_pr_data (msg, msglen, 10);
510 }
511
512
513 static void
514 print_p2r_getparameters (const unsigned char *msg, size_t msglen)
515 {
516   print_p2r_header ("PC_to_RDR_GetParameters", msg, msglen);
517   print_pr_data (msg, msglen, 7);
518 }
519
520
521 static void
522 print_p2r_resetparameters (const unsigned char *msg, size_t msglen)
523 {
524   print_p2r_header ("PC_to_RDR_ResetParameters", msg, msglen);
525   print_pr_data (msg, msglen, 7);
526 }
527
528
529 static void
530 print_p2r_setparameters (const unsigned char *msg, size_t msglen)
531 {
532   print_p2r_header ("PC_to_RDR_SetParameters", msg, msglen);
533   if (msglen < 10)
534     return;
535   DEBUGOUT_1 ("  bProtocolNum ......: 0x%02x\n", msg[7]);
536   print_pr_data (msg, msglen, 8);
537 }
538
539
540 static void
541 print_p2r_escape (const unsigned char *msg, size_t msglen)
542 {
543   print_p2r_header ("PC_to_RDR_Escape", msg, msglen);
544   print_pr_data (msg, msglen, 7);
545 }
546
547
548 static void
549 print_p2r_iccclock (const unsigned char *msg, size_t msglen)
550 {
551   print_p2r_header ("PC_to_RDR_IccClock", msg, msglen);
552   if (msglen < 10)
553     return;
554   DEBUGOUT_1 ("  bClockCommand .....: 0x%02x\n", msg[7]);
555   print_pr_data (msg, msglen, 8);
556 }
557
558
559 static void
560 print_p2r_to0apdu (const unsigned char *msg, size_t msglen)
561 {
562   print_p2r_header ("PC_to_RDR_T0APDU", msg, msglen);
563   if (msglen < 10)
564     return;
565   DEBUGOUT_1 ("  bmChanges .........: 0x%02x\n", msg[7]);
566   DEBUGOUT_1 ("  bClassGetResponse .: 0x%02x\n", msg[8]);
567   DEBUGOUT_1 ("  bClassEnvelope ....: 0x%02x\n", msg[9]);
568   print_pr_data (msg, msglen, 10);
569 }
570
571
572 static void
573 print_p2r_secure (const unsigned char *msg, size_t msglen)
574 {
575   unsigned int val;
576
577   print_p2r_header ("PC_to_RDR_Secure", msg, msglen);
578   if (msglen < 10)
579     return;
580   DEBUGOUT_1 ("  bBMI ..............: 0x%02x\n", msg[7]);
581   val = convert_le_u16 (msg+8);
582   DEBUGOUT_2 ("  wLevelParameter ...: 0x%04x%s\n", val,
583               val == 1? " (continued)":
584               val == 2? " (continues+ends)":
585               val == 3? " (continues+continued)":
586               val == 16? " (DataBlock-expected)":"");
587   print_pr_data (msg, msglen, 10);
588 }
589
590
591 static void
592 print_p2r_mechanical (const unsigned char *msg, size_t msglen)
593 {
594   print_p2r_header ("PC_to_RDR_Mechanical", msg, msglen);
595   if (msglen < 10)
596     return;
597   DEBUGOUT_1 ("  bFunction .........: 0x%02x\n", msg[7]);
598   print_pr_data (msg, msglen, 8);
599 }
600
601
602 static void
603 print_p2r_abort (const unsigned char *msg, size_t msglen)
604 {
605   print_p2r_header ("PC_to_RDR_Abort", msg, msglen);
606   print_pr_data (msg, msglen, 7);
607 }
608
609
610 static void
611 print_p2r_setdatarate (const unsigned char *msg, size_t msglen)
612 {
613   print_p2r_header ("PC_to_RDR_SetDataRate", msg, msglen);
614   if (msglen < 10)
615     return;
616   print_pr_data (msg, msglen, 7);
617 }
618
619
620 static void
621 print_p2r_unknown (const unsigned char *msg, size_t msglen)
622 {
623   print_p2r_header ("Unknown PC_to_RDR command", msg, msglen);
624   if (msglen < 10)
625     return;
626   print_pr_data (msg, msglen, 0);
627 }
628
629
630 static void
631 print_r2p_header (const char *name, const unsigned char *msg, size_t msglen)
632 {
633   DEBUGOUT_1 ("%s:\n", name);
634   if (msglen < 9)
635     return;
636   DEBUGOUT_1 ("  dwLength ..........: %u\n", convert_le_u32 (msg+1));
637   DEBUGOUT_1 ("  bSlot .............: %u\n", msg[5]);
638   DEBUGOUT_1 ("  bSeq ..............: %u\n", msg[6]);
639   DEBUGOUT_1 ("  bStatus ...........: %u\n", msg[7]);
640   if (msg[8])
641     DEBUGOUT_1 ("  bError ............: %u\n", msg[8]);
642 }
643
644
645 static void
646 print_r2p_datablock (const unsigned char *msg, size_t msglen)
647 {
648   print_r2p_header ("RDR_to_PC_DataBlock", msg, msglen);
649   if (msglen < 10)
650     return;
651   if (msg[9])
652     DEBUGOUT_2 ("  bChainParameter ...: 0x%02x%s\n", msg[9],
653                 msg[9] == 1? " (continued)":
654                 msg[9] == 2? " (continues+ends)":
655                 msg[9] == 3? " (continues+continued)":
656                 msg[9] == 16? " (XferBlock-expected)":"");
657   print_pr_data (msg, msglen, 10);
658 }
659
660
661 static void
662 print_r2p_slotstatus (const unsigned char *msg, size_t msglen)
663 {
664   print_r2p_header ("RDR_to_PC_SlotStatus", msg, msglen);
665   if (msglen < 10)
666     return;
667   DEBUGOUT_2 ("  bClockStatus ......: 0x%02x%s\n", msg[9],
668               msg[9] == 0? " (running)":
669               msg[9] == 1? " (stopped-L)":
670               msg[9] == 2? " (stopped-H)":
671               msg[9] == 3? " (stopped)":"");
672   print_pr_data (msg, msglen, 10);
673 }
674
675
676 static void
677 print_r2p_parameters (const unsigned char *msg, size_t msglen)
678 {
679   print_r2p_header ("RDR_to_PC_Parameters", msg, msglen);
680   if (msglen < 10)
681     return;
682
683   DEBUGOUT_1 ("  protocol ..........: T=%d\n", msg[9]);
684   if (msglen == 17 && msg[9] == 1)
685     {
686       /* Protocol T=1.  */
687       DEBUGOUT_1 ("  bmFindexDindex ....: %02X\n", msg[10]);
688       DEBUGOUT_1 ("  bmTCCKST1 .........: %02X\n", msg[11]);
689       DEBUGOUT_1 ("  bGuardTimeT1 ......: %02X\n", msg[12]);
690       DEBUGOUT_1 ("  bmWaitingIntegersT1: %02X\n", msg[13]);
691       DEBUGOUT_1 ("  bClockStop ........: %02X\n", msg[14]);
692       DEBUGOUT_1 ("  bIFSC .............: %d\n", msg[15]);
693       DEBUGOUT_1 ("  bNadValue .........: %d\n", msg[16]);
694     }
695   else
696     print_pr_data (msg, msglen, 10);
697 }
698
699
700 static void
701 print_r2p_escape (const unsigned char *msg, size_t msglen)
702 {
703   print_r2p_header ("RDR_to_PC_Escape", msg, msglen);
704   if (msglen < 10)
705     return;
706   DEBUGOUT_1 ("  buffer[9] .........: %02X\n", msg[9]);
707   print_pr_data (msg, msglen, 10);
708 }
709
710
711 static void
712 print_r2p_datarate (const unsigned char *msg, size_t msglen)
713 {
714   print_r2p_header ("RDR_to_PC_DataRate", msg, msglen);
715   if (msglen < 10)
716     return;
717   if (msglen >= 18)
718     {
719       DEBUGOUT_1 ("  dwClockFrequency ..: %u\n", convert_le_u32 (msg+10));
720       DEBUGOUT_1 ("  dwDataRate ..... ..: %u\n", convert_le_u32 (msg+14));
721       print_pr_data (msg, msglen, 18);
722     }
723   else
724     print_pr_data (msg, msglen, 10);
725 }
726
727
728 static void
729 print_r2p_unknown (const unsigned char *msg, size_t msglen)
730 {
731   print_r2p_header ("Unknown RDR_to_PC command", msg, msglen);
732   if (msglen < 10)
733     return;
734   DEBUGOUT_1 ("  bMessageType ......: %02X\n", msg[0]);
735   DEBUGOUT_1 ("  buffer[9] .........: %02X\n", msg[9]);
736   print_pr_data (msg, msglen, 10);
737 }
738
739
740 /* Given a handle used for special transport prepare it for use.  In
741    particular setup all information in way that resembles what
742    parse_cccid_descriptor does. */
743 static void
744 prepare_special_transport (ccid_driver_t handle)
745 {
746   assert (!handle->id_vendor);
747
748   handle->nonnull_nad = 0;
749   handle->auto_ifsd = 0;
750   handle->max_ifsd = 32;
751   handle->ifsd = 0;
752   handle->has_pinpad = 0;
753   handle->apdu_level = 0;
754   switch (handle->id_product)
755     {
756     case TRANSPORT_CM4040:
757       DEBUGOUT ("setting up transport for CardMan 4040\n");
758       handle->apdu_level = 1;
759       break;
760
761     default: assert (!"transport not defined");
762     }
763 }
764
765 /* Parse a CCID descriptor, optionally print all available features
766    and test whether this reader is usable by this driver.  Returns 0
767    if it is usable.
768
769    Note, that this code is based on the one in lsusb.c of the
770    usb-utils package, I wrote on 2003-09-01. -wk. */
771 static int
772 parse_ccid_descriptor (ccid_driver_t handle,
773                        const unsigned char *buf, size_t buflen)
774 {
775   unsigned int i;
776   unsigned int us;
777   int have_t1 = 0, have_tpdu=0;
778
779
780   handle->nonnull_nad = 0;
781   handle->auto_ifsd = 0;
782   handle->max_ifsd = 32;
783   handle->ifsd = 0;
784   handle->has_pinpad = 0;
785   handle->apdu_level = 0;
786   handle->auto_voltage = 0;
787   handle->auto_param = 0;
788   handle->auto_pps = 0;
789   DEBUGOUT_3 ("idVendor: %04X  idProduct: %04X  bcdDevice: %04X\n",
790               handle->id_vendor, handle->id_product, handle->bcd_device);
791   if (buflen < 54 || buf[0] < 54)
792     {
793       DEBUGOUT ("CCID device descriptor is too short\n");
794       return -1;
795     }
796
797   DEBUGOUT   ("ChipCard Interface Descriptor:\n");
798   DEBUGOUT_1 ("  bLength             %5u\n", buf[0]);
799   DEBUGOUT_1 ("  bDescriptorType     %5u\n", buf[1]);
800   DEBUGOUT_2 ("  bcdCCID             %2x.%02x", buf[3], buf[2]);
801     if (buf[3] != 1 || buf[2] != 0)
802       DEBUGOUT_CONT("  (Warning: Only accurate for version 1.0)");
803   DEBUGOUT_LF ();
804
805   DEBUGOUT_1 ("  nMaxSlotIndex       %5u\n", buf[4]);
806   DEBUGOUT_2 ("  bVoltageSupport     %5u  %s\n",
807               buf[5], (buf[5] == 1? "5.0V" : buf[5] == 2? "3.0V"
808                        : buf[5] == 3? "1.8V":"?"));
809
810   us = convert_le_u32 (buf+6);
811   DEBUGOUT_1 ("  dwProtocols         %5u ", us);
812   if ((us & 1))
813     DEBUGOUT_CONT (" T=0");
814   if ((us & 2))
815     {
816       DEBUGOUT_CONT (" T=1");
817       have_t1 = 1;
818     }
819   if ((us & ~3))
820     DEBUGOUT_CONT (" (Invalid values detected)");
821   DEBUGOUT_LF ();
822
823   us = convert_le_u32(buf+10);
824   DEBUGOUT_1 ("  dwDefaultClock      %5u\n", us);
825   us = convert_le_u32(buf+14);
826   DEBUGOUT_1 ("  dwMaxiumumClock     %5u\n", us);
827   DEBUGOUT_1 ("  bNumClockSupported  %5u\n", buf[18]);
828   us = convert_le_u32(buf+19);
829   DEBUGOUT_1 ("  dwDataRate        %7u bps\n", us);
830   us = convert_le_u32(buf+23);
831   DEBUGOUT_1 ("  dwMaxDataRate     %7u bps\n", us);
832   DEBUGOUT_1 ("  bNumDataRatesSupp.  %5u\n", buf[27]);
833
834   us = convert_le_u32(buf+28);
835   DEBUGOUT_1 ("  dwMaxIFSD           %5u\n", us);
836   handle->max_ifsd = us;
837
838   us = convert_le_u32(buf+32);
839   DEBUGOUT_1 ("  dwSyncProtocols  %08X ", us);
840   if ((us&1))
841     DEBUGOUT_CONT ( " 2-wire");
842   if ((us&2))
843     DEBUGOUT_CONT ( " 3-wire");
844   if ((us&4))
845     DEBUGOUT_CONT ( " I2C");
846   DEBUGOUT_LF ();
847
848   us = convert_le_u32(buf+36);
849   DEBUGOUT_1 ("  dwMechanical     %08X ", us);
850   if ((us & 1))
851     DEBUGOUT_CONT (" accept");
852   if ((us & 2))
853     DEBUGOUT_CONT (" eject");
854   if ((us & 4))
855     DEBUGOUT_CONT (" capture");
856   if ((us & 8))
857     DEBUGOUT_CONT (" lock");
858   DEBUGOUT_LF ();
859
860   us = convert_le_u32(buf+40);
861   DEBUGOUT_1 ("  dwFeatures       %08X\n", us);
862   if ((us & 0x0002))
863     {
864       DEBUGOUT ("    Auto configuration based on ATR (assumes auto voltage)\n");
865       handle->auto_voltage = 1;
866     }
867   if ((us & 0x0004))
868     DEBUGOUT ("    Auto activation on insert\n");
869   if ((us & 0x0008))
870     {
871       DEBUGOUT ("    Auto voltage selection\n");
872       handle->auto_voltage = 1;
873     }
874   if ((us & 0x0010))
875     DEBUGOUT ("    Auto clock change\n");
876   if ((us & 0x0020))
877     DEBUGOUT ("    Auto baud rate change\n");
878   if ((us & 0x0040))
879     {
880       DEBUGOUT ("    Auto parameter negotiation made by CCID\n");
881       handle->auto_param = 1;
882     }
883   else if ((us & 0x0080))
884     {
885       DEBUGOUT ("    Auto PPS made by CCID\n");
886       handle->auto_pps = 1;
887     }
888   if ((us & (0x0040 | 0x0080)) == (0x0040 | 0x0080))
889     DEBUGOUT ("    WARNING: conflicting negotiation features\n");
890
891   if ((us & 0x0100))
892     DEBUGOUT ("    CCID can set ICC in clock stop mode\n");
893   if ((us & 0x0200))
894     {
895       DEBUGOUT ("    NAD value other than 0x00 accepted\n");
896       handle->nonnull_nad = 1;
897     }
898   if ((us & 0x0400))
899     {
900       DEBUGOUT ("    Auto IFSD exchange\n");
901       handle->auto_ifsd = 1;
902     }
903
904   if ((us & 0x00010000))
905     {
906       DEBUGOUT ("    TPDU level exchange\n");
907       have_tpdu = 1;
908     }
909   else if ((us & 0x00020000))
910     {
911       DEBUGOUT ("    Short APDU level exchange\n");
912       handle->apdu_level = 1;
913     }
914   else if ((us & 0x00040000))
915     {
916       DEBUGOUT ("    Short and extended APDU level exchange\n");
917       handle->apdu_level = 2;
918     }
919   else if ((us & 0x00070000))
920     DEBUGOUT ("    WARNING: conflicting exchange levels\n");
921
922   us = convert_le_u32(buf+44);
923   DEBUGOUT_1 ("  dwMaxCCIDMsgLen     %5u\n", us);
924
925   DEBUGOUT (  "  bClassGetResponse    ");
926   if (buf[48] == 0xff)
927     DEBUGOUT_CONT ("echo\n");
928   else
929     DEBUGOUT_CONT_1 ("  %02X\n", buf[48]);
930
931   DEBUGOUT (  "  bClassEnvelope       ");
932   if (buf[49] == 0xff)
933     DEBUGOUT_CONT ("echo\n");
934   else
935     DEBUGOUT_CONT_1 ("  %02X\n", buf[48]);
936
937   DEBUGOUT (  "  wlcdLayout           ");
938   if (!buf[50] && !buf[51])
939     DEBUGOUT_CONT ("none\n");
940   else
941     DEBUGOUT_CONT_2 ("%u cols %u lines\n", buf[50], buf[51]);
942
943   DEBUGOUT_1 ("  bPINSupport         %5u ", buf[52]);
944   if ((buf[52] & 1))
945     {
946       DEBUGOUT_CONT ( " verification");
947       handle->has_pinpad |= 1;
948     }
949   if ((buf[52] & 2))
950     {
951       DEBUGOUT_CONT ( " modification");
952       handle->has_pinpad |= 2;
953     }
954   DEBUGOUT_LF ();
955
956   DEBUGOUT_1 ("  bMaxCCIDBusySlots   %5u\n", buf[53]);
957
958   if (buf[0] > 54) {
959     DEBUGOUT ("  junk             ");
960     for (i=54; i < buf[0]-54; i++)
961       DEBUGOUT_CONT_1 (" %02X", buf[i]);
962     DEBUGOUT_LF ();
963   }
964
965   if (!have_t1 || !(have_tpdu  || handle->apdu_level))
966     {
967       DEBUGOUT ("this drivers requires that the reader supports T=1, "
968                 "TPDU or APDU level exchange - this is not available\n");
969       return -1;
970     }
971
972
973   /* SCM drivers get stuck in their internal USB stack if they try to
974      send a frame of n*wMaxPacketSize back to us.  Given that
975      wMaxPacketSize is 64 for these readers we set the IFSD to a value
976      lower than that:
977         64 - 10 CCID header -  4 T1frame - 2 reserved = 48
978      Product Ids:
979          0xe001 - SCR 331
980          0x5111 - SCR 331-DI
981          0x5115 - SCR 335
982          0xe003 - SPR 532
983      The
984          0x5117 - SCR 3320 USB ID-000 reader
985      seems to be very slow but enabling this workaround boosts the
986      performance to a a more or less acceptable level (tested by David).
987
988   */
989   if (handle->id_vendor == VENDOR_SCM
990       && handle->max_ifsd > 48
991       && (  (handle->id_product == SCM_SCR331   && handle->bcd_device < 0x0516)
992           ||(handle->id_product == SCM_SCR331DI && handle->bcd_device < 0x0620)
993           ||(handle->id_product == SCM_SCR335   && handle->bcd_device < 0x0514)
994           ||(handle->id_product == SCM_SPR532   && handle->bcd_device < 0x0504)
995           ||(handle->id_product == SCM_SCR3320  && handle->bcd_device < 0x0522)
996           ))
997     {
998       DEBUGOUT ("enabling workaround for buggy SCM readers\n");
999       handle->max_ifsd = 48;
1000     }
1001
1002   if (handle->id_vendor == VENDOR_GEMPC && handle->id_product == GEMPC_CT30)
1003     {
1004       DEBUGOUT ("enabling product quirk: disable non-null NAD\n");
1005       handle->nonnull_nad = 0;
1006     }
1007
1008   return 0;
1009 }
1010
1011
1012 static char *
1013 get_escaped_usb_string (usb_dev_handle *idev, int idx,
1014                         const char *prefix, const char *suffix)
1015 {
1016   int rc;
1017   unsigned char buf[280];
1018   unsigned char *s;
1019   unsigned int langid;
1020   size_t i, n, len;
1021   char *result;
1022
1023   if (!idx)
1024     return NULL;
1025
1026   /* Fixme: The next line is for the current Valgrid without support
1027      for USB IOCTLs. */
1028   memset (buf, 0, sizeof buf);
1029
1030   /* First get the list of supported languages and use the first one.
1031      If we do don't find it we try to use English.  Note that this is
1032      all in a 2 bute Unicode encoding using little endian. */
1033   rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1034                         (USB_DT_STRING << 8), 0,
1035                         (char*)buf, sizeof buf, 1000 /* ms timeout */);
1036   if (rc < 4)
1037     langid = 0x0409; /* English.  */
1038   else
1039     langid = (buf[3] << 8) | buf[2];
1040
1041   rc = usb_control_msg (idev, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR,
1042                         (USB_DT_STRING << 8) + idx, langid,
1043                         (char*)buf, sizeof buf, 1000 /* ms timeout */);
1044   if (rc < 2 || buf[1] != USB_DT_STRING)
1045     return NULL; /* Error or not a string. */
1046   len = buf[0];
1047   if (len > rc)
1048     return NULL; /* Larger than our buffer. */
1049
1050   for (s=buf+2, i=2, n=0; i+1 < len; i += 2, s += 2)
1051     {
1052       if (s[1])
1053         n++; /* High byte set. */
1054       else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1055         n += 3 ;
1056       else
1057         n++;
1058     }
1059
1060   result = malloc (strlen (prefix) + n + strlen (suffix) + 1);
1061   if (!result)
1062     return NULL;
1063
1064   strcpy (result, prefix);
1065   n = strlen (prefix);
1066   for (s=buf+2, i=2; i+1 < len; i += 2, s += 2)
1067     {
1068       if (s[1])
1069         result[n++] = '\xff'; /* High byte set. */
1070       else if (*s <= 0x20 || *s >= 0x7f || *s == '%' || *s == ':')
1071         {
1072           sprintf (result+n, "%%%02X", *s);
1073           n += 3;
1074         }
1075       else
1076         result[n++] = *s;
1077     }
1078   strcpy (result+n, suffix);
1079
1080   return result;
1081 }
1082
1083 /* This function creates an reader id to be used to find the same
1084    physical reader after a reset.  It returns an allocated and possibly
1085    percent escaped string or NULL if not enough memory is available. */
1086 static char *
1087 make_reader_id (usb_dev_handle *idev,
1088                 unsigned int vendor, unsigned int product,
1089                 unsigned char serialno_index)
1090 {
1091   char *rid;
1092   char prefix[20];
1093
1094   sprintf (prefix, "%04X:%04X:", (vendor & 0xffff), (product & 0xffff));
1095   rid = get_escaped_usb_string (idev, serialno_index, prefix, ":0");
1096   if (!rid)
1097     {
1098       rid = malloc (strlen (prefix) + 3 + 1);
1099       if (!rid)
1100         return NULL;
1101       strcpy (rid, prefix);
1102       strcat (rid, "X:0");
1103     }
1104   return rid;
1105 }
1106
1107
1108 /* Helper to find the endpoint from an interface descriptor.  */
1109 static int
1110 find_endpoint (struct usb_interface_descriptor *ifcdesc, int mode)
1111 {
1112   int no;
1113   int want_bulk_in = 0;
1114
1115   if (mode == 1)
1116     want_bulk_in = 0x80;
1117   for (no=0; no < ifcdesc->bNumEndpoints; no++)
1118     {
1119       struct usb_endpoint_descriptor *ep = ifcdesc->endpoint + no;
1120       if (ep->bDescriptorType != USB_DT_ENDPOINT)
1121         ;
1122       else if (mode == 2
1123           && ((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1124               == USB_ENDPOINT_TYPE_INTERRUPT)
1125           && (ep->bEndpointAddress & 0x80))
1126         return (ep->bEndpointAddress & 0x0f);
1127       else if (((ep->bmAttributes & USB_ENDPOINT_TYPE_MASK)
1128                 == USB_ENDPOINT_TYPE_BULK)
1129                && (ep->bEndpointAddress & 0x80) == want_bulk_in)
1130         return (ep->bEndpointAddress & 0x0f);
1131     }
1132   /* Should never happen.  */
1133   return mode == 2? 0x83 : mode == 1? 0x82 :1;
1134 }
1135
1136
1137 /* Helper for scan_or_find_devices. This function returns true if a
1138    requested device has been found or the caller should stop scanning
1139    for other reasons. */
1140 static int
1141 scan_or_find_usb_device (int scan_mode,
1142                          int *readerno, int *count, char **rid_list,
1143                          const char *readerid,
1144                          struct usb_device *dev,
1145                          char **r_rid,
1146                          struct usb_device **r_dev,
1147                          usb_dev_handle **r_idev,
1148                          unsigned char **ifcdesc_extra,
1149                          size_t *ifcdesc_extra_len,
1150                          int *interface_number,
1151                          int *ep_bulk_out, int *ep_bulk_in, int *ep_intr)
1152 {
1153   int cfg_no;
1154   int ifc_no;
1155   int set_no;
1156   struct usb_config_descriptor *config;
1157   struct usb_interface *interface;
1158   struct usb_interface_descriptor *ifcdesc;
1159   char *rid;
1160   usb_dev_handle *idev;
1161
1162   *r_idev = NULL;
1163
1164   for (cfg_no=0; cfg_no < dev->descriptor.bNumConfigurations; cfg_no++)
1165     {
1166       config = dev->config + cfg_no;
1167       if(!config)
1168         continue;
1169
1170       for (ifc_no=0; ifc_no < config->bNumInterfaces; ifc_no++)
1171         {
1172           interface = config->interface + ifc_no;
1173           if (!interface)
1174             continue;
1175
1176           for (set_no=0; set_no < interface->num_altsetting; set_no++)
1177             {
1178               ifcdesc = (interface->altsetting + set_no);
1179               /* The second condition is for older SCM SPR 532 who did
1180                  not know about the assigned CCID class.  The third
1181                  condition does the same for a Cherry SmartTerminal
1182                  ST-2000.  Instead of trying to interpret the strings
1183                  we simply check the product ID. */
1184               if (ifcdesc && ifcdesc->extra
1185                   && ((ifcdesc->bInterfaceClass == 11
1186                        && ifcdesc->bInterfaceSubClass == 0
1187                        && ifcdesc->bInterfaceProtocol == 0)
1188                       || (ifcdesc->bInterfaceClass == 255
1189                           && dev->descriptor.idVendor == VENDOR_SCM
1190                           && dev->descriptor.idProduct == SCM_SPR532)
1191                       || (ifcdesc->bInterfaceClass == 255
1192                           && dev->descriptor.idVendor == VENDOR_CHERRY
1193                           && dev->descriptor.idProduct == CHERRY_ST2000)))
1194                 {
1195                   idev = usb_open (dev);
1196                   if (!idev)
1197                     {
1198                       DEBUGOUT_1 ("usb_open failed: %s\n",
1199                                   strerror (errno));
1200                       continue; /* with next setting. */
1201                     }
1202
1203                   rid = make_reader_id (idev,
1204                                         dev->descriptor.idVendor,
1205                                         dev->descriptor.idProduct,
1206                                         dev->descriptor.iSerialNumber);
1207                   if (rid)
1208                     {
1209                       if (scan_mode)
1210                         {
1211                           char *p;
1212
1213                           /* We are collecting infos about all
1214                              available CCID readers.  Store them and
1215                              continue. */
1216                           DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n",
1217                                       *count, rid );
1218                           p = malloc ((*rid_list? strlen (*rid_list):0) + 1
1219                                       + strlen (rid) + 1);
1220                           if (p)
1221                             {
1222                               *p = 0;
1223                               if (*rid_list)
1224                                 {
1225                                   strcat (p, *rid_list);
1226                                   free (*rid_list);
1227                                 }
1228                               strcat (p, rid);
1229                               strcat (p, "\n");
1230                               *rid_list = p;
1231                             }
1232                           else /* Out of memory. */
1233                             free (rid);
1234
1235                           rid = NULL;
1236                           ++*count;
1237                         }
1238                       else if (!*readerno
1239                                || (*readerno < 0
1240                                    && readerid
1241                                    && !strcmp (readerid, rid)))
1242                         {
1243                           /* We found the requested reader. */
1244                           if (ifcdesc_extra && ifcdesc_extra_len)
1245                             {
1246                               *ifcdesc_extra = malloc (ifcdesc
1247                                                        ->extralen);
1248                               if (!*ifcdesc_extra)
1249                                 {
1250                                   usb_close (idev);
1251                                   free (rid);
1252                                   return 1; /* Out of core. */
1253                                 }
1254                               memcpy (*ifcdesc_extra, ifcdesc->extra,
1255                                       ifcdesc->extralen);
1256                               *ifcdesc_extra_len = ifcdesc->extralen;
1257                             }
1258
1259                           if (interface_number)
1260                             *interface_number = (ifcdesc->bInterfaceNumber);
1261
1262                           if (ep_bulk_out)
1263                             *ep_bulk_out = find_endpoint (ifcdesc, 0);
1264                           if (ep_bulk_in)
1265                             *ep_bulk_in = find_endpoint (ifcdesc, 1);
1266                           if (ep_intr)
1267                             *ep_intr = find_endpoint (ifcdesc, 2);
1268
1269                           if (r_dev)
1270                             *r_dev = dev;
1271                           if (r_rid)
1272                             {
1273                               *r_rid = rid;
1274                               rid = NULL;
1275                             }
1276                           else
1277                             free (rid);
1278
1279                           *r_idev = idev;
1280                           return 1; /* Found requested device. */
1281                         }
1282                       else
1283                         {
1284                           /* This is not yet the reader we want.
1285                              fixme: We should avoid the extra usb_open
1286                              in this case. */
1287                           if (*readerno >= 0)
1288                             --*readerno;
1289                         }
1290                       free (rid);
1291                     }
1292
1293                   usb_close (idev);
1294                   idev = NULL;
1295                   return 0;
1296                 }
1297             }
1298         }
1299     }
1300
1301   return 0;
1302 }
1303
1304 /* Combination function to either scan all CCID devices or to find and
1305    open one specific device.
1306
1307    The function returns 0 if a reader has been found or when a scan
1308    returned without error.
1309
1310    With READERNO = -1 and READERID is NULL, scan mode is used and
1311    R_RID should be the address where to store the list of reader_ids
1312    we found.  If on return this list is empty, no CCID device has been
1313    found; otherwise it points to an allocated linked list of reader
1314    IDs.  Note that in this mode the function always returns NULL.
1315
1316    With READERNO >= 0 or READERID is not NULL find mode is used.  This
1317    uses the same algorithm as the scan mode but stops and returns at
1318    the entry number READERNO and return the handle for the the opened
1319    USB device. If R_RID is not NULL it will receive the reader ID of
1320    that device.  If R_DEV is not NULL it will the device pointer of
1321    that device.  If IFCDESC_EXTRA is NOT NULL it will receive a
1322    malloced copy of the interfaces "extra: data filed;
1323    IFCDESC_EXTRA_LEN receive the length of this field.  If there is
1324    no reader with number READERNO or that reader is not usable by our
1325    implementation NULL will be returned.  The caller must close a
1326    returned USB device handle and free (if not passed as NULL) the
1327    returned reader ID info as well as the IFCDESC_EXTRA.  On error
1328    NULL will get stored at R_RID, R_DEV, IFCDESC_EXTRA and
1329    IFCDESC_EXTRA_LEN.  With READERID being -1 the function stops if
1330    the READERID was found.
1331
1332    If R_FD is not -1 on return the device is not using USB for
1333    transport but the device associated with that file descriptor.  In
1334    this case INTERFACE will receive the transport type and the other
1335    USB specific return values are not used; the return value is
1336    (void*)(1).
1337
1338    Note that the first entry of the returned reader ID list in scan mode
1339    corresponds with a READERNO of 0 in find mode.
1340 */
1341 static int
1342 scan_or_find_devices (int readerno, const char *readerid,
1343                       char **r_rid,
1344                       struct usb_device **r_dev,
1345                       unsigned char **ifcdesc_extra,
1346                       size_t *ifcdesc_extra_len,
1347                       int *interface_number,
1348                       int *ep_bulk_out, int *ep_bulk_in, int *ep_intr,
1349                       usb_dev_handle **r_idev,
1350                       int *r_fd)
1351 {
1352   char *rid_list = NULL;
1353   int count = 0;
1354   struct usb_bus *busses, *bus;
1355   struct usb_device *dev = NULL;
1356   usb_dev_handle *idev = NULL;
1357   int scan_mode = (readerno == -1 && !readerid);
1358   int i;
1359
1360   /* Set return values to a default. */
1361   if (r_rid)
1362     *r_rid = NULL;
1363   if (r_dev)
1364     *r_dev = NULL;
1365   if (ifcdesc_extra)
1366     *ifcdesc_extra = NULL;
1367   if (ifcdesc_extra_len)
1368     *ifcdesc_extra_len = 0;
1369   if (interface_number)
1370     *interface_number = 0;
1371   if (r_idev)
1372     *r_idev = NULL;
1373   if (r_fd)
1374     *r_fd = -1;
1375
1376   /* See whether we want scan or find mode. */
1377   if (scan_mode)
1378     {
1379       assert (r_rid);
1380     }
1381
1382   usb_find_busses();
1383   usb_find_devices();
1384
1385 #ifdef HAVE_USB_GET_BUSSES
1386   busses = usb_get_busses();
1387 #else
1388   busses = usb_busses;
1389 #endif
1390
1391   for (bus = busses; bus; bus = bus->next)
1392     {
1393       for (dev = bus->devices; dev; dev = dev->next)
1394         {
1395           if (scan_or_find_usb_device (scan_mode, &readerno, &count, &rid_list,
1396                                        readerid,
1397                                        dev,
1398                                        r_rid,
1399                                        r_dev,
1400                                        &idev,
1401                                        ifcdesc_extra,
1402                                        ifcdesc_extra_len,
1403                                        interface_number,
1404                                        ep_bulk_out, ep_bulk_in, ep_intr))
1405             {
1406               /* Found requested device or out of core. */
1407               if (!idev)
1408                 {
1409                   free (rid_list);
1410                   return -1; /* error */
1411                 }
1412               *r_idev = idev;
1413               return 0;
1414             }
1415         }
1416     }
1417
1418   /* Now check whether there are any devices with special transport types. */
1419   for (i=0; transports[i].name; i++)
1420     {
1421       int fd;
1422       char *rid, *p;
1423
1424       fd = open (transports[i].name, O_RDWR);
1425       if (fd == -1 && scan_mode && errno == EBUSY)
1426         {
1427           /* Ignore this error in scan mode because it indicates that
1428              the device exists but is already open (most likely by us)
1429              and thus in general suitable as a reader.  */
1430         }
1431       else if (fd == -1)
1432         {
1433           DEBUGOUT_2 ("failed to open `%s': %s\n",
1434                      transports[i].name, strerror (errno));
1435           continue;
1436         }
1437
1438       rid = malloc (strlen (transports[i].name) + 30 + 10);
1439       if (!rid)
1440         {
1441           if (fd != -1)
1442             close (fd);
1443           free (rid_list);
1444           return -1; /* Error. */
1445         }
1446       sprintf (rid, "0000:%04X:%s:0", transports[i].type, transports[i].name);
1447       if (scan_mode)
1448         {
1449           DEBUGOUT_2 ("found CCID reader %d (ID=%s)\n", count, rid);
1450           p = malloc ((rid_list? strlen (rid_list):0) + 1 + strlen (rid) + 1);
1451           if (!p)
1452             {
1453               if (fd != -1)
1454                 close (fd);
1455               free (rid_list);
1456               free (rid);
1457               return -1; /* Error. */
1458             }
1459           *p = 0;
1460           if (rid_list)
1461             {
1462               strcat (p, rid_list);
1463               free (rid_list);
1464             }
1465           strcat (p, rid);
1466           strcat (p, "\n");
1467           rid_list = p;
1468           ++count;
1469         }
1470       else if (!readerno ||
1471                (readerno < 0 && readerid && !strcmp (readerid, rid)))
1472         {
1473           /* Found requested device. */
1474           if (interface_number)
1475             *interface_number = transports[i].type;
1476           if (r_rid)
1477             *r_rid = rid;
1478           else
1479             free (rid);
1480           if (r_fd)
1481             *r_fd = fd;
1482           return 0; /* Okay, found device */
1483         }
1484       else /* This is not yet the reader we want. */
1485         {
1486           if (readerno >= 0)
1487             --readerno;
1488         }
1489       free (rid);
1490       if (fd != -1)
1491         close (fd);
1492     }
1493
1494   if (scan_mode)
1495     {
1496       *r_rid = rid_list;
1497       return 0;
1498     }
1499   else
1500     return -1;
1501 }
1502
1503
1504 /* Set the level of debugging to LEVEL and return the old level.  -1
1505    just returns the old level.  A level of 0 disables debugging, 1
1506    enables debugging, 2 enables additional tracing of the T=1
1507    protocol, 3 additionally enables debugging for GetSlotStatus, other
1508    values are not yet defined.
1509
1510    Note that libusb may provide its own debugging feature which is
1511    enabled by setting the envvar USB_DEBUG.  */
1512 int
1513 ccid_set_debug_level (int level)
1514 {
1515   int old = debug_level;
1516   if (level != -1)
1517     debug_level = level;
1518   return old;
1519 }
1520
1521
1522 char *
1523 ccid_get_reader_list (void)
1524 {
1525   char *reader_list;
1526
1527   if (!initialized_usb)
1528     {
1529       usb_init ();
1530       initialized_usb = 1;
1531     }
1532
1533   if (scan_or_find_devices (-1, NULL, &reader_list, NULL, NULL, NULL, NULL,
1534                             NULL, NULL, NULL, NULL, NULL))
1535     return NULL; /* Error. */
1536   return reader_list;
1537 }
1538
1539
1540 /* Vendor specific custom initialization.  */
1541 static int
1542 ccid_vendor_specific_init (ccid_driver_t handle)
1543 {
1544   if (handle->id_vendor == VENDOR_VEGA && handle->id_product == VEGA_ALPHA)
1545     {
1546       int r;
1547       /*
1548        * Vega alpha has a feature to show retry counter on the pinpad
1549        * display.  But it assumes that the card returns the value of
1550        * retry counter by VERIFY with empty data (return code of
1551        * 63Cx).  Unfortunately, existing OpenPGP cards don't support
1552        * VERIFY command with empty data.  This vendor specific command
1553        * sequence is to disable the feature.
1554        */
1555       const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1556
1557       r = send_escape_cmd (handle, cmd, sizeof (cmd), NULL, 0, NULL);
1558       if (r != 0 && r != CCID_DRIVER_ERR_CARD_INACTIVE
1559           && r != CCID_DRIVER_ERR_NO_CARD)
1560         return r;
1561     }
1562
1563   return 0;
1564 }
1565
1566
1567 /* Open the reader with the internal number READERNO and return a
1568    pointer to be used as handle in HANDLE.  Returns 0 on success. */
1569 int
1570 ccid_open_reader (ccid_driver_t *handle, const char *readerid)
1571 {
1572   int rc = 0;
1573   struct usb_device *dev = NULL;
1574   usb_dev_handle *idev = NULL;
1575   int dev_fd = -1;
1576   char *rid = NULL;
1577   unsigned char *ifcdesc_extra = NULL;
1578   size_t ifcdesc_extra_len;
1579   int readerno;
1580   int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1581
1582   *handle = NULL;
1583
1584   if (!initialized_usb)
1585     {
1586       usb_init ();
1587       initialized_usb = 1;
1588     }
1589
1590   /* See whether we want to use the reader ID string or a reader
1591      number. A readerno of -1 indicates that the reader ID string is
1592      to be used. */
1593   if (readerid && strchr (readerid, ':'))
1594     readerno = -1; /* We want to use the readerid.  */
1595   else if (readerid)
1596     {
1597       readerno = atoi (readerid);
1598       if (readerno < 0)
1599         {
1600           DEBUGOUT ("no CCID readers found\n");
1601           rc = CCID_DRIVER_ERR_NO_READER;
1602           goto leave;
1603         }
1604     }
1605   else
1606     readerno = 0;  /* Default. */
1607
1608   if (scan_or_find_devices (readerno, readerid, &rid, &dev,
1609                             &ifcdesc_extra, &ifcdesc_extra_len,
1610                             &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1611                             &idev, &dev_fd) )
1612     {
1613       if (readerno == -1)
1614         DEBUGOUT_1 ("no CCID reader with ID %s\n", readerid );
1615       else
1616         DEBUGOUT_1 ("no CCID reader with number %d\n", readerno );
1617       rc = CCID_DRIVER_ERR_NO_READER;
1618       goto leave;
1619     }
1620
1621   /* Okay, this is a CCID reader. */
1622   *handle = calloc (1, sizeof **handle);
1623   if (!*handle)
1624     {
1625       DEBUGOUT ("out of memory\n");
1626       rc = CCID_DRIVER_ERR_OUT_OF_CORE;
1627       goto leave;
1628     }
1629   (*handle)->rid = rid;
1630   if (idev) /* Regular USB transport. */
1631     {
1632       (*handle)->idev = idev;
1633       (*handle)->dev_fd = -1;
1634       (*handle)->id_vendor = dev->descriptor.idVendor;
1635       (*handle)->id_product = dev->descriptor.idProduct;
1636       (*handle)->bcd_device = dev->descriptor.bcdDevice;
1637       (*handle)->ifc_no = ifc_no;
1638       (*handle)->ep_bulk_out = ep_bulk_out;
1639       (*handle)->ep_bulk_in = ep_bulk_in;
1640       (*handle)->ep_intr = ep_intr;
1641     }
1642   else if (dev_fd != -1) /* Device transport. */
1643     {
1644       (*handle)->idev = NULL;
1645       (*handle)->dev_fd = dev_fd;
1646       (*handle)->id_vendor = 0;  /* Magic vendor for special transport. */
1647       (*handle)->id_product = ifc_no; /* Transport type */
1648       prepare_special_transport (*handle);
1649     }
1650   else
1651     {
1652       assert (!"no transport"); /* Bug. */
1653     }
1654
1655   DEBUGOUT_2 ("using CCID reader %d (ID=%s)\n",  readerno, rid );
1656
1657   if (idev)
1658     {
1659       if (parse_ccid_descriptor (*handle, ifcdesc_extra, ifcdesc_extra_len))
1660         {
1661           DEBUGOUT ("device not supported\n");
1662           rc = CCID_DRIVER_ERR_NO_READER;
1663           goto leave;
1664         }
1665
1666       rc = usb_claim_interface (idev, ifc_no);
1667       if (rc)
1668         {
1669           DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1670           rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1671           goto leave;
1672         }
1673     }
1674
1675   rc = ccid_vendor_specific_init (*handle);
1676
1677  leave:
1678   free (ifcdesc_extra);
1679   if (rc)
1680     {
1681       free (rid);
1682       if (idev)
1683         usb_close (idev);
1684       if (dev_fd != -1)
1685         close (dev_fd);
1686       free (*handle);
1687       *handle = NULL;
1688     }
1689
1690   return rc;
1691 }
1692
1693
1694 static void
1695 do_close_reader (ccid_driver_t handle)
1696 {
1697   int rc;
1698   unsigned char msg[100];
1699   size_t msglen;
1700   unsigned char seqno;
1701
1702   if (!handle->powered_off)
1703     {
1704       msg[0] = PC_to_RDR_IccPowerOff;
1705       msg[5] = 0; /* slot */
1706       msg[6] = seqno = handle->seqno++;
1707       msg[7] = 0; /* RFU */
1708       msg[8] = 0; /* RFU */
1709       msg[9] = 0; /* RFU */
1710       set_msg_len (msg, 0);
1711       msglen = 10;
1712
1713       rc = bulk_out (handle, msg, msglen, 0);
1714       if (!rc)
1715         bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
1716                  seqno, 2000, 0);
1717       handle->powered_off = 1;
1718     }
1719   if (handle->idev)
1720     {
1721       usb_release_interface (handle->idev, handle->ifc_no);
1722       usb_close (handle->idev);
1723       handle->idev = NULL;
1724     }
1725   if (handle->dev_fd != -1)
1726     {
1727       close (handle->dev_fd);
1728       handle->dev_fd = -1;
1729     }
1730 }
1731
1732
1733 /* Reset a reader on HANDLE.  This is useful in case a reader has been
1734    plugged of and inserted at a different port.  By resetting the
1735    handle, the same reader will be get used.  Note, that on error the
1736    handle won't get released.
1737
1738    This does not return an ATR, so ccid_get_atr should be called right
1739    after this one.
1740 */
1741 int
1742 ccid_shutdown_reader (ccid_driver_t handle)
1743 {
1744   int rc = 0;
1745   struct usb_device *dev = NULL;
1746   usb_dev_handle *idev = NULL;
1747   unsigned char *ifcdesc_extra = NULL;
1748   size_t ifcdesc_extra_len;
1749   int ifc_no, ep_bulk_out, ep_bulk_in, ep_intr;
1750
1751   if (!handle || !handle->rid)
1752     return CCID_DRIVER_ERR_INV_VALUE;
1753
1754   do_close_reader (handle);
1755
1756   if (scan_or_find_devices (-1, handle->rid, NULL, &dev,
1757                             &ifcdesc_extra, &ifcdesc_extra_len,
1758                             &ifc_no, &ep_bulk_out, &ep_bulk_in, &ep_intr,
1759                             &idev, NULL) || !idev)
1760     {
1761       DEBUGOUT_1 ("no CCID reader with ID %s\n", handle->rid);
1762       return CCID_DRIVER_ERR_NO_READER;
1763     }
1764
1765   if (idev)
1766     {
1767       handle->idev = idev;
1768       handle->ifc_no = ifc_no;
1769       handle->ep_bulk_out = ep_bulk_out;
1770       handle->ep_bulk_in = ep_bulk_in;
1771       handle->ep_intr = ep_intr;
1772
1773       if (parse_ccid_descriptor (handle, ifcdesc_extra, ifcdesc_extra_len))
1774         {
1775           DEBUGOUT ("device not supported\n");
1776           rc = CCID_DRIVER_ERR_NO_READER;
1777           goto leave;
1778         }
1779
1780       rc = usb_claim_interface (idev, ifc_no);
1781       if (rc)
1782         {
1783           DEBUGOUT_1 ("usb_claim_interface failed: %d\n", rc);
1784           rc = CCID_DRIVER_ERR_CARD_IO_ERROR;
1785           goto leave;
1786         }
1787     }
1788
1789  leave:
1790   free (ifcdesc_extra);
1791   if (rc)
1792     {
1793       if (handle->idev)
1794         usb_close (handle->idev);
1795       handle->idev = NULL;
1796       if (handle->dev_fd != -1)
1797         close (handle->dev_fd);
1798       handle->dev_fd = -1;
1799     }
1800
1801   return rc;
1802
1803 }
1804
1805
1806 int
1807 ccid_set_progress_cb (ccid_driver_t handle,
1808                       void (*cb)(void *, const char *, int, int, int),
1809                       void *cb_arg)
1810 {
1811   if (!handle || !handle->rid)
1812     return CCID_DRIVER_ERR_INV_VALUE;
1813
1814   handle->progress_cb = cb;
1815   handle->progress_cb_arg = cb_arg;
1816   return 0;
1817 }
1818
1819
1820 /* Close the reader HANDLE. */
1821 int
1822 ccid_close_reader (ccid_driver_t handle)
1823 {
1824   if (!handle || (!handle->idev && handle->dev_fd == -1))
1825     return 0;
1826
1827   do_close_reader (handle);
1828   free (handle->rid);
1829   free (handle);
1830   return 0;
1831 }
1832
1833
1834 /* Return False if a card is present and powered. */
1835 int
1836 ccid_check_card_presence (ccid_driver_t handle)
1837 {
1838   (void)handle;  /* Not yet implemented.  */
1839   return -1;
1840 }
1841
1842
1843 /* Write NBYTES of BUF to file descriptor FD. */
1844 static int
1845 writen (int fd, const void *buf, size_t nbytes)
1846 {
1847   size_t nleft = nbytes;
1848   int nwritten;
1849
1850   while (nleft > 0)
1851     {
1852       nwritten = write (fd, buf, nleft);
1853       if (nwritten < 0)
1854         {
1855           if (errno == EINTR)
1856             nwritten = 0;
1857           else
1858             return -1;
1859         }
1860       nleft -= nwritten;
1861       buf = (const char*)buf + nwritten;
1862     }
1863
1864   return 0;
1865 }
1866
1867
1868 /* Write a MSG of length MSGLEN to the designated bulk out endpoint.
1869    Returns 0 on success. */
1870 static int
1871 bulk_out (ccid_driver_t handle, unsigned char *msg, size_t msglen,
1872           int no_debug)
1873 {
1874   int rc;
1875
1876   /* No need to continue and clutter the log with USB write error
1877      messages after we got the first ENODEV.  */
1878   if (handle->enodev_seen)
1879     return CCID_DRIVER_ERR_NO_READER;
1880
1881   if (debug_level && (!no_debug || debug_level >= 3))
1882     {
1883       switch (msglen? msg[0]:0)
1884         {
1885         case PC_to_RDR_IccPowerOn:
1886           print_p2r_iccpoweron (msg, msglen);
1887           break;
1888         case PC_to_RDR_IccPowerOff:
1889           print_p2r_iccpoweroff (msg, msglen);
1890           break;
1891         case PC_to_RDR_GetSlotStatus:
1892           print_p2r_getslotstatus (msg, msglen);
1893           break;
1894         case PC_to_RDR_XfrBlock:
1895           print_p2r_xfrblock (msg, msglen);
1896           break;
1897         case PC_to_RDR_GetParameters:
1898           print_p2r_getparameters (msg, msglen);
1899           break;
1900         case PC_to_RDR_ResetParameters:
1901           print_p2r_resetparameters (msg, msglen);
1902           break;
1903         case PC_to_RDR_SetParameters:
1904           print_p2r_setparameters (msg, msglen);
1905           break;
1906         case PC_to_RDR_Escape:
1907           print_p2r_escape (msg, msglen);
1908           break;
1909         case PC_to_RDR_IccClock:
1910           print_p2r_iccclock (msg, msglen);
1911           break;
1912         case PC_to_RDR_T0APDU:
1913           print_p2r_to0apdu (msg, msglen);
1914           break;
1915         case PC_to_RDR_Secure:
1916           print_p2r_secure (msg, msglen);
1917           break;
1918         case PC_to_RDR_Mechanical:
1919           print_p2r_mechanical (msg, msglen);
1920           break;
1921         case PC_to_RDR_Abort:
1922           print_p2r_abort (msg, msglen);
1923           break;
1924         case PC_to_RDR_SetDataRate:
1925           print_p2r_setdatarate (msg, msglen);
1926           break;
1927         default:
1928           print_p2r_unknown (msg, msglen);
1929           break;
1930         }
1931     }
1932
1933   if (handle->idev)
1934     {
1935       rc = usb_bulk_write (handle->idev,
1936                            handle->ep_bulk_out,
1937                            (char*)msg, msglen,
1938                            5000 /* ms timeout */);
1939       if (rc == msglen)
1940         return 0;
1941 #ifdef ENODEV
1942       if (rc == -(ENODEV))
1943         {
1944           /* The Linux libusb returns a negative error value.  Catch
1945              the most important one.  */
1946           errno = ENODEV;
1947           rc = -1;
1948         }
1949 #endif /*ENODEV*/
1950
1951       if (rc == -1)
1952         {
1953           DEBUGOUT_1 ("usb_bulk_write error: %s\n", strerror (errno));
1954 #ifdef ENODEV
1955           if (errno == ENODEV)
1956             {
1957               handle->enodev_seen = 1;
1958               return CCID_DRIVER_ERR_NO_READER;
1959             }
1960 #endif /*ENODEV*/
1961         }
1962       else
1963         DEBUGOUT_1 ("usb_bulk_write failed: %d\n", rc);
1964     }
1965   else
1966     {
1967       rc = writen (handle->dev_fd, msg, msglen);
1968       if (!rc)
1969         return 0;
1970       DEBUGOUT_2 ("writen to %d failed: %s\n",
1971                   handle->dev_fd, strerror (errno));
1972
1973     }
1974   return CCID_DRIVER_ERR_CARD_IO_ERROR;
1975 }
1976
1977
1978 /* Read a maximum of LENGTH bytes from the bulk in endpoint into
1979    BUFFER and return the actual read number if bytes in NREAD. SEQNO
1980    is the sequence number used to send the request and EXPECTED_TYPE
1981    the type of message we expect. Does checks on the ccid
1982    header. TIMEOUT is the timeout value in ms. NO_DEBUG may be set to
1983    avoid debug messages in case of no error; this can be overriden
1984    with a glibal debug level of at least 3. Returns 0 on success. */
1985 static int
1986 bulk_in (ccid_driver_t handle, unsigned char *buffer, size_t length,
1987          size_t *nread, int expected_type, int seqno, int timeout,
1988          int no_debug)
1989 {
1990   int rc;
1991   size_t msglen;
1992   int eagain_retries = 0;
1993
1994   /* Fixme: The next line for the current Valgrind without support
1995      for USB IOCTLs. */
1996   memset (buffer, 0, length);
1997  retry:
1998   if (handle->idev)
1999     {
2000       rc = usb_bulk_read (handle->idev,
2001                           handle->ep_bulk_in,
2002                           (char*)buffer, length,
2003                           timeout);
2004       if (rc < 0)
2005         {
2006           rc = errno;
2007           DEBUGOUT_1 ("usb_bulk_read error: %s\n", strerror (rc));
2008           if (rc == EAGAIN && eagain_retries++ < 3)
2009             {
2010               my_sleep (1);
2011               goto retry;
2012             }
2013           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2014         }
2015       *nread = msglen = rc;
2016     }
2017   else
2018     {
2019       rc = read (handle->dev_fd, buffer, length);
2020       if (rc < 0)
2021         {
2022           rc = errno;
2023           DEBUGOUT_2 ("read from %d failed: %s\n",
2024                       handle->dev_fd, strerror (rc));
2025           if (rc == EAGAIN && eagain_retries++ < 5)
2026             {
2027               my_sleep (1);
2028               goto retry;
2029             }
2030           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2031         }
2032       *nread = msglen = rc;
2033     }
2034   eagain_retries = 0;
2035
2036   if (msglen < 10)
2037     {
2038       DEBUGOUT_1 ("bulk-in msg too short (%u)\n", (unsigned int)msglen);
2039       abort_cmd (handle, seqno);
2040       return CCID_DRIVER_ERR_INV_VALUE;
2041     }
2042   if (buffer[5] != 0)
2043     {
2044       DEBUGOUT_1 ("unexpected bulk-in slot (%d)\n", buffer[5]);
2045       return CCID_DRIVER_ERR_INV_VALUE;
2046     }
2047   if (buffer[6] != seqno)
2048     {
2049       DEBUGOUT_2 ("bulk-in seqno does not match (%d/%d)\n",
2050                   seqno, buffer[6]);
2051       /* Retry until we are synced again.  */
2052       goto retry;
2053     }
2054
2055   /* We need to handle the time extension request before we check that
2056      we got the expected message type.  This is in particular required
2057      for the Cherry keyboard which sends a time extension request for
2058      each key hit.  */
2059   if ( !(buffer[7] & 0x03) && (buffer[7] & 0xC0) == 0x80)
2060     {
2061       /* Card present and active, time extension requested. */
2062       DEBUGOUT_2 ("time extension requested (%02X,%02X)\n",
2063                   buffer[7], buffer[8]);
2064       goto retry;
2065     }
2066
2067   if (buffer[0] != expected_type)
2068     {
2069       DEBUGOUT_1 ("unexpected bulk-in msg type (%02x)\n", buffer[0]);
2070       abort_cmd (handle, seqno);
2071       return CCID_DRIVER_ERR_INV_VALUE;
2072     }
2073
2074   if (debug_level && (!no_debug || debug_level >= 3))
2075     {
2076       switch (buffer[0])
2077         {
2078         case RDR_to_PC_DataBlock:
2079           print_r2p_datablock (buffer, msglen);
2080           break;
2081         case RDR_to_PC_SlotStatus:
2082           print_r2p_slotstatus (buffer, msglen);
2083           break;
2084         case RDR_to_PC_Parameters:
2085           print_r2p_parameters (buffer, msglen);
2086           break;
2087         case RDR_to_PC_Escape:
2088           print_r2p_escape (buffer, msglen);
2089           break;
2090         case RDR_to_PC_DataRate:
2091           print_r2p_datarate (buffer, msglen);
2092           break;
2093         default:
2094           print_r2p_unknown (buffer, msglen);
2095           break;
2096         }
2097     }
2098   if (CCID_COMMAND_FAILED (buffer))
2099     print_command_failed (buffer);
2100
2101   /* Check whether a card is at all available.  Note: If you add new
2102      error codes here, check whether they need to be ignored in
2103      send_escape_cmd. */
2104   switch ((buffer[7] & 0x03))
2105     {
2106     case 0: /* no error */ break;
2107     case 1: return CCID_DRIVER_ERR_CARD_INACTIVE;
2108     case 2: return CCID_DRIVER_ERR_NO_CARD;
2109     case 3: /* RFU */ break;
2110     }
2111   return 0;
2112 }
2113
2114
2115
2116 /* Send an abort sequence and wait until everything settled.  */
2117 static int
2118 abort_cmd (ccid_driver_t handle, int seqno)
2119 {
2120   int rc;
2121   char dummybuf[8];
2122   unsigned char msg[100];
2123   size_t msglen;
2124
2125   if (!handle->idev)
2126     {
2127       /* I don't know how to send an abort to non-USB devices.  */
2128       rc = CCID_DRIVER_ERR_NOT_SUPPORTED;
2129     }
2130
2131   seqno &= 0xff;
2132   DEBUGOUT_1 ("sending abort sequence for seqno %d\n", seqno);
2133   /* Send the abort command to the control pipe.  Note that we don't
2134      need to keep track of sent abort commands because there should
2135      never be another thread using the same slot concurrently.  */
2136   rc = usb_control_msg (handle->idev,
2137                         0x21,/* bmRequestType: host-to-device,
2138                                 class specific, to interface.  */
2139                         1,   /* ABORT */
2140                         (seqno << 8 | 0 /* slot */),
2141                         handle->ifc_no,
2142                         dummybuf, 0,
2143                         1000 /* ms timeout */);
2144   if (rc < 0)
2145     {
2146       DEBUGOUT_1 ("usb_control_msg error: %s\n", strerror (errno));
2147       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2148     }
2149
2150   /* Now send the abort command to the bulk out pipe using the same
2151      SEQNO and SLOT.  Do this in a loop to so that all seqno are
2152      tried.  */
2153   seqno--;  /* Adjust for next increment.  */
2154   do
2155     {
2156       seqno++;
2157       msg[0] = PC_to_RDR_Abort;
2158       msg[5] = 0; /* slot */
2159       msg[6] = seqno;
2160       msg[7] = 0; /* RFU */
2161       msg[8] = 0; /* RFU */
2162       msg[9] = 0; /* RFU */
2163       msglen = 10;
2164       set_msg_len (msg, 0);
2165
2166       rc = usb_bulk_write (handle->idev,
2167                            handle->ep_bulk_out,
2168                            (char*)msg, msglen,
2169                            5000 /* ms timeout */);
2170       if (rc == msglen)
2171         rc = 0;
2172       else if (rc == -1)
2173         DEBUGOUT_1 ("usb_bulk_write error in abort_cmd: %s\n",
2174                     strerror (errno));
2175       else
2176         DEBUGOUT_1 ("usb_bulk_write failed in abort_cmd: %d\n", rc);
2177
2178       if (rc)
2179         return rc;
2180
2181       rc = usb_bulk_read (handle->idev,
2182                           handle->ep_bulk_in,
2183                           (char*)msg, sizeof msg,
2184                           5000 /*ms timeout*/);
2185       if (rc < 0)
2186         {
2187           DEBUGOUT_1 ("usb_bulk_read error in abort_cmd: %s\n",
2188                       strerror (errno));
2189           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2190         }
2191       msglen = rc;
2192
2193       if (msglen < 10)
2194         {
2195           DEBUGOUT_1 ("bulk-in msg in abort_cmd too short (%u)\n",
2196                       (unsigned int)msglen);
2197           return CCID_DRIVER_ERR_INV_VALUE;
2198         }
2199       if (msg[5] != 0)
2200         {
2201           DEBUGOUT_1 ("unexpected bulk-in slot (%d) in abort_cmd\n", msg[5]);
2202           return CCID_DRIVER_ERR_INV_VALUE;
2203         }
2204
2205       DEBUGOUT_3 ("status: %02X  error: %02X  octet[9]: %02X\n",
2206                   msg[7], msg[8], msg[9]);
2207       if (CCID_COMMAND_FAILED (msg))
2208         print_command_failed (msg);
2209     }
2210   while (msg[0] != RDR_to_PC_SlotStatus && msg[5] != 0 && msg[6] != seqno);
2211
2212   handle->seqno = ((seqno + 1) & 0xff);
2213   DEBUGOUT ("sending abort sequence succeeded\n");
2214
2215   return 0;
2216 }
2217
2218
2219 /* Note that this function won't return the error codes NO_CARD or
2220    CARD_INACTIVE.  IF RESULT is not NULL, the result from the
2221    operation will get returned in RESULT and its length in RESULTLEN.
2222    If the response is larger than RESULTMAX, an error is returned and
2223    the required buffer length returned in RESULTLEN.  */
2224 static int
2225 send_escape_cmd (ccid_driver_t handle,
2226                  const unsigned char *data, size_t datalen,
2227                  unsigned char *result, size_t resultmax, size_t *resultlen)
2228 {
2229   int rc;
2230   unsigned char msg[100];
2231   size_t msglen;
2232   unsigned char seqno;
2233
2234   if (resultlen)
2235     *resultlen = 0;
2236
2237   if (datalen > sizeof msg - 10)
2238     return CCID_DRIVER_ERR_INV_VALUE; /* Escape data too large.  */
2239
2240   msg[0] = PC_to_RDR_Escape;
2241   msg[5] = 0; /* slot */
2242   msg[6] = seqno = handle->seqno++;
2243   msg[7] = 0; /* RFU */
2244   msg[8] = 0; /* RFU */
2245   msg[9] = 0; /* RFU */
2246   memcpy (msg+10, data, datalen);
2247   msglen = 10 + datalen;
2248   set_msg_len (msg, datalen);
2249
2250   rc = bulk_out (handle, msg, msglen, 0);
2251   if (rc)
2252     return rc;
2253   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Escape,
2254                 seqno, 5000, 0);
2255   if (result)
2256     switch (rc)
2257       {
2258         /* We need to ignore certain errorcode here. */
2259       case 0:
2260       case CCID_DRIVER_ERR_CARD_INACTIVE:
2261       case CCID_DRIVER_ERR_NO_CARD:
2262         {
2263           if (msglen > resultmax)
2264             rc = CCID_DRIVER_ERR_INV_VALUE; /* Response too large. */
2265           else
2266             {
2267               memcpy (result, msg, msglen);
2268               *resultlen = msglen;
2269             }
2270           rc = 0;
2271         }
2272         break;
2273       default:
2274         break;
2275       }
2276
2277   return rc;
2278 }
2279
2280
2281 int
2282 ccid_transceive_escape (ccid_driver_t handle,
2283                         const unsigned char *data, size_t datalen,
2284                         unsigned char *resp, size_t maxresplen, size_t *nresp)
2285 {
2286   return send_escape_cmd (handle, data, datalen, resp, maxresplen, nresp);
2287 }
2288
2289
2290
2291 /* experimental */
2292 int
2293 ccid_poll (ccid_driver_t handle)
2294 {
2295   int rc;
2296   unsigned char msg[10];
2297   size_t msglen;
2298   int i, j;
2299
2300   if (handle->idev)
2301     {
2302       rc = usb_bulk_read (handle->idev,
2303                           handle->ep_intr,
2304                           (char*)msg, sizeof msg,
2305                           0 /* ms timeout */ );
2306       if (rc < 0 && errno == ETIMEDOUT)
2307         return 0;
2308     }
2309   else
2310     return 0;
2311
2312   if (rc < 0)
2313     {
2314       DEBUGOUT_1 ("usb_intr_read error: %s\n", strerror (errno));
2315       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2316     }
2317
2318   msglen = rc;
2319   rc = 0;
2320
2321   if (msglen < 1)
2322     {
2323       DEBUGOUT ("intr-in msg too short\n");
2324       return CCID_DRIVER_ERR_INV_VALUE;
2325     }
2326
2327   if (msg[0] == RDR_to_PC_NotifySlotChange)
2328     {
2329       DEBUGOUT ("notify slot change:");
2330       for (i=1; i < msglen; i++)
2331         for (j=0; j < 4; j++)
2332           DEBUGOUT_CONT_3 (" %d:%c%c",
2333                            (i-1)*4+j,
2334                            (msg[i] & (1<<(j*2)))? 'p':'-',
2335                            (msg[i] & (2<<(j*2)))? '*':' ');
2336       DEBUGOUT_LF ();
2337     }
2338   else if (msg[0] == RDR_to_PC_HardwareError)
2339     {
2340       DEBUGOUT ("hardware error occured\n");
2341     }
2342   else
2343     {
2344       DEBUGOUT_1 ("unknown intr-in msg of type %02X\n", msg[0]);
2345     }
2346
2347   return 0;
2348 }
2349
2350
2351 /* Note that this function won't return the error codes NO_CARD or
2352    CARD_INACTIVE */
2353 int
2354 ccid_slot_status (ccid_driver_t handle, int *statusbits)
2355 {
2356   int rc;
2357   unsigned char msg[100];
2358   size_t msglen;
2359   unsigned char seqno;
2360   int retries = 0;
2361
2362  retry:
2363   msg[0] = PC_to_RDR_GetSlotStatus;
2364   msg[5] = 0; /* slot */
2365   msg[6] = seqno = handle->seqno++;
2366   msg[7] = 0; /* RFU */
2367   msg[8] = 0; /* RFU */
2368   msg[9] = 0; /* RFU */
2369   set_msg_len (msg, 0);
2370
2371   rc = bulk_out (handle, msg, 10, 1);
2372   if (rc)
2373     return rc;
2374   /* Note that we set the NO_DEBUG flag here, so that the logs won't
2375      get cluttered up by a ticker function checking for the slot
2376      status and debugging enabled. */
2377   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_SlotStatus,
2378                 seqno, retries? 1000 : 200, 1);
2379   if (rc == CCID_DRIVER_ERR_CARD_IO_ERROR && retries < 3)
2380     {
2381       if (!retries)
2382         {
2383           DEBUGOUT ("USB: CALLING USB_CLEAR_HALT\n");
2384           usb_clear_halt (handle->idev, handle->ep_bulk_in);
2385           usb_clear_halt (handle->idev, handle->ep_bulk_out);
2386         }
2387       else
2388           DEBUGOUT ("USB: RETRYING bulk_in AGAIN\n");
2389       retries++;
2390       goto retry;
2391     }
2392   if (rc && rc != CCID_DRIVER_ERR_NO_CARD
2393       && rc != CCID_DRIVER_ERR_CARD_INACTIVE)
2394     return rc;
2395   *statusbits = (msg[7] & 3);
2396
2397   return 0;
2398 }
2399
2400
2401 /* Parse ATR string (of ATRLEN) and update parameters at PARAM.
2402    Calling this routine, it should prepare default values at PARAM
2403    beforehand.  This routine assumes that card is accessed by T=1
2404    protocol.  It doesn't analyze historical bytes at all.
2405
2406    Returns < 0 value on error:
2407      -1 for parse error or integrity check error
2408      -2 for card doesn't support T=1 protocol
2409      -3 for parameters are nod explicitly defined by ATR
2410      -4 for this driver doesn't support CRC
2411
2412    Returns >= 0 on success:
2413       0 for card is negotiable mode
2414       1 for card is specific mode (and not negotiable)
2415  */
2416 static int
2417 update_param_by_atr (unsigned char *param, unsigned char *atr, size_t atrlen)
2418 {
2419   int i = -1;
2420   int t, y, chk;
2421   int historical_bytes_num, negotiable = 1;
2422
2423 #define NEXTBYTE() do { i++; if (atrlen <= i) return -1; } while (0)
2424
2425   NEXTBYTE ();
2426
2427   if (atr[i] == 0x3F)
2428     param[1] |= 0x02;           /* Convention is inverse.  */
2429   NEXTBYTE ();
2430
2431   y = (atr[i] >> 4);
2432   historical_bytes_num = atr[i] & 0x0f;
2433   NEXTBYTE ();
2434
2435   if ((y & 1))
2436     {
2437       param[0] = atr[i];        /* TA1 - Fi & Di */
2438       NEXTBYTE ();
2439     }
2440
2441   if ((y & 2))
2442     NEXTBYTE ();                /* TB1 - ignore */
2443
2444   if ((y & 4))
2445     {
2446       param[2] = atr[i];        /* TC1 - Guard Time */
2447       NEXTBYTE ();
2448     }
2449
2450   if ((y & 8))
2451     {
2452       y = (atr[i] >> 4);        /* TD1 */
2453       t = atr[i] & 0x0f;
2454       NEXTBYTE ();
2455
2456       if ((y & 1))
2457         {                       /* TA2 - PPS mode */
2458           if ((atr[i] & 0x0f) != 1)
2459             return -2;          /* Wrong card protocol (!= 1).  */
2460
2461           if ((atr[i] & 0x10) != 0x10)
2462             return -3; /* Transmission parameters are implicitly defined. */
2463
2464           negotiable = 0;       /* TA2 means specific mode.  */
2465           NEXTBYTE ();
2466         }
2467
2468       if ((y & 2))
2469         NEXTBYTE ();            /* TB2 - ignore */
2470
2471       if ((y & 4))
2472         NEXTBYTE ();            /* TC2 - ignore */
2473
2474       if ((y & 8))
2475         {
2476           y = (atr[i] >> 4);    /* TD2 */
2477           t = atr[i] & 0x0f;
2478           NEXTBYTE ();
2479         }
2480       else
2481         y = 0;
2482
2483       while (y)
2484         {
2485           if ((y & 1))
2486             {                   /* TAx */
2487               if (t == 1)
2488                 param[5] = atr[i]; /* IFSC */
2489               else if (t == 15)
2490                 /* XXX: check voltage? */
2491                 param[4] = (atr[i] >> 6); /* ClockStop */
2492
2493               NEXTBYTE ();
2494             }
2495
2496           if ((y & 2))
2497             {
2498               if (t == 1)
2499                 param[3] = atr[i]; /* TBx - BWI & CWI */
2500               NEXTBYTE ();
2501             }
2502
2503           if ((y & 4))
2504             {
2505               if (t == 1)
2506                 param[1] |= (atr[i] & 0x01); /* TCx - LRC/CRC */
2507               NEXTBYTE ();
2508
2509               if (param[1] & 0x01)
2510                 return -4;      /* CRC not supported yet.  */
2511             }
2512
2513           if ((y & 8))
2514             {
2515               y = (atr[i] >> 4); /* TDx */
2516               t = atr[i] & 0x0f;
2517               NEXTBYTE ();
2518             }
2519           else
2520             y = 0;
2521         }
2522     }
2523
2524   i += historical_bytes_num - 1;
2525   NEXTBYTE ();
2526   if (atrlen != i+1)
2527     return -1;
2528
2529 #undef NEXTBYTE
2530
2531   chk = 0;
2532   do
2533     {
2534       chk ^= atr[i];
2535       i--;
2536     }
2537   while (i > 0);
2538
2539   if (chk != 0)
2540     return -1;
2541
2542   return negotiable;
2543 }
2544
2545
2546 /* Return the ATR of the card.  This is not a cached value and thus an
2547    actual reset is done.  */
2548 int
2549 ccid_get_atr (ccid_driver_t handle,
2550               unsigned char *atr, size_t maxatrlen, size_t *atrlen)
2551 {
2552   int rc;
2553   int statusbits;
2554   unsigned char msg[100];
2555   unsigned char *tpdu;
2556   size_t msglen, tpdulen;
2557   unsigned char seqno;
2558   int use_crc = 0;
2559   unsigned int edc;
2560   int tried_iso = 0;
2561   int got_param;
2562   unsigned char param[7] = { /* For Protocol T=1 */
2563     0x11, /* bmFindexDindex */
2564     0x10, /* bmTCCKST1 */
2565     0x00, /* bGuardTimeT1 */
2566     0x4d, /* bmWaitingIntegersT1 */
2567     0x00, /* bClockStop */
2568     0x20, /* bIFSC */
2569     0x00  /* bNadValue */
2570   };
2571
2572   /* First check whether a card is available.  */
2573   rc = ccid_slot_status (handle, &statusbits);
2574   if (rc)
2575     return rc;
2576   if (statusbits == 2)
2577     return CCID_DRIVER_ERR_NO_CARD;
2578
2579   /* For an inactive and also for an active card, issue the PowerOn
2580      command to get the ATR.  */
2581  again:
2582   msg[0] = PC_to_RDR_IccPowerOn;
2583   msg[5] = 0; /* slot */
2584   msg[6] = seqno = handle->seqno++;
2585   /* power select (0=auto, 1=5V, 2=3V, 3=1.8V) */
2586   msg[7] = handle->auto_voltage ? 0 : 1;
2587   msg[8] = 0; /* RFU */
2588   msg[9] = 0; /* RFU */
2589   set_msg_len (msg, 0);
2590   msglen = 10;
2591
2592   rc = bulk_out (handle, msg, msglen, 0);
2593   if (rc)
2594     return rc;
2595   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2596                 seqno, 5000, 0);
2597   if (rc)
2598     return rc;
2599   if (!tried_iso && CCID_COMMAND_FAILED (msg) && CCID_ERROR_CODE (msg) == 0xbb
2600       && ((handle->id_vendor == VENDOR_CHERRY
2601            && handle->id_product == 0x0005)
2602           || (handle->id_vendor == VENDOR_GEMPC
2603               && handle->id_product == 0x4433)
2604           ))
2605     {
2606       tried_iso = 1;
2607       /* Try switching to ISO mode. */
2608       if (!send_escape_cmd (handle, (const unsigned char*)"\xF1\x01", 2,
2609                             NULL, 0, NULL))
2610         goto again;
2611     }
2612   else if (CCID_COMMAND_FAILED (msg))
2613     return CCID_DRIVER_ERR_CARD_IO_ERROR;
2614
2615
2616   handle->powered_off = 0;
2617
2618   if (atr)
2619     {
2620       size_t n = msglen - 10;
2621
2622       if (n > maxatrlen)
2623         n = maxatrlen;
2624       memcpy (atr, msg+10, n);
2625       *atrlen = n;
2626     }
2627
2628   param[6] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2629   rc = update_param_by_atr (param, msg+10, msglen - 10);
2630   if (rc < 0)
2631     {
2632       DEBUGOUT_1 ("update_param_by_atr failed: %d\n", rc);
2633       return CCID_DRIVER_ERR_CARD_IO_ERROR;
2634     }
2635
2636   got_param = 0;
2637
2638   if (handle->auto_param)
2639     {
2640       msg[0] = PC_to_RDR_GetParameters;
2641       msg[5] = 0; /* slot */
2642       msg[6] = seqno = handle->seqno++;
2643       msg[7] = 0; /* RFU */
2644       msg[8] = 0; /* RFU */
2645       msg[9] = 0; /* RFU */
2646       set_msg_len (msg, 0);
2647       msglen = 10;
2648       rc = bulk_out (handle, msg, msglen, 0);
2649       if (!rc)
2650         rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2651                       seqno, 2000, 0);
2652       if (rc)
2653         DEBUGOUT ("GetParameters failed\n");
2654       else if (msglen == 17 && msg[9] == 1)
2655         got_param = 1;
2656     }
2657   else if (handle->auto_pps)
2658     ;
2659   else if (rc == 1)             /* It's negotiable, send PPS.  */
2660     {
2661       msg[0] = PC_to_RDR_XfrBlock;
2662       msg[5] = 0; /* slot */
2663       msg[6] = seqno = handle->seqno++;
2664       msg[7] = 0;
2665       msg[8] = 0;
2666       msg[9] = 0;
2667       msg[10] = 0xff;           /* PPSS */
2668       msg[11] = 0x11;           /* PPS0: PPS1, Protocol T=1 */
2669       msg[12] = param[0];       /* PPS1: Fi / Di */
2670       msg[13] = 0xff ^ 0x11 ^ param[0]; /* PCK */
2671       set_msg_len (msg, 4);
2672       msglen = 10 + 4;
2673
2674       rc = bulk_out (handle, msg, msglen, 0);
2675       if (rc)
2676         return rc;
2677
2678       rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_DataBlock,
2679                     seqno, 5000, 0);
2680       if (rc)
2681         return rc;
2682
2683       if (msglen != 10 + 4)
2684         {
2685           DEBUGOUT_1 ("Setting PPS failed: %d\n", (int)msglen);
2686           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2687         }
2688
2689       if (msg[10] != 0xff || msg[11] != 0x11 || msg[12] != param[0])
2690         {
2691           DEBUGOUT_1 ("Setting PPS failed: 0x%02x\n", param[0]);
2692           return CCID_DRIVER_ERR_CARD_IO_ERROR;
2693         }
2694     }
2695
2696   /* Setup parameters to select T=1. */
2697   msg[0] = PC_to_RDR_SetParameters;
2698   msg[5] = 0; /* slot */
2699   msg[6] = seqno = handle->seqno++;
2700   msg[7] = 1; /* Select T=1. */
2701   msg[8] = 0; /* RFU */
2702   msg[9] = 0; /* RFU */
2703
2704   if (!got_param)
2705     memcpy (&msg[10], param, 7);
2706   set_msg_len (msg, 7);
2707   msglen = 10 + 7;
2708
2709   rc = bulk_out (handle, msg, msglen, 0);
2710   if (rc)
2711     return rc;
2712   rc = bulk_in (handle, msg, sizeof msg, &msglen, RDR_to_PC_Parameters,
2713                 seqno, 5000, 0);
2714   if (rc)
2715     DEBUGOUT ("SetParameters failed (ignored)\n");
2716
2717   if (!rc && msglen > 15 && msg[15] >= 16 && msg[15] <= 254 )
2718     handle->ifsc = msg[15];
2719   else
2720     handle->ifsc = 128; /* Something went wrong, assume 128 bytes.  */
2721
2722   if (handle->nonnull_nad && msglen > 16 && msg[16] == 0)
2723     {
2724       DEBUGOUT ("Use Null-NAD, clearing handle->nonnull_nad.\n");
2725       handle->nonnull_nad = 0;
2726     }
2727
2728   handle->t1_ns = 0;
2729   handle->t1_nr = 0;
2730
2731   /* Send an S-Block with our maximum IFSD to the CCID.  */
2732   if (!handle->apdu_level && !handle->auto_ifsd)
2733     {
2734       tpdu = msg+10;
2735       /* NAD: DAD=1, SAD=0 */
2736       tpdu[0] = handle->nonnull_nad? ((1 << 4) | 0): 0;
2737       tpdu[1] = (0xc0 | 0 | 1); /* S-block request: change IFSD */
2738       tpdu[2] = 1;
2739       tpdu[3] = handle->max_ifsd? handle->max_ifsd : 32;
2740       tpdulen = 4;
2741       edc = compute_edc (tpdu, tpdulen, use_crc);
2742       if (use_crc)
2743         tpdu[tpdulen++] = (edc >> 8);
2744       tpdu[tpdulen++] = edc;
2745
2746       msg[0] = PC_to_RDR_XfrBlock;
2747       msg[5] = 0; /* slot */
2748       msg[6] = seqno = handle->seqno++;
2749       msg[7] = 0;
2750       msg[8] = 0; /* RFU */
2751       msg[9] = 0; /* RFU */
2752       set_msg_len (msg, tpdulen);
2753       msglen = 10 + tpdulen;
2754
2755       if (debug_level > 1)
2756         DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
2757                       ((msg[11] & 0xc0) == 0x80)? 'R' :
2758                                 (msg[11] & 0x80)? 'S' : 'I',
2759                       ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2760                                        : !!(msg[11] & 0x40)),
2761                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2762
2763       rc = bulk_out (handle, msg, msglen, 0);
2764       if (rc)
2765         return rc;
2766
2767
2768       rc = bulk_in (handle, msg, sizeof msg, &msglen,
2769                     RDR_to_PC_DataBlock, seqno, 5000, 0);
2770       if (rc)
2771         return rc;
2772
2773       tpdu = msg + 10;
2774       tpdulen = msglen - 10;
2775
2776       if (tpdulen < 4)
2777         return CCID_DRIVER_ERR_ABORTED;
2778
2779       if (debug_level > 1)
2780         DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
2781                     ((msg[11] & 0xc0) == 0x80)? 'R' :
2782                               (msg[11] & 0x80)? 'S' : 'I',
2783                     ((msg[11] & 0x80)? !!(msg[11]& 0x10)
2784                                      : !!(msg[11] & 0x40)),
2785                     ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
2786                     (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
2787
2788       if ((tpdu[1] & 0xe0) != 0xe0 || tpdu[2] != 1)
2789         {
2790           DEBUGOUT ("invalid response for S-block (Change-IFSD)\n");
2791           return -1;
2792         }
2793       DEBUGOUT_1 ("IFSD has been set to %d\n", tpdu[3]);
2794     }
2795
2796   return 0;
2797 }
2798
2799
2800 \f
2801
2802 static unsigned int
2803 compute_edc (const unsigned char *data, size_t datalen, int use_crc)
2804 {
2805   if (use_crc)
2806     {
2807       return 0x42; /* Not yet implemented. */
2808     }
2809   else
2810     {
2811       unsigned char crc = 0;
2812
2813       for (; datalen; datalen--)
2814         crc ^= *data++;
2815       return crc;
2816     }
2817 }
2818
2819
2820 /* Return true if APDU is an extended length one.  */
2821 static int
2822 is_exlen_apdu (const unsigned char *apdu, size_t apdulen)
2823 {
2824   if (apdulen < 7 || apdu[4])
2825     return 0;  /* Too short or no Z byte.  */
2826   return 1;
2827 }
2828
2829
2830 /* Helper for ccid_transceive used for APDU level exchanges.  */
2831 static int
2832 ccid_transceive_apdu_level (ccid_driver_t handle,
2833                             const unsigned char *apdu_buf, size_t apdu_buflen,
2834                             unsigned char *resp, size_t maxresplen,
2835                             size_t *nresp)
2836 {
2837   int rc;
2838   unsigned char send_buffer[10+261+300], recv_buffer[10+261+300];
2839   const unsigned char *apdu;
2840   size_t apdulen;
2841   unsigned char *msg;
2842   size_t msglen;
2843   unsigned char seqno;
2844   int bwi = 4;
2845
2846   msg = send_buffer;
2847
2848   apdu = apdu_buf;
2849   apdulen = apdu_buflen;
2850   assert (apdulen);
2851
2852   /* The maximum length for a short APDU T=1 block is 261.  For an
2853      extended APDU T=1 block the maximum length 65544; however
2854      extended APDU exchange level is not fully supported yet.  */
2855   if (apdulen > sizeof (send_buffer) - 10)
2856     return CCID_DRIVER_ERR_INV_VALUE; /* Invalid length. */
2857
2858   msg[0] = PC_to_RDR_XfrBlock;
2859   msg[5] = 0; /* slot */
2860   msg[6] = seqno = handle->seqno++;
2861   msg[7] = bwi; /* bBWI */
2862   msg[8] = 0; /* RFU */
2863   msg[9] = 0; /* RFU */
2864   memcpy (msg+10, apdu, apdulen);
2865   set_msg_len (msg, apdulen);
2866   msglen = 10 + apdulen;
2867
2868   rc = bulk_out (handle, msg, msglen, 0);
2869   if (rc)
2870     return rc;
2871
2872   msg = recv_buffer;
2873   rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
2874                 RDR_to_PC_DataBlock, seqno, 5000, 0);
2875   if (rc)
2876     return rc;
2877
2878   if (msg[9] == 1)
2879     {
2880       size_t total_msglen = msglen;
2881
2882       while (1)
2883         {
2884           unsigned char status;
2885
2886           msg = recv_buffer + total_msglen;
2887
2888           msg[0] = PC_to_RDR_XfrBlock;
2889           msg[5] = 0; /* slot */
2890           msg[6] = seqno = handle->seqno++;
2891           msg[7] = bwi; /* bBWI */
2892           msg[8] = 0x10;                /* Request next data block */
2893           msg[9] = 0;
2894           set_msg_len (msg, 0);
2895           msglen = 10;
2896
2897           rc = bulk_out (handle, msg, msglen, 0);
2898           if (rc)
2899             return rc;
2900
2901           rc = bulk_in (handle, msg, sizeof recv_buffer - total_msglen, &msglen,
2902                         RDR_to_PC_DataBlock, seqno, 5000, 0);
2903           if (rc)
2904             return rc;
2905           status = msg[9];
2906           memmove (msg, msg+10, msglen - 10);
2907           total_msglen += msglen - 10;
2908           if (total_msglen >= sizeof recv_buffer)
2909             return CCID_DRIVER_ERR_OUT_OF_CORE;
2910
2911           if (status == 0x02)
2912             break;
2913         }
2914
2915       apdu = recv_buffer + 10;
2916       apdulen = total_msglen - 10;
2917     }
2918   else
2919     {
2920       apdu = msg + 10;
2921       apdulen = msglen - 10;
2922     }
2923
2924   if (resp)
2925     {
2926       if (apdulen > maxresplen)
2927         {
2928           DEBUGOUT_2 ("provided buffer too short for received data "
2929                       "(%u/%u)\n",
2930                       (unsigned int)apdulen, (unsigned int)maxresplen);
2931           return CCID_DRIVER_ERR_INV_VALUE;
2932         }
2933
2934       memcpy (resp, apdu, apdulen);
2935       *nresp = apdulen;
2936     }
2937
2938   return 0;
2939 }
2940
2941
2942
2943 /*
2944   Protocol T=1 overview
2945
2946   Block Structure:
2947            Prologue Field:
2948    1 byte     Node Address (NAD)
2949    1 byte     Protocol Control Byte (PCB)
2950    1 byte     Length (LEN)
2951            Information Field:
2952    0-254 byte APDU or Control Information (INF)
2953            Epilogue Field:
2954    1 byte     Error Detection Code (EDC)
2955
2956   NAD:
2957    bit 7     unused
2958    bit 4..6  Destination Node Address (DAD)
2959    bit 3     unused
2960    bit 2..0  Source Node Address (SAD)
2961
2962    If node adresses are not used, SAD and DAD should be set to 0 on
2963    the first block sent to the card.  If they are used they should
2964    have different values (0 for one is okay); that first block sets up
2965    the addresses of the nodes.
2966
2967   PCB:
2968    Information Block (I-Block):
2969       bit 7    0
2970       bit 6    Sequence number (yep, that is modulo 2)
2971       bit 5    Chaining flag
2972       bit 4..0 reserved
2973    Received-Ready Block (R-Block):
2974       bit 7    1
2975       bit 6    0
2976       bit 5    0
2977       bit 4    Sequence number
2978       bit 3..0  0 = no error
2979                 1 = EDC or parity error
2980                 2 = other error
2981                 other values are reserved
2982    Supervisory Block (S-Block):
2983       bit 7    1
2984       bit 6    1
2985       bit 5    clear=request,set=response
2986       bit 4..0  0 = resyncronisation request
2987                 1 = information field size request
2988                 2 = abort request
2989                 3 = extension of BWT request
2990                 4 = VPP error
2991                 other values are reserved
2992
2993 */
2994
2995 int
2996 ccid_transceive (ccid_driver_t handle,
2997                  const unsigned char *apdu_buf, size_t apdu_buflen,
2998                  unsigned char *resp, size_t maxresplen, size_t *nresp)
2999 {
3000   int rc;
3001   /* The size of the buffer used to be 10+259.  For the via_escape
3002      hack we need one extra byte, thus 11+259.  */
3003   unsigned char send_buffer[11+259], recv_buffer[11+259];
3004   const unsigned char *apdu;
3005   size_t apdulen;
3006   unsigned char *msg, *tpdu, *p;
3007   size_t msglen, tpdulen, last_tpdulen, n;
3008   unsigned char seqno;
3009   unsigned int edc;
3010   int use_crc = 0;
3011   int hdrlen, pcboff;
3012   size_t dummy_nresp;
3013   int via_escape = 0;
3014   int next_chunk = 1;
3015   int sending = 1;
3016   int retries = 0;
3017   int resyncing = 0;
3018   int nad_byte;
3019
3020   if (!nresp)
3021     nresp = &dummy_nresp;
3022   *nresp = 0;
3023
3024   /* Smarter readers allow to send APDUs directly; divert here. */
3025   if (handle->apdu_level)
3026     {
3027       /* We employ a hack for Omnikey readers which are able to send
3028          TPDUs using an escape sequence.  There is no documentation
3029          but the Windows driver does it this way.  Tested using a
3030          CM6121.  This method works also for the Cherry XX44
3031          keyboards; however there are problems with the
3032          ccid_tranceive_secure which leads to a loss of sync on the
3033          CCID level.  If Cherry wants to make their keyboard work
3034          again, they should hand over some docs. */
3035       if ((handle->id_vendor == VENDOR_OMNIKEY
3036            || (!handle->idev && handle->id_product == TRANSPORT_CM4040))
3037           && handle->apdu_level < 2
3038           && is_exlen_apdu (apdu_buf, apdu_buflen))
3039         via_escape = 1;
3040       else
3041         return ccid_transceive_apdu_level (handle, apdu_buf, apdu_buflen,
3042                                            resp, maxresplen, nresp);
3043     }
3044
3045   /* The other readers we support require sending TPDUs.  */
3046
3047   tpdulen = 0; /* Avoid compiler warning about no initialization. */
3048   msg = send_buffer;
3049   hdrlen = via_escape? 11 : 10;
3050
3051   /* NAD: DAD=1, SAD=0 */
3052   nad_byte = handle->nonnull_nad? ((1 << 4) | 0): 0;
3053   if (via_escape)
3054     nad_byte = 0;
3055
3056   last_tpdulen = 0;  /* Avoid gcc warning (controlled by RESYNCING). */
3057   for (;;)
3058     {
3059       if (next_chunk)
3060         {
3061           next_chunk = 0;
3062
3063           apdu = apdu_buf;
3064           apdulen = apdu_buflen;
3065           assert (apdulen);
3066
3067           /* Construct an I-Block. */
3068           tpdu = msg + hdrlen;
3069           tpdu[0] = nad_byte;
3070           tpdu[1] = ((handle->t1_ns & 1) << 6); /* I-block */
3071           if (apdulen > handle->ifsc )
3072             {
3073               apdulen = handle->ifsc;
3074               apdu_buf += handle->ifsc;
3075               apdu_buflen -= handle->ifsc;
3076               tpdu[1] |= (1 << 5); /* Set more bit. */
3077             }
3078           tpdu[2] = apdulen;
3079           memcpy (tpdu+3, apdu, apdulen);
3080           tpdulen = 3 + apdulen;
3081           edc = compute_edc (tpdu, tpdulen, use_crc);
3082           if (use_crc)
3083             tpdu[tpdulen++] = (edc >> 8);
3084           tpdu[tpdulen++] = edc;
3085         }
3086
3087       if (via_escape)
3088         {
3089           msg[0] = PC_to_RDR_Escape;
3090           msg[5] = 0; /* slot */
3091           msg[6] = seqno = handle->seqno++;
3092           msg[7] = 0; /* RFU */
3093           msg[8] = 0; /* RFU */
3094           msg[9] = 0; /* RFU */
3095           msg[10] = 0x1a; /* Omnikey command to send a TPDU.  */
3096           set_msg_len (msg, 1 + tpdulen);
3097         }
3098       else
3099         {
3100           msg[0] = PC_to_RDR_XfrBlock;
3101           msg[5] = 0; /* slot */
3102           msg[6] = seqno = handle->seqno++;
3103           msg[7] = 4; /* bBWI */
3104           msg[8] = 0; /* RFU */
3105           msg[9] = 0; /* RFU */
3106           set_msg_len (msg, tpdulen);
3107         }
3108       msglen = hdrlen + tpdulen;
3109       if (!resyncing)
3110         last_tpdulen = tpdulen;
3111       pcboff = hdrlen+1;
3112
3113       if (debug_level > 1)
3114         DEBUGOUT_3 ("T=1: put %c-block seq=%d%s\n",
3115                     ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3116                     (msg[pcboff] & 0x80)? 'S' : 'I',
3117                     ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3118                      : !!(msg[pcboff] & 0x40)),
3119                     (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3120                      " [more]":""));
3121
3122       rc = bulk_out (handle, msg, msglen, 0);
3123       if (rc)
3124         return rc;
3125
3126       msg = recv_buffer;
3127       rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3128                     via_escape? RDR_to_PC_Escape : RDR_to_PC_DataBlock,
3129                     seqno, 5000, 0);
3130       if (rc)
3131         return rc;
3132
3133       tpdu = msg + hdrlen;
3134       tpdulen = msglen - hdrlen;
3135       resyncing = 0;
3136
3137       if (tpdulen < 4)
3138         {
3139           usb_clear_halt (handle->idev, handle->ep_bulk_in);
3140           return CCID_DRIVER_ERR_ABORTED;
3141         }
3142
3143       if (debug_level > 1)
3144         DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3145                     ((msg[pcboff] & 0xc0) == 0x80)? 'R' :
3146                               (msg[pcboff] & 0x80)? 'S' : 'I',
3147                     ((msg[pcboff] & 0x80)? !!(msg[pcboff]& 0x10)
3148                      : !!(msg[pcboff] & 0x40)),
3149                     ((msg[pcboff] & 0xc0) == 0x80)? (msg[pcboff] & 0x0f) : 0,
3150                     (!(msg[pcboff] & 0x80) && (msg[pcboff] & 0x20)?
3151                      " [more]":""));
3152
3153       if (!(tpdu[1] & 0x80))
3154         { /* This is an I-block. */
3155           retries = 0;
3156           if (sending)
3157             { /* last block sent was successful. */
3158               handle->t1_ns ^= 1;
3159               sending = 0;
3160             }
3161
3162           if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3163             { /* Reponse does not match our sequence number. */
3164               msg = send_buffer;
3165               tpdu = msg + hdrlen;
3166               tpdu[0] = nad_byte;
3167               tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4 | 2); /* R-block */
3168               tpdu[2] = 0;
3169               tpdulen = 3;
3170               edc = compute_edc (tpdu, tpdulen, use_crc);
3171               if (use_crc)
3172                 tpdu[tpdulen++] = (edc >> 8);
3173               tpdu[tpdulen++] = edc;
3174
3175               continue;
3176             }
3177
3178           handle->t1_nr ^= 1;
3179
3180           p = tpdu + 3; /* Skip the prologue field. */
3181           n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3182           /* fixme: verify the checksum. */
3183           if (resp)
3184             {
3185               if (n > maxresplen)
3186                 {
3187                   DEBUGOUT_2 ("provided buffer too short for received data "
3188                               "(%u/%u)\n",
3189                               (unsigned int)n, (unsigned int)maxresplen);
3190                   return CCID_DRIVER_ERR_INV_VALUE;
3191                 }
3192
3193               memcpy (resp, p, n);
3194               resp += n;
3195               *nresp += n;
3196               maxresplen -= n;
3197             }
3198
3199           if (!(tpdu[1] & 0x20))
3200             return 0; /* No chaining requested - ready. */
3201
3202           msg = send_buffer;
3203           tpdu = msg + hdrlen;
3204           tpdu[0] = nad_byte;
3205           tpdu[1] = (0x80 | (handle->t1_nr & 1) << 4); /* R-block */
3206           tpdu[2] = 0;
3207           tpdulen = 3;
3208           edc = compute_edc (tpdu, tpdulen, use_crc);
3209           if (use_crc)
3210             tpdu[tpdulen++] = (edc >> 8);
3211           tpdu[tpdulen++] = edc;
3212         }
3213       else if ((tpdu[1] & 0xc0) == 0x80)
3214         { /* This is a R-block. */
3215           if ( (tpdu[1] & 0x0f))
3216             {
3217               retries++;
3218               if (via_escape && retries == 1 && (msg[pcboff] & 0x0f))
3219                 {
3220                   /* Error probably due to switching to TPDU.  Send a
3221                      resync request.  We use the recv_buffer so that
3222                      we don't corrupt the send_buffer.  */
3223                   msg = recv_buffer;
3224                   tpdu = msg + hdrlen;
3225                   tpdu[0] = nad_byte;
3226                   tpdu[1] = 0xc0; /* S-block resync request. */
3227                   tpdu[2] = 0;
3228                   tpdulen = 3;
3229                   edc = compute_edc (tpdu, tpdulen, use_crc);
3230                   if (use_crc)
3231                     tpdu[tpdulen++] = (edc >> 8);
3232                   tpdu[tpdulen++] = edc;
3233                   resyncing = 1;
3234                   DEBUGOUT ("T=1: requesting resync\n");
3235                 }
3236               else if (retries > 3)
3237                 {
3238                   DEBUGOUT ("T=1: 3 failed retries\n");
3239                   return CCID_DRIVER_ERR_CARD_IO_ERROR;
3240                 }
3241               else
3242                 {
3243                   /* Error: repeat last block */
3244                   msg = send_buffer;
3245                   tpdulen = last_tpdulen;
3246                 }
3247             }
3248           else if (sending && !!(tpdu[1] & 0x10) == handle->t1_ns)
3249             { /* Response does not match our sequence number. */
3250               DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3251               return CCID_DRIVER_ERR_CARD_IO_ERROR;
3252             }
3253           else if (sending)
3254             { /* Send next chunk. */
3255               retries = 0;
3256               msg = send_buffer;
3257               next_chunk = 1;
3258               handle->t1_ns ^= 1;
3259             }
3260           else
3261             {
3262               DEBUGOUT ("unexpected ACK R-block received\n");
3263               return CCID_DRIVER_ERR_CARD_IO_ERROR;
3264             }
3265         }
3266       else
3267         { /* This is a S-block. */
3268           retries = 0;
3269           DEBUGOUT_2 ("T=1: S-block %s received cmd=%d\n",
3270                       (tpdu[1] & 0x20)? "response": "request",
3271                       (tpdu[1] & 0x1f));
3272           if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 1 && tpdu[2] == 1)
3273             {
3274               /* Information field size request.  */
3275               unsigned char ifsc = tpdu[3];
3276
3277               if (ifsc < 16 || ifsc > 254)
3278                 return CCID_DRIVER_ERR_CARD_IO_ERROR;
3279
3280               msg = send_buffer;
3281               tpdu = msg + hdrlen;
3282               tpdu[0] = nad_byte;
3283               tpdu[1] = (0xc0 | 0x20 | 1); /* S-block response */
3284               tpdu[2] = 1;
3285               tpdu[3] = ifsc;
3286               tpdulen = 4;
3287               edc = compute_edc (tpdu, tpdulen, use_crc);
3288               if (use_crc)
3289                 tpdu[tpdulen++] = (edc >> 8);
3290               tpdu[tpdulen++] = edc;
3291               DEBUGOUT_1 ("T=1: requesting an ifsc=%d\n", ifsc);
3292             }
3293           else if ( !(tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 3 && tpdu[2])
3294             {
3295               /* Wait time extension request. */
3296               unsigned char bwi = tpdu[3];
3297               msg = send_buffer;
3298               tpdu = msg + hdrlen;
3299               tpdu[0] = nad_byte;
3300               tpdu[1] = (0xc0 | 0x20 | 3); /* S-block response */
3301               tpdu[2] = 1;
3302               tpdu[3] = bwi;
3303               tpdulen = 4;
3304               edc = compute_edc (tpdu, tpdulen, use_crc);
3305               if (use_crc)
3306                 tpdu[tpdulen++] = (edc >> 8);
3307               tpdu[tpdulen++] = edc;
3308               DEBUGOUT_1 ("T=1: waittime extension of bwi=%d\n", bwi);
3309               print_progress (handle);
3310             }
3311           else if ( (tpdu[1] & 0x20) && (tpdu[1] & 0x1f) == 0 && !tpdu[2])
3312             {
3313               DEBUGOUT ("T=1: resync ack from reader\n");
3314               /* Repeat previous block.  */
3315               msg = send_buffer;
3316               tpdulen = last_tpdulen;
3317             }
3318           else
3319             return CCID_DRIVER_ERR_CARD_IO_ERROR;
3320         }
3321     } /* end T=1 protocol loop. */
3322
3323   return 0;
3324 }
3325
3326
3327 /* Send the CCID Secure command to the reader.  APDU_BUF should
3328    contain the APDU template.  PIN_MODE defines how the pin gets
3329    formatted:
3330
3331      1 := The PIN is ASCII encoded and of variable length.  The
3332           length of the PIN entered will be put into Lc by the reader.
3333           The APDU should me made up of 4 bytes without Lc.
3334
3335    PINLEN_MIN and PINLEN_MAX define the limits for the pin length. 0
3336    may be used t enable reasonable defaults.
3337
3338    When called with RESP and NRESP set to NULL, the function will
3339    merely check whether the reader supports the secure command for the
3340    given APDU and PIN_MODE. */
3341 int
3342 ccid_transceive_secure (ccid_driver_t handle,
3343                         const unsigned char *apdu_buf, size_t apdu_buflen,
3344                         pininfo_t *pininfo,
3345                         unsigned char *resp, size_t maxresplen, size_t *nresp)
3346 {
3347   int rc;
3348   unsigned char send_buffer[10+259], recv_buffer[10+259];
3349   unsigned char *msg, *tpdu, *p;
3350   size_t msglen, tpdulen, n;
3351   unsigned char seqno;
3352   size_t dummy_nresp;
3353   int testmode;
3354   int cherry_mode = 0;
3355   int enable_varlen = 0;
3356
3357   testmode = !resp && !nresp;
3358
3359   if (!nresp)
3360     nresp = &dummy_nresp;
3361   *nresp = 0;
3362
3363   if (apdu_buflen >= 4 && apdu_buf[1] == 0x20 && (handle->has_pinpad & 1))
3364     ;
3365   else if (apdu_buflen >= 4 && apdu_buf[1] == 0x24 && (handle->has_pinpad & 2))
3366     ;
3367   else
3368     return CCID_DRIVER_ERR_NO_PINPAD;
3369
3370   if (!pininfo->minlen)
3371     pininfo->minlen = 1;
3372   if (!pininfo->maxlen)
3373     pininfo->maxlen = 15;
3374
3375   /* Note that the 25 is the maximum value the SPR532 allows.  */
3376   if (pininfo->minlen < 1 || pininfo->minlen > 25
3377       || pininfo->maxlen < 1 || pininfo->maxlen > 25
3378       || pininfo->minlen > pininfo->maxlen)
3379     return CCID_DRIVER_ERR_INV_VALUE;
3380
3381   /* We have only tested a few readers so better don't risk anything
3382      and do not allow the use with other readers. */
3383   switch (handle->id_vendor)
3384     {
3385     case VENDOR_SCM:  /* Tested with SPR 532. */
3386     case VENDOR_KAAN: /* Tested with KAAN Advanced (1.02). */
3387     case VENDOR_FSIJ: /* Tested with Gnuk (0.21). */
3388       pininfo->maxlen = 25;
3389       enable_varlen = 1;
3390       break;
3391     case VENDOR_REINER: /* Tested with cyberJack go */
3392     case VENDOR_VASCO: /* Tested with DIGIPASS 920 */
3393       enable_varlen = 1;
3394       break;
3395     case VENDOR_CHERRY:
3396       pininfo->maxlen = 25;
3397       enable_varlen = 1;
3398       /* The CHERRY XX44 keyboard echos an asterisk for each entered
3399          character on the keyboard channel.  We use a special variant
3400          of PC_to_RDR_Secure which directs these characters to the
3401          smart card's bulk-in channel.  We also need to append a zero
3402          Lc byte to the APDU.  It seems that it will be replaced with
3403          the actual length instead of being appended before the APDU
3404          is send to the card. */
3405       if (handle->id_product != CHERRY_ST2000)
3406         cherry_mode = 1;
3407       break;
3408     default:
3409       if ((handle->id_vendor == VENDOR_GEMPC &&
3410            handle->id_product == GEMPC_PINPAD)
3411           || (handle->id_vendor == VENDOR_VEGA &&
3412               handle->id_product == VEGA_ALPHA))
3413         {
3414           enable_varlen = 0;
3415           pininfo->minlen = 4;
3416           pininfo->maxlen = 8;
3417           break;
3418         }
3419      return CCID_DRIVER_ERR_NOT_SUPPORTED;
3420     }
3421
3422   if (enable_varlen)
3423     pininfo->fixedlen = 0;
3424
3425   if (testmode)
3426     return 0; /* Success */
3427
3428   if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
3429     return CCID_DRIVER_ERR_NOT_SUPPORTED;
3430
3431   msg = send_buffer;
3432   if (handle->id_vendor == VENDOR_SCM)
3433     {
3434       DEBUGOUT ("sending escape sequence to switch to a case 1 APDU\n");
3435       rc = send_escape_cmd (handle, (const unsigned char*)"\x80\x02\x00", 3,
3436                             NULL, 0, NULL);
3437       if (rc)
3438         return rc;
3439     }
3440
3441   msg[0] = cherry_mode? 0x89 : PC_to_RDR_Secure;
3442   msg[5] = 0; /* slot */
3443   msg[6] = seqno = handle->seqno++;
3444   msg[7] = 0; /* bBWI */
3445   msg[8] = 0; /* RFU */
3446   msg[9] = 0; /* RFU */
3447   msg[10] = apdu_buf[1] == 0x20 ? 0 : 1;
3448                /* Perform PIN verification or PIN modification. */
3449   msg[11] = 0; /* Timeout in seconds. */
3450   msg[12] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
3451   if (handle->id_vendor == VENDOR_SCM)
3452     {
3453       /* For the SPR532 the next 2 bytes need to be zero.  We do this
3454          for all SCM products.  Kudos to Martin Paljak for this
3455          hint.  */
3456       msg[13] = msg[14] = 0;
3457     }
3458   else
3459     {
3460       msg[13] = pininfo->fixedlen; /* bmPINBlockString:
3461                                       0 bits of pin length to insert.
3462                                       PIN block size by fixedlen.  */
3463       msg[14] = 0x00; /* bmPINLengthFormat:
3464                          Units are bytes, position is 0. */
3465     }
3466
3467   msglen = 15;
3468   if (apdu_buf[1] == 0x24)
3469     {
3470       msg[msglen++] = 0;    /* bInsertionOffsetOld */
3471       msg[msglen++] = pininfo->fixedlen;    /* bInsertionOffsetNew */
3472     }
3473
3474   /* The following is a little endian word. */
3475   msg[msglen++] = pininfo->maxlen;   /* wPINMaxExtraDigit-Maximum.  */
3476   msg[msglen++] = pininfo->minlen;   /* wPINMaxExtraDigit-Minimum.  */
3477
3478   if (apdu_buf[1] == 0x24)
3479     msg[msglen++] = apdu_buf[2] == 0 ? 0x03 : 0x01;
3480               /* bConfirmPIN
3481                *    0x00: new PIN once
3482                *    0x01: new PIN twice (confirmation)
3483                *    0x02: old PIN and new PIN once
3484                *    0x03: old PIN and new PIN twice (confirmation)
3485                */
3486
3487   msg[msglen] = 0x02; /* bEntryValidationCondition:
3488                          Validation key pressed */
3489   if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
3490     msg[msglen] |= 0x01; /* Max size reached.  */
3491   msglen++;
3492
3493   if (apdu_buf[1] == 0x20)
3494     msg[msglen++] = 0x01; /* bNumberMessage. */
3495   else
3496     msg[msglen++] = 0x03; /* bNumberMessage. */
3497
3498   msg[msglen++] = 0x09; /* wLangId-Low:  English FIXME: use the first entry. */
3499   msg[msglen++] = 0x04; /* wLangId-High. */
3500
3501   if (apdu_buf[1] == 0x20)
3502     msg[msglen++] = 0;    /* bMsgIndex. */
3503   else
3504     {
3505       msg[msglen++] = 0;    /* bMsgIndex1. */
3506       msg[msglen++] = 1;    /* bMsgIndex2. */
3507       msg[msglen++] = 2;    /* bMsgIndex3. */
3508     }
3509
3510   /* Calculate Lc.  */
3511   n = pininfo->fixedlen;
3512   if (apdu_buf[1] == 0x24)
3513     n += pininfo->fixedlen;
3514
3515   /* bTeoProlog follows: */
3516   msg[msglen++] = handle->nonnull_nad? ((1 << 4) | 0): 0;
3517   msg[msglen++] = ((handle->t1_ns & 1) << 6); /* I-block */
3518   if (n)
3519     msg[msglen++] = n + 5; /* apdulen should be filled for fixed length.  */
3520   else
3521     msg[msglen++] = 0; /* The apdulen will be filled in by the reader.  */
3522   /* APDU follows:  */
3523   msg[msglen++] = apdu_buf[0]; /* CLA */
3524   msg[msglen++] = apdu_buf[1]; /* INS */
3525   msg[msglen++] = apdu_buf[2]; /* P1 */
3526   msg[msglen++] = apdu_buf[3]; /* P2 */
3527   if (cherry_mode)
3528     msg[msglen++] = 0;
3529   else if (pininfo->fixedlen != 0)
3530     {
3531       msg[msglen++] = n;
3532       memset (&msg[msglen], 0xff, n);
3533       msglen += n;
3534     }
3535   /* An EDC is not required. */
3536   set_msg_len (msg, msglen - 10);
3537
3538   rc = bulk_out (handle, msg, msglen, 0);
3539   if (rc)
3540     return rc;
3541
3542   msg = recv_buffer;
3543   rc = bulk_in (handle, msg, sizeof recv_buffer, &msglen,
3544                 RDR_to_PC_DataBlock, seqno, 30000, 0);
3545   if (rc)
3546     return rc;
3547
3548   tpdu = msg + 10;
3549   tpdulen = msglen - 10;
3550
3551   if (handle->apdu_level)
3552     {
3553       if (resp)
3554         {
3555           if (tpdulen > maxresplen)
3556             {
3557               DEBUGOUT_2 ("provided buffer too short for received data "
3558                           "(%u/%u)\n",
3559                           (unsigned int)tpdulen, (unsigned int)maxresplen);
3560               return CCID_DRIVER_ERR_INV_VALUE;
3561             }
3562
3563           memcpy (resp, tpdu, tpdulen);
3564           *nresp = tpdulen;
3565         }
3566       return 0;
3567     }
3568
3569   if (tpdulen < 4)
3570     {
3571       usb_clear_halt (handle->idev, handle->ep_bulk_in);
3572       return CCID_DRIVER_ERR_ABORTED;
3573     }
3574   if (debug_level > 1)
3575     DEBUGOUT_4 ("T=1: got %c-block seq=%d err=%d%s\n",
3576                 ((msg[11] & 0xc0) == 0x80)? 'R' :
3577                           (msg[11] & 0x80)? 'S' : 'I',
3578                 ((msg[11] & 0x80)? !!(msg[11]& 0x10) : !!(msg[11] & 0x40)),
3579                 ((msg[11] & 0xc0) == 0x80)? (msg[11] & 0x0f) : 0,
3580                 (!(msg[11] & 0x80) && (msg[11] & 0x20)? " [more]":""));
3581
3582   if (!(tpdu[1] & 0x80))
3583     { /* This is an I-block. */
3584       /* Last block sent was successful. */
3585       handle->t1_ns ^= 1;
3586
3587       if (!!(tpdu[1] & 0x40) != handle->t1_nr)
3588         { /* Reponse does not match our sequence number. */
3589           DEBUGOUT ("I-block with wrong seqno received\n");
3590           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3591         }
3592
3593       handle->t1_nr ^= 1;
3594
3595       p = tpdu + 3; /* Skip the prologue field. */
3596       n = tpdulen - 3 - 1; /* Strip the epilogue field. */
3597       /* fixme: verify the checksum. */
3598       if (resp)
3599         {
3600           if (n > maxresplen)
3601             {
3602               DEBUGOUT_2 ("provided buffer too short for received data "
3603                           "(%u/%u)\n",
3604                           (unsigned int)n, (unsigned int)maxresplen);
3605               return CCID_DRIVER_ERR_INV_VALUE;
3606             }
3607
3608           memcpy (resp, p, n);
3609           resp += n;
3610           *nresp += n;
3611           maxresplen -= n;
3612         }
3613
3614       if (!(tpdu[1] & 0x20))
3615         return 0; /* No chaining requested - ready. */
3616
3617       DEBUGOUT ("chaining requested but not supported for Secure operation\n");
3618       return CCID_DRIVER_ERR_CARD_IO_ERROR;
3619     }
3620   else if ((tpdu[1] & 0xc0) == 0x80)
3621     { /* This is a R-block. */
3622       if ( (tpdu[1] & 0x0f))
3623         { /* Error: repeat last block */
3624           DEBUGOUT ("No retries supported for Secure operation\n");
3625           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3626         }
3627       else if (!!(tpdu[1] & 0x10) == handle->t1_ns)
3628         { /* Reponse does not match our sequence number. */
3629           DEBUGOUT ("R-block with wrong seqno received on more bit\n");
3630           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3631         }
3632       else
3633         { /* Send next chunk. */
3634           DEBUGOUT ("chaining not supported on Secure operation\n");
3635           return CCID_DRIVER_ERR_CARD_IO_ERROR;
3636         }
3637     }
3638   else
3639     { /* This is a S-block. */
3640       DEBUGOUT_2 ("T=1: S-block %s received cmd=%d for Secure operation\n",
3641                   (tpdu[1] & 0x20)? "response": "request",
3642                   (tpdu[1] & 0x1f));
3643       return CCID_DRIVER_ERR_CARD_IO_ERROR;
3644     }
3645
3646   return 0;
3647 }
3648
3649
3650
3651
3652 #ifdef TEST
3653
3654
3655 static void
3656 print_error (int err)
3657 {
3658   const char *p;
3659   char buf[50];
3660
3661   switch (err)
3662     {
3663     case 0: p = "success";
3664     case CCID_DRIVER_ERR_OUT_OF_CORE: p = "out of core"; break;
3665     case CCID_DRIVER_ERR_INV_VALUE: p = "invalid value"; break;
3666     case CCID_DRIVER_ERR_NO_DRIVER: p = "no driver"; break;
3667     case CCID_DRIVER_ERR_NOT_SUPPORTED: p = "not supported"; break;
3668     case CCID_DRIVER_ERR_LOCKING_FAILED: p = "locking failed"; break;
3669     case CCID_DRIVER_ERR_BUSY: p = "busy"; break;
3670     case CCID_DRIVER_ERR_NO_CARD: p = "no card"; break;
3671     case CCID_DRIVER_ERR_CARD_INACTIVE: p = "card inactive"; break;
3672     case CCID_DRIVER_ERR_CARD_IO_ERROR: p = "card I/O error"; break;
3673     case CCID_DRIVER_ERR_GENERAL_ERROR: p = "general error"; break;
3674     case CCID_DRIVER_ERR_NO_READER: p = "no reader"; break;
3675     case CCID_DRIVER_ERR_ABORTED: p = "aborted"; break;
3676     default: sprintf (buf, "0x%05x", err); p = buf; break;
3677     }
3678   fprintf (stderr, "operation failed: %s\n", p);
3679 }
3680
3681
3682 static void
3683 print_data (const unsigned char *data, size_t length)
3684 {
3685   if (length >= 2)
3686     {
3687       fprintf (stderr, "operation status: %02X%02X\n",
3688                data[length-2], data[length-1]);
3689       length -= 2;
3690     }
3691   if (length)
3692     {
3693         fputs ("   returned data:", stderr);
3694         for (; length; length--, data++)
3695           fprintf (stderr, " %02X", *data);
3696         putc ('\n', stderr);
3697     }
3698 }
3699
3700 static void
3701 print_result (int rc, const unsigned char *data, size_t length)
3702 {
3703   if (rc)
3704     print_error (rc);
3705   else if (data)
3706     print_data (data, length);
3707 }
3708
3709 int
3710 main (int argc, char **argv)
3711 {
3712   int rc;
3713   ccid_driver_t ccid;
3714   int slotstat;
3715   unsigned char result[512];
3716   size_t resultlen;
3717   int no_pinpad = 0;
3718   int verify_123456 = 0;
3719   int did_verify = 0;
3720   int no_poll = 0;
3721
3722   if (argc)
3723     {
3724       argc--;
3725       argv++;
3726     }
3727
3728   while (argc)
3729     {
3730       if ( !strcmp (*argv, "--list"))
3731         {
3732           char *p;
3733           p = ccid_get_reader_list ();
3734           if (!p)
3735             return 1;
3736           fputs (p, stderr);
3737           free (p);
3738           return 0;
3739         }
3740       else if ( !strcmp (*argv, "--debug"))
3741         {
3742           ccid_set_debug_level (ccid_set_debug_level (-1)+1);
3743           argc--; argv++;
3744         }
3745       else if ( !strcmp (*argv, "--no-poll"))
3746         {
3747           no_poll = 1;
3748           argc--; argv++;
3749         }
3750       else if ( !strcmp (*argv, "--no-pinpad"))
3751         {
3752           no_pinpad = 1;
3753           argc--; argv++;
3754         }
3755       else if ( !strcmp (*argv, "--verify-123456"))
3756         {
3757           verify_123456 = 1;
3758           argc--; argv++;
3759         }
3760       else
3761         break;
3762     }
3763
3764   rc = ccid_open_reader (&ccid, argc? *argv:NULL);
3765   if (rc)
3766     return 1;
3767
3768   if (!no_poll)
3769     ccid_poll (ccid);
3770   fputs ("getting ATR ...\n", stderr);
3771   rc = ccid_get_atr (ccid, NULL, 0, NULL);
3772   if (rc)
3773     {
3774       print_error (rc);
3775       return 1;
3776     }
3777
3778   if (!no_poll)
3779     ccid_poll (ccid);
3780   fputs ("getting slot status ...\n", stderr);
3781   rc = ccid_slot_status (ccid, &slotstat);
3782   if (rc)
3783     {
3784       print_error (rc);
3785       return 1;
3786     }
3787
3788   if (!no_poll)
3789     ccid_poll (ccid);
3790
3791   fputs ("selecting application OpenPGP ....\n", stderr);
3792   {
3793     static unsigned char apdu[] = {
3794       0, 0xA4, 4, 0, 6, 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01};
3795     rc = ccid_transceive (ccid,
3796                           apdu, sizeof apdu,
3797                           result, sizeof result, &resultlen);
3798     print_result (rc, result, resultlen);
3799   }
3800
3801
3802   if (!no_poll)
3803     ccid_poll (ccid);
3804
3805   fputs ("getting OpenPGP DO 0x65 ....\n", stderr);
3806   {
3807     static unsigned char apdu[] = { 0, 0xCA, 0, 0x65, 254 };
3808     rc = ccid_transceive (ccid, apdu, sizeof apdu,
3809                           result, sizeof result, &resultlen);
3810     print_result (rc, result, resultlen);
3811   }
3812
3813   if (!no_pinpad)
3814     {
3815     }
3816
3817   if (!no_pinpad)
3818     {
3819       static unsigned char apdu[] = { 0, 0x20, 0, 0x81 };
3820
3821
3822       if (ccid_transceive_secure (ccid,
3823                                   apdu, sizeof apdu,
3824                                   1, 0, 0, 0,
3825                                   NULL, 0, NULL))
3826         fputs ("can't verify using a PIN-Pad reader\n", stderr);
3827       else
3828         {
3829           fputs ("verifying CHV1 using the PINPad ....\n", stderr);
3830
3831           rc = ccid_transceive_secure (ccid,
3832                                        apdu, sizeof apdu,
3833                                        1, 0, 0, 0,
3834                                        result, sizeof result, &resultlen);
3835           print_result (rc, result, resultlen);
3836           did_verify = 1;
3837         }
3838     }
3839
3840   if (verify_123456 && !did_verify)
3841     {
3842       fputs ("verifying that CHV1 is 123456....\n", stderr);
3843       {
3844         static unsigned char apdu[] = {0, 0x20, 0, 0x81,
3845                                        6, '1','2','3','4','5','6'};
3846         rc = ccid_transceive (ccid, apdu, sizeof apdu,
3847                               result, sizeof result, &resultlen);
3848         print_result (rc, result, resultlen);
3849       }
3850     }
3851
3852   if (!rc)
3853     {
3854       fputs ("getting OpenPGP DO 0x5E ....\n", stderr);
3855       {
3856         static unsigned char apdu[] = { 0, 0xCA, 0, 0x5E, 254 };
3857         rc = ccid_transceive (ccid, apdu, sizeof apdu,
3858                               result, sizeof result, &resultlen);
3859         print_result (rc, result, resultlen);
3860       }
3861     }
3862
3863   ccid_close_reader (ccid);
3864
3865   return 0;
3866 }
3867
3868 /*
3869  * Local Variables:
3870  *  compile-command: "gcc -DTEST -Wall -I/usr/local/include -lusb -g ccid-driver.c"
3871  * End:
3872  */
3873 #endif /*TEST*/
3874 #endif /*HAVE_LIBUSB*/