chiark / gitweb /
38ebd2be5b4f62c57ab8b17f97e8751918b6c2b9
[gnupg2.git] / scd / apdu.c
1 /* apdu.c - ISO 7816 APDU functions and low level I/O
2  * Copyright (C) 2003, 2004, 2008, 2009, 2010,
3  *               2011 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 /* NOTE: This module is also used by other software, thus the use of
22    the macro USE_NPTH is mandatory.  For GnuPG this macro is
23    guaranteed to be defined true. */
24
25 #include <config.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <assert.h>
31 #include <signal.h>
32 #ifdef USE_NPTH
33 # include <unistd.h>
34 # include <fcntl.h>
35 # include <npth.h>
36 #endif
37
38
39 /* If requested include the definitions for the remote APDU protocol
40    code. */
41 #ifdef USE_G10CODE_RAPDU
42 #include "rapdu.h"
43 #endif /*USE_G10CODE_RAPDU*/
44
45 #if defined(GNUPG_SCD_MAIN_HEADER)
46 #include GNUPG_SCD_MAIN_HEADER
47 #elif GNUPG_MAJOR_VERSION == 1
48 /* This is used with GnuPG version < 1.9.  The code has been source
49    copied from the current GnuPG >= 1.9  and is maintained over
50    there. */
51 #include "options.h"
52 #include "errors.h"
53 #include "memory.h"
54 #include "util.h"
55 #include "i18n.h"
56 #include "dynload.h"
57 #include "cardglue.h"
58 #else /* GNUPG_MAJOR_VERSION != 1 */
59 #include "scdaemon.h"
60 #include "exechelp.h"
61 #endif /* GNUPG_MAJOR_VERSION != 1 */
62 #include "host2net.h"
63
64 #include "iso7816.h"
65 #include "apdu.h"
66 #define CCID_DRIVER_INCLUDE_USB_IDS 1
67 #include "ccid-driver.h"
68
69 struct dev_list {
70   struct ccid_dev_table *ccid_table;
71   const char *portstr;
72   int idx;
73   int idx_max;
74 };
75
76 /* Due to conflicting use of threading libraries we usually can't link
77    against libpcsclite if we are using Pth.  Instead we use a wrapper
78    program.  Note that with nPth there is no need for a wrapper. */
79 #ifdef USE_PTH  /* Right, plain old Pth.  */
80 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
81 #define NEED_PCSC_WRAPPER 1
82 #endif
83 #endif
84
85
86 #define MAX_READER 4 /* Number of readers we support concurrently. */
87
88
89 #if defined(_WIN32) || defined(__CYGWIN__)
90 #define DLSTDCALL __stdcall
91 #else
92 #define DLSTDCALL
93 #endif
94
95 #if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
96 typedef unsigned int pcsc_dword_t;
97 #else
98 typedef unsigned long pcsc_dword_t;
99 #endif
100
101 /* A structure to collect information pertaining to one reader
102    slot. */
103 struct reader_table_s {
104   int used;            /* True if slot is used. */
105   unsigned short port; /* Port number:  0 = unused, 1 - dev/tty */
106
107   /* Function pointers intialized to the various backends.  */
108   int (*connect_card)(int);
109   int (*disconnect_card)(int);
110   int (*close_reader)(int);
111   int (*reset_reader)(int);
112   int (*get_status_reader)(int, unsigned int *);
113   int (*send_apdu_reader)(int,unsigned char *,size_t,
114                           unsigned char *, size_t *, pininfo_t *);
115   int (*check_pinpad)(int, int, pininfo_t *);
116   void (*dump_status_reader)(int);
117   int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
118   int (*pinpad_verify)(int, int, int, int, int, pininfo_t *);
119   int (*pinpad_modify)(int, int, int, int, int, pininfo_t *);
120
121   struct {
122     ccid_driver_t handle;
123   } ccid;
124   struct {
125     long context;
126     long card;
127     pcsc_dword_t protocol;
128     pcsc_dword_t verify_ioctl;
129     pcsc_dword_t modify_ioctl;
130     int pinmin;
131     int pinmax;
132 #ifdef NEED_PCSC_WRAPPER
133     int req_fd;
134     int rsp_fd;
135     pid_t pid;
136 #endif /*NEED_PCSC_WRAPPER*/
137   } pcsc;
138 #ifdef USE_G10CODE_RAPDU
139   struct {
140     rapdu_t handle;
141   } rapdu;
142 #endif /*USE_G10CODE_RAPDU*/
143   char *rdrname;     /* Name of the connected reader or NULL if unknown. */
144   int is_t0;         /* True if we know that we are running T=0. */
145   int is_spr532;     /* True if we know that the reader is a SPR532.  */
146   int pinpad_varlen_supported;  /* True if we know that the reader
147                                    supports variable length pinpad
148                                    input.  */
149   unsigned char atr[33];
150   size_t atrlen;           /* A zero length indicates that the ATR has
151                               not yet been read; i.e. the card is not
152                               ready for use. */
153 #ifdef USE_NPTH
154   npth_mutex_t lock;
155 #endif
156 };
157 typedef struct reader_table_s *reader_table_t;
158
159 /* A global table to keep track of active readers. */
160 static struct reader_table_s reader_table[MAX_READER];
161
162 #ifdef USE_NPTH
163 static npth_mutex_t reader_table_lock;
164 #endif
165
166
167 /* ct API function pointer. */
168 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
169 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
170                                    unsigned char *sad, unsigned short lc,
171                                    unsigned char *cmd, unsigned short *lr,
172                                    unsigned char *rsp);
173 static char (* DLSTDCALL CT_close) (unsigned short ctn);
174
175 /* PC/SC constants and function pointer. */
176 #define PCSC_SCOPE_USER      0
177 #define PCSC_SCOPE_TERMINAL  1
178 #define PCSC_SCOPE_SYSTEM    2
179 #define PCSC_SCOPE_GLOBAL    3
180
181 #define PCSC_PROTOCOL_T0     1
182 #define PCSC_PROTOCOL_T1     2
183 #ifdef HAVE_W32_SYSTEM
184 # define PCSC_PROTOCOL_RAW   0x00010000  /* The active protocol.  */
185 #else
186 # define PCSC_PROTOCOL_RAW   4
187 #endif
188
189 #define PCSC_SHARE_EXCLUSIVE 1
190 #define PCSC_SHARE_SHARED    2
191 #define PCSC_SHARE_DIRECT    3
192
193 #define PCSC_LEAVE_CARD      0
194 #define PCSC_RESET_CARD      1
195 #define PCSC_UNPOWER_CARD    2
196 #define PCSC_EJECT_CARD      3
197
198 #ifdef HAVE_W32_SYSTEM
199 # define PCSC_UNKNOWN    0x0000  /* The driver is not aware of the status.  */
200 # define PCSC_ABSENT     0x0001  /* Card is absent.  */
201 # define PCSC_PRESENT    0x0002  /* Card is present.  */
202 # define PCSC_SWALLOWED  0x0003  /* Card is present and electrical connected. */
203 # define PCSC_POWERED    0x0004  /* Card is powered.  */
204 # define PCSC_NEGOTIABLE 0x0005  /* Card is awaiting PTS.  */
205 # define PCSC_SPECIFIC   0x0006  /* Card is ready for use.  */
206 #else
207 # define PCSC_UNKNOWN    0x0001
208 # define PCSC_ABSENT     0x0002  /* Card is absent.  */
209 # define PCSC_PRESENT    0x0004  /* Card is present.  */
210 # define PCSC_SWALLOWED  0x0008  /* Card is present and electrical connected. */
211 # define PCSC_POWERED    0x0010  /* Card is powered.  */
212 # define PCSC_NEGOTIABLE 0x0020  /* Card is awaiting PTS.  */
213 # define PCSC_SPECIFIC   0x0040  /* Card is ready for use.  */
214 #endif
215
216 #define PCSC_STATE_UNAWARE     0x0000  /* Want status.  */
217 #define PCSC_STATE_IGNORE      0x0001  /* Ignore this reader.  */
218 #define PCSC_STATE_CHANGED     0x0002  /* State has changed.  */
219 #define PCSC_STATE_UNKNOWN     0x0004  /* Reader unknown.  */
220 #define PCSC_STATE_UNAVAILABLE 0x0008  /* Status unavailable.  */
221 #define PCSC_STATE_EMPTY       0x0010  /* Card removed.  */
222 #define PCSC_STATE_PRESENT     0x0020  /* Card inserted.  */
223 #define PCSC_STATE_ATRMATCH    0x0040  /* ATR matches card. */
224 #define PCSC_STATE_EXCLUSIVE   0x0080  /* Exclusive Mode.  */
225 #define PCSC_STATE_INUSE       0x0100  /* Shared mode.  */
226 #define PCSC_STATE_MUTE        0x0200  /* Unresponsive card.  */
227 #ifdef HAVE_W32_SYSTEM
228 # define PCSC_STATE_UNPOWERED  0x0400  /* Card not powerred up.  */
229 #endif
230
231 /* Some PC/SC error codes.  */
232 #define PCSC_E_CANCELLED               0x80100002
233 #define PCSC_E_CANT_DISPOSE            0x8010000E
234 #define PCSC_E_INSUFFICIENT_BUFFER     0x80100008
235 #define PCSC_E_INVALID_ATR             0x80100015
236 #define PCSC_E_INVALID_HANDLE          0x80100003
237 #define PCSC_E_INVALID_PARAMETER       0x80100004
238 #define PCSC_E_INVALID_TARGET          0x80100005
239 #define PCSC_E_INVALID_VALUE           0x80100011
240 #define PCSC_E_NO_MEMORY               0x80100006
241 #define PCSC_E_UNKNOWN_READER          0x80100009
242 #define PCSC_E_TIMEOUT                 0x8010000A
243 #define PCSC_E_SHARING_VIOLATION       0x8010000B
244 #define PCSC_E_NO_SMARTCARD            0x8010000C
245 #define PCSC_E_UNKNOWN_CARD            0x8010000D
246 #define PCSC_E_PROTO_MISMATCH          0x8010000F
247 #define PCSC_E_NOT_READY               0x80100010
248 #define PCSC_E_SYSTEM_CANCELLED        0x80100012
249 #define PCSC_E_NOT_TRANSACTED          0x80100016
250 #define PCSC_E_READER_UNAVAILABLE      0x80100017
251 #define PCSC_E_NO_SERVICE              0x8010001D
252 #define PCSC_E_SERVICE_STOPPED         0x8010001E
253 #define PCSC_W_REMOVED_CARD            0x80100069
254
255 /* Fix pcsc-lite ABI incompatibilty.  */
256 #ifndef SCARD_CTL_CODE
257 #ifdef _WIN32
258 #include <winioctl.h>
259 #define SCARD_CTL_CODE(code) CTL_CODE(FILE_DEVICE_SMARTCARD, (code), \
260                                       METHOD_BUFFERED, FILE_ANY_ACCESS)
261 #else
262 #define SCARD_CTL_CODE(code) (0x42000000 + (code))
263 #endif
264 #endif
265
266 #define CM_IOCTL_GET_FEATURE_REQUEST     SCARD_CTL_CODE(3400)
267 #define CM_IOCTL_VENDOR_IFD_EXCHANGE     SCARD_CTL_CODE(1)
268 #define FEATURE_VERIFY_PIN_DIRECT        0x06
269 #define FEATURE_MODIFY_PIN_DIRECT        0x07
270 #define FEATURE_GET_TLV_PROPERTIES       0x12
271
272 #define PCSCv2_PART10_PROPERTY_bEntryValidationCondition 2
273 #define PCSCv2_PART10_PROPERTY_bTimeOut2                 3
274 #define PCSCv2_PART10_PROPERTY_bMinPINSize               6
275 #define PCSCv2_PART10_PROPERTY_bMaxPINSize               7
276 #define PCSCv2_PART10_PROPERTY_wIdVendor                11
277 #define PCSCv2_PART10_PROPERTY_wIdProduct               12
278
279
280 /* The PC/SC error is defined as a long as per specs.  Due to left
281    shifts bit 31 will get sign extended.  We use this mask to fix
282    it. */
283 #define PCSC_ERR_MASK(a)  ((a) & 0xffffffff)
284
285
286 struct pcsc_io_request_s
287 {
288   unsigned long protocol;
289   unsigned long pci_len;
290 };
291
292 typedef struct pcsc_io_request_s *pcsc_io_request_t;
293
294 #ifdef __APPLE__
295 #pragma pack(1)
296 #endif
297
298 struct pcsc_readerstate_s
299 {
300   const char *reader;
301   void *user_data;
302   pcsc_dword_t current_state;
303   pcsc_dword_t event_state;
304   pcsc_dword_t atrlen;
305   unsigned char atr[33];
306 };
307
308 #ifdef __APPLE__
309 #pragma pack()
310 #endif
311
312 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
313
314 long (* DLSTDCALL pcsc_establish_context) (pcsc_dword_t scope,
315                                            const void *reserved1,
316                                            const void *reserved2,
317                                            long *r_context);
318 long (* DLSTDCALL pcsc_release_context) (long context);
319 long (* DLSTDCALL pcsc_list_readers) (long context,
320                                       const char *groups,
321                                       char *readers, pcsc_dword_t*readerslen);
322 long (* DLSTDCALL pcsc_get_status_change) (long context,
323                                            pcsc_dword_t timeout,
324                                            pcsc_readerstate_t readerstates,
325                                            pcsc_dword_t nreaderstates);
326 long (* DLSTDCALL pcsc_connect) (long context,
327                                  const char *reader,
328                                  pcsc_dword_t share_mode,
329                                  pcsc_dword_t preferred_protocols,
330                                  long *r_card,
331                                  pcsc_dword_t *r_active_protocol);
332 long (* DLSTDCALL pcsc_reconnect) (long card,
333                                    pcsc_dword_t share_mode,
334                                    pcsc_dword_t preferred_protocols,
335                                    pcsc_dword_t initialization,
336                                    pcsc_dword_t *r_active_protocol);
337 long (* DLSTDCALL pcsc_disconnect) (long card,
338                                     pcsc_dword_t disposition);
339 long (* DLSTDCALL pcsc_status) (long card,
340                                 char *reader, pcsc_dword_t *readerlen,
341                                 pcsc_dword_t *r_state,
342                                 pcsc_dword_t *r_protocol,
343                                 unsigned char *atr, pcsc_dword_t *atrlen);
344 long (* DLSTDCALL pcsc_begin_transaction) (long card);
345 long (* DLSTDCALL pcsc_end_transaction) (long card,
346                                          pcsc_dword_t disposition);
347 long (* DLSTDCALL pcsc_transmit) (long card,
348                                   const pcsc_io_request_t send_pci,
349                                   const unsigned char *send_buffer,
350                                   pcsc_dword_t send_len,
351                                   pcsc_io_request_t recv_pci,
352                                   unsigned char *recv_buffer,
353                                   pcsc_dword_t *recv_len);
354 long (* DLSTDCALL pcsc_set_timeout) (long context,
355                                      pcsc_dword_t timeout);
356 long (* DLSTDCALL pcsc_control) (long card,
357                                  pcsc_dword_t control_code,
358                                  const void *send_buffer,
359                                  pcsc_dword_t send_len,
360                                  void *recv_buffer,
361                                  pcsc_dword_t recv_len,
362                                  pcsc_dword_t *bytes_returned);
363
364
365 /*  Prototypes.  */
366 static int pcsc_vendor_specific_init (int slot);
367 static int pcsc_get_status (int slot, unsigned int *status);
368 static int reset_pcsc_reader (int slot);
369 static int apdu_get_status_internal (int slot, int hang, int no_atr_reset,
370                                      unsigned int *status);
371 static int check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo);
372 static int pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
373                                pininfo_t *pininfo);
374 static int pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
375                                pininfo_t *pininfo);
376
377
378 \f
379 /*
380       Helper
381  */
382
383 static int
384 lock_slot (int slot)
385 {
386 #ifdef USE_NPTH
387   int err;
388
389   err = npth_mutex_lock (&reader_table[slot].lock);
390   if (err)
391     {
392       log_error ("failed to acquire apdu lock: %s\n", strerror (err));
393       return SW_HOST_LOCKING_FAILED;
394     }
395 #endif /*USE_NPTH*/
396   return 0;
397 }
398
399 static int
400 trylock_slot (int slot)
401 {
402 #ifdef USE_NPTH
403   int err;
404
405   err = npth_mutex_trylock (&reader_table[slot].lock);
406   if (err == EBUSY)
407     return SW_HOST_BUSY;
408   else if (err)
409     {
410       log_error ("failed to acquire apdu lock: %s\n", strerror (err));
411       return SW_HOST_LOCKING_FAILED;
412     }
413 #endif /*USE_NPTH*/
414   return 0;
415 }
416
417 static void
418 unlock_slot (int slot)
419 {
420 #ifdef USE_NPTH
421   int err;
422
423   err = npth_mutex_unlock (&reader_table[slot].lock);
424   if (err)
425     log_error ("failed to release apdu lock: %s\n", strerror (errno));
426 #endif /*USE_NPTH*/
427 }
428
429
430 /* Find an unused reader slot for PORTSTR and put it into the reader
431    table.  Return -1 on error or the index into the reader table.
432    Acquire slot's lock on successful return.  Caller needs to unlock it.  */
433 static int
434 new_reader_slot (void)
435 {
436   int i, reader = -1;
437
438   for (i=0; i < MAX_READER; i++)
439     if (!reader_table[i].used)
440       {
441         reader = i;
442         reader_table[reader].used = 1;
443         break;
444       }
445
446   if (reader == -1)
447     {
448       log_error ("new_reader_slot: out of slots\n");
449       return -1;
450     }
451
452   if (lock_slot (reader))
453     {
454       reader_table[reader].used = 0;
455       return -1;
456     }
457
458   reader_table[reader].connect_card = NULL;
459   reader_table[reader].disconnect_card = NULL;
460   reader_table[reader].close_reader = NULL;
461   reader_table[reader].reset_reader = NULL;
462   reader_table[reader].get_status_reader = NULL;
463   reader_table[reader].send_apdu_reader = NULL;
464   reader_table[reader].check_pinpad = check_pcsc_pinpad;
465   reader_table[reader].dump_status_reader = NULL;
466   reader_table[reader].set_progress_cb = NULL;
467   reader_table[reader].pinpad_verify = pcsc_pinpad_verify;
468   reader_table[reader].pinpad_modify = pcsc_pinpad_modify;
469
470   reader_table[reader].is_t0 = 1;
471   reader_table[reader].is_spr532 = 0;
472   reader_table[reader].pinpad_varlen_supported = 0;
473 #ifdef NEED_PCSC_WRAPPER
474   reader_table[reader].pcsc.req_fd = -1;
475   reader_table[reader].pcsc.rsp_fd = -1;
476   reader_table[reader].pcsc.pid = (pid_t)(-1);
477 #endif
478   reader_table[reader].pcsc.verify_ioctl = 0;
479   reader_table[reader].pcsc.modify_ioctl = 0;
480   reader_table[reader].pcsc.pinmin = -1;
481   reader_table[reader].pcsc.pinmax = -1;
482
483   return reader;
484 }
485
486
487 static void
488 dump_reader_status (int slot)
489 {
490   if (!opt.verbose)
491     return;
492
493   if (reader_table[slot].dump_status_reader)
494     reader_table[slot].dump_status_reader (slot);
495
496   if (reader_table[slot].atrlen)
497     {
498       log_info ("slot %d: ATR=", slot);
499       log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
500     }
501 }
502
503
504
505 static const char *
506 host_sw_string (long err)
507 {
508   switch (err)
509     {
510     case 0: return "okay";
511     case SW_HOST_OUT_OF_CORE: return "out of core";
512     case SW_HOST_INV_VALUE: return "invalid value";
513     case SW_HOST_NO_DRIVER: return "no driver";
514     case SW_HOST_NOT_SUPPORTED: return "not supported";
515     case SW_HOST_LOCKING_FAILED: return "locking failed";
516     case SW_HOST_BUSY: return "busy";
517     case SW_HOST_NO_CARD: return "no card";
518     case SW_HOST_CARD_INACTIVE: return "card inactive";
519     case SW_HOST_CARD_IO_ERROR: return "card I/O error";
520     case SW_HOST_GENERAL_ERROR: return "general error";
521     case SW_HOST_NO_READER: return "no reader";
522     case SW_HOST_ABORTED: return "aborted";
523     case SW_HOST_NO_PINPAD: return "no pinpad";
524     case SW_HOST_ALREADY_CONNECTED: return "already connected";
525     default: return "unknown host status error";
526     }
527 }
528
529
530 const char *
531 apdu_strerror (int rc)
532 {
533   switch (rc)
534     {
535     case SW_EOF_REACHED    : return "eof reached";
536     case SW_EEPROM_FAILURE : return "eeprom failure";
537     case SW_WRONG_LENGTH   : return "wrong length";
538     case SW_CHV_WRONG      : return "CHV wrong";
539     case SW_CHV_BLOCKED    : return "CHV blocked";
540     case SW_REF_DATA_INV   : return "referenced data invalidated";
541     case SW_USE_CONDITIONS : return "use conditions not satisfied";
542     case SW_BAD_PARAMETER  : return "bad parameter";
543     case SW_NOT_SUPPORTED  : return "not supported";
544     case SW_FILE_NOT_FOUND : return "file not found";
545     case SW_RECORD_NOT_FOUND:return "record not found";
546     case SW_REF_NOT_FOUND  : return "reference not found";
547     case SW_NOT_ENOUGH_MEMORY: return "not enough memory space in the file";
548     case SW_INCONSISTENT_LC: return "Lc inconsistent with TLV structure.";
549     case SW_INCORRECT_P0_P1: return "incorrect parameters P0,P1";
550     case SW_BAD_LC         : return "Lc inconsistent with P0,P1";
551     case SW_BAD_P0_P1      : return "bad P0,P1";
552     case SW_INS_NOT_SUP    : return "instruction not supported";
553     case SW_CLA_NOT_SUP    : return "class not supported";
554     case SW_SUCCESS        : return "success";
555     default:
556       if ((rc & ~0x00ff) == SW_MORE_DATA)
557         return "more data available";
558       if ( (rc & 0x10000) )
559         return host_sw_string (rc);
560       return "unknown status error";
561     }
562 }
563
564
565 \f
566 /*
567        ct API Interface
568  */
569
570 static const char *
571 ct_error_string (long err)
572 {
573   switch (err)
574     {
575     case 0: return "okay";
576     case -1: return "invalid data";
577     case -8: return "ct error";
578     case -10: return "transmission error";
579     case -11: return "memory allocation error";
580     case -128: return "HTSI error";
581     default: return "unknown CT-API error";
582     }
583 }
584
585
586 /* Wait for the card in SLOT and activate it.  Return a status word
587    error or 0 on success. */
588 static int
589 ct_activate_card (int slot)
590 {
591   int rc;
592   unsigned char dad[1], sad[1], cmd[11], buf[256];
593   unsigned short buflen;
594
595   /* Check whether card has been inserted. */
596   dad[0] = 1;     /* Destination address: CT. */
597   sad[0] = 2;     /* Source address: Host. */
598
599   cmd[0] = 0x20;  /* Class byte. */
600   cmd[1] = 0x13;  /* Request status. */
601   cmd[2] = 0x00;  /* From kernel. */
602   cmd[3] = 0x80;  /* Return card's DO. */
603   cmd[4] = 0x00;
604
605   buflen = DIM(buf);
606
607   rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
608   if (rc || buflen < 2 || buf[buflen-2] != 0x90)
609     {
610       log_error ("ct_activate_card: can't get status of reader %d: %s\n",
611                  slot, ct_error_string (rc));
612       return SW_HOST_CARD_IO_ERROR;
613     }
614
615   /* Connected, now activate the card. */
616   dad[0] = 1;    /* Destination address: CT. */
617   sad[0] = 2;    /* Source address: Host. */
618
619   cmd[0] = 0x20;  /* Class byte. */
620   cmd[1] = 0x12;  /* Request ICC. */
621   cmd[2] = 0x01;  /* From first interface. */
622   cmd[3] = 0x01;  /* Return card's ATR. */
623   cmd[4] = 0x00;
624
625   buflen = DIM(buf);
626
627   rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
628   if (rc || buflen < 2 || buf[buflen-2] != 0x90)
629     {
630       log_error ("ct_activate_card(%d): activation failed: %s\n",
631                  slot, ct_error_string (rc));
632       if (!rc)
633         log_printhex ("  received data:", buf, buflen);
634       return SW_HOST_CARD_IO_ERROR;
635     }
636
637   /* Store the type and the ATR. */
638   if (buflen - 2 > DIM (reader_table[0].atr))
639     {
640       log_error ("ct_activate_card(%d): ATR too long\n", slot);
641       return SW_HOST_CARD_IO_ERROR;
642     }
643
644   memcpy (reader_table[slot].atr, buf, buflen - 2);
645   reader_table[slot].atrlen = buflen - 2;
646   return 0;
647 }
648
649
650 static int
651 close_ct_reader (int slot)
652 {
653   CT_close (slot);
654   return 0;
655 }
656
657 static int
658 reset_ct_reader (int slot)
659 {
660   /* FIXME: Check is this is sufficient do do a reset. */
661   return ct_activate_card (slot);
662 }
663
664
665 static int
666 ct_get_status (int slot, unsigned int *status)
667 {
668   (void)slot;
669   /* The status we returned is wrong but we don't care because ctAPI
670      is not anymore required.  */
671   *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
672   return 0;
673 }
674
675 /* Actually send the APDU of length APDULEN to SLOT and return a
676    maximum of *BUFLEN data in BUFFER, the actual returned size will be
677    set to BUFLEN.  Returns: CT API error code. */
678 static int
679 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
680               unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
681 {
682   int rc;
683   unsigned char dad[1], sad[1];
684   unsigned short ctbuflen;
685
686   (void)pininfo;
687
688   /* If we don't have an ATR, we need to reset the reader first. */
689   if (!reader_table[slot].atrlen
690       && (rc = reset_ct_reader (slot)))
691     return rc;
692
693   dad[0] = 0;     /* Destination address: Card. */
694   sad[0] = 2;     /* Source address: Host. */
695   ctbuflen = *buflen;
696   if (DBG_CARD_IO)
697     log_printhex ("  CT_data:", apdu, apdulen);
698   rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
699   *buflen = ctbuflen;
700
701   return rc? SW_HOST_CARD_IO_ERROR: 0;
702 }
703
704
705
706 /* Open a reader and return an internal handle for it.  PORT is a
707    non-negative value with the port number of the reader. USB readers
708    do have port numbers starting at 32769. */
709 static int
710 open_ct_reader (int port)
711 {
712   int rc, reader;
713
714   if (port < 0 || port > 0xffff)
715     {
716       log_error ("open_ct_reader: invalid port %d requested\n", port);
717       return -1;
718     }
719   reader = new_reader_slot ();
720   if (reader == -1)
721     return reader;
722   reader_table[reader].port = port;
723
724   rc = CT_init (reader, (unsigned short)port);
725   if (rc)
726     {
727       log_error ("apdu_open_ct_reader failed on port %d: %s\n",
728                  port, ct_error_string (rc));
729       reader_table[reader].used = 0;
730       unlock_slot (reader);
731       return -1;
732     }
733
734   /* Only try to activate the card. */
735   rc = ct_activate_card (reader);
736   if (rc)
737     {
738       reader_table[reader].atrlen = 0;
739       rc = 0;
740     }
741
742   reader_table[reader].close_reader = close_ct_reader;
743   reader_table[reader].reset_reader = reset_ct_reader;
744   reader_table[reader].get_status_reader = ct_get_status;
745   reader_table[reader].send_apdu_reader = ct_send_apdu;
746   reader_table[reader].check_pinpad = NULL;
747   reader_table[reader].dump_status_reader = NULL;
748   reader_table[reader].pinpad_verify = NULL;
749   reader_table[reader].pinpad_modify = NULL;
750
751   dump_reader_status (reader);
752   unlock_slot (reader);
753   return reader;
754 }
755
756 \f
757 /*
758        PC/SC Interface
759  */
760
761 #ifdef NEED_PCSC_WRAPPER
762 static int
763 writen (int fd, const void *buf, size_t nbytes)
764 {
765   size_t nleft = nbytes;
766   int nwritten;
767
768 /*   log_printhex (" writen:", buf, nbytes); */
769
770   while (nleft > 0)
771     {
772 #ifdef USE_NPTH
773       nwritten = npth_write (fd, buf, nleft);
774 #else
775       nwritten = write (fd, buf, nleft);
776 #endif
777       if (nwritten < 0 && errno == EINTR)
778         continue;
779       if (nwritten < 0)
780         return -1;
781       nleft -= nwritten;
782       buf = (const char*)buf + nwritten;
783     }
784   return 0;
785 }
786
787 /* Read up to BUFLEN bytes from FD and return the number of bytes
788    actually read in NREAD.  Returns -1 on error or 0 on success. */
789 static int
790 readn (int fd, void *buf, size_t buflen, size_t *nread)
791 {
792   size_t nleft = buflen;
793   int n;
794 /*   void *orig_buf = buf; */
795
796   while (nleft > 0)
797     {
798 #ifdef USE_NPTH
799 # ifdef HAVE_W32_SYSTEM
800 #  error Cannot use npth_read here because it expects a system HANDLE.
801 # endif
802       n = npth_read (fd, buf, nleft);
803 #else
804       n = read (fd, buf, nleft);
805 #endif
806       if (n < 0 && errno == EINTR)
807         continue;
808       if (n < 0)
809         return -1; /* read error. */
810       if (!n)
811         break; /* EOF */
812       nleft -= n;
813       buf = (char*)buf + n;
814     }
815   if (nread)
816     *nread = buflen - nleft;
817
818 /*   log_printhex ("  readn:", orig_buf, *nread); */
819
820   return 0;
821 }
822 #endif /*NEED_PCSC_WRAPPER*/
823
824 static const char *
825 pcsc_error_string (long err)
826 {
827   const char *s;
828
829   if (!err)
830     return "okay";
831   if ((err & 0x80100000) != 0x80100000)
832     return "invalid PC/SC error code";
833   err &= 0xffff;
834   switch (err)
835     {
836     case 0x0002: s = "cancelled"; break;
837     case 0x000e: s = "can't dispose"; break;
838     case 0x0008: s = "insufficient buffer"; break;
839     case 0x0015: s = "invalid ATR"; break;
840     case 0x0003: s = "invalid handle"; break;
841     case 0x0004: s = "invalid parameter"; break;
842     case 0x0005: s = "invalid target"; break;
843     case 0x0011: s = "invalid value"; break;
844     case 0x0006: s = "no memory"; break;
845     case 0x0013: s = "comm error"; break;
846     case 0x0001: s = "internal error"; break;
847     case 0x0014: s = "unknown error"; break;
848     case 0x0007: s = "waited too long"; break;
849     case 0x0009: s = "unknown reader"; break;
850     case 0x000a: s = "timeout"; break;
851     case 0x000b: s = "sharing violation"; break;
852     case 0x000c: s = "no smartcard"; break;
853     case 0x000d: s = "unknown card"; break;
854     case 0x000f: s = "proto mismatch"; break;
855     case 0x0010: s = "not ready"; break;
856     case 0x0012: s = "system cancelled"; break;
857     case 0x0016: s = "not transacted"; break;
858     case 0x0017: s = "reader unavailable"; break;
859     case 0x0065: s = "unsupported card"; break;
860     case 0x0066: s = "unresponsive card"; break;
861     case 0x0067: s = "unpowered card"; break;
862     case 0x0068: s = "reset card"; break;
863     case 0x0069: s = "removed card"; break;
864     case 0x006a: s = "inserted card"; break;
865     case 0x001f: s = "unsupported feature"; break;
866     case 0x0019: s = "PCI too small"; break;
867     case 0x001a: s = "reader unsupported"; break;
868     case 0x001b: s = "duplicate reader"; break;
869     case 0x001c: s = "card unsupported"; break;
870     case 0x001d: s = "no service"; break;
871     case 0x001e: s = "service stopped"; break;
872     default:     s = "unknown PC/SC error code"; break;
873     }
874   return s;
875 }
876
877 /* Map PC/SC error codes to our special host status words.  */
878 static int
879 pcsc_error_to_sw (long ec)
880 {
881   int rc;
882
883   switch ( PCSC_ERR_MASK (ec) )
884     {
885     case 0:  rc = 0; break;
886
887     case PCSC_E_CANCELLED:           rc = SW_HOST_ABORTED; break;
888     case PCSC_E_NO_MEMORY:           rc = SW_HOST_OUT_OF_CORE; break;
889     case PCSC_E_TIMEOUT:             rc = SW_HOST_CARD_IO_ERROR; break;
890     case PCSC_E_NO_SERVICE:
891     case PCSC_E_SERVICE_STOPPED:
892     case PCSC_E_UNKNOWN_READER:      rc = SW_HOST_NO_READER; break;
893     case PCSC_E_SHARING_VIOLATION:   rc = SW_HOST_LOCKING_FAILED; break;
894     case PCSC_E_NO_SMARTCARD:        rc = SW_HOST_NO_CARD; break;
895     case PCSC_W_REMOVED_CARD:        rc = SW_HOST_NO_CARD; break;
896
897     case PCSC_E_INVALID_TARGET:
898     case PCSC_E_INVALID_VALUE:
899     case PCSC_E_INVALID_HANDLE:
900     case PCSC_E_INVALID_PARAMETER:
901     case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
902
903     default:  rc = SW_HOST_GENERAL_ERROR; break;
904     }
905
906   return rc;
907 }
908
909 static void
910 dump_pcsc_reader_status (int slot)
911 {
912   if (reader_table[slot].pcsc.card)
913     {
914       log_info ("reader slot %d: active protocol:", slot);
915       if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
916         log_printf (" T0");
917       else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
918         log_printf (" T1");
919       else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
920         log_printf (" raw");
921       log_printf ("\n");
922     }
923   else
924     log_info ("reader slot %d: not connected\n", slot);
925 }
926
927
928 #ifndef NEED_PCSC_WRAPPER
929 static int
930 pcsc_get_status_direct (int slot, unsigned int *status)
931 {
932   long err;
933   struct pcsc_readerstate_s rdrstates[1];
934
935   memset (rdrstates, 0, sizeof *rdrstates);
936   rdrstates[0].reader = reader_table[slot].rdrname;
937   rdrstates[0].current_state = PCSC_STATE_UNAWARE;
938   err = pcsc_get_status_change (reader_table[slot].pcsc.context,
939                                 0,
940                                 rdrstates, 1);
941   if (err == PCSC_E_TIMEOUT)
942     err = 0; /* Timeout is no error error here. */
943   if (err)
944     {
945       log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
946                  pcsc_error_string (err), err);
947       return pcsc_error_to_sw (err);
948     }
949
950   /*   log_debug  */
951   /*     ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
952   /*      (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
953   /*      (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
954   /*      (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
955   /*      (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
956   /*      (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
957   /*      (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
958   /*      (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
959   /*      (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
960   /*      (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
961   /*      (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
962
963   *status = 0;
964   if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
965     {
966       *status |= APDU_CARD_PRESENT;
967       if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
968         *status |= APDU_CARD_ACTIVE;
969     }
970 #ifndef HAVE_W32_SYSTEM
971   /* We indicate a useful card if it is not in use by another
972      application.  This is because we only use exclusive access
973      mode.  */
974   if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
975        == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
976        && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
977     *status |= APDU_CARD_USABLE;
978 #else
979   /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
980      time when we are the only user (SCM SCR335) under Windows.  */
981   if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
982       == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
983     *status |= APDU_CARD_USABLE;
984 #endif
985
986   return 0;
987 }
988 #endif /*!NEED_PCSC_WRAPPER*/
989
990
991 #ifdef NEED_PCSC_WRAPPER
992 static int
993 pcsc_get_status_wrapped (int slot, unsigned int *status)
994 {
995   long err;
996   reader_table_t slotp;
997   size_t len, full_len;
998   int i, n;
999   unsigned char msgbuf[9];
1000   unsigned char buffer[16];
1001   int sw = SW_HOST_CARD_IO_ERROR;
1002
1003   slotp = reader_table + slot;
1004
1005   if (slotp->pcsc.req_fd == -1
1006       || slotp->pcsc.rsp_fd == -1
1007       || slotp->pcsc.pid == (pid_t)(-1) )
1008     {
1009       log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1010       return sw;
1011     }
1012
1013   msgbuf[0] = 0x04; /* STATUS command. */
1014   len = 0;
1015   msgbuf[1] = (len >> 24);
1016   msgbuf[2] = (len >> 16);
1017   msgbuf[3] = (len >>  8);
1018   msgbuf[4] = (len      );
1019   if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1020     {
1021       log_error ("error sending PC/SC STATUS request: %s\n",
1022                  strerror (errno));
1023       goto command_failed;
1024     }
1025
1026   /* Read the response. */
1027   if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1028     {
1029       log_error ("error receiving PC/SC STATUS response: %s\n",
1030                  i? strerror (errno) : "premature EOF");
1031       goto command_failed;
1032     }
1033   len = buf_to_size_t (msgbuf+1);
1034   if (msgbuf[0] != 0x81 || len < 4)
1035     {
1036       log_error ("invalid response header from PC/SC received\n");
1037       goto command_failed;
1038     }
1039   len -= 4; /* Already read the error code. */
1040   err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1041   if (err)
1042     {
1043       log_error ("pcsc_status failed: %s (0x%lx)\n",
1044                  pcsc_error_string (err), err);
1045       /* This is a proper error code, so return immediately.  */
1046       return pcsc_error_to_sw (err);
1047     }
1048
1049   full_len = len;
1050
1051   /* The current version returns 3 words but we allow also for old
1052      versions returning only 2 words. */
1053   n = 12 < len ? 12 : len;
1054   if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
1055       || (len != 8 && len != 12))
1056     {
1057       log_error ("error receiving PC/SC STATUS response: %s\n",
1058                  i? strerror (errno) : "premature EOF");
1059       goto command_failed;
1060     }
1061
1062   slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
1063
1064
1065   full_len -= len;
1066   /* Newer versions of the wrapper might send more status bytes.
1067      Read them. */
1068   while (full_len)
1069     {
1070       unsigned char dummybuf[128];
1071
1072       n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1073       if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1074         {
1075           log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1076                      i? strerror (errno) : "premature EOF");
1077           goto command_failed;
1078         }
1079       full_len -= n;
1080     }
1081
1082   /* We are lucky: The wrapper already returns the data in the
1083      required format. */
1084   *status = buffer[3];
1085   return 0;
1086
1087  command_failed:
1088   close (slotp->pcsc.req_fd);
1089   close (slotp->pcsc.rsp_fd);
1090   slotp->pcsc.req_fd = -1;
1091   slotp->pcsc.rsp_fd = -1;
1092   if (slotp->pcsc.pid != -1)
1093     kill (slotp->pcsc.pid, SIGTERM);
1094   slotp->pcsc.pid = (pid_t)(-1);
1095   slotp->used = 0;
1096   return sw;
1097 }
1098 #endif /*NEED_PCSC_WRAPPER*/
1099
1100
1101 static int
1102 pcsc_get_status (int slot, unsigned int *status)
1103 {
1104 #ifdef NEED_PCSC_WRAPPER
1105   return pcsc_get_status_wrapped (slot, status);
1106 #else
1107   return pcsc_get_status_direct (slot, status);
1108 #endif
1109 }
1110
1111
1112 #ifndef NEED_PCSC_WRAPPER
1113 static int
1114 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
1115                        unsigned char *buffer, size_t *buflen,
1116                        pininfo_t *pininfo)
1117 {
1118   long err;
1119   struct pcsc_io_request_s send_pci;
1120   pcsc_dword_t recv_len;
1121
1122   (void)pininfo;
1123
1124   if (!reader_table[slot].atrlen
1125       && (err = reset_pcsc_reader (slot)))
1126     return err;
1127
1128   if (DBG_CARD_IO)
1129     log_printhex ("  PCSC_data:", apdu, apdulen);
1130
1131   if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1132       send_pci.protocol = PCSC_PROTOCOL_T1;
1133   else
1134       send_pci.protocol = PCSC_PROTOCOL_T0;
1135   send_pci.pci_len = sizeof send_pci;
1136   recv_len = *buflen;
1137   err = pcsc_transmit (reader_table[slot].pcsc.card,
1138                        &send_pci, apdu, apdulen,
1139                        NULL, buffer, &recv_len);
1140   *buflen = recv_len;
1141   if (err)
1142     log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1143                pcsc_error_string (err), err);
1144
1145   return pcsc_error_to_sw (err);
1146 }
1147 #endif /*!NEED_PCSC_WRAPPER*/
1148
1149
1150 #ifdef NEED_PCSC_WRAPPER
1151 static int
1152 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1153                         unsigned char *buffer, size_t *buflen,
1154                         pininfo_t *pininfo)
1155 {
1156   long err;
1157   reader_table_t slotp;
1158   size_t len, full_len;
1159   int i, n;
1160   unsigned char msgbuf[9];
1161   int sw = SW_HOST_CARD_IO_ERROR;
1162
1163   (void)pininfo;
1164
1165   if (!reader_table[slot].atrlen
1166       && (err = reset_pcsc_reader (slot)))
1167     return err;
1168
1169   if (DBG_CARD_IO)
1170     log_printhex ("  PCSC_data:", apdu, apdulen);
1171
1172   slotp = reader_table + slot;
1173
1174   if (slotp->pcsc.req_fd == -1
1175       || slotp->pcsc.rsp_fd == -1
1176       || slotp->pcsc.pid == (pid_t)(-1) )
1177     {
1178       log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1179       return sw;
1180     }
1181
1182   msgbuf[0] = 0x03; /* TRANSMIT command. */
1183   len = apdulen;
1184   msgbuf[1] = (len >> 24);
1185   msgbuf[2] = (len >> 16);
1186   msgbuf[3] = (len >>  8);
1187   msgbuf[4] = (len      );
1188   if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1189        || writen (slotp->pcsc.req_fd, apdu, len))
1190     {
1191       log_error ("error sending PC/SC TRANSMIT request: %s\n",
1192                  strerror (errno));
1193       goto command_failed;
1194     }
1195
1196   /* Read the response. */
1197   if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1198     {
1199       log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1200                  i? strerror (errno) : "premature EOF");
1201       goto command_failed;
1202     }
1203   len = buf_to_size_t (msgbuf+1);
1204   if (msgbuf[0] != 0x81 || len < 4)
1205     {
1206       log_error ("invalid response header from PC/SC received\n");
1207       goto command_failed;
1208     }
1209   len -= 4; /* Already read the error code. */
1210   err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1211   if (err)
1212     {
1213       log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1214                  pcsc_error_string (err), err);
1215       return pcsc_error_to_sw (err);
1216     }
1217
1218    full_len = len;
1219
1220    n = *buflen < len ? *buflen : len;
1221    if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1222      {
1223        log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1224                   i? strerror (errno) : "premature EOF");
1225        goto command_failed;
1226      }
1227    *buflen = n;
1228
1229    full_len -= len;
1230    if (full_len)
1231      {
1232        log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1233        err = SW_HOST_INV_VALUE;
1234      }
1235    /* We need to read any rest of the response, to keep the
1236       protocol running.  */
1237    while (full_len)
1238      {
1239        unsigned char dummybuf[128];
1240
1241        n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1242        if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1243          {
1244            log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1245                       i? strerror (errno) : "premature EOF");
1246            goto command_failed;
1247          }
1248        full_len -= n;
1249      }
1250
1251    return err;
1252
1253  command_failed:
1254   close (slotp->pcsc.req_fd);
1255   close (slotp->pcsc.rsp_fd);
1256   slotp->pcsc.req_fd = -1;
1257   slotp->pcsc.rsp_fd = -1;
1258   if (slotp->pcsc.pid != -1)
1259     kill (slotp->pcsc.pid, SIGTERM);
1260   slotp->pcsc.pid = (pid_t)(-1);
1261   slotp->used = 0;
1262   return sw;
1263 }
1264 #endif /*NEED_PCSC_WRAPPER*/
1265
1266
1267 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1268    *BUFLEN data in BUFFER, the actual returned size will be stored at
1269    BUFLEN.  Returns: A status word. */
1270 static int
1271 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1272                 unsigned char *buffer, size_t *buflen,
1273                 pininfo_t *pininfo)
1274 {
1275 #ifdef NEED_PCSC_WRAPPER
1276   return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1277 #else
1278   return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1279 #endif
1280 }
1281
1282
1283 #ifndef NEED_PCSC_WRAPPER
1284 static int
1285 control_pcsc_direct (int slot, pcsc_dword_t ioctl_code,
1286                      const unsigned char *cntlbuf, size_t len,
1287                      unsigned char *buffer, pcsc_dword_t *buflen)
1288 {
1289   long err;
1290
1291   err = pcsc_control (reader_table[slot].pcsc.card, ioctl_code,
1292                       cntlbuf, len, buffer, buflen? *buflen:0, buflen);
1293   if (err)
1294     {
1295       log_error ("pcsc_control failed: %s (0x%lx)\n",
1296                  pcsc_error_string (err), err);
1297       return pcsc_error_to_sw (err);
1298     }
1299
1300   return 0;
1301 }
1302 #endif /*!NEED_PCSC_WRAPPER*/
1303
1304
1305 #ifdef NEED_PCSC_WRAPPER
1306 static int
1307 control_pcsc_wrapped (int slot, pcsc_dword_t ioctl_code,
1308                       const unsigned char *cntlbuf, size_t len,
1309                       unsigned char *buffer, pcsc_dword_t *buflen)
1310 {
1311   long err = PCSC_E_NOT_TRANSACTED;
1312   reader_table_t slotp;
1313   unsigned char msgbuf[9];
1314   int i, n;
1315   size_t full_len;
1316
1317   slotp = reader_table + slot;
1318
1319   msgbuf[0] = 0x06; /* CONTROL command. */
1320   msgbuf[1] = ((len + 4) >> 24);
1321   msgbuf[2] = ((len + 4) >> 16);
1322   msgbuf[3] = ((len + 4) >>  8);
1323   msgbuf[4] = ((len + 4)      );
1324   msgbuf[5] = (ioctl_code >> 24);
1325   msgbuf[6] = (ioctl_code >> 16);
1326   msgbuf[7] = (ioctl_code >>  8);
1327   msgbuf[8] = (ioctl_code      );
1328   if ( writen (slotp->pcsc.req_fd, msgbuf, 9)
1329        || writen (slotp->pcsc.req_fd, cntlbuf, len))
1330     {
1331       log_error ("error sending PC/SC CONTROL request: %s\n",
1332                  strerror (errno));
1333       goto command_failed;
1334     }
1335
1336   /* Read the response. */
1337   if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1338     {
1339       log_error ("error receiving PC/SC CONTROL response: %s\n",
1340                  i? strerror (errno) : "premature EOF");
1341       goto command_failed;
1342     }
1343   len = buf32_to_size_t (msgbuf+1);
1344   if (msgbuf[0] != 0x81 || len < 4)
1345     {
1346       log_error ("invalid response header from PC/SC received\n");
1347       goto command_failed;
1348     }
1349   len -= 4; /* Already read the error code. */
1350   err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1351   if (err)
1352     {
1353       log_error ("pcsc_control failed: %s (0x%lx)\n",
1354                  pcsc_error_string (err), err);
1355       return pcsc_error_to_sw (err);
1356     }
1357
1358   full_len = len;
1359
1360   if (buflen)
1361     n = *buflen < len ? *buflen : len;
1362   else
1363     n = 0;
1364   if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1365     {
1366       log_error ("error receiving PC/SC CONTROL response: %s\n",
1367                  i? strerror (errno) : "premature EOF");
1368       goto command_failed;
1369     }
1370   if (buflen)
1371     *buflen = n;
1372
1373   full_len -= len;
1374   if (full_len)
1375     {
1376       log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1377       err = PCSC_E_INVALID_VALUE;
1378     }
1379   /* We need to read any rest of the response, to keep the
1380      protocol running.  */
1381   while (full_len)
1382     {
1383       unsigned char dummybuf[128];
1384
1385       n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1386       if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1387         {
1388           log_error ("error receiving PC/SC CONTROL response: %s\n",
1389                      i? strerror (errno) : "premature EOF");
1390           goto command_failed;
1391         }
1392       full_len -= n;
1393     }
1394
1395   if (!err)
1396     return 0;
1397
1398  command_failed:
1399   close (slotp->pcsc.req_fd);
1400   close (slotp->pcsc.rsp_fd);
1401   slotp->pcsc.req_fd = -1;
1402   slotp->pcsc.rsp_fd = -1;
1403   if (slotp->pcsc.pid != -1)
1404     kill (slotp->pcsc.pid, SIGTERM);
1405   slotp->pcsc.pid = (pid_t)(-1);
1406   slotp->used = 0;
1407   return pcsc_error_to_sw (err);
1408 }
1409 #endif /*NEED_PCSC_WRAPPER*/
1410
1411
1412
1413 /* Do some control with the value of IOCTL_CODE to the card inserted
1414    to SLOT.  Input buffer is specified by CNTLBUF of length LEN.
1415    Output buffer is specified by BUFFER of length *BUFLEN, and the
1416    actual output size will be stored at BUFLEN.  Returns: A status word.
1417    This routine is used for PIN pad input support.  */
1418 static int
1419 control_pcsc (int slot, pcsc_dword_t ioctl_code,
1420               const unsigned char *cntlbuf, size_t len,
1421               unsigned char *buffer, pcsc_dword_t *buflen)
1422 {
1423 #ifdef NEED_PCSC_WRAPPER
1424   return control_pcsc_wrapped (slot, ioctl_code, cntlbuf, len, buffer, buflen);
1425 #else
1426   return control_pcsc_direct (slot, ioctl_code, cntlbuf, len, buffer, buflen);
1427 #endif
1428 }
1429
1430
1431 #ifndef NEED_PCSC_WRAPPER
1432 static int
1433 close_pcsc_reader_direct (int slot)
1434 {
1435   pcsc_release_context (reader_table[slot].pcsc.context);
1436   return 0;
1437 }
1438 #endif /*!NEED_PCSC_WRAPPER*/
1439
1440
1441 #ifdef NEED_PCSC_WRAPPER
1442 static int
1443 close_pcsc_reader_wrapped (int slot)
1444 {
1445   long err;
1446   reader_table_t slotp;
1447   size_t len;
1448   int i;
1449   unsigned char msgbuf[9];
1450
1451   slotp = reader_table + slot;
1452
1453   if (slotp->pcsc.req_fd == -1
1454       || slotp->pcsc.rsp_fd == -1
1455       || slotp->pcsc.pid == (pid_t)(-1) )
1456     {
1457       log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1458       return 0;
1459     }
1460
1461   msgbuf[0] = 0x02; /* CLOSE command. */
1462   len = 0;
1463   msgbuf[1] = (len >> 24);
1464   msgbuf[2] = (len >> 16);
1465   msgbuf[3] = (len >>  8);
1466   msgbuf[4] = (len      );
1467   if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1468     {
1469       log_error ("error sending PC/SC CLOSE request: %s\n",
1470                  strerror (errno));
1471       goto command_failed;
1472     }
1473
1474   /* Read the response. */
1475   if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1476     {
1477       log_error ("error receiving PC/SC CLOSE response: %s\n",
1478                  i? strerror (errno) : "premature EOF");
1479       goto command_failed;
1480     }
1481   len = buf32_to_size_t (msgbuf+1);
1482   if (msgbuf[0] != 0x81 || len < 4)
1483     {
1484       log_error ("invalid response header from PC/SC received\n");
1485       goto command_failed;
1486     }
1487   len -= 4; /* Already read the error code. */
1488   err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1489   if (err)
1490     log_error ("pcsc_close failed: %s (0x%lx)\n",
1491                pcsc_error_string (err), err);
1492
1493   /* We will close the wrapper in any case - errors are merely
1494      informational. */
1495
1496  command_failed:
1497   close (slotp->pcsc.req_fd);
1498   close (slotp->pcsc.rsp_fd);
1499   slotp->pcsc.req_fd = -1;
1500   slotp->pcsc.rsp_fd = -1;
1501   if (slotp->pcsc.pid != -1)
1502     kill (slotp->pcsc.pid, SIGTERM);
1503   slotp->pcsc.pid = (pid_t)(-1);
1504   slotp->used = 0;
1505   return 0;
1506 }
1507 #endif /*NEED_PCSC_WRAPPER*/
1508
1509
1510 static int
1511 close_pcsc_reader (int slot)
1512 {
1513 #ifdef NEED_PCSC_WRAPPER
1514   return close_pcsc_reader_wrapped (slot);
1515 #else
1516   return close_pcsc_reader_direct (slot);
1517 #endif
1518 }
1519
1520
1521 /* Connect a PC/SC card.  */
1522 #ifndef NEED_PCSC_WRAPPER
1523 static int
1524 connect_pcsc_card (int slot)
1525 {
1526   long err;
1527
1528   assert (slot >= 0 && slot < MAX_READER);
1529
1530   if (reader_table[slot].pcsc.card)
1531     return SW_HOST_ALREADY_CONNECTED;
1532
1533   reader_table[slot].atrlen = 0;
1534   reader_table[slot].is_t0 = 0;
1535
1536   err = pcsc_connect (reader_table[slot].pcsc.context,
1537                       reader_table[slot].rdrname,
1538                       PCSC_SHARE_EXCLUSIVE,
1539                       PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1540                       &reader_table[slot].pcsc.card,
1541                       &reader_table[slot].pcsc.protocol);
1542   if (err)
1543     {
1544       reader_table[slot].pcsc.card = 0;
1545       if (err != PCSC_E_NO_SMARTCARD)
1546         log_error ("pcsc_connect failed: %s (0x%lx)\n",
1547                    pcsc_error_string (err), err);
1548     }
1549   else
1550     {
1551       char reader[250];
1552       pcsc_dword_t readerlen, atrlen;
1553       pcsc_dword_t card_state, card_protocol;
1554
1555       pcsc_vendor_specific_init (slot);
1556
1557       atrlen = DIM (reader_table[0].atr);
1558       readerlen = sizeof reader -1 ;
1559       err = pcsc_status (reader_table[slot].pcsc.card,
1560                          reader, &readerlen,
1561                          &card_state, &card_protocol,
1562                          reader_table[slot].atr, &atrlen);
1563       if (err)
1564         log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1565                    pcsc_error_string (err), err, (long unsigned int)readerlen);
1566       else
1567         {
1568           if (atrlen > DIM (reader_table[0].atr))
1569             log_bug ("ATR returned by pcsc_status is too large\n");
1570           reader_table[slot].atrlen = atrlen;
1571           reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1572         }
1573     }
1574
1575   dump_reader_status (slot);
1576   return pcsc_error_to_sw (err);
1577 }
1578 #endif /*!NEED_PCSC_WRAPPER*/
1579
1580
1581 /* Disconnect a PC/SC card.  Note that this succeeds even if the card
1582    is not connected.  */
1583 #ifndef NEED_PCSC_WRAPPER
1584 static int
1585 disconnect_pcsc_card (int slot)
1586 {
1587   long err;
1588
1589   assert (slot >= 0 && slot < MAX_READER);
1590
1591   if (!reader_table[slot].pcsc.card)
1592     return 0;
1593
1594   err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1595   if (err)
1596     {
1597       log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1598                  pcsc_error_string (err), err);
1599       return SW_HOST_CARD_IO_ERROR;
1600     }
1601   reader_table[slot].pcsc.card = 0;
1602   return 0;
1603 }
1604 #endif /*!NEED_PCSC_WRAPPER*/
1605
1606
1607 #ifndef NEED_PCSC_WRAPPER
1608 static int
1609 reset_pcsc_reader_direct (int slot)
1610 {
1611   int sw;
1612
1613   sw = disconnect_pcsc_card (slot);
1614   if (!sw)
1615     sw = connect_pcsc_card (slot);
1616
1617   return sw;
1618 }
1619 #endif /*NEED_PCSC_WRAPPER*/
1620
1621
1622 #ifdef NEED_PCSC_WRAPPER
1623 static int
1624 reset_pcsc_reader_wrapped (int slot)
1625 {
1626   long err;
1627   reader_table_t slotp;
1628   size_t len;
1629   int i, n;
1630   unsigned char msgbuf[9];
1631   unsigned int dummy_status;
1632   int sw = SW_HOST_CARD_IO_ERROR;
1633
1634   slotp = reader_table + slot;
1635
1636   if (slotp->pcsc.req_fd == -1
1637       || slotp->pcsc.rsp_fd == -1
1638       || slotp->pcsc.pid == (pid_t)(-1) )
1639     {
1640       log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1641       return sw;
1642     }
1643
1644   msgbuf[0] = 0x05; /* RESET command. */
1645   len = 0;
1646   msgbuf[1] = (len >> 24);
1647   msgbuf[2] = (len >> 16);
1648   msgbuf[3] = (len >>  8);
1649   msgbuf[4] = (len      );
1650   if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1651     {
1652       log_error ("error sending PC/SC RESET request: %s\n",
1653                  strerror (errno));
1654       goto command_failed;
1655     }
1656
1657   /* Read the response. */
1658   if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1659     {
1660       log_error ("error receiving PC/SC RESET response: %s\n",
1661                  i? strerror (errno) : "premature EOF");
1662       goto command_failed;
1663     }
1664   len = buf32_to_size_t (msgbuf+1);
1665   if (msgbuf[0] != 0x81 || len < 4)
1666     {
1667       log_error ("invalid response header from PC/SC received\n");
1668       goto command_failed;
1669     }
1670   len -= 4; /* Already read the error code. */
1671   if (len > DIM (slotp->atr))
1672     {
1673       log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1674                  (unsigned long)len);
1675       sw = SW_HOST_GENERAL_ERROR;
1676       goto command_failed;
1677     }
1678   err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1679   if (err)
1680     {
1681       log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1682                  pcsc_error_string (err), err);
1683       /* If the error code is no smart card, we should not considere
1684          this a major error and close the wrapper.  */
1685       sw = pcsc_error_to_sw (err);
1686       if (err == PCSC_E_NO_SMARTCARD)
1687         return sw;
1688       goto command_failed;
1689     }
1690
1691   /* The open function may return a zero for the ATR length to
1692      indicate that no card is present.  */
1693   n = len;
1694   if (n)
1695     {
1696       if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1697         {
1698           log_error ("error receiving PC/SC RESET response: %s\n",
1699                      i? strerror (errno) : "premature EOF");
1700           goto command_failed;
1701         }
1702     }
1703   slotp->atrlen = len;
1704
1705   /* Read the status so that IS_T0 will be set. */
1706   pcsc_get_status (slot, &dummy_status);
1707
1708   return 0;
1709
1710  command_failed:
1711   close (slotp->pcsc.req_fd);
1712   close (slotp->pcsc.rsp_fd);
1713   slotp->pcsc.req_fd = -1;
1714   slotp->pcsc.rsp_fd = -1;
1715   if (slotp->pcsc.pid != -1)
1716     kill (slotp->pcsc.pid, SIGTERM);
1717   slotp->pcsc.pid = (pid_t)(-1);
1718   slotp->used = 0;
1719   return sw;
1720 }
1721 #endif /* !NEED_PCSC_WRAPPER */
1722
1723
1724 /* Send an PC/SC reset command and return a status word on error or 0
1725    on success. */
1726 static int
1727 reset_pcsc_reader (int slot)
1728 {
1729 #ifdef NEED_PCSC_WRAPPER
1730   return reset_pcsc_reader_wrapped (slot);
1731 #else
1732   return reset_pcsc_reader_direct (slot);
1733 #endif
1734 }
1735
1736
1737 /* Examine reader specific parameters and initialize.  This is mostly
1738    for pinpad input.  Called at opening the connection to the reader.  */
1739 static int
1740 pcsc_vendor_specific_init (int slot)
1741 {
1742   unsigned char buf[256];
1743   pcsc_dword_t len;
1744   int sw;
1745   int vendor = 0;
1746   int product = 0;
1747   pcsc_dword_t get_tlv_ioctl = (pcsc_dword_t)-1;
1748   unsigned char *p;
1749
1750   len = sizeof (buf);
1751   sw = control_pcsc (slot, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, &len);
1752   if (sw)
1753     {
1754       log_error ("pcsc_vendor_specific_init: GET_FEATURE_REQUEST failed: %d\n",
1755                  sw);
1756       return SW_NOT_SUPPORTED;
1757     }
1758   else
1759     {
1760       p = buf;
1761       while (p < buf + len)
1762         {
1763           unsigned char code = *p++;
1764           int l = *p++;
1765           unsigned int v = 0;
1766
1767           if (l == 1)
1768             v = p[0];
1769           else if (l == 2)
1770             v = buf16_to_uint (p);
1771           else if (l == 4)
1772             v = buf32_to_uint (p);
1773
1774           if (code == FEATURE_VERIFY_PIN_DIRECT)
1775             reader_table[slot].pcsc.verify_ioctl = v;
1776           else if (code == FEATURE_MODIFY_PIN_DIRECT)
1777             reader_table[slot].pcsc.modify_ioctl = v;
1778           else if (code == FEATURE_GET_TLV_PROPERTIES)
1779             get_tlv_ioctl = v;
1780
1781           if (DBG_CARD_IO)
1782             log_debug ("feature: code=%02X, len=%d, v=%02X\n", code, l, v);
1783
1784           p += l;
1785         }
1786     }
1787
1788   if (get_tlv_ioctl == (pcsc_dword_t)-1)
1789     {
1790       /*
1791        * For system which doesn't support GET_TLV_PROPERTIES,
1792        * we put some heuristics here.
1793        */
1794       if (reader_table[slot].rdrname)
1795         {
1796           if (strstr (reader_table[slot].rdrname, "SPRx32"))
1797             {
1798               reader_table[slot].is_spr532 = 1;
1799               reader_table[slot].pinpad_varlen_supported = 1;
1800             }
1801           else if (strstr (reader_table[slot].rdrname, "ST-2xxx"))
1802             {
1803               reader_table[slot].pcsc.pinmax = 15;
1804               reader_table[slot].pinpad_varlen_supported = 1;
1805             }
1806           else if (strstr (reader_table[slot].rdrname, "cyberJack")
1807                    || strstr (reader_table[slot].rdrname, "DIGIPASS")
1808                    || strstr (reader_table[slot].rdrname, "Gnuk")
1809                    || strstr (reader_table[slot].rdrname, "KAAN"))
1810             reader_table[slot].pinpad_varlen_supported = 1;
1811         }
1812
1813       return 0;
1814     }
1815
1816   len = sizeof (buf);
1817   sw = control_pcsc (slot, get_tlv_ioctl, NULL, 0, buf, &len);
1818   if (sw)
1819     {
1820       log_error ("pcsc_vendor_specific_init: GET_TLV_IOCTL failed: %d\n", sw);
1821       return SW_NOT_SUPPORTED;
1822     }
1823
1824   p = buf;
1825   while (p < buf + len)
1826     {
1827       unsigned char tag = *p++;
1828       int l = *p++;
1829       unsigned int v = 0;
1830
1831       /* Umm... here is little endian, while the encoding above is big.  */
1832       if (l == 1)
1833         v = p[0];
1834       else if (l == 2)
1835         v = (((unsigned int)p[1] << 8) | p[0]);
1836       else if (l == 4)
1837         v = (((unsigned int)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
1838
1839       if (tag == PCSCv2_PART10_PROPERTY_bMinPINSize)
1840         reader_table[slot].pcsc.pinmin = v;
1841       else if (tag == PCSCv2_PART10_PROPERTY_bMaxPINSize)
1842         reader_table[slot].pcsc.pinmax = v;
1843       else if (tag == PCSCv2_PART10_PROPERTY_wIdVendor)
1844         vendor = v;
1845       else if (tag == PCSCv2_PART10_PROPERTY_wIdProduct)
1846         product = v;
1847
1848       if (DBG_CARD_IO)
1849         log_debug ("TLV properties: tag=%02X, len=%d, v=%08X\n", tag, l, v);
1850
1851       p += l;
1852     }
1853
1854   if (vendor == VENDOR_VEGA && product == VEGA_ALPHA)
1855     {
1856       /*
1857        * Please read the comment of ccid_vendor_specific_init in
1858        * ccid-driver.c.
1859        */
1860       const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1861       sw = control_pcsc (slot, CM_IOCTL_VENDOR_IFD_EXCHANGE,
1862                          cmd, sizeof (cmd), NULL, 0);
1863       if (sw)
1864         return SW_NOT_SUPPORTED;
1865     }
1866   else if (vendor == VENDOR_SCM && product == SCM_SPR532) /* SCM SPR532 */
1867     {
1868       reader_table[slot].is_spr532 = 1;
1869       reader_table[slot].pinpad_varlen_supported = 1;
1870     }
1871   else if (vendor == 0x046a)
1872     {
1873       /* Cherry ST-2xxx (product == 0x003e) supports TPDU level
1874        * exchange.  Other products which only support short APDU level
1875        * exchange only work with shorter keys like RSA 1024.
1876        */
1877       reader_table[slot].pcsc.pinmax = 15;
1878       reader_table[slot].pinpad_varlen_supported = 1;
1879     }
1880   else if (vendor == 0x0c4b /* Tested with Reiner cyberJack GO */
1881            || vendor == 0x1a44 /* Tested with Vasco DIGIPASS 920 */
1882            || vendor == 0x234b /* Tested with FSIJ Gnuk Token */
1883            || vendor == 0x0d46 /* Tested with KAAN Advanced??? */)
1884     reader_table[slot].pinpad_varlen_supported = 1;
1885
1886   return 0;
1887 }
1888
1889
1890 /* Open the PC/SC reader without using the wrapper.  Returns -1 on
1891    error or a slot number for the reader.  */
1892 #ifndef NEED_PCSC_WRAPPER
1893 static int
1894 open_pcsc_reader_direct (const char *portstr)
1895 {
1896   long err;
1897   int slot;
1898   char *list = NULL;
1899   char *rdrname = NULL;
1900   pcsc_dword_t nreader;
1901   char *p;
1902
1903   slot = new_reader_slot ();
1904   if (slot == -1)
1905     return -1;
1906
1907   /* Fixme: Allocating a context for each slot is not required.  One
1908      global context should be sufficient.  */
1909   err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1910                                 &reader_table[slot].pcsc.context);
1911   if (err)
1912     {
1913       log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1914                  pcsc_error_string (err), err);
1915       reader_table[slot].used = 0;
1916       unlock_slot (slot);
1917       return -1;
1918     }
1919
1920   err = pcsc_list_readers (reader_table[slot].pcsc.context,
1921                            NULL, NULL, &nreader);
1922   if (!err)
1923     {
1924       list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1925       if (!list)
1926         {
1927           log_error ("error allocating memory for reader list\n");
1928           pcsc_release_context (reader_table[slot].pcsc.context);
1929           reader_table[slot].used = 0;
1930           unlock_slot (slot);
1931           return -1 /*SW_HOST_OUT_OF_CORE*/;
1932         }
1933       err = pcsc_list_readers (reader_table[slot].pcsc.context,
1934                                NULL, list, &nreader);
1935     }
1936   if (err)
1937     {
1938       log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1939                  pcsc_error_string (err), err);
1940       pcsc_release_context (reader_table[slot].pcsc.context);
1941       reader_table[slot].used = 0;
1942       xfree (list);
1943       unlock_slot (slot);
1944       return -1;
1945     }
1946
1947   p = list;
1948   while (nreader)
1949     {
1950       if (!*p && !p[1])
1951         break;
1952       log_info ("detected reader '%s'\n", p);
1953       if (nreader < (strlen (p)+1))
1954         {
1955           log_error ("invalid response from pcsc_list_readers\n");
1956           break;
1957         }
1958       if (!rdrname && portstr && !strncmp (p, portstr, strlen (portstr)))
1959         rdrname = p;
1960       nreader -= strlen (p)+1;
1961       p += strlen (p) + 1;
1962     }
1963
1964   if (!rdrname)
1965     rdrname = list;
1966
1967   reader_table[slot].rdrname = xtrystrdup (rdrname);
1968   if (!reader_table[slot].rdrname)
1969     {
1970       log_error ("error allocating memory for reader name\n");
1971       pcsc_release_context (reader_table[slot].pcsc.context);
1972       reader_table[slot].used = 0;
1973       unlock_slot (slot);
1974       return -1;
1975     }
1976   xfree (list);
1977   list = NULL;
1978
1979   reader_table[slot].pcsc.card = 0;
1980   reader_table[slot].atrlen = 0;
1981
1982   reader_table[slot].connect_card = connect_pcsc_card;
1983   reader_table[slot].disconnect_card = disconnect_pcsc_card;
1984   reader_table[slot].close_reader = close_pcsc_reader;
1985   reader_table[slot].reset_reader = reset_pcsc_reader;
1986   reader_table[slot].get_status_reader = pcsc_get_status;
1987   reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1988   reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1989
1990   dump_reader_status (slot);
1991   unlock_slot (slot);
1992   return slot;
1993 }
1994 #endif /*!NEED_PCSC_WRAPPER */
1995
1996
1997 /* Open the PC/SC reader using the pcsc_wrapper program.  This is
1998    needed to cope with different thread models and other peculiarities
1999    of libpcsclite. */
2000 #ifdef NEED_PCSC_WRAPPER
2001 static int
2002 open_pcsc_reader_wrapped (const char *portstr)
2003 {
2004   int slot;
2005   reader_table_t slotp;
2006   int fd, rp[2], wp[2];
2007   int n, i;
2008   pid_t pid;
2009   size_t len;
2010   unsigned char msgbuf[9];
2011   int err;
2012   unsigned int dummy_status;
2013
2014   /* Note that we use the constant and not the function because this
2015      code won't be be used under Windows.  */
2016   const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
2017
2018   if (access (wrapperpgm, X_OK))
2019     {
2020       log_error ("can't run PC/SC access module '%s': %s\n",
2021                  wrapperpgm, strerror (errno));
2022       return -1;
2023     }
2024
2025   slot = new_reader_slot ();
2026   if (slot == -1)
2027     return -1;
2028   slotp = reader_table + slot;
2029
2030   /* Fire up the PC/SCc wrapper.  We don't use any fork/exec code from
2031      the common directy but implement it directly so that this file
2032      may still be source copied. */
2033
2034   if (pipe (rp) == -1)
2035     {
2036       log_error ("error creating a pipe: %s\n", strerror (errno));
2037       slotp->used = 0;
2038       unlock_slot (slot);
2039       return -1;
2040     }
2041   if (pipe (wp) == -1)
2042     {
2043       log_error ("error creating a pipe: %s\n", strerror (errno));
2044       close (rp[0]);
2045       close (rp[1]);
2046       slotp->used = 0;
2047       unlock_slot (slot);
2048       return -1;
2049     }
2050
2051   pid = fork ();
2052   if (pid == -1)
2053     {
2054       log_error ("error forking process: %s\n", strerror (errno));
2055       close (rp[0]);
2056       close (rp[1]);
2057       close (wp[0]);
2058       close (wp[1]);
2059       slotp->used = 0;
2060       unlock_slot (slot);
2061       return -1;
2062     }
2063   slotp->pcsc.pid = pid;
2064
2065   if (!pid)
2066     { /*
2067          === Child ===
2068        */
2069
2070       /* Double fork. */
2071       pid = fork ();
2072       if (pid == -1)
2073         _exit (31);
2074       if (pid)
2075         _exit (0); /* Immediate exit this parent, so that the child
2076                       gets cleaned up by the init process. */
2077
2078       /* Connect our pipes. */
2079       if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
2080         log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
2081       if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
2082         log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
2083
2084       /* Send stderr to the bit bucket. */
2085       fd = open ("/dev/null", O_WRONLY);
2086       if (fd == -1)
2087         log_fatal ("can't open '/dev/null': %s", strerror (errno));
2088       if (fd != 2 && dup2 (fd, 2) == -1)
2089         log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
2090
2091       /* Close all other files. */
2092       close_all_fds (3, NULL);
2093
2094       execl (wrapperpgm,
2095              "pcsc-wrapper",
2096              "--",
2097              "1", /* API version */
2098              opt.pcsc_driver, /* Name of the PC/SC library. */
2099               NULL);
2100       _exit (31);
2101     }
2102
2103   /*
2104      === Parent ===
2105    */
2106   close (wp[0]);
2107   close (rp[1]);
2108   slotp->pcsc.req_fd = wp[1];
2109   slotp->pcsc.rsp_fd = rp[0];
2110
2111   /* Wait for the intermediate child to terminate. */
2112 #ifdef USE_NPTH
2113 #define WAIT npth_waitpid
2114 #else
2115 #define WAIT waitpid
2116 #endif
2117   while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
2118     ;
2119 #undef WAIT
2120
2121   /* Now send the open request. */
2122   msgbuf[0] = 0x01; /* OPEN command. */
2123   len = portstr? strlen (portstr):0;
2124   msgbuf[1] = (len >> 24);
2125   msgbuf[2] = (len >> 16);
2126   msgbuf[3] = (len >>  8);
2127   msgbuf[4] = (len      );
2128   if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
2129        || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
2130     {
2131       log_error ("error sending PC/SC OPEN request: %s\n",
2132                  strerror (errno));
2133       goto command_failed;
2134     }
2135   /* Read the response. */
2136   if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
2137     {
2138       log_error ("error receiving PC/SC OPEN response: %s\n",
2139                  i? strerror (errno) : "premature EOF");
2140       goto command_failed;
2141     }
2142   len = buf32_to_size_t (msgbuf+1);
2143   if (msgbuf[0] != 0x81 || len < 4)
2144     {
2145       log_error ("invalid response header from PC/SC received\n");
2146       goto command_failed;
2147     }
2148   len -= 4; /* Already read the error code. */
2149   if (len > DIM (slotp->atr))
2150     {
2151       log_error ("PC/SC returned a too large ATR (len=%lx)\n",
2152                  (unsigned long)len);
2153       goto command_failed;
2154     }
2155   err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
2156   if (err)
2157     {
2158       log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
2159       goto command_failed;
2160     }
2161
2162   /* The open request may return a zero for the ATR length to
2163      indicate that no card is present.  */
2164   n = len;
2165   if (n)
2166     {
2167       if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
2168         {
2169           log_error ("error receiving PC/SC OPEN response: %s\n",
2170                      i? strerror (errno) : "premature EOF");
2171           goto command_failed;
2172         }
2173     }
2174   slotp->atrlen = len;
2175
2176   reader_table[slot].close_reader = close_pcsc_reader;
2177   reader_table[slot].reset_reader = reset_pcsc_reader;
2178   reader_table[slot].get_status_reader = pcsc_get_status;
2179   reader_table[slot].send_apdu_reader = pcsc_send_apdu;
2180   reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
2181
2182   pcsc_vendor_specific_init (slot);
2183
2184   /* Read the status so that IS_T0 will be set. */
2185   pcsc_get_status (slot, &dummy_status);
2186
2187   dump_reader_status (slot);
2188   unlock_slot (slot);
2189   return slot;
2190
2191  command_failed:
2192   close (slotp->pcsc.req_fd);
2193   close (slotp->pcsc.rsp_fd);
2194   slotp->pcsc.req_fd = -1;
2195   slotp->pcsc.rsp_fd = -1;
2196   if (slotp->pcsc.pid != -1)
2197     kill (slotp->pcsc.pid, SIGTERM);
2198   slotp->pcsc.pid = (pid_t)(-1);
2199   slotp->used = 0;
2200   unlock_slot (slot);
2201   /* There is no way to return SW. */
2202   return -1;
2203
2204 }
2205 #endif /*NEED_PCSC_WRAPPER*/
2206
2207
2208 static int
2209 open_pcsc_reader (const char *portstr)
2210 {
2211 #ifdef NEED_PCSC_WRAPPER
2212   return open_pcsc_reader_wrapped (portstr);
2213 #else
2214   return open_pcsc_reader_direct (portstr);
2215 #endif
2216 }
2217
2218
2219 /* Check whether the reader supports the ISO command code COMMAND
2220    on the pinpad.  Return 0 on success.  */
2221 static int
2222 check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo)
2223 {
2224   int r;
2225
2226   if (reader_table[slot].pcsc.pinmin >= 0)
2227     pininfo->minlen = reader_table[slot].pcsc.pinmin;
2228
2229   if (reader_table[slot].pcsc.pinmax >= 0)
2230     pininfo->maxlen = reader_table[slot].pcsc.pinmax;
2231
2232   if (!pininfo->minlen)
2233     pininfo->minlen = 1;
2234   if (!pininfo->maxlen)
2235     pininfo->maxlen = 15;
2236
2237   if ((command == ISO7816_VERIFY && reader_table[slot].pcsc.verify_ioctl != 0)
2238       || (command == ISO7816_CHANGE_REFERENCE_DATA
2239           && reader_table[slot].pcsc.modify_ioctl != 0))
2240     r = 0;                       /* Success */
2241   else
2242     r = SW_NOT_SUPPORTED;
2243
2244   if (DBG_CARD_IO)
2245     log_debug ("check_pcsc_pinpad: command=%02X, r=%d\n",
2246                (unsigned int)command, r);
2247
2248   if (reader_table[slot].pinpad_varlen_supported)
2249     pininfo->fixedlen = 0;
2250
2251   return r;
2252 }
2253
2254 #define PIN_VERIFY_STRUCTURE_SIZE 24
2255 static int
2256 pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
2257                     pininfo_t *pininfo)
2258 {
2259   int sw;
2260   unsigned char *pin_verify;
2261   int len = PIN_VERIFY_STRUCTURE_SIZE + pininfo->fixedlen;
2262   /*
2263    * The result buffer is only expected to have two-byte result on
2264    * return.  However, some implementation uses this buffer for lower
2265    * layer too and it assumes that there is enough space for lower
2266    * layer communication.  Such an implementation fails for TPDU
2267    * readers with "insufficient buffer", as it needs header and
2268    * trailer.  Six is the number for header + result + trailer (TPDU).
2269    */
2270   unsigned char result[6];
2271   pcsc_dword_t resultlen = 6;
2272   int no_lc;
2273
2274   if (!reader_table[slot].atrlen
2275       && (sw = reset_pcsc_reader (slot)))
2276     return sw;
2277
2278   if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
2279     return SW_NOT_SUPPORTED;
2280
2281   pin_verify = xtrymalloc (len);
2282   if (!pin_verify)
2283     return SW_HOST_OUT_OF_CORE;
2284
2285   no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
2286
2287   pin_verify[0] = 0x00; /* bTimeOut */
2288   pin_verify[1] = 0x00; /* bTimeOut2 */
2289   pin_verify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2290   pin_verify[3] = pininfo->fixedlen; /* bmPINBlockString */
2291   pin_verify[4] = 0x00; /* bmPINLengthFormat */
2292   pin_verify[5] = pininfo->maxlen; /* wPINMaxExtraDigit */
2293   pin_verify[6] = pininfo->minlen; /* wPINMaxExtraDigit */
2294   pin_verify[7] = 0x02; /* bEntryValidationCondition: Validation key pressed */
2295   if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
2296     pin_verify[7] |= 0x01; /* Max size reached.  */
2297   pin_verify[8] = 0x01; /* bNumberMessage: One message */
2298   pin_verify[9] =  0x09; /* wLangId: 0x0409: US English */
2299   pin_verify[10] = 0x04; /* wLangId: 0x0409: US English */
2300   pin_verify[11] = 0x00; /* bMsgIndex */
2301   pin_verify[12] = 0x00; /* bTeoPrologue[0] */
2302   pin_verify[13] = 0x00; /* bTeoPrologue[1] */
2303   pin_verify[14] = pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
2304   pin_verify[15] = pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
2305   pin_verify[16] = 0x00; /* ulDataLength */
2306   pin_verify[17] = 0x00; /* ulDataLength */
2307   pin_verify[18] = 0x00; /* ulDataLength */
2308   pin_verify[19] = class; /* abData[0] */
2309   pin_verify[20] = ins; /* abData[1] */
2310   pin_verify[21] = p0; /* abData[2] */
2311   pin_verify[22] = p1; /* abData[3] */
2312   pin_verify[23] = pininfo->fixedlen; /* abData[4] */
2313   if (pininfo->fixedlen)
2314     memset (&pin_verify[24], 0xff, pininfo->fixedlen);
2315   else if (no_lc)
2316     len--;
2317
2318   if (DBG_CARD_IO)
2319     log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
2320                class, ins, p0, p1, len, pininfo->maxlen);
2321
2322   sw = control_pcsc (slot, reader_table[slot].pcsc.verify_ioctl,
2323                      pin_verify, len, result, &resultlen);
2324   xfree (pin_verify);
2325   if (sw || resultlen < 2)
2326     {
2327       log_error ("control_pcsc failed: %d\n", sw);
2328       return sw? sw: SW_HOST_INCOMPLETE_CARD_RESPONSE;
2329     }
2330   sw = (result[resultlen-2] << 8) | result[resultlen-1];
2331   if (DBG_CARD_IO)
2332     log_debug (" response: sw=%04X  datalen=%d\n", sw, (unsigned int)resultlen);
2333   return sw;
2334 }
2335
2336
2337 #define PIN_MODIFY_STRUCTURE_SIZE 29
2338 static int
2339 pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
2340                     pininfo_t *pininfo)
2341 {
2342   int sw;
2343   unsigned char *pin_modify;
2344   int len = PIN_MODIFY_STRUCTURE_SIZE + 2 * pininfo->fixedlen;
2345   unsigned char result[6];      /* See the comment at pinpad_verify.  */
2346   pcsc_dword_t resultlen = 6;
2347   int no_lc;
2348
2349   if (!reader_table[slot].atrlen
2350       && (sw = reset_pcsc_reader (slot)))
2351     return sw;
2352
2353   if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
2354     return SW_NOT_SUPPORTED;
2355
2356   pin_modify = xtrymalloc (len);
2357   if (!pin_modify)
2358     return SW_HOST_OUT_OF_CORE;
2359
2360   no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
2361
2362   pin_modify[0] = 0x00; /* bTimeOut */
2363   pin_modify[1] = 0x00; /* bTimeOut2 */
2364   pin_modify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2365   pin_modify[3] = pininfo->fixedlen; /* bmPINBlockString */
2366   pin_modify[4] = 0x00; /* bmPINLengthFormat */
2367   pin_modify[5] = 0x00; /* bInsertionOffsetOld */
2368   pin_modify[6] = pininfo->fixedlen; /* bInsertionOffsetNew */
2369   pin_modify[7] = pininfo->maxlen; /* wPINMaxExtraDigit */
2370   pin_modify[8] = pininfo->minlen; /* wPINMaxExtraDigit */
2371   pin_modify[9] = (p0 == 0 ? 0x03 : 0x01);
2372                   /* bConfirmPIN
2373                    *    0x00: new PIN once
2374                    *    0x01: new PIN twice (confirmation)
2375                    *    0x02: old PIN and new PIN once
2376                    *    0x03: old PIN and new PIN twice (confirmation)
2377                    */
2378   pin_modify[10] = 0x02; /* bEntryValidationCondition: Validation key pressed */
2379   if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
2380     pin_modify[10] |= 0x01; /* Max size reached.  */
2381   pin_modify[11] = 0x03; /* bNumberMessage: Three messages */
2382   pin_modify[12] = 0x09; /* wLangId: 0x0409: US English */
2383   pin_modify[13] = 0x04; /* wLangId: 0x0409: US English */
2384   pin_modify[14] = 0x00; /* bMsgIndex1 */
2385   pin_modify[15] = 0x01; /* bMsgIndex2 */
2386   pin_modify[16] = 0x02; /* bMsgIndex3 */
2387   pin_modify[17] = 0x00; /* bTeoPrologue[0] */
2388   pin_modify[18] = 0x00; /* bTeoPrologue[1] */
2389   pin_modify[19] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
2390   pin_modify[20] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
2391   pin_modify[21] = 0x00; /* ulDataLength */
2392   pin_modify[22] = 0x00; /* ulDataLength */
2393   pin_modify[23] = 0x00; /* ulDataLength */
2394   pin_modify[24] = class; /* abData[0] */
2395   pin_modify[25] = ins; /* abData[1] */
2396   pin_modify[26] = p0; /* abData[2] */
2397   pin_modify[27] = p1; /* abData[3] */
2398   pin_modify[28] = 2 * pininfo->fixedlen; /* abData[4] */
2399   if (pininfo->fixedlen)
2400     memset (&pin_modify[29], 0xff, 2 * pininfo->fixedlen);
2401   else if (no_lc)
2402     len--;
2403
2404   if (DBG_CARD_IO)
2405     log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
2406                class, ins, p0, p1, len, (int)pininfo->maxlen);
2407
2408   sw = control_pcsc (slot, reader_table[slot].pcsc.modify_ioctl,
2409                      pin_modify, len, result, &resultlen);
2410   xfree (pin_modify);
2411   if (sw || resultlen < 2)
2412     {
2413       log_error ("control_pcsc failed: %d\n", sw);
2414       return sw? sw : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2415     }
2416   sw = (result[resultlen-2] << 8) | result[resultlen-1];
2417   if (DBG_CARD_IO)
2418     log_debug (" response: sw=%04X  datalen=%d\n", sw, (unsigned int)resultlen);
2419   return sw;
2420 }
2421 \f
2422 #ifdef HAVE_LIBUSB
2423 /*
2424      Internal CCID driver interface.
2425  */
2426
2427
2428 static void
2429 dump_ccid_reader_status (int slot)
2430 {
2431   log_info ("reader slot %d: using ccid driver\n", slot);
2432 }
2433
2434 static int
2435 close_ccid_reader (int slot)
2436 {
2437   ccid_close_reader (reader_table[slot].ccid.handle);
2438   return 0;
2439 }
2440
2441
2442 static int
2443 reset_ccid_reader (int slot)
2444 {
2445   int err;
2446   reader_table_t slotp = reader_table + slot;
2447   unsigned char atr[33];
2448   size_t atrlen;
2449
2450   err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
2451   if (err)
2452     return err;
2453   /* If the reset was successful, update the ATR. */
2454   assert (sizeof slotp->atr >= sizeof atr);
2455   slotp->atrlen = atrlen;
2456   memcpy (slotp->atr, atr, atrlen);
2457   dump_reader_status (slot);
2458   return 0;
2459 }
2460
2461
2462 static int
2463 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
2464 {
2465   reader_table_t slotp = reader_table + slot;
2466
2467   return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
2468 }
2469
2470
2471 static int
2472 get_status_ccid (int slot, unsigned int *status)
2473 {
2474   int rc;
2475   int bits;
2476
2477   rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
2478   if (rc)
2479     return rc;
2480
2481   if (bits == 0)
2482     *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
2483   else if (bits == 1)
2484     *status = APDU_CARD_PRESENT;
2485   else
2486     *status = 0;
2487
2488   return 0;
2489 }
2490
2491
2492 /* Actually send the APDU of length APDULEN to SLOT and return a
2493    maximum of *BUFLEN data in BUFFER, the actual returned size will be
2494    set to BUFLEN.  Returns: Internal CCID driver error code. */
2495 static int
2496 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
2497                 unsigned char *buffer, size_t *buflen,
2498                 pininfo_t *pininfo)
2499 {
2500   long err;
2501   size_t maxbuflen;
2502
2503   /* If we don't have an ATR, we need to reset the reader first. */
2504   if (!reader_table[slot].atrlen
2505       && (err = reset_ccid_reader (slot)))
2506     return err;
2507
2508   if (DBG_CARD_IO)
2509     log_printhex (" raw apdu:", apdu, apdulen);
2510
2511   maxbuflen = *buflen;
2512   if (pininfo)
2513     err = ccid_transceive_secure (reader_table[slot].ccid.handle,
2514                                   apdu, apdulen, pininfo,
2515                                   buffer, maxbuflen, buflen);
2516   else
2517     err = ccid_transceive (reader_table[slot].ccid.handle,
2518                            apdu, apdulen,
2519                            buffer, maxbuflen, buflen);
2520   if (err)
2521     log_error ("ccid_transceive failed: (0x%lx)\n",
2522                err);
2523
2524   return err;
2525 }
2526
2527
2528 /* Check whether the CCID reader supports the ISO command code COMMAND
2529    on the pinpad.  Return 0 on success.  For a description of the pin
2530    parameters, see ccid-driver.c */
2531 static int
2532 check_ccid_pinpad (int slot, int command, pininfo_t *pininfo)
2533 {
2534   unsigned char apdu[] = { 0, 0, 0, 0x81 };
2535
2536   apdu[1] = command;
2537   return ccid_transceive_secure (reader_table[slot].ccid.handle, apdu,
2538                                  sizeof apdu, pininfo, NULL, 0, NULL);
2539 }
2540
2541
2542 static int
2543 ccid_pinpad_operation (int slot, int class, int ins, int p0, int p1,
2544                        pininfo_t *pininfo)
2545 {
2546   unsigned char apdu[4];
2547   int err, sw;
2548   unsigned char result[2];
2549   size_t resultlen = 2;
2550
2551   apdu[0] = class;
2552   apdu[1] = ins;
2553   apdu[2] = p0;
2554   apdu[3] = p1;
2555   err = ccid_transceive_secure (reader_table[slot].ccid.handle,
2556                                 apdu, sizeof apdu, pininfo,
2557                                 result, 2, &resultlen);
2558   if (err)
2559     return err;
2560
2561   if (resultlen < 2)
2562     return SW_HOST_INCOMPLETE_CARD_RESPONSE;
2563
2564   sw = (result[resultlen-2] << 8) | result[resultlen-1];
2565   return sw;
2566 }
2567
2568
2569 /* Open the reader and try to read an ATR.  */
2570 static int
2571 open_ccid_reader (struct dev_list *dl)
2572 {
2573   int err;
2574   int slot;
2575   reader_table_t slotp;
2576
2577   slot = new_reader_slot ();
2578   if (slot == -1)
2579     return -1;
2580   slotp = reader_table + slot;
2581
2582   err = ccid_open_reader (dl->portstr, dl->idx, dl->ccid_table,
2583                           &slotp->ccid.handle, &slotp->rdrname);
2584   if (err)
2585     {
2586       slotp->used = 0;
2587       unlock_slot (slot);
2588       return -1;
2589     }
2590
2591   err = ccid_get_atr (slotp->ccid.handle,
2592                       slotp->atr, sizeof slotp->atr, &slotp->atrlen);
2593   if (err)
2594     {
2595       slotp->atrlen = 0;
2596       err = 0;
2597     }
2598
2599   reader_table[slot].close_reader = close_ccid_reader;
2600   reader_table[slot].reset_reader = reset_ccid_reader;
2601   reader_table[slot].get_status_reader = get_status_ccid;
2602   reader_table[slot].send_apdu_reader = send_apdu_ccid;
2603   reader_table[slot].check_pinpad = check_ccid_pinpad;
2604   reader_table[slot].dump_status_reader = dump_ccid_reader_status;
2605   reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
2606   reader_table[slot].pinpad_verify = ccid_pinpad_operation;
2607   reader_table[slot].pinpad_modify = ccid_pinpad_operation;
2608   /* Our CCID reader code does not support T=0 at all, thus reset the
2609      flag.  */
2610   reader_table[slot].is_t0 = 0;
2611
2612   dump_reader_status (slot);
2613   unlock_slot (slot);
2614   return slot;
2615 }
2616 #endif /* HAVE_LIBUSB */
2617 \f
2618 #ifdef USE_G10CODE_RAPDU
2619 /*
2620      The Remote APDU Interface.
2621
2622      This uses the Remote APDU protocol to contact a reader.
2623
2624      The port number is actually an index into the list of ports as
2625      returned via the protocol.
2626  */
2627
2628
2629 static int
2630 rapdu_status_to_sw (int status)
2631 {
2632   int rc;
2633
2634   switch (status)
2635     {
2636     case RAPDU_STATUS_SUCCESS:  rc = 0; break;
2637
2638     case RAPDU_STATUS_INVCMD:
2639     case RAPDU_STATUS_INVPROT:
2640     case RAPDU_STATUS_INVSEQ:
2641     case RAPDU_STATUS_INVCOOKIE:
2642     case RAPDU_STATUS_INVREADER:  rc = SW_HOST_INV_VALUE;  break;
2643
2644     case RAPDU_STATUS_TIMEOUT:  rc = SW_HOST_CARD_IO_ERROR; break;
2645     case RAPDU_STATUS_CARDIO:   rc = SW_HOST_CARD_IO_ERROR; break;
2646     case RAPDU_STATUS_NOCARD:   rc = SW_HOST_NO_CARD; break;
2647     case RAPDU_STATUS_CARDCHG:  rc = SW_HOST_NO_CARD; break;
2648     case RAPDU_STATUS_BUSY:     rc = SW_HOST_BUSY; break;
2649     case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2650
2651     default: rc = SW_HOST_GENERAL_ERROR; break;
2652     }
2653
2654   return rc;
2655 }
2656
2657
2658
2659 static int
2660 close_rapdu_reader (int slot)
2661 {
2662   rapdu_release (reader_table[slot].rapdu.handle);
2663   return 0;
2664 }
2665
2666
2667 static int
2668 reset_rapdu_reader (int slot)
2669 {
2670   int err;
2671   reader_table_t slotp;
2672   rapdu_msg_t msg = NULL;
2673
2674   slotp = reader_table + slot;
2675
2676   err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2677   if (err)
2678     {
2679       log_error ("sending rapdu command RESET failed: %s\n",
2680                 err < 0 ? strerror (errno): rapdu_strerror (err));
2681       rapdu_msg_release (msg);
2682       return rapdu_status_to_sw (err);
2683     }
2684   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2685   if (err)
2686     {
2687       log_error ("receiving rapdu message failed: %s\n",
2688                 err < 0 ? strerror (errno): rapdu_strerror (err));
2689       rapdu_msg_release (msg);
2690       return rapdu_status_to_sw (err);
2691     }
2692   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2693     {
2694       int sw = rapdu_status_to_sw (msg->cmd);
2695       log_error ("rapdu command RESET failed: %s\n",
2696                  rapdu_strerror (msg->cmd));
2697       rapdu_msg_release (msg);
2698       return sw;
2699     }
2700   if (msg->datalen > DIM (slotp->atr))
2701     {
2702       log_error ("ATR returned by the RAPDU layer is too large\n");
2703       rapdu_msg_release (msg);
2704       return SW_HOST_INV_VALUE;
2705     }
2706   slotp->atrlen = msg->datalen;
2707   memcpy (slotp->atr, msg->data, msg->datalen);
2708
2709   rapdu_msg_release (msg);
2710   return 0;
2711 }
2712
2713
2714 static int
2715 my_rapdu_get_status (int slot, unsigned int *status)
2716 {
2717   int err;
2718   reader_table_t slotp;
2719   rapdu_msg_t msg = NULL;
2720   int oldslot;
2721
2722   slotp = reader_table + slot;
2723
2724   oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2725   err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2726   rapdu_set_reader (slotp->rapdu.handle, oldslot);
2727   if (err)
2728     {
2729       log_error ("sending rapdu command GET_STATUS failed: %s\n",
2730                 err < 0 ? strerror (errno): rapdu_strerror (err));
2731       return rapdu_status_to_sw (err);
2732     }
2733   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2734   if (err)
2735     {
2736       log_error ("receiving rapdu message failed: %s\n",
2737                 err < 0 ? strerror (errno): rapdu_strerror (err));
2738       rapdu_msg_release (msg);
2739       return rapdu_status_to_sw (err);
2740     }
2741   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2742     {
2743       int sw = rapdu_status_to_sw (msg->cmd);
2744       log_error ("rapdu command GET_STATUS failed: %s\n",
2745                  rapdu_strerror (msg->cmd));
2746       rapdu_msg_release (msg);
2747       return sw;
2748     }
2749   *status = msg->data[0];
2750
2751   rapdu_msg_release (msg);
2752   return 0;
2753 }
2754
2755
2756 /* Actually send the APDU of length APDULEN to SLOT and return a
2757    maximum of *BUFLEN data in BUFFER, the actual returned size will be
2758    set to BUFLEN.  Returns: APDU error code. */
2759 static int
2760 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2761                     unsigned char *buffer, size_t *buflen,
2762                     pininfo_t *pininfo)
2763 {
2764   int err;
2765   reader_table_t slotp;
2766   rapdu_msg_t msg = NULL;
2767   size_t maxlen = *buflen;
2768
2769   slotp = reader_table + slot;
2770
2771   *buflen = 0;
2772   if (DBG_CARD_IO)
2773     log_printhex ("  APDU_data:", apdu, apdulen);
2774
2775   if (apdulen < 4)
2776     {
2777       log_error ("rapdu_send_apdu: APDU is too short\n");
2778       return SW_HOST_INV_VALUE;
2779     }
2780
2781   err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2782   if (err)
2783     {
2784       log_error ("sending rapdu command APDU failed: %s\n",
2785                 err < 0 ? strerror (errno): rapdu_strerror (err));
2786       rapdu_msg_release (msg);
2787       return rapdu_status_to_sw (err);
2788     }
2789   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2790   if (err)
2791     {
2792       log_error ("receiving rapdu message failed: %s\n",
2793                 err < 0 ? strerror (errno): rapdu_strerror (err));
2794       rapdu_msg_release (msg);
2795       return rapdu_status_to_sw (err);
2796     }
2797   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2798     {
2799       int sw = rapdu_status_to_sw (msg->cmd);
2800       log_error ("rapdu command APDU failed: %s\n",
2801                  rapdu_strerror (msg->cmd));
2802       rapdu_msg_release (msg);
2803       return sw;
2804     }
2805
2806   if (msg->datalen > maxlen)
2807     {
2808       log_error ("rapdu response apdu too large\n");
2809       rapdu_msg_release (msg);
2810       return SW_HOST_INV_VALUE;
2811     }
2812
2813   *buflen = msg->datalen;
2814   memcpy (buffer, msg->data, msg->datalen);
2815
2816   rapdu_msg_release (msg);
2817   return 0;
2818 }
2819
2820 static int
2821 open_rapdu_reader (int portno,
2822                    const unsigned char *cookie, size_t length,
2823                    int (*readfnc) (void *opaque,
2824                                    void *buffer, size_t size),
2825                    void *readfnc_value,
2826                    int (*writefnc) (void *opaque,
2827                                     const void *buffer, size_t size),
2828                    void *writefnc_value,
2829                    void (*closefnc) (void *opaque),
2830                    void *closefnc_value)
2831 {
2832   int err;
2833   int slot;
2834   reader_table_t slotp;
2835   rapdu_msg_t msg = NULL;
2836
2837   slot = new_reader_slot ();
2838   if (slot == -1)
2839     return -1;
2840   slotp = reader_table + slot;
2841
2842   slotp->rapdu.handle = rapdu_new ();
2843   if (!slotp->rapdu.handle)
2844     {
2845       slotp->used = 0;
2846       unlock_slot (slot);
2847       return -1;
2848     }
2849
2850   rapdu_set_reader (slotp->rapdu.handle, portno);
2851
2852   rapdu_set_iofunc (slotp->rapdu.handle,
2853                     readfnc, readfnc_value,
2854                     writefnc, writefnc_value,
2855                     closefnc, closefnc_value);
2856   rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2857
2858   /* First try to get the current ATR, but if the card is inactive
2859      issue a reset instead.  */
2860   err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2861   if (err == RAPDU_STATUS_NEEDRESET)
2862     err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2863   if (err)
2864     {
2865       log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2866                 err < 0 ? strerror (errno): rapdu_strerror (err));
2867       goto failure;
2868     }
2869   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2870   if (err)
2871     {
2872       log_info ("receiving rapdu message failed: %s\n",
2873                 err < 0 ? strerror (errno): rapdu_strerror (err));
2874       goto failure;
2875     }
2876   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2877     {
2878       log_info ("rapdu command GET ATR failed: %s\n",
2879                  rapdu_strerror (msg->cmd));
2880       goto failure;
2881     }
2882   if (msg->datalen > DIM (slotp->atr))
2883     {
2884       log_error ("ATR returned by the RAPDU layer is too large\n");
2885       goto failure;
2886     }
2887   slotp->atrlen = msg->datalen;
2888   memcpy (slotp->atr, msg->data, msg->datalen);
2889
2890   reader_table[slot].close_reader = close_rapdu_reader;
2891   reader_table[slot].reset_reader = reset_rapdu_reader;
2892   reader_table[slot].get_status_reader = my_rapdu_get_status;
2893   reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2894   reader_table[slot].check_pinpad = NULL;
2895   reader_table[slot].dump_status_reader = NULL;
2896   reader_table[slot].pinpad_verify = NULL;
2897   reader_table[slot].pinpad_modify = NULL;
2898
2899   dump_reader_status (slot);
2900   rapdu_msg_release (msg);
2901   unlock_slot (slot);
2902   return slot;
2903
2904  failure:
2905   rapdu_msg_release (msg);
2906   rapdu_release (slotp->rapdu.handle);
2907   slotp->used = 0;
2908   unlock_slot (slot);
2909   return -1;
2910 }
2911
2912 #endif /*USE_G10CODE_RAPDU*/
2913
2914
2915 \f
2916 /*
2917        Driver Access
2918  */
2919 gpg_error_t
2920 apdu_dev_list_start (const char *portstr, struct dev_list **l_p)
2921 {
2922   struct dev_list *dl = xtrymalloc (sizeof (struct dev_list));
2923
2924   *l_p = NULL;
2925   if (!dl)
2926     return gpg_error_from_syserror ();
2927
2928   dl->portstr = portstr;
2929   dl->idx = 0;
2930
2931   npth_mutex_lock (&reader_table_lock);
2932
2933 #ifdef HAVE_LIBUSB
2934   if (opt.disable_ccid)
2935     {
2936       dl->ccid_table = NULL;
2937       dl->idx_max = 1;
2938     }
2939   else
2940     {
2941       gpg_error_t err;
2942
2943       err = ccid_dev_scan (&dl->idx_max, &dl->ccid_table);
2944       if (err)
2945         return err;
2946
2947       if (dl->idx_max == 0)
2948         {
2949           /* If a CCID reader specification has been given, the user does
2950              not want a fallback to other drivers. */
2951           if (portstr && strlen (portstr) > 5 && portstr[4] == ':')
2952             {
2953               if (DBG_READER)
2954                 log_debug ("leave: apdu_open_reader => slot=-1 (no ccid)\n");
2955
2956               xfree (dl);
2957               npth_mutex_unlock (&reader_table_lock);
2958               return gpg_error (GPG_ERR_ENODEV);
2959             }
2960           else
2961             dl->idx_max = 1;
2962         }
2963     }
2964 #else
2965   dl->ccid_table = NULL;
2966   dl->idx_max = 1;
2967 #endif /* HAVE_LIBUSB */
2968
2969   *l_p = dl;
2970   return 0;
2971 }
2972
2973 void
2974 apdu_dev_list_finish (struct dev_list *dl)
2975 {
2976 #ifdef HAVE_LIBUSB
2977   if (dl->ccid_table)
2978     ccid_dev_scan_finish (dl->ccid_table, dl->idx_max);
2979 #endif
2980   xfree (dl);
2981   npth_mutex_unlock (&reader_table_lock);
2982 }
2983
2984
2985 /* Open the reader and return an internal slot number or -1 on
2986    error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2987    the first USB reader.  For PC/SC the first listed reader). */
2988 static int
2989 apdu_open_one_reader (const char *portstr)
2990 {
2991   static int pcsc_api_loaded, ct_api_loaded;
2992   int slot;
2993
2994   if (DBG_READER)
2995     log_debug ("enter: apdu_open_reader: portstr=%s\n", portstr);
2996
2997   if (opt.ctapi_driver && *opt.ctapi_driver)
2998     {
2999       int port = portstr? atoi (portstr) : 32768;
3000
3001       if (!ct_api_loaded)
3002         {
3003           void *handle;
3004
3005           handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
3006           if (!handle)
3007             {
3008               log_error ("apdu_open_reader: failed to open driver: %s\n",
3009                          dlerror ());
3010               return -1;
3011             }
3012           CT_init = dlsym (handle, "CT_init");
3013           CT_data = dlsym (handle, "CT_data");
3014           CT_close = dlsym (handle, "CT_close");
3015           if (!CT_init || !CT_data || !CT_close)
3016             {
3017               log_error ("apdu_open_reader: invalid CT-API driver\n");
3018               dlclose (handle);
3019               return -1;
3020             }
3021           ct_api_loaded = 1;
3022         }
3023       return open_ct_reader (port);
3024     }
3025
3026   /* No ctAPI configured, so lets try the PC/SC API */
3027   if (!pcsc_api_loaded)
3028     {
3029 #ifndef NEED_PCSC_WRAPPER
3030       void *handle;
3031
3032       handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
3033       if (!handle)
3034         {
3035           log_error ("apdu_open_reader: failed to open driver '%s': %s\n",
3036                      opt.pcsc_driver, dlerror ());
3037           return -1;
3038         }
3039
3040       pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
3041       pcsc_release_context   = dlsym (handle, "SCardReleaseContext");
3042       pcsc_list_readers      = dlsym (handle, "SCardListReaders");
3043 #if defined(_WIN32) || defined(__CYGWIN__)
3044       if (!pcsc_list_readers)
3045         pcsc_list_readers    = dlsym (handle, "SCardListReadersA");
3046 #endif
3047       pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
3048 #if defined(_WIN32) || defined(__CYGWIN__)
3049       if (!pcsc_get_status_change)
3050         pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
3051 #endif
3052       pcsc_connect           = dlsym (handle, "SCardConnect");
3053 #if defined(_WIN32) || defined(__CYGWIN__)
3054       if (!pcsc_connect)
3055         pcsc_connect         = dlsym (handle, "SCardConnectA");
3056 #endif
3057       pcsc_reconnect         = dlsym (handle, "SCardReconnect");
3058 #if defined(_WIN32) || defined(__CYGWIN__)
3059       if (!pcsc_reconnect)
3060         pcsc_reconnect       = dlsym (handle, "SCardReconnectA");
3061 #endif
3062       pcsc_disconnect        = dlsym (handle, "SCardDisconnect");
3063       pcsc_status            = dlsym (handle, "SCardStatus");
3064 #if defined(_WIN32) || defined(__CYGWIN__)
3065       if (!pcsc_status)
3066         pcsc_status          = dlsym (handle, "SCardStatusA");
3067 #endif
3068       pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
3069       pcsc_end_transaction   = dlsym (handle, "SCardEndTransaction");
3070       pcsc_transmit          = dlsym (handle, "SCardTransmit");
3071       pcsc_set_timeout       = dlsym (handle, "SCardSetTimeout");
3072       pcsc_control           = dlsym (handle, "SCardControl");
3073
3074       if (!pcsc_establish_context
3075           || !pcsc_release_context
3076           || !pcsc_list_readers
3077           || !pcsc_get_status_change
3078           || !pcsc_connect
3079           || !pcsc_reconnect
3080           || !pcsc_disconnect
3081           || !pcsc_status
3082           || !pcsc_begin_transaction
3083           || !pcsc_end_transaction
3084           || !pcsc_transmit
3085           || !pcsc_control
3086           /* || !pcsc_set_timeout */)
3087         {
3088           /* Note that set_timeout is currently not used and also not
3089              available under Windows. */
3090           log_error ("apdu_open_reader: invalid PC/SC driver "
3091                      "(%d%d%d%d%d%d%d%d%d%d%d%d%d)\n",
3092                      !!pcsc_establish_context,
3093                      !!pcsc_release_context,
3094                      !!pcsc_list_readers,
3095                      !!pcsc_get_status_change,
3096                      !!pcsc_connect,
3097                      !!pcsc_reconnect,
3098                      !!pcsc_disconnect,
3099                      !!pcsc_status,
3100                      !!pcsc_begin_transaction,
3101                      !!pcsc_end_transaction,
3102                      !!pcsc_transmit,
3103                      !!pcsc_set_timeout,
3104                      !!pcsc_control );
3105           dlclose (handle);
3106           return -1;
3107         }
3108 #endif /*!NEED_PCSC_WRAPPER*/
3109       pcsc_api_loaded = 1;
3110     }
3111
3112   slot = open_pcsc_reader (portstr);
3113
3114   if (DBG_READER)
3115     log_debug ("leave: apdu_open_reader => slot=%d [pc/sc]\n", slot);
3116   return slot;
3117 }
3118
3119 int
3120 apdu_open_reader (struct dev_list *dl)
3121 {
3122   int slot;
3123
3124 #ifdef HAVE_LIBUSB
3125   if (dl->ccid_table)
3126     { /* CCID readers.  */
3127       int readerno;
3128
3129       /* See whether we want to use the reader ID string or a reader
3130          number. A readerno of -1 indicates that the reader ID string is
3131          to be used. */
3132       if (dl->portstr && strchr (dl->portstr, ':'))
3133         readerno = -1; /* We want to use the readerid.  */
3134       else if (dl->portstr)
3135         {
3136           readerno = atoi (dl->portstr);
3137           if (readerno < 0)
3138             {
3139               return -1;
3140             }
3141         }
3142       else
3143         readerno = 0;  /* Default. */
3144
3145       if (readerno > 0)
3146         { /* Use single, the specific reader.  */
3147           if (readerno >= dl->idx_max)
3148             return -1;
3149
3150           dl->idx = readerno;
3151           dl->portstr = NULL;
3152           slot = open_ccid_reader (dl);
3153           dl->idx = dl->idx_max;
3154           if (slot >= 0)
3155             return slot;
3156           else
3157             return -1;
3158         }
3159
3160       while (dl->idx < dl->idx_max)
3161         {
3162           unsigned int bai = ccid_get_BAI (dl->idx, dl->ccid_table);
3163
3164           if (DBG_READER)
3165             log_debug ("apdu_open_reader: BAI=%x\n", bai);
3166
3167           /* Check identity by BAI against already opened HANDLEs.  */
3168           for (slot = 0; slot < MAX_READER; slot++)
3169             if (reader_table[slot].used
3170                 && ccid_compare_BAI (reader_table[slot].ccid.handle, bai))
3171               break;
3172
3173           if (slot == MAX_READER)
3174             { /* Found a new device.  */
3175               if (DBG_READER)
3176                 log_debug ("apdu_open_reader: new device=%x\n", bai);
3177
3178               slot = open_ccid_reader (dl);
3179
3180               dl->idx++;
3181               if (slot >= 0)
3182                 return slot;
3183               else
3184                 {
3185                   /* Skip this reader.  */
3186                   log_error ("ccid open error: skip\n");
3187                   continue;
3188                 }
3189             }
3190           else
3191             dl->idx++;
3192         }
3193
3194       slot = -1;
3195     }
3196   else
3197 #endif
3198     { /* PC/SC readers.  */
3199       if (dl->idx == 0)
3200         {
3201           dl->idx++;
3202           slot = apdu_open_one_reader (dl->portstr);
3203         }
3204       else
3205         slot = -1;
3206     }
3207
3208   return slot;
3209 }
3210
3211
3212 /* Open an remote reader and return an internal slot number or -1 on
3213    error. This function is an alternative to apdu_open_reader and used
3214    with remote readers only.  Note that the supplied CLOSEFNC will
3215    only be called once and the slot will not be valid afther this.
3216
3217    If PORTSTR is NULL we default to the first available port.
3218 */
3219 int
3220 apdu_open_remote_reader (const char *portstr,
3221                          const unsigned char *cookie, size_t length,
3222                          int (*readfnc) (void *opaque,
3223                                          void *buffer, size_t size),
3224                          void *readfnc_value,
3225                          int (*writefnc) (void *opaque,
3226                                           const void *buffer, size_t size),
3227                          void *writefnc_value,
3228                          void (*closefnc) (void *opaque),
3229                          void *closefnc_value)
3230 {
3231 #ifdef USE_G10CODE_RAPDU
3232   return open_rapdu_reader (portstr? atoi (portstr) : 0,
3233                             cookie, length,
3234                             readfnc, readfnc_value,
3235                             writefnc, writefnc_value,
3236                             closefnc, closefnc_value);
3237 #else
3238   (void)portstr;
3239   (void)cookie;
3240   (void)length;
3241   (void)readfnc;
3242   (void)readfnc_value;
3243   (void)writefnc;
3244   (void)writefnc_value;
3245   (void)closefnc;
3246   (void)closefnc_value;
3247 #ifdef _WIN32
3248   errno = ENOENT;
3249 #else
3250   errno = ENOSYS;
3251 #endif
3252   return -1;
3253 #endif
3254 }
3255
3256
3257 int
3258 apdu_close_reader (int slot)
3259 {
3260   int sw;
3261
3262   if (DBG_READER)
3263     log_debug ("enter: apdu_close_reader: slot=%d\n", slot);
3264
3265   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3266     {
3267       if (DBG_READER)
3268         log_debug ("leave: apdu_close_reader => SW_HOST_NO_DRIVER\n");
3269       return SW_HOST_NO_DRIVER;
3270     }
3271   sw = apdu_disconnect (slot);
3272   if (sw)
3273     {
3274       /*
3275        * When the reader/token was removed it might come here.
3276        * It should go through to call CLOSE_READER even if we got an error.
3277        */
3278       if (DBG_READER)
3279         log_debug ("apdu_close_reader => 0x%x (apdu_disconnect)\n", sw);
3280     }
3281   if (reader_table[slot].close_reader)
3282     {
3283       sw = reader_table[slot].close_reader (slot);
3284       reader_table[slot].used = 0;
3285       if (DBG_READER)
3286         log_debug ("leave: apdu_close_reader => 0x%x (close_reader)\n", sw);
3287       return sw;
3288     }
3289   xfree (reader_table[slot].rdrname);
3290   reader_table[slot].rdrname = NULL;
3291   reader_table[slot].used = 0;
3292   if (DBG_READER)
3293     log_debug ("leave: apdu_close_reader => SW_HOST_NOT_SUPPORTED\n");
3294   return SW_HOST_NOT_SUPPORTED;
3295 }
3296
3297
3298 /* Function suitable for a cleanup function to close all reader.  It
3299    should not be used if the reader will be opened again.  The reason
3300    for implementing this to properly close USB devices so that they
3301    will startup the next time without error. */
3302 void
3303 apdu_prepare_exit (void)
3304 {
3305   static int sentinel;
3306   int slot;
3307
3308   if (!sentinel)
3309     {
3310       sentinel = 1;
3311       npth_mutex_lock (&reader_table_lock);
3312       for (slot = 0; slot < MAX_READER; slot++)
3313         if (reader_table[slot].used)
3314           {
3315             apdu_disconnect (slot);
3316             if (reader_table[slot].close_reader)
3317               reader_table[slot].close_reader (slot);
3318             xfree (reader_table[slot].rdrname);
3319             reader_table[slot].rdrname = NULL;
3320             reader_table[slot].used = 0;
3321           }
3322       npth_mutex_unlock (&reader_table_lock);
3323       sentinel = 0;
3324     }
3325 }
3326
3327
3328 /* Enumerate all readers and return information on whether this reader
3329    is in use.  The caller should start with SLOT set to 0 and
3330    increment it with each call until an error is returned. */
3331 int
3332 apdu_enum_reader (int slot, int *used)
3333 {
3334   if (slot < 0 || slot >= MAX_READER)
3335     return SW_HOST_NO_DRIVER;
3336   *used = reader_table[slot].used;
3337   return 0;
3338 }
3339
3340
3341 /* Connect a card.  This is used to power up the card and make sure
3342    that an ATR is available.  Depending on the reader backend it may
3343    return an error for an inactive card or if no card is
3344    available.  */
3345 int
3346 apdu_connect (int slot)
3347 {
3348   int sw = 0;
3349   unsigned int status = 0;
3350
3351   if (DBG_READER)
3352     log_debug ("enter: apdu_connect: slot=%d\n", slot);
3353
3354   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3355     {
3356       if (DBG_READER)
3357         log_debug ("leave: apdu_connect => SW_HOST_NO_DRIVER\n");
3358       return SW_HOST_NO_DRIVER;
3359     }
3360
3361   /* Only if the access method provides a connect function we use it.
3362      If not, we expect that the card has been implicitly connected by
3363      apdu_open_reader.  */
3364   if (reader_table[slot].connect_card)
3365     {
3366       sw = lock_slot (slot);
3367       if (!sw)
3368         {
3369           sw = reader_table[slot].connect_card (slot);
3370           unlock_slot (slot);
3371         }
3372     }
3373
3374   /* We need to call apdu_get_status_internal, so that the last-status
3375      machinery gets setup properly even if a card is inserted while
3376      scdaemon is fired up and apdu_get_status has not yet been called.
3377      Without that we would force a reset of the card with the next
3378      call to apdu_get_status.  */
3379   if (!sw)
3380     sw = apdu_get_status_internal (slot, 1, 1, &status);
3381
3382   if (sw)
3383     ;
3384   else if (!(status & APDU_CARD_PRESENT))
3385     sw = SW_HOST_NO_CARD;
3386   else if ((status & APDU_CARD_PRESENT) && !(status & APDU_CARD_ACTIVE))
3387     sw = SW_HOST_CARD_INACTIVE;
3388
3389   if (DBG_READER)
3390     log_debug ("leave: apdu_connect => sw=0x%x\n", sw);
3391
3392   return sw;
3393 }
3394
3395
3396 int
3397 apdu_disconnect (int slot)
3398 {
3399   int sw;
3400
3401   if (DBG_READER)
3402     log_debug ("enter: apdu_disconnect: slot=%d\n", slot);
3403
3404   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3405     {
3406       if (DBG_READER)
3407         log_debug ("leave: apdu_disconnect => SW_HOST_NO_DRIVER\n");
3408       return SW_HOST_NO_DRIVER;
3409     }
3410
3411   if (reader_table[slot].disconnect_card)
3412     {
3413       sw = lock_slot (slot);
3414       if (!sw)
3415         {
3416           sw = reader_table[slot].disconnect_card (slot);
3417           unlock_slot (slot);
3418         }
3419     }
3420   else
3421     sw = 0;
3422
3423   if (DBG_READER)
3424     log_debug ("leave: apdu_disconnect => sw=0x%x\n", sw);
3425   return sw;
3426 }
3427
3428
3429 /* Set the progress callback of SLOT to CB and its args to CB_ARG.  If
3430    CB is NULL the progress callback is removed.  */
3431 int
3432 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
3433 {
3434   int sw;
3435
3436   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3437     return SW_HOST_NO_DRIVER;
3438
3439   if (reader_table[slot].set_progress_cb)
3440     {
3441       sw = lock_slot (slot);
3442       if (!sw)
3443         {
3444           sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
3445           unlock_slot (slot);
3446         }
3447     }
3448   else
3449     sw = 0;
3450   return sw;
3451 }
3452
3453
3454 /* Do a reset for the card in reader at SLOT. */
3455 int
3456 apdu_reset (int slot)
3457 {
3458   int sw;
3459
3460   if (DBG_READER)
3461     log_debug ("enter: apdu_reset: slot=%d\n", slot);
3462
3463   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3464     {
3465       if (DBG_READER)
3466         log_debug ("leave: apdu_reset => SW_HOST_NO_DRIVER\n");
3467       return SW_HOST_NO_DRIVER;
3468     }
3469
3470   if ((sw = lock_slot (slot)))
3471     {
3472       if (DBG_READER)
3473         log_debug ("leave: apdu_reset => sw=0x%x (lock_slot)\n", sw);
3474       return sw;
3475     }
3476
3477   if (reader_table[slot].reset_reader)
3478     sw = reader_table[slot].reset_reader (slot);
3479
3480   unlock_slot (slot);
3481   if (DBG_READER)
3482     log_debug ("leave: apdu_reset => sw=0x%x\n", sw);
3483   return sw;
3484 }
3485
3486
3487 /* Return the ATR or NULL if none is available.  On success the length
3488    of the ATR is stored at ATRLEN.  The caller must free the returned
3489    value.  */
3490 unsigned char *
3491 apdu_get_atr (int slot, size_t *atrlen)
3492 {
3493   unsigned char *buf;
3494
3495   if (DBG_READER)
3496     log_debug ("enter: apdu_get_atr: slot=%d\n", slot);
3497
3498   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3499     {
3500       if (DBG_READER)
3501         log_debug ("leave: apdu_get_atr => NULL (bad slot)\n");
3502       return NULL;
3503     }
3504   if (!reader_table[slot].atrlen)
3505     {
3506       if (DBG_READER)
3507         log_debug ("leave: apdu_get_atr => NULL (no ATR)\n");
3508       return NULL;
3509     }
3510
3511   buf = xtrymalloc (reader_table[slot].atrlen);
3512   if (!buf)
3513     {
3514       if (DBG_READER)
3515         log_debug ("leave: apdu_get_atr => NULL (out of core)\n");
3516       return NULL;
3517     }
3518   memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
3519   *atrlen = reader_table[slot].atrlen;
3520   if (DBG_READER)
3521     log_debug ("leave: apdu_get_atr => atrlen=%zu\n", *atrlen);
3522   return buf;
3523 }
3524
3525
3526
3527 /* Retrieve the status for SLOT. The function does only wait for the
3528    card to become available if HANG is set to true. On success the
3529    bits in STATUS will be set to
3530
3531      APDU_CARD_USABLE  (bit 0) = card present and usable
3532      APDU_CARD_PRESENT (bit 1) = card present
3533      APDU_CARD_ACTIVE  (bit 2) = card active
3534                        (bit 3) = card access locked [not yet implemented]
3535
3536    For must applications, testing bit 0 is sufficient.
3537 */
3538 static int
3539 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
3540                           unsigned int *status)
3541 {
3542   int sw;
3543   unsigned int s;
3544
3545   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3546     return SW_HOST_NO_DRIVER;
3547
3548   if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
3549     return sw;
3550
3551   if (reader_table[slot].get_status_reader)
3552     sw = reader_table[slot].get_status_reader (slot, &s);
3553
3554   unlock_slot (slot);
3555
3556   if (sw)
3557     {
3558       if (!no_atr_reset)
3559         reader_table[slot].atrlen = 0;
3560       s = 0;
3561     }
3562
3563   if (status)
3564     *status = s;
3565   return sw;
3566 }
3567
3568
3569 /* See above for a description.  */
3570 int
3571 apdu_get_status (int slot, int hang, unsigned int *status)
3572 {
3573   int sw;
3574
3575   if (DBG_READER)
3576     log_debug ("enter: apdu_get_status: slot=%d hang=%d\n", slot, hang);
3577   sw = apdu_get_status_internal (slot, hang, 0, status);
3578   if (DBG_READER)
3579     {
3580       if (status)
3581         log_debug ("leave: apdu_get_status => sw=0x%x status=%u\n",
3582                    sw, *status);
3583       else
3584         log_debug ("leave: apdu_get_status => sw=0x%x\n", sw);
3585     }
3586   return sw;
3587 }
3588
3589
3590 /* Check whether the reader supports the ISO command code COMMAND on
3591    the pinpad.  Return 0 on success.  For a description of the pin
3592    parameters, see ccid-driver.c */
3593 int
3594 apdu_check_pinpad (int slot, int command, pininfo_t *pininfo)
3595 {
3596   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3597     return SW_HOST_NO_DRIVER;
3598
3599   if (opt.enable_pinpad_varlen)
3600     pininfo->fixedlen = 0;
3601
3602   if (reader_table[slot].check_pinpad)
3603     {
3604       int sw;
3605
3606       if ((sw = lock_slot (slot)))
3607         return sw;
3608
3609       sw = reader_table[slot].check_pinpad (slot, command, pininfo);
3610       unlock_slot (slot);
3611       return sw;
3612     }
3613   else
3614     return SW_HOST_NOT_SUPPORTED;
3615 }
3616
3617
3618 int
3619 apdu_pinpad_verify (int slot, int class, int ins, int p0, int p1,
3620                     pininfo_t *pininfo)
3621 {
3622   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3623     return SW_HOST_NO_DRIVER;
3624
3625   if (reader_table[slot].pinpad_verify)
3626     {
3627       int sw;
3628
3629       if ((sw = lock_slot (slot)))
3630         return sw;
3631
3632       sw = reader_table[slot].pinpad_verify (slot, class, ins, p0, p1,
3633                                              pininfo);
3634       unlock_slot (slot);
3635       return sw;
3636     }
3637   else
3638     return SW_HOST_NOT_SUPPORTED;
3639 }
3640
3641
3642 int
3643 apdu_pinpad_modify (int slot, int class, int ins, int p0, int p1,
3644                     pininfo_t *pininfo)
3645 {
3646   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3647     return SW_HOST_NO_DRIVER;
3648
3649   if (reader_table[slot].pinpad_modify)
3650     {
3651       int sw;
3652
3653       if ((sw = lock_slot (slot)))
3654         return sw;
3655
3656       sw = reader_table[slot].pinpad_modify (slot, class, ins, p0, p1,
3657                                              pininfo);
3658       unlock_slot (slot);
3659       return sw;
3660     }
3661   else
3662     return SW_HOST_NOT_SUPPORTED;
3663 }
3664
3665
3666 /* Dispatcher for the actual send_apdu function. Note, that this
3667    function should be called in locked state. */
3668 static int
3669 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
3670            unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
3671 {
3672   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3673     return SW_HOST_NO_DRIVER;
3674
3675   if (reader_table[slot].send_apdu_reader)
3676     return reader_table[slot].send_apdu_reader (slot,
3677                                                 apdu, apdulen,
3678                                                 buffer, buflen,
3679                                                 pininfo);
3680   else
3681     return SW_HOST_NOT_SUPPORTED;
3682 }
3683
3684
3685 /* Core APDU tranceiver function. Parameters are described at
3686    apdu_send_le with the exception of PININFO which indicates pinpad
3687    related operations if not NULL.  If EXTENDED_MODE is not 0
3688    command chaining or extended length will be used according to these
3689    values:
3690        n < 0 := Use command chaining with the data part limited to -n
3691                 in each chunk.  If -1 is used a default value is used.
3692       n == 0 := No extended mode or command chaining.
3693       n == 1 := Use extended length for input and output without a
3694                 length limit.
3695        n > 1 := Use extended length with up to N bytes.
3696
3697 */
3698 static int
3699 send_le (int slot, int class, int ins, int p0, int p1,
3700          int lc, const char *data, int le,
3701          unsigned char **retbuf, size_t *retbuflen,
3702          pininfo_t *pininfo, int extended_mode)
3703 {
3704 #define SHORT_RESULT_BUFFER_SIZE 258
3705   /* We allocate 8 extra bytes as a safety margin towards a driver bug.  */
3706   unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3707   unsigned char *result_buffer = NULL;
3708   size_t result_buffer_size;
3709   unsigned char *result;
3710   size_t resultlen;
3711   unsigned char short_apdu_buffer[5+256+1];
3712   unsigned char *apdu_buffer = NULL;
3713   size_t apdu_buffer_size;
3714   unsigned char *apdu;
3715   size_t apdulen;
3716   int sw;
3717   long rc; /* We need a long here due to PC/SC. */
3718   int did_exact_length_hack = 0;
3719   int use_chaining = 0;
3720   int use_extended_length = 0;
3721   int lc_chunk;
3722
3723   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3724     return SW_HOST_NO_DRIVER;
3725
3726   if (DBG_CARD_IO)
3727     log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
3728                class, ins, p0, p1, lc, le, extended_mode);
3729
3730   if (lc != -1 && (lc > 255 || lc < 0))
3731     {
3732       /* Data does not fit into an APDU.  What we do now depends on
3733          the EXTENDED_MODE parameter.  */
3734       if (!extended_mode)
3735         return SW_WRONG_LENGTH; /* No way to send such an APDU.  */
3736       else if (extended_mode > 0)
3737         use_extended_length = 1;
3738       else if (extended_mode < 0)
3739         {
3740           /* Send APDU using chaining mode.  */
3741           if (lc > 16384)
3742             return SW_WRONG_LENGTH;   /* Sanity check.  */
3743           if ((class&0xf0) != 0)
3744             return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0.  */
3745           use_chaining = extended_mode == -1? 255 : -extended_mode;
3746           use_chaining &= 0xff;
3747         }
3748       else
3749         return SW_HOST_INV_VALUE;
3750     }
3751   else if (lc == -1 && extended_mode > 0)
3752     use_extended_length = 1;
3753
3754   if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
3755     {
3756       /* Expected Data does not fit into an APDU.  What we do now
3757          depends on the EXTENDED_MODE parameter.  Note that a check
3758          for command chaining does not make sense because we are
3759          looking at Le.  */
3760       if (!extended_mode)
3761         return SW_WRONG_LENGTH; /* No way to send such an APDU.  */
3762       else if (use_extended_length)
3763         ; /* We are already using extended length.  */
3764       else if (extended_mode > 0)
3765         use_extended_length = 1;
3766       else
3767         return SW_HOST_INV_VALUE;
3768     }
3769
3770   if ((!data && lc != -1) || (data && lc == -1))
3771     return SW_HOST_INV_VALUE;
3772
3773   if (use_extended_length)
3774     {
3775       if (reader_table[slot].is_t0)
3776         return SW_HOST_NOT_SUPPORTED;
3777
3778       /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le.  */
3779       apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
3780       apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
3781       if (!apdu_buffer)
3782         return SW_HOST_OUT_OF_CORE;
3783       apdu = apdu_buffer;
3784     }
3785   else
3786     {
3787       apdu_buffer_size = sizeof short_apdu_buffer;
3788       apdu = short_apdu_buffer;
3789     }
3790
3791   if (use_extended_length && (le > 256 || le < 0))
3792     {
3793       /* Two more bytes are needed for status bytes.  */
3794       result_buffer_size = le < 0? 4096 : (le + 2);
3795       result_buffer = xtrymalloc (result_buffer_size);
3796       if (!result_buffer)
3797         {
3798           xfree (apdu_buffer);
3799           return SW_HOST_OUT_OF_CORE;
3800         }
3801       result = result_buffer;
3802     }
3803   else
3804     {
3805       result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3806       result = short_result_buffer;
3807     }
3808 #undef SHORT_RESULT_BUFFER_SIZE
3809
3810   if ((sw = lock_slot (slot)))
3811     {
3812       xfree (apdu_buffer);
3813       xfree (result_buffer);
3814       return sw;
3815     }
3816
3817   do
3818     {
3819       if (use_extended_length)
3820         {
3821           use_chaining = 0;
3822           apdulen = 0;
3823           apdu[apdulen++] = class;
3824           apdu[apdulen++] = ins;
3825           apdu[apdulen++] = p0;
3826           apdu[apdulen++] = p1;
3827           if (lc > 0)
3828             {
3829               apdu[apdulen++] = 0;  /* Z byte: Extended length marker.  */
3830               apdu[apdulen++] = ((lc >> 8) & 0xff);
3831               apdu[apdulen++] = (lc & 0xff);
3832               memcpy (apdu+apdulen, data, lc);
3833               data += lc;
3834               apdulen += lc;
3835             }
3836           if (le != -1)
3837             {
3838               if (lc <= 0)
3839                 apdu[apdulen++] = 0;  /* Z byte: Extended length marker.  */
3840               apdu[apdulen++] = ((le >> 8) & 0xff);
3841               apdu[apdulen++] = (le & 0xff);
3842             }
3843         }
3844       else
3845         {
3846           apdulen = 0;
3847           apdu[apdulen] = class;
3848           if (use_chaining && lc > 255)
3849             {
3850               apdu[apdulen] |= 0x10;
3851               assert (use_chaining < 256);
3852               lc_chunk = use_chaining;
3853               lc -= use_chaining;
3854             }
3855           else
3856             {
3857               use_chaining = 0;
3858               lc_chunk = lc;
3859             }
3860           apdulen++;
3861           apdu[apdulen++] = ins;
3862           apdu[apdulen++] = p0;
3863           apdu[apdulen++] = p1;
3864           if (lc_chunk != -1)
3865             {
3866               apdu[apdulen++] = lc_chunk;
3867               memcpy (apdu+apdulen, data, lc_chunk);
3868               data += lc_chunk;
3869               apdulen += lc_chunk;
3870               /* T=0 does not allow the use of Lc together with Le;
3871                  thus disable Le in this case.  */
3872               if (reader_table[slot].is_t0)
3873                 le = -1;
3874             }
3875           if (le != -1 && !use_chaining)
3876             apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3877         }
3878
3879     exact_length_hack:
3880       /* As a safeguard don't pass any garbage to the driver.  */
3881       assert (apdulen <= apdu_buffer_size);
3882       memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3883       resultlen = result_buffer_size;
3884       rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3885       if (rc || resultlen < 2)
3886         {
3887           log_info ("apdu_send_simple(%d) failed: %s\n",
3888                     slot, apdu_strerror (rc));
3889           unlock_slot (slot);
3890           xfree (apdu_buffer);
3891           xfree (result_buffer);
3892           return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3893         }
3894       sw = (result[resultlen-2] << 8) | result[resultlen-1];
3895       if (!use_extended_length
3896           && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3897         {
3898           apdu[apdulen-1] = (sw & 0x00ff);
3899           did_exact_length_hack = 1;
3900           goto exact_length_hack;
3901         }
3902     }
3903   while (use_chaining && sw == SW_SUCCESS);
3904
3905   if (apdu_buffer)
3906     {
3907       xfree (apdu_buffer);
3908       apdu_buffer = NULL;
3909       apdu_buffer_size = 0;
3910     }
3911
3912   /* Store away the returned data but strip the statusword. */
3913   resultlen -= 2;
3914   if (DBG_CARD_IO)
3915     {
3916       log_debug (" response: sw=%04X  datalen=%d\n",
3917                  sw, (unsigned int)resultlen);
3918       if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3919         log_printhex ("    dump: ", result, resultlen);
3920     }
3921
3922   if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3923     {
3924       if (retbuf)
3925         {
3926           *retbuf = xtrymalloc (resultlen? resultlen : 1);
3927           if (!*retbuf)
3928             {
3929               unlock_slot (slot);
3930               xfree (result_buffer);
3931               return SW_HOST_OUT_OF_CORE;
3932             }
3933           *retbuflen = resultlen;
3934           memcpy (*retbuf, result, resultlen);
3935         }
3936     }
3937   else if ((sw & 0xff00) == SW_MORE_DATA)
3938     {
3939       unsigned char *p = NULL, *tmp;
3940       size_t bufsize = 4096;
3941
3942       /* It is likely that we need to return much more data, so we
3943          start off with a large buffer. */
3944       if (retbuf)
3945         {
3946           *retbuf = p = xtrymalloc (bufsize);
3947           if (!*retbuf)
3948             {
3949               unlock_slot (slot);
3950               xfree (result_buffer);
3951               return SW_HOST_OUT_OF_CORE;
3952             }
3953           assert (resultlen < bufsize);
3954           memcpy (p, result, resultlen);
3955           p += resultlen;
3956         }
3957
3958       do
3959         {
3960           int len = (sw & 0x00ff);
3961
3962           if (DBG_CARD_IO)
3963             log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3964                        slot, len);
3965           apdu_buffer_size = sizeof short_apdu_buffer;
3966           apdu = short_apdu_buffer;
3967           apdulen = 0;
3968           apdu[apdulen++] = class;
3969           apdu[apdulen++] = 0xC0;
3970           apdu[apdulen++] = 0;
3971           apdu[apdulen++] = 0;
3972           apdu[apdulen++] = len;
3973           assert (apdulen <= apdu_buffer_size);
3974           memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3975           resultlen = result_buffer_size;
3976           rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3977           if (rc || resultlen < 2)
3978             {
3979               log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3980                          slot, apdu_strerror (rc));
3981               unlock_slot (slot);
3982               xfree (result_buffer);
3983               return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3984             }
3985           sw = (result[resultlen-2] << 8) | result[resultlen-1];
3986           resultlen -= 2;
3987           if (DBG_CARD_IO)
3988             {
3989               log_debug ("     more: sw=%04X  datalen=%d\n",
3990                          sw, (unsigned int)resultlen);
3991               if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3992                 log_printhex ("     dump: ", result, resultlen);
3993             }
3994
3995           if ((sw & 0xff00) == SW_MORE_DATA
3996               || sw == SW_SUCCESS
3997               || sw == SW_EOF_REACHED )
3998             {
3999               if (retbuf && resultlen)
4000                 {
4001                   if (p - *retbuf + resultlen > bufsize)
4002                     {
4003                       bufsize += resultlen > 4096? resultlen: 4096;
4004                       tmp = xtryrealloc (*retbuf, bufsize);
4005                       if (!tmp)
4006                         {
4007                           unlock_slot (slot);
4008                           xfree (result_buffer);
4009                           return SW_HOST_OUT_OF_CORE;
4010                         }
4011                       p = tmp + (p - *retbuf);
4012                       *retbuf = tmp;
4013                     }
4014                   memcpy (p, result, resultlen);
4015                   p += resultlen;
4016                 }
4017             }
4018           else
4019             log_info ("apdu_send_simple(%d) "
4020                       "got unexpected status %04X from get response\n",
4021                       slot, sw);
4022         }
4023       while ((sw & 0xff00) == SW_MORE_DATA);
4024
4025       if (retbuf)
4026         {
4027           *retbuflen = p - *retbuf;
4028           tmp = xtryrealloc (*retbuf, *retbuflen);
4029           if (tmp)
4030             *retbuf = tmp;
4031         }
4032     }
4033
4034   unlock_slot (slot);
4035   xfree (result_buffer);
4036
4037   if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
4038     log_printhex ("      dump: ", *retbuf, *retbuflen);
4039
4040   return sw;
4041 }
4042
4043 /* Send an APDU to the card in SLOT.  The APDU is created from all
4044    given parameters: CLASS, INS, P0, P1, LC, DATA, LE.  A value of -1
4045    for LC won't sent this field and the data field; in this case DATA
4046    must also be passed as NULL.  If EXTENDED_MODE is not 0 command
4047    chaining or extended length will be used; see send_le for details.
4048    The return value is the status word or -1 for an invalid SLOT or
4049    other non card related error.  If RETBUF is not NULL, it will
4050    receive an allocated buffer with the returned data.  The length of
4051    that data will be put into *RETBUFLEN.  The caller is responsible
4052    for releasing the buffer even in case of errors.  */
4053 int
4054 apdu_send_le(int slot, int extended_mode,
4055              int class, int ins, int p0, int p1,
4056              int lc, const char *data, int le,
4057              unsigned char **retbuf, size_t *retbuflen)
4058 {
4059   return send_le (slot, class, ins, p0, p1,
4060                   lc, data, le,
4061                   retbuf, retbuflen,
4062                   NULL, extended_mode);
4063 }
4064
4065
4066 /* Send an APDU to the card in SLOT.  The APDU is created from all
4067    given parameters: CLASS, INS, P0, P1, LC, DATA.  A value of -1 for
4068    LC won't sent this field and the data field; in this case DATA must
4069    also be passed as NULL.  If EXTENDED_MODE is not 0 command chaining
4070    or extended length will be used; see send_le for details.  The
4071    return value is the status word or -1 for an invalid SLOT or other
4072    non card related error.  If RETBUF is not NULL, it will receive an
4073    allocated buffer with the returned data.  The length of that data
4074    will be put into *RETBUFLEN.  The caller is responsible for
4075    releasing the buffer even in case of errors.  */
4076 int
4077 apdu_send (int slot, int extended_mode,
4078            int class, int ins, int p0, int p1,
4079            int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
4080 {
4081   return send_le (slot, class, ins, p0, p1, lc, data, 256,
4082                   retbuf, retbuflen, NULL, extended_mode);
4083 }
4084
4085 /* Send an APDU to the card in SLOT.  The APDU is created from all
4086    given parameters: CLASS, INS, P0, P1, LC, DATA.  A value of -1 for
4087    LC won't sent this field and the data field; in this case DATA must
4088    also be passed as NULL.  If EXTENDED_MODE is not 0 command chaining
4089    or extended length will be used; see send_le for details.  The
4090    return value is the status word or -1 for an invalid SLOT or other
4091    non card related error.  No data will be returned.  */
4092 int
4093 apdu_send_simple (int slot, int extended_mode,
4094                   int class, int ins, int p0, int p1,
4095                   int lc, const char *data)
4096 {
4097   return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
4098                   extended_mode);
4099 }
4100
4101
4102 /* This is a more generic version of the apdu sending routine.  It
4103    takes an already formatted APDU in APDUDATA or length APDUDATALEN
4104    and returns with an APDU including the status word.  With
4105    HANDLE_MORE set to true this function will handle the MORE DATA
4106    status and return all APDUs concatenated with one status word at
4107    the end.  If EXTENDED_LENGTH is != 0 extended lengths are allowed
4108    with a max. result data length of EXTENDED_LENGTH bytes.  The
4109    function does not return a regular status word but 0 on success.
4110    If the slot is locked, the function returns immediately with an
4111    error.  */
4112 int
4113 apdu_send_direct (int slot, size_t extended_length,
4114                   const unsigned char *apdudata, size_t apdudatalen,
4115                   int handle_more,
4116                   unsigned char **retbuf, size_t *retbuflen)
4117 {
4118 #define SHORT_RESULT_BUFFER_SIZE 258
4119   unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
4120   unsigned char *result_buffer = NULL;
4121   size_t result_buffer_size;
4122   unsigned char *result;
4123   size_t resultlen;
4124   unsigned char short_apdu_buffer[5+256+10];
4125   unsigned char *apdu_buffer = NULL;
4126   unsigned char *apdu;
4127   size_t apdulen;
4128   int sw;
4129   long rc; /* we need a long here due to PC/SC. */
4130   int class;
4131
4132   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
4133     return SW_HOST_NO_DRIVER;
4134
4135   if (apdudatalen > 65535)
4136     return SW_HOST_INV_VALUE;
4137
4138   if (apdudatalen > sizeof short_apdu_buffer - 5)
4139     {
4140       apdu_buffer = xtrymalloc (apdudatalen + 5);
4141       if (!apdu_buffer)
4142         return SW_HOST_OUT_OF_CORE;
4143       apdu = apdu_buffer;
4144     }
4145   else
4146     {
4147       apdu = short_apdu_buffer;
4148     }
4149   apdulen = apdudatalen;
4150   memcpy (apdu, apdudata, apdudatalen);
4151   class = apdulen? *apdu : 0;
4152
4153   if (extended_length >= 256 && extended_length <= 65536)
4154     {
4155       result_buffer_size = extended_length;
4156       result_buffer = xtrymalloc (result_buffer_size + 10);
4157       if (!result_buffer)
4158         {
4159           xfree (apdu_buffer);
4160           return SW_HOST_OUT_OF_CORE;
4161         }
4162       result = result_buffer;
4163     }
4164   else
4165     {
4166       result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
4167       result = short_result_buffer;
4168     }
4169 #undef SHORT_RESULT_BUFFER_SIZE
4170
4171   if ((sw = trylock_slot (slot)))
4172     {
4173       xfree (apdu_buffer);
4174       xfree (result_buffer);
4175       return sw;
4176     }
4177
4178   resultlen = result_buffer_size;
4179   rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
4180   xfree (apdu_buffer);
4181   apdu_buffer = NULL;
4182   if (rc || resultlen < 2)
4183     {
4184       log_error ("apdu_send_direct(%d) failed: %s\n",
4185                  slot, apdu_strerror (rc));
4186       unlock_slot (slot);
4187       xfree (result_buffer);
4188       return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
4189     }
4190   sw = (result[resultlen-2] << 8) | result[resultlen-1];
4191   /* Store away the returned data but strip the statusword. */
4192   resultlen -= 2;
4193   if (DBG_CARD_IO)
4194     {
4195       log_debug (" response: sw=%04X  datalen=%d\n",
4196                  sw, (unsigned int)resultlen);
4197       if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
4198         log_printhex ("     dump: ", result, resultlen);
4199     }
4200
4201   if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
4202     {
4203       unsigned char *p = NULL, *tmp;
4204       size_t bufsize = 4096;
4205
4206       /* It is likely that we need to return much more data, so we
4207          start off with a large buffer. */
4208       if (retbuf)
4209         {
4210           *retbuf = p = xtrymalloc (bufsize + 2);
4211           if (!*retbuf)
4212             {
4213               unlock_slot (slot);
4214               xfree (result_buffer);
4215               return SW_HOST_OUT_OF_CORE;
4216             }
4217           assert (resultlen < bufsize);
4218           memcpy (p, result, resultlen);
4219           p += resultlen;
4220         }
4221
4222       do
4223         {
4224           int len = (sw & 0x00ff);
4225
4226           if (DBG_CARD_IO)
4227             log_debug ("apdu_send_direct(%d): %d more bytes available\n",
4228                        slot, len);
4229           apdu = short_apdu_buffer;
4230           apdulen = 0;
4231           apdu[apdulen++] = class;
4232           apdu[apdulen++] = 0xC0;
4233           apdu[apdulen++] = 0;
4234           apdu[apdulen++] = 0;
4235           apdu[apdulen++] = len;
4236           memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
4237           resultlen = result_buffer_size;
4238           rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
4239           if (rc || resultlen < 2)
4240             {
4241               log_error ("apdu_send_direct(%d) for get response failed: %s\n",
4242                          slot, apdu_strerror (rc));
4243               unlock_slot (slot);
4244               xfree (result_buffer);
4245               return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
4246             }
4247           sw = (result[resultlen-2] << 8) | result[resultlen-1];
4248           resultlen -= 2;
4249           if (DBG_CARD_IO)
4250             {
4251               log_debug ("     more: sw=%04X  datalen=%d\n",
4252                          sw, (unsigned int)resultlen);
4253               if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
4254                 log_printhex ("     dump: ", result, resultlen);
4255             }
4256
4257           if ((sw & 0xff00) == SW_MORE_DATA
4258               || sw == SW_SUCCESS
4259               || sw == SW_EOF_REACHED )
4260             {
4261               if (retbuf && resultlen)
4262                 {
4263                   if (p - *retbuf + resultlen > bufsize)
4264                     {
4265                       bufsize += resultlen > 4096? resultlen: 4096;
4266                       tmp = xtryrealloc (*retbuf, bufsize + 2);
4267                       if (!tmp)
4268                         {
4269                           unlock_slot (slot);
4270                           xfree (result_buffer);
4271                           return SW_HOST_OUT_OF_CORE;
4272                         }
4273                       p = tmp + (p - *retbuf);
4274                       *retbuf = tmp;
4275                     }
4276                   memcpy (p, result, resultlen);
4277                   p += resultlen;
4278                 }
4279             }
4280           else
4281             log_info ("apdu_send_direct(%d) "
4282                       "got unexpected status %04X from get response\n",
4283                       slot, sw);
4284         }
4285       while ((sw & 0xff00) == SW_MORE_DATA);
4286
4287       if (retbuf)
4288         {
4289           *retbuflen = p - *retbuf;
4290           tmp = xtryrealloc (*retbuf, *retbuflen + 2);
4291           if (tmp)
4292             *retbuf = tmp;
4293         }
4294     }
4295   else
4296     {
4297       if (retbuf)
4298         {
4299           *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
4300           if (!*retbuf)
4301             {
4302               unlock_slot (slot);
4303               xfree (result_buffer);
4304               return SW_HOST_OUT_OF_CORE;
4305             }
4306           *retbuflen = resultlen;
4307           memcpy (*retbuf, result, resultlen);
4308         }
4309     }
4310
4311   unlock_slot (slot);
4312   xfree (result_buffer);
4313
4314   /* Append the status word.  Note that we reserved the two extra
4315      bytes while allocating the buffer.  */
4316   if (retbuf)
4317     {
4318       (*retbuf)[(*retbuflen)++] = (sw >> 8);
4319       (*retbuf)[(*retbuflen)++] = sw;
4320     }
4321
4322   if (DBG_CARD_IO && retbuf)
4323     log_printhex ("      dump: ", *retbuf, *retbuflen);
4324
4325   return 0;
4326 }
4327
4328
4329 const char *
4330 apdu_get_reader_name (int slot)
4331 {
4332   return reader_table[slot].rdrname;
4333 }
4334
4335 gpg_error_t
4336 apdu_init (void)
4337 {
4338 #ifdef USE_NPTH
4339   gpg_error_t err;
4340   int i;
4341
4342   if (npth_mutex_init (&reader_table_lock, NULL))
4343     goto leave;
4344
4345   for (i = 0; i < MAX_READER; i++)
4346     if (npth_mutex_init (&reader_table[i].lock, NULL))
4347       goto leave;
4348
4349   /* All done well.  */
4350   return 0;
4351
4352  leave:
4353   err = gpg_error_from_syserror ();
4354   log_error ("apdu: error initializing mutex: %s\n", gpg_strerror (err));
4355   return err;
4356 #endif /*USE_NPTH*/
4357   return 0;
4358 }