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