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