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