97624ebad5aedfd9b61606a773f4fa5abbe89110
[platform/upstream/gpg2.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 "../common/options.h"
52 #include "errors.h"
53 #include "memory.h"
54 #include "../common/util.h"
55 #include "../common/i18n.h"
56 #include "dynload.h"
57 #include "cardglue.h"
58 #else /* GNUPG_MAJOR_VERSION != 1 */
59 #include "scdaemon.h"
60 #include "../common/exechelp.h"
61 #endif /* GNUPG_MAJOR_VERSION != 1 */
62 #include "../common/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 #define MAX_READER 4 /* Number of readers we support concurrently. */
77
78
79 #if defined(_WIN32) || defined(__CYGWIN__)
80 #define DLSTDCALL __stdcall
81 #else
82 #define DLSTDCALL
83 #endif
84
85 #if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
86 typedef unsigned int pcsc_dword_t;
87 #else
88 typedef unsigned long pcsc_dword_t;
89 #endif
90
91 /* A structure to collect information pertaining to one reader
92    slot. */
93 struct reader_table_s {
94   int used;            /* True if slot is used. */
95   unsigned short port; /* Port number:  0 = unused, 1 - dev/tty */
96
97   /* Function pointers initialized to the various backends.  */
98   int (*connect_card)(int);
99   int (*disconnect_card)(int);
100   int (*close_reader)(int);
101   int (*reset_reader)(int);
102   int (*get_status_reader)(int, unsigned int *, int);
103   int (*send_apdu_reader)(int,unsigned char *,size_t,
104                           unsigned char *, size_t *, pininfo_t *);
105   int (*check_pinpad)(int, int, pininfo_t *);
106   void (*dump_status_reader)(int);
107   int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
108   int (*pinpad_verify)(int, int, int, int, int, pininfo_t *);
109   int (*pinpad_modify)(int, int, int, int, int, pininfo_t *);
110
111   struct {
112     ccid_driver_t handle;
113   } ccid;
114   struct {
115     long context;
116     long card;
117     pcsc_dword_t protocol;
118     pcsc_dword_t verify_ioctl;
119     pcsc_dword_t modify_ioctl;
120     int pinmin;
121     int pinmax;
122   } pcsc;
123 #ifdef USE_G10CODE_RAPDU
124   struct {
125     rapdu_t handle;
126   } rapdu;
127 #endif /*USE_G10CODE_RAPDU*/
128   char *rdrname;     /* Name of the connected reader or NULL if unknown. */
129   unsigned int is_t0:1;     /* True if we know that we are running T=0. */
130   unsigned int is_spr532:1; /* True if we know that the reader is a SPR532.  */
131   unsigned int pinpad_varlen_supported:1;  /* True if we know that the reader
132                                               supports variable length pinpad
133                                               input.  */
134   unsigned int require_get_status:1;
135   unsigned char atr[33];
136   size_t atrlen;           /* A zero length indicates that the ATR has
137                               not yet been read; i.e. the card is not
138                               ready for use. */
139 #ifdef USE_NPTH
140   npth_mutex_t lock;
141 #endif
142 };
143 typedef struct reader_table_s *reader_table_t;
144
145 /* A global table to keep track of active readers. */
146 static struct reader_table_s reader_table[MAX_READER];
147
148 #ifdef USE_NPTH
149 static npth_mutex_t reader_table_lock;
150 #endif
151
152
153 /* PC/SC constants and function pointer. */
154 #define PCSC_SCOPE_USER      0
155 #define PCSC_SCOPE_TERMINAL  1
156 #define PCSC_SCOPE_SYSTEM    2
157 #define PCSC_SCOPE_GLOBAL    3
158
159 #define PCSC_PROTOCOL_T0     1
160 #define PCSC_PROTOCOL_T1     2
161 #ifdef HAVE_W32_SYSTEM
162 # define PCSC_PROTOCOL_RAW   0x00010000  /* The active protocol.  */
163 #else
164 # define PCSC_PROTOCOL_RAW   4
165 #endif
166
167 #define PCSC_SHARE_EXCLUSIVE 1
168 #define PCSC_SHARE_SHARED    2
169 #define PCSC_SHARE_DIRECT    3
170
171 #define PCSC_LEAVE_CARD      0
172 #define PCSC_RESET_CARD      1
173 #define PCSC_UNPOWER_CARD    2
174 #define PCSC_EJECT_CARD      3
175
176 #ifdef HAVE_W32_SYSTEM
177 # define PCSC_UNKNOWN    0x0000  /* The driver is not aware of the status.  */
178 # define PCSC_ABSENT     0x0001  /* Card is absent.  */
179 # define PCSC_PRESENT    0x0002  /* Card is present.  */
180 # define PCSC_SWALLOWED  0x0003  /* Card is present and electrical connected. */
181 # define PCSC_POWERED    0x0004  /* Card is powered.  */
182 # define PCSC_NEGOTIABLE 0x0005  /* Card is awaiting PTS.  */
183 # define PCSC_SPECIFIC   0x0006  /* Card is ready for use.  */
184 #else
185 # define PCSC_UNKNOWN    0x0001
186 # define PCSC_ABSENT     0x0002  /* Card is absent.  */
187 # define PCSC_PRESENT    0x0004  /* Card is present.  */
188 # define PCSC_SWALLOWED  0x0008  /* Card is present and electrical connected. */
189 # define PCSC_POWERED    0x0010  /* Card is powered.  */
190 # define PCSC_NEGOTIABLE 0x0020  /* Card is awaiting PTS.  */
191 # define PCSC_SPECIFIC   0x0040  /* Card is ready for use.  */
192 #endif
193
194 #define PCSC_STATE_UNAWARE     0x0000  /* Want status.  */
195 #define PCSC_STATE_IGNORE      0x0001  /* Ignore this reader.  */
196 #define PCSC_STATE_CHANGED     0x0002  /* State has changed.  */
197 #define PCSC_STATE_UNKNOWN     0x0004  /* Reader unknown.  */
198 #define PCSC_STATE_UNAVAILABLE 0x0008  /* Status unavailable.  */
199 #define PCSC_STATE_EMPTY       0x0010  /* Card removed.  */
200 #define PCSC_STATE_PRESENT     0x0020  /* Card inserted.  */
201 #define PCSC_STATE_ATRMATCH    0x0040  /* ATR matches card. */
202 #define PCSC_STATE_EXCLUSIVE   0x0080  /* Exclusive Mode.  */
203 #define PCSC_STATE_INUSE       0x0100  /* Shared mode.  */
204 #define PCSC_STATE_MUTE        0x0200  /* Unresponsive card.  */
205 #ifdef HAVE_W32_SYSTEM
206 # define PCSC_STATE_UNPOWERED  0x0400  /* Card not powerred up.  */
207 #endif
208
209 /* Some PC/SC error codes.  */
210 #define PCSC_E_CANCELLED               0x80100002
211 #define PCSC_E_CANT_DISPOSE            0x8010000E
212 #define PCSC_E_INSUFFICIENT_BUFFER     0x80100008
213 #define PCSC_E_INVALID_ATR             0x80100015
214 #define PCSC_E_INVALID_HANDLE          0x80100003
215 #define PCSC_E_INVALID_PARAMETER       0x80100004
216 #define PCSC_E_INVALID_TARGET          0x80100005
217 #define PCSC_E_INVALID_VALUE           0x80100011
218 #define PCSC_E_NO_MEMORY               0x80100006
219 #define PCSC_E_UNKNOWN_READER          0x80100009
220 #define PCSC_E_TIMEOUT                 0x8010000A
221 #define PCSC_E_SHARING_VIOLATION       0x8010000B
222 #define PCSC_E_NO_SMARTCARD            0x8010000C
223 #define PCSC_E_UNKNOWN_CARD            0x8010000D
224 #define PCSC_E_PROTO_MISMATCH          0x8010000F
225 #define PCSC_E_NOT_READY               0x80100010
226 #define PCSC_E_SYSTEM_CANCELLED        0x80100012
227 #define PCSC_E_NOT_TRANSACTED          0x80100016
228 #define PCSC_E_READER_UNAVAILABLE      0x80100017
229 #define PCSC_E_NO_SERVICE              0x8010001D
230 #define PCSC_E_SERVICE_STOPPED         0x8010001E
231 #define PCSC_W_REMOVED_CARD            0x80100069
232
233 /* Fix pcsc-lite ABI incompatibility.  */
234 #ifndef SCARD_CTL_CODE
235 #ifdef _WIN32
236 #include <winioctl.h>
237 #define SCARD_CTL_CODE(code) CTL_CODE(FILE_DEVICE_SMARTCARD, (code), \
238                                       METHOD_BUFFERED, FILE_ANY_ACCESS)
239 #else
240 #define SCARD_CTL_CODE(code) (0x42000000 + (code))
241 #endif
242 #endif
243
244 #define CM_IOCTL_GET_FEATURE_REQUEST     SCARD_CTL_CODE(3400)
245 #define CM_IOCTL_VENDOR_IFD_EXCHANGE     SCARD_CTL_CODE(1)
246 #define FEATURE_VERIFY_PIN_DIRECT        0x06
247 #define FEATURE_MODIFY_PIN_DIRECT        0x07
248 #define FEATURE_GET_TLV_PROPERTIES       0x12
249
250 #define PCSCv2_PART10_PROPERTY_bEntryValidationCondition 2
251 #define PCSCv2_PART10_PROPERTY_bTimeOut2                 3
252 #define PCSCv2_PART10_PROPERTY_bMinPINSize               6
253 #define PCSCv2_PART10_PROPERTY_bMaxPINSize               7
254 #define PCSCv2_PART10_PROPERTY_wIdVendor                11
255 #define PCSCv2_PART10_PROPERTY_wIdProduct               12
256
257
258 /* The PC/SC error is defined as a long as per specs.  Due to left
259    shifts bit 31 will get sign extended.  We use this mask to fix
260    it. */
261 #define PCSC_ERR_MASK(a)  ((a) & 0xffffffff)
262
263
264 struct pcsc_io_request_s
265 {
266   unsigned long protocol;
267   unsigned long pci_len;
268 };
269
270 typedef struct pcsc_io_request_s *pcsc_io_request_t;
271
272 #ifdef __APPLE__
273 #pragma pack(1)
274 #endif
275
276 struct pcsc_readerstate_s
277 {
278   const char *reader;
279   void *user_data;
280   pcsc_dword_t current_state;
281   pcsc_dword_t event_state;
282   pcsc_dword_t atrlen;
283   unsigned char atr[33];
284 };
285
286 #ifdef __APPLE__
287 #pragma pack()
288 #endif
289
290 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
291
292 long (* DLSTDCALL pcsc_establish_context) (pcsc_dword_t scope,
293                                            const void *reserved1,
294                                            const void *reserved2,
295                                            long *r_context);
296 long (* DLSTDCALL pcsc_release_context) (long context);
297 long (* DLSTDCALL pcsc_list_readers) (long context,
298                                       const char *groups,
299                                       char *readers, pcsc_dword_t*readerslen);
300 long (* DLSTDCALL pcsc_get_status_change) (long context,
301                                            pcsc_dword_t timeout,
302                                            pcsc_readerstate_t readerstates,
303                                            pcsc_dword_t nreaderstates);
304 long (* DLSTDCALL pcsc_connect) (long context,
305                                  const char *reader,
306                                  pcsc_dword_t share_mode,
307                                  pcsc_dword_t preferred_protocols,
308                                  long *r_card,
309                                  pcsc_dword_t *r_active_protocol);
310 long (* DLSTDCALL pcsc_reconnect) (long card,
311                                    pcsc_dword_t share_mode,
312                                    pcsc_dword_t preferred_protocols,
313                                    pcsc_dword_t initialization,
314                                    pcsc_dword_t *r_active_protocol);
315 long (* DLSTDCALL pcsc_disconnect) (long card,
316                                     pcsc_dword_t disposition);
317 long (* DLSTDCALL pcsc_status) (long card,
318                                 char *reader, pcsc_dword_t *readerlen,
319                                 pcsc_dword_t *r_state,
320                                 pcsc_dword_t *r_protocol,
321                                 unsigned char *atr, pcsc_dword_t *atrlen);
322 long (* DLSTDCALL pcsc_begin_transaction) (long card);
323 long (* DLSTDCALL pcsc_end_transaction) (long card,
324                                          pcsc_dword_t disposition);
325 long (* DLSTDCALL pcsc_transmit) (long card,
326                                   const pcsc_io_request_t send_pci,
327                                   const unsigned char *send_buffer,
328                                   pcsc_dword_t send_len,
329                                   pcsc_io_request_t recv_pci,
330                                   unsigned char *recv_buffer,
331                                   pcsc_dword_t *recv_len);
332 long (* DLSTDCALL pcsc_set_timeout) (long context,
333                                      pcsc_dword_t timeout);
334 long (* DLSTDCALL pcsc_control) (long card,
335                                  pcsc_dword_t control_code,
336                                  const void *send_buffer,
337                                  pcsc_dword_t send_len,
338                                  void *recv_buffer,
339                                  pcsc_dword_t recv_len,
340                                  pcsc_dword_t *bytes_returned);
341
342
343 /*  Prototypes.  */
344 static int pcsc_vendor_specific_init (int slot);
345 static int pcsc_get_status (int slot, unsigned int *status, int on_wire);
346 static int reset_pcsc_reader (int slot);
347 static int apdu_get_status_internal (int slot, int hang, unsigned int *status,
348                                      int on_wire);
349 static int check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo);
350 static int pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
351                                pininfo_t *pininfo);
352 static int pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
353                                pininfo_t *pininfo);
354
355
356 \f
357 /*
358       Helper
359  */
360
361 static int
362 lock_slot (int slot)
363 {
364 #ifdef USE_NPTH
365   int err;
366
367   err = npth_mutex_lock (&reader_table[slot].lock);
368   if (err)
369     {
370       log_error ("failed to acquire apdu lock: %s\n", strerror (err));
371       return SW_HOST_LOCKING_FAILED;
372     }
373 #endif /*USE_NPTH*/
374   return 0;
375 }
376
377 static int
378 trylock_slot (int slot)
379 {
380 #ifdef USE_NPTH
381   int err;
382
383   err = npth_mutex_trylock (&reader_table[slot].lock);
384   if (err == EBUSY)
385     return SW_HOST_BUSY;
386   else if (err)
387     {
388       log_error ("failed to acquire apdu lock: %s\n", strerror (err));
389       return SW_HOST_LOCKING_FAILED;
390     }
391 #endif /*USE_NPTH*/
392   return 0;
393 }
394
395 static void
396 unlock_slot (int slot)
397 {
398 #ifdef USE_NPTH
399   int err;
400
401   err = npth_mutex_unlock (&reader_table[slot].lock);
402   if (err)
403     log_error ("failed to release apdu lock: %s\n", strerror (errno));
404 #endif /*USE_NPTH*/
405 }
406
407
408 /* Find an unused reader slot for PORTSTR and put it into the reader
409    table.  Return -1 on error or the index into the reader table.
410    Acquire slot's lock on successful return.  Caller needs to unlock it.  */
411 static int
412 new_reader_slot (void)
413 {
414   int i, reader = -1;
415
416   for (i=0; i < MAX_READER; i++)
417     if (!reader_table[i].used)
418       {
419         reader = i;
420         reader_table[reader].used = 1;
421         break;
422       }
423
424   if (reader == -1)
425     {
426       log_error ("new_reader_slot: out of slots\n");
427       return -1;
428     }
429
430   if (lock_slot (reader))
431     {
432       reader_table[reader].used = 0;
433       return -1;
434     }
435
436   reader_table[reader].connect_card = NULL;
437   reader_table[reader].disconnect_card = NULL;
438   reader_table[reader].close_reader = NULL;
439   reader_table[reader].reset_reader = NULL;
440   reader_table[reader].get_status_reader = NULL;
441   reader_table[reader].send_apdu_reader = NULL;
442   reader_table[reader].check_pinpad = check_pcsc_pinpad;
443   reader_table[reader].dump_status_reader = NULL;
444   reader_table[reader].set_progress_cb = NULL;
445   reader_table[reader].pinpad_verify = pcsc_pinpad_verify;
446   reader_table[reader].pinpad_modify = pcsc_pinpad_modify;
447
448   reader_table[reader].is_t0 = 1;
449   reader_table[reader].is_spr532 = 0;
450   reader_table[reader].pinpad_varlen_supported = 0;
451   reader_table[reader].require_get_status = 1;
452   reader_table[reader].pcsc.verify_ioctl = 0;
453   reader_table[reader].pcsc.modify_ioctl = 0;
454   reader_table[reader].pcsc.pinmin = -1;
455   reader_table[reader].pcsc.pinmax = -1;
456
457   return reader;
458 }
459
460
461 static void
462 dump_reader_status (int slot)
463 {
464   if (!opt.verbose)
465     return;
466
467   if (reader_table[slot].dump_status_reader)
468     reader_table[slot].dump_status_reader (slot);
469
470   if (reader_table[slot].atrlen)
471     {
472       log_info ("slot %d: ATR=", slot);
473       log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
474     }
475 }
476
477
478
479 static const char *
480 host_sw_string (long err)
481 {
482   switch (err)
483     {
484     case 0: return "okay";
485     case SW_HOST_OUT_OF_CORE: return "out of core";
486     case SW_HOST_INV_VALUE: return "invalid value";
487     case SW_HOST_NO_DRIVER: return "no driver";
488     case SW_HOST_NOT_SUPPORTED: return "not supported";
489     case SW_HOST_LOCKING_FAILED: return "locking failed";
490     case SW_HOST_BUSY: return "busy";
491     case SW_HOST_NO_CARD: return "no card";
492     case SW_HOST_CARD_INACTIVE: return "card inactive";
493     case SW_HOST_CARD_IO_ERROR: return "card I/O error";
494     case SW_HOST_GENERAL_ERROR: return "general error";
495     case SW_HOST_NO_READER: return "no reader";
496     case SW_HOST_ABORTED: return "aborted";
497     case SW_HOST_NO_PINPAD: return "no pinpad";
498     case SW_HOST_ALREADY_CONNECTED: return "already connected";
499     default: return "unknown host status error";
500     }
501 }
502
503
504 const char *
505 apdu_strerror (int rc)
506 {
507   switch (rc)
508     {
509     case SW_EOF_REACHED    : return "eof reached";
510     case SW_EEPROM_FAILURE : return "eeprom failure";
511     case SW_WRONG_LENGTH   : return "wrong length";
512     case SW_CHV_WRONG      : return "CHV wrong";
513     case SW_CHV_BLOCKED    : return "CHV blocked";
514     case SW_REF_DATA_INV   : return "referenced data invalidated";
515     case SW_USE_CONDITIONS : return "use conditions not satisfied";
516     case SW_BAD_PARAMETER  : return "bad parameter";
517     case SW_NOT_SUPPORTED  : return "not supported";
518     case SW_FILE_NOT_FOUND : return "file not found";
519     case SW_RECORD_NOT_FOUND:return "record not found";
520     case SW_REF_NOT_FOUND  : return "reference not found";
521     case SW_NOT_ENOUGH_MEMORY: return "not enough memory space in the file";
522     case SW_INCONSISTENT_LC: return "Lc inconsistent with TLV structure.";
523     case SW_INCORRECT_P0_P1: return "incorrect parameters P0,P1";
524     case SW_BAD_LC         : return "Lc inconsistent with P0,P1";
525     case SW_BAD_P0_P1      : return "bad P0,P1";
526     case SW_INS_NOT_SUP    : return "instruction not supported";
527     case SW_CLA_NOT_SUP    : return "class not supported";
528     case SW_SUCCESS        : return "success";
529     default:
530       if ((rc & ~0x00ff) == SW_MORE_DATA)
531         return "more data available";
532       if ( (rc & 0x10000) )
533         return host_sw_string (rc);
534       return "unknown status error";
535     }
536 }
537 \f
538 /*
539        PC/SC Interface
540  */
541
542 static const char *
543 pcsc_error_string (long err)
544 {
545   const char *s;
546
547   if (!err)
548     return "okay";
549   if ((err & 0x80100000) != 0x80100000)
550     return "invalid PC/SC error code";
551   err &= 0xffff;
552   switch (err)
553     {
554     case 0x0002: s = "cancelled"; break;
555     case 0x000e: s = "can't dispose"; break;
556     case 0x0008: s = "insufficient buffer"; break;
557     case 0x0015: s = "invalid ATR"; break;
558     case 0x0003: s = "invalid handle"; break;
559     case 0x0004: s = "invalid parameter"; break;
560     case 0x0005: s = "invalid target"; break;
561     case 0x0011: s = "invalid value"; break;
562     case 0x0006: s = "no memory"; break;
563     case 0x0013: s = "comm error"; break;
564     case 0x0001: s = "internal error"; break;
565     case 0x0014: s = "unknown error"; break;
566     case 0x0007: s = "waited too long"; break;
567     case 0x0009: s = "unknown reader"; break;
568     case 0x000a: s = "timeout"; break;
569     case 0x000b: s = "sharing violation"; break;
570     case 0x000c: s = "no smartcard"; break;
571     case 0x000d: s = "unknown card"; break;
572     case 0x000f: s = "proto mismatch"; break;
573     case 0x0010: s = "not ready"; break;
574     case 0x0012: s = "system cancelled"; break;
575     case 0x0016: s = "not transacted"; break;
576     case 0x0017: s = "reader unavailable"; break;
577     case 0x0065: s = "unsupported card"; break;
578     case 0x0066: s = "unresponsive card"; break;
579     case 0x0067: s = "unpowered card"; break;
580     case 0x0068: s = "reset card"; break;
581     case 0x0069: s = "removed card"; break;
582     case 0x006a: s = "inserted card"; break;
583     case 0x001f: s = "unsupported feature"; break;
584     case 0x0019: s = "PCI too small"; break;
585     case 0x001a: s = "reader unsupported"; break;
586     case 0x001b: s = "duplicate reader"; break;
587     case 0x001c: s = "card unsupported"; break;
588     case 0x001d: s = "no service"; break;
589     case 0x001e: s = "service stopped"; break;
590     default:     s = "unknown PC/SC error code"; break;
591     }
592   return s;
593 }
594
595 /* Map PC/SC error codes to our special host status words.  */
596 static int
597 pcsc_error_to_sw (long ec)
598 {
599   int rc;
600
601   switch ( PCSC_ERR_MASK (ec) )
602     {
603     case 0:  rc = 0; break;
604
605     case PCSC_E_CANCELLED:           rc = SW_HOST_ABORTED; break;
606     case PCSC_E_NO_MEMORY:           rc = SW_HOST_OUT_OF_CORE; break;
607     case PCSC_E_TIMEOUT:             rc = SW_HOST_CARD_IO_ERROR; break;
608     case PCSC_E_NO_SERVICE:
609     case PCSC_E_SERVICE_STOPPED:
610     case PCSC_E_UNKNOWN_READER:      rc = SW_HOST_NO_READER; break;
611     case PCSC_E_SHARING_VIOLATION:   rc = SW_HOST_LOCKING_FAILED; break;
612     case PCSC_E_NO_SMARTCARD:        rc = SW_HOST_NO_CARD; break;
613     case PCSC_W_REMOVED_CARD:        rc = SW_HOST_NO_CARD; break;
614
615     case PCSC_E_INVALID_TARGET:
616     case PCSC_E_INVALID_VALUE:
617     case PCSC_E_INVALID_HANDLE:
618     case PCSC_E_INVALID_PARAMETER:
619     case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
620
621     default:  rc = SW_HOST_GENERAL_ERROR; break;
622     }
623
624   return rc;
625 }
626
627 static void
628 dump_pcsc_reader_status (int slot)
629 {
630   if (reader_table[slot].pcsc.card)
631     {
632       log_info ("reader slot %d: active protocol:", slot);
633       if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
634         log_printf (" T0");
635       else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
636         log_printf (" T1");
637       else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
638         log_printf (" raw");
639       log_printf ("\n");
640     }
641   else
642     log_info ("reader slot %d: not connected\n", slot);
643 }
644
645
646 static int
647 pcsc_get_status (int slot, unsigned int *status, int on_wire)
648 {
649   long err;
650   struct pcsc_readerstate_s rdrstates[1];
651
652   (void)on_wire;
653   memset (rdrstates, 0, sizeof *rdrstates);
654   rdrstates[0].reader = reader_table[slot].rdrname;
655   rdrstates[0].current_state = PCSC_STATE_UNAWARE;
656   err = pcsc_get_status_change (reader_table[slot].pcsc.context,
657                                 0,
658                                 rdrstates, 1);
659   if (err == PCSC_E_TIMEOUT)
660     err = 0; /* Timeout is no error error here. */
661   if (err)
662     {
663       log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
664                  pcsc_error_string (err), err);
665       return pcsc_error_to_sw (err);
666     }
667
668   /*   log_debug  */
669   /*     ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
670   /*      (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
671   /*      (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
672   /*      (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
673   /*      (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
674   /*      (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
675   /*      (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
676   /*      (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
677   /*      (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
678   /*      (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
679   /*      (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
680
681   *status = 0;
682   if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
683     {
684       *status |= APDU_CARD_PRESENT;
685       if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
686         *status |= APDU_CARD_ACTIVE;
687     }
688 #ifndef HAVE_W32_SYSTEM
689   /* We indicate a useful card if it is not in use by another
690      application.  This is because we only use exclusive access
691      mode.  */
692   if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
693        == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
694        && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
695     *status |= APDU_CARD_USABLE;
696 #else
697   /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
698      time when we are the only user (SCM SCR335) under Windows.  */
699   if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
700       == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
701     *status |= APDU_CARD_USABLE;
702 #endif
703
704   return 0;
705 }
706
707
708 /* Send the APDU of length APDULEN to SLOT and return a maximum of
709    *BUFLEN data in BUFFER, the actual returned size will be stored at
710    BUFLEN.  Returns: A status word. */
711 static int
712 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
713                 unsigned char *buffer, size_t *buflen,
714                 pininfo_t *pininfo)
715 {
716   long err;
717   struct pcsc_io_request_s send_pci;
718   pcsc_dword_t recv_len;
719
720   (void)pininfo;
721
722   if (!reader_table[slot].atrlen
723       && (err = reset_pcsc_reader (slot)))
724     return err;
725
726   if (DBG_CARD_IO)
727     log_printhex ("  PCSC_data:", apdu, apdulen);
728
729   if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
730       send_pci.protocol = PCSC_PROTOCOL_T1;
731   else
732       send_pci.protocol = PCSC_PROTOCOL_T0;
733   send_pci.pci_len = sizeof send_pci;
734   recv_len = *buflen;
735   err = pcsc_transmit (reader_table[slot].pcsc.card,
736                        &send_pci, apdu, apdulen,
737                        NULL, buffer, &recv_len);
738   *buflen = recv_len;
739   if (err)
740     log_error ("pcsc_transmit failed: %s (0x%lx)\n",
741                pcsc_error_string (err), err);
742
743   return pcsc_error_to_sw (err);
744 }
745
746
747 /* Do some control with the value of IOCTL_CODE to the card inserted
748    to SLOT.  Input buffer is specified by CNTLBUF of length LEN.
749    Output buffer is specified by BUFFER of length *BUFLEN, and the
750    actual output size will be stored at BUFLEN.  Returns: A status word.
751    This routine is used for PIN pad input support.  */
752 static int
753 control_pcsc (int slot, pcsc_dword_t ioctl_code,
754               const unsigned char *cntlbuf, size_t len,
755               unsigned char *buffer, pcsc_dword_t *buflen)
756 {
757   long err;
758
759   err = pcsc_control (reader_table[slot].pcsc.card, ioctl_code,
760                       cntlbuf, len, buffer, buflen? *buflen:0, buflen);
761   if (err)
762     {
763       log_error ("pcsc_control failed: %s (0x%lx)\n",
764                  pcsc_error_string (err), err);
765       return pcsc_error_to_sw (err);
766     }
767
768   return 0;
769 }
770
771
772 static int
773 close_pcsc_reader (int slot)
774 {
775   pcsc_release_context (reader_table[slot].pcsc.context);
776   return 0;
777 }
778
779
780 /* Connect a PC/SC card.  */
781 static int
782 connect_pcsc_card (int slot)
783 {
784   long err;
785
786   assert (slot >= 0 && slot < MAX_READER);
787
788   if (reader_table[slot].pcsc.card)
789     return SW_HOST_ALREADY_CONNECTED;
790
791   reader_table[slot].atrlen = 0;
792   reader_table[slot].is_t0 = 0;
793
794   err = pcsc_connect (reader_table[slot].pcsc.context,
795                       reader_table[slot].rdrname,
796                       PCSC_SHARE_EXCLUSIVE,
797                       PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
798                       &reader_table[slot].pcsc.card,
799                       &reader_table[slot].pcsc.protocol);
800   if (err)
801     {
802       reader_table[slot].pcsc.card = 0;
803       if (err != PCSC_E_NO_SMARTCARD)
804         log_error ("pcsc_connect failed: %s (0x%lx)\n",
805                    pcsc_error_string (err), err);
806     }
807   else
808     {
809       char reader[250];
810       pcsc_dword_t readerlen, atrlen;
811       pcsc_dword_t card_state, card_protocol;
812
813       pcsc_vendor_specific_init (slot);
814
815       atrlen = DIM (reader_table[0].atr);
816       readerlen = sizeof reader -1 ;
817       err = pcsc_status (reader_table[slot].pcsc.card,
818                          reader, &readerlen,
819                          &card_state, &card_protocol,
820                          reader_table[slot].atr, &atrlen);
821       if (err)
822         log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
823                    pcsc_error_string (err), err, (long unsigned int)readerlen);
824       else
825         {
826           if (atrlen > DIM (reader_table[0].atr))
827             log_bug ("ATR returned by pcsc_status is too large\n");
828           reader_table[slot].atrlen = atrlen;
829           reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
830         }
831     }
832
833   dump_reader_status (slot);
834   return pcsc_error_to_sw (err);
835 }
836
837
838 static int
839 disconnect_pcsc_card (int slot)
840 {
841   long err;
842
843   assert (slot >= 0 && slot < MAX_READER);
844
845   if (!reader_table[slot].pcsc.card)
846     return 0;
847
848   err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
849   if (err)
850     {
851       log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
852                  pcsc_error_string (err), err);
853       return SW_HOST_CARD_IO_ERROR;
854     }
855   reader_table[slot].pcsc.card = 0;
856   return 0;
857 }
858
859
860 /* Send an PC/SC reset command and return a status word on error or 0
861    on success. */
862 static int
863 reset_pcsc_reader (int slot)
864 {
865   int sw;
866
867   sw = disconnect_pcsc_card (slot);
868   if (!sw)
869     sw = connect_pcsc_card (slot);
870
871   return sw;
872 }
873
874
875 /* Examine reader specific parameters and initialize.  This is mostly
876    for pinpad input.  Called at opening the connection to the reader.  */
877 static int
878 pcsc_vendor_specific_init (int slot)
879 {
880   unsigned char buf[256];
881   pcsc_dword_t len;
882   int sw;
883   int vendor = 0;
884   int product = 0;
885   pcsc_dword_t get_tlv_ioctl = (pcsc_dword_t)-1;
886   unsigned char *p;
887
888   len = sizeof (buf);
889   sw = control_pcsc (slot, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, &len);
890   if (sw)
891     {
892       log_error ("pcsc_vendor_specific_init: GET_FEATURE_REQUEST failed: %d\n",
893                  sw);
894       return SW_NOT_SUPPORTED;
895     }
896   else
897     {
898       p = buf;
899       while (p < buf + len)
900         {
901           unsigned char code = *p++;
902           int l = *p++;
903           unsigned int v = 0;
904
905           if (l == 1)
906             v = p[0];
907           else if (l == 2)
908             v = buf16_to_uint (p);
909           else if (l == 4)
910             v = buf32_to_uint (p);
911
912           if (code == FEATURE_VERIFY_PIN_DIRECT)
913             reader_table[slot].pcsc.verify_ioctl = v;
914           else if (code == FEATURE_MODIFY_PIN_DIRECT)
915             reader_table[slot].pcsc.modify_ioctl = v;
916           else if (code == FEATURE_GET_TLV_PROPERTIES)
917             get_tlv_ioctl = v;
918
919           if (DBG_CARD_IO)
920             log_debug ("feature: code=%02X, len=%d, v=%02X\n", code, l, v);
921
922           p += l;
923         }
924     }
925
926   if (get_tlv_ioctl == (pcsc_dword_t)-1)
927     {
928       /*
929        * For system which doesn't support GET_TLV_PROPERTIES,
930        * we put some heuristics here.
931        */
932       if (reader_table[slot].rdrname)
933         {
934           if (strstr (reader_table[slot].rdrname, "SPRx32"))
935             {
936               reader_table[slot].is_spr532 = 1;
937               reader_table[slot].pinpad_varlen_supported = 1;
938             }
939           else if (strstr (reader_table[slot].rdrname, "ST-2xxx"))
940             {
941               reader_table[slot].pcsc.pinmax = 15;
942               reader_table[slot].pinpad_varlen_supported = 1;
943             }
944           else if (strstr (reader_table[slot].rdrname, "cyberJack")
945                    || strstr (reader_table[slot].rdrname, "DIGIPASS")
946                    || strstr (reader_table[slot].rdrname, "Gnuk")
947                    || strstr (reader_table[slot].rdrname, "KAAN"))
948             reader_table[slot].pinpad_varlen_supported = 1;
949         }
950
951       return 0;
952     }
953
954   len = sizeof (buf);
955   sw = control_pcsc (slot, get_tlv_ioctl, NULL, 0, buf, &len);
956   if (sw)
957     {
958       log_error ("pcsc_vendor_specific_init: GET_TLV_IOCTL failed: %d\n", sw);
959       return SW_NOT_SUPPORTED;
960     }
961
962   p = buf;
963   while (p < buf + len)
964     {
965       unsigned char tag = *p++;
966       int l = *p++;
967       unsigned int v = 0;
968
969       /* Umm... here is little endian, while the encoding above is big.  */
970       if (l == 1)
971         v = p[0];
972       else if (l == 2)
973         v = (((unsigned int)p[1] << 8) | p[0]);
974       else if (l == 4)
975         v = (((unsigned int)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
976
977       if (tag == PCSCv2_PART10_PROPERTY_bMinPINSize)
978         reader_table[slot].pcsc.pinmin = v;
979       else if (tag == PCSCv2_PART10_PROPERTY_bMaxPINSize)
980         reader_table[slot].pcsc.pinmax = v;
981       else if (tag == PCSCv2_PART10_PROPERTY_wIdVendor)
982         vendor = v;
983       else if (tag == PCSCv2_PART10_PROPERTY_wIdProduct)
984         product = v;
985
986       if (DBG_CARD_IO)
987         log_debug ("TLV properties: tag=%02X, len=%d, v=%08X\n", tag, l, v);
988
989       p += l;
990     }
991
992   if (vendor == VENDOR_VEGA && product == VEGA_ALPHA)
993     {
994       /*
995        * Please read the comment of ccid_vendor_specific_init in
996        * ccid-driver.c.
997        */
998       const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
999       sw = control_pcsc (slot, CM_IOCTL_VENDOR_IFD_EXCHANGE,
1000                          cmd, sizeof (cmd), NULL, 0);
1001       if (sw)
1002         return SW_NOT_SUPPORTED;
1003     }
1004   else if (vendor == VENDOR_SCM && product == SCM_SPR532) /* SCM SPR532 */
1005     {
1006       reader_table[slot].is_spr532 = 1;
1007       reader_table[slot].pinpad_varlen_supported = 1;
1008     }
1009   else if (vendor == 0x046a)
1010     {
1011       /* Cherry ST-2xxx (product == 0x003e) supports TPDU level
1012        * exchange.  Other products which only support short APDU level
1013        * exchange only work with shorter keys like RSA 1024.
1014        */
1015       reader_table[slot].pcsc.pinmax = 15;
1016       reader_table[slot].pinpad_varlen_supported = 1;
1017     }
1018   else if (vendor == 0x0c4b /* Tested with Reiner cyberJack GO */
1019            || vendor == 0x1a44 /* Tested with Vasco DIGIPASS 920 */
1020            || vendor == 0x234b /* Tested with FSIJ Gnuk Token */
1021            || vendor == 0x0d46 /* Tested with KAAN Advanced??? */)
1022     reader_table[slot].pinpad_varlen_supported = 1;
1023
1024   return 0;
1025 }
1026
1027
1028 /* Open the PC/SC reader without using the wrapper.  Returns -1 on
1029    error or a slot number for the reader.  */
1030 static int
1031 open_pcsc_reader (const char *portstr)
1032 {
1033   long err;
1034   int slot;
1035   char *list = NULL;
1036   char *rdrname = NULL;
1037   pcsc_dword_t nreader;
1038   char *p;
1039
1040   slot = new_reader_slot ();
1041   if (slot == -1)
1042     return -1;
1043
1044   /* Fixme: Allocating a context for each slot is not required.  One
1045      global context should be sufficient.  */
1046   err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1047                                 &reader_table[slot].pcsc.context);
1048   if (err)
1049     {
1050       log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1051                  pcsc_error_string (err), err);
1052       reader_table[slot].used = 0;
1053       unlock_slot (slot);
1054       return -1;
1055     }
1056
1057   err = pcsc_list_readers (reader_table[slot].pcsc.context,
1058                            NULL, NULL, &nreader);
1059   if (!err)
1060     {
1061       list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1062       if (!list)
1063         {
1064           log_error ("error allocating memory for reader list\n");
1065           pcsc_release_context (reader_table[slot].pcsc.context);
1066           reader_table[slot].used = 0;
1067           unlock_slot (slot);
1068           return -1 /*SW_HOST_OUT_OF_CORE*/;
1069         }
1070       err = pcsc_list_readers (reader_table[slot].pcsc.context,
1071                                NULL, list, &nreader);
1072     }
1073   if (err)
1074     {
1075       log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1076                  pcsc_error_string (err), err);
1077       pcsc_release_context (reader_table[slot].pcsc.context);
1078       reader_table[slot].used = 0;
1079       xfree (list);
1080       unlock_slot (slot);
1081       return -1;
1082     }
1083
1084   p = list;
1085   while (nreader)
1086     {
1087       if (!*p && !p[1])
1088         break;
1089       log_info ("detected reader '%s'\n", p);
1090       if (nreader < (strlen (p)+1))
1091         {
1092           log_error ("invalid response from pcsc_list_readers\n");
1093           break;
1094         }
1095       if (!rdrname && portstr && !strncmp (p, portstr, strlen (portstr)))
1096         rdrname = p;
1097       nreader -= strlen (p)+1;
1098       p += strlen (p) + 1;
1099     }
1100
1101   if (!rdrname)
1102     rdrname = list;
1103
1104   reader_table[slot].rdrname = xtrystrdup (rdrname);
1105   if (!reader_table[slot].rdrname)
1106     {
1107       log_error ("error allocating memory for reader name\n");
1108       pcsc_release_context (reader_table[slot].pcsc.context);
1109       reader_table[slot].used = 0;
1110       unlock_slot (slot);
1111       return -1;
1112     }
1113   xfree (list);
1114   list = NULL;
1115
1116   reader_table[slot].pcsc.card = 0;
1117   reader_table[slot].atrlen = 0;
1118
1119   reader_table[slot].connect_card = connect_pcsc_card;
1120   reader_table[slot].disconnect_card = disconnect_pcsc_card;
1121   reader_table[slot].close_reader = close_pcsc_reader;
1122   reader_table[slot].reset_reader = reset_pcsc_reader;
1123   reader_table[slot].get_status_reader = pcsc_get_status;
1124   reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1125   reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1126
1127   dump_reader_status (slot);
1128   unlock_slot (slot);
1129   return slot;
1130 }
1131
1132
1133 /* Check whether the reader supports the ISO command code COMMAND
1134    on the pinpad.  Return 0 on success.  */
1135 static int
1136 check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo)
1137 {
1138   int r;
1139
1140   if (reader_table[slot].pcsc.pinmin >= 0)
1141     pininfo->minlen = reader_table[slot].pcsc.pinmin;
1142
1143   if (reader_table[slot].pcsc.pinmax >= 0)
1144     pininfo->maxlen = reader_table[slot].pcsc.pinmax;
1145
1146   if (!pininfo->minlen)
1147     pininfo->minlen = 1;
1148   if (!pininfo->maxlen)
1149     pininfo->maxlen = 15;
1150
1151   if ((command == ISO7816_VERIFY && reader_table[slot].pcsc.verify_ioctl != 0)
1152       || (command == ISO7816_CHANGE_REFERENCE_DATA
1153           && reader_table[slot].pcsc.modify_ioctl != 0))
1154     r = 0;                       /* Success */
1155   else
1156     r = SW_NOT_SUPPORTED;
1157
1158   if (DBG_CARD_IO)
1159     log_debug ("check_pcsc_pinpad: command=%02X, r=%d\n",
1160                (unsigned int)command, r);
1161
1162   if (reader_table[slot].pinpad_varlen_supported)
1163     pininfo->fixedlen = 0;
1164
1165   return r;
1166 }
1167
1168 #define PIN_VERIFY_STRUCTURE_SIZE 24
1169 static int
1170 pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
1171                     pininfo_t *pininfo)
1172 {
1173   int sw;
1174   unsigned char *pin_verify;
1175   int len = PIN_VERIFY_STRUCTURE_SIZE + pininfo->fixedlen;
1176   /*
1177    * The result buffer is only expected to have two-byte result on
1178    * return.  However, some implementation uses this buffer for lower
1179    * layer too and it assumes that there is enough space for lower
1180    * layer communication.  Such an implementation fails for TPDU
1181    * readers with "insufficient buffer", as it needs header and
1182    * trailer.  Six is the number for header + result + trailer (TPDU).
1183    */
1184   unsigned char result[6];
1185   pcsc_dword_t resultlen = 6;
1186   int no_lc;
1187
1188   if (!reader_table[slot].atrlen
1189       && (sw = reset_pcsc_reader (slot)))
1190     return sw;
1191
1192   if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
1193     return SW_NOT_SUPPORTED;
1194
1195   pin_verify = xtrymalloc (len);
1196   if (!pin_verify)
1197     return SW_HOST_OUT_OF_CORE;
1198
1199   no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
1200
1201   pin_verify[0] = 0x00; /* bTimeOut */
1202   pin_verify[1] = 0x00; /* bTimeOut2 */
1203   pin_verify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
1204   pin_verify[3] = pininfo->fixedlen; /* bmPINBlockString */
1205   pin_verify[4] = 0x00; /* bmPINLengthFormat */
1206   pin_verify[5] = pininfo->maxlen; /* wPINMaxExtraDigit */
1207   pin_verify[6] = pininfo->minlen; /* wPINMaxExtraDigit */
1208   pin_verify[7] = 0x02; /* bEntryValidationCondition: Validation key pressed */
1209   if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
1210     pin_verify[7] |= 0x01; /* Max size reached.  */
1211   pin_verify[8] = 0x01; /* bNumberMessage: One message */
1212   pin_verify[9] =  0x09; /* wLangId: 0x0409: US English */
1213   pin_verify[10] = 0x04; /* wLangId: 0x0409: US English */
1214   pin_verify[11] = 0x00; /* bMsgIndex */
1215   pin_verify[12] = 0x00; /* bTeoPrologue[0] */
1216   pin_verify[13] = 0x00; /* bTeoPrologue[1] */
1217   pin_verify[14] = pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
1218   pin_verify[15] = pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
1219   pin_verify[16] = 0x00; /* ulDataLength */
1220   pin_verify[17] = 0x00; /* ulDataLength */
1221   pin_verify[18] = 0x00; /* ulDataLength */
1222   pin_verify[19] = class; /* abData[0] */
1223   pin_verify[20] = ins; /* abData[1] */
1224   pin_verify[21] = p0; /* abData[2] */
1225   pin_verify[22] = p1; /* abData[3] */
1226   pin_verify[23] = pininfo->fixedlen; /* abData[4] */
1227   if (pininfo->fixedlen)
1228     memset (&pin_verify[24], 0xff, pininfo->fixedlen);
1229   else if (no_lc)
1230     len--;
1231
1232   if (DBG_CARD_IO)
1233     log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
1234                class, ins, p0, p1, len, pininfo->maxlen);
1235
1236   sw = control_pcsc (slot, reader_table[slot].pcsc.verify_ioctl,
1237                      pin_verify, len, result, &resultlen);
1238   xfree (pin_verify);
1239   if (sw || resultlen < 2)
1240     {
1241       log_error ("control_pcsc failed: %d\n", sw);
1242       return sw? sw: SW_HOST_INCOMPLETE_CARD_RESPONSE;
1243     }
1244   sw = (result[resultlen-2] << 8) | result[resultlen-1];
1245   if (DBG_CARD_IO)
1246     log_debug (" response: sw=%04X  datalen=%d\n", sw, (unsigned int)resultlen);
1247   return sw;
1248 }
1249
1250
1251 #define PIN_MODIFY_STRUCTURE_SIZE 29
1252 static int
1253 pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
1254                     pininfo_t *pininfo)
1255 {
1256   int sw;
1257   unsigned char *pin_modify;
1258   int len = PIN_MODIFY_STRUCTURE_SIZE + 2 * pininfo->fixedlen;
1259   unsigned char result[6];      /* See the comment at pinpad_verify.  */
1260   pcsc_dword_t resultlen = 6;
1261   int no_lc;
1262
1263   if (!reader_table[slot].atrlen
1264       && (sw = reset_pcsc_reader (slot)))
1265     return sw;
1266
1267   if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
1268     return SW_NOT_SUPPORTED;
1269
1270   pin_modify = xtrymalloc (len);
1271   if (!pin_modify)
1272     return SW_HOST_OUT_OF_CORE;
1273
1274   no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
1275
1276   pin_modify[0] = 0x00; /* bTimeOut */
1277   pin_modify[1] = 0x00; /* bTimeOut2 */
1278   pin_modify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
1279   pin_modify[3] = pininfo->fixedlen; /* bmPINBlockString */
1280   pin_modify[4] = 0x00; /* bmPINLengthFormat */
1281   pin_modify[5] = 0x00; /* bInsertionOffsetOld */
1282   pin_modify[6] = pininfo->fixedlen; /* bInsertionOffsetNew */
1283   pin_modify[7] = pininfo->maxlen; /* wPINMaxExtraDigit */
1284   pin_modify[8] = pininfo->minlen; /* wPINMaxExtraDigit */
1285   pin_modify[9] = (p0 == 0 ? 0x03 : 0x01);
1286                   /* bConfirmPIN
1287                    *    0x00: new PIN once
1288                    *    0x01: new PIN twice (confirmation)
1289                    *    0x02: old PIN and new PIN once
1290                    *    0x03: old PIN and new PIN twice (confirmation)
1291                    */
1292   pin_modify[10] = 0x02; /* bEntryValidationCondition: Validation key pressed */
1293   if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
1294     pin_modify[10] |= 0x01; /* Max size reached.  */
1295   pin_modify[11] = 0x03; /* bNumberMessage: Three messages */
1296   pin_modify[12] = 0x09; /* wLangId: 0x0409: US English */
1297   pin_modify[13] = 0x04; /* wLangId: 0x0409: US English */
1298   pin_modify[14] = 0x00; /* bMsgIndex1 */
1299   pin_modify[15] = 0x01; /* bMsgIndex2 */
1300   pin_modify[16] = 0x02; /* bMsgIndex3 */
1301   pin_modify[17] = 0x00; /* bTeoPrologue[0] */
1302   pin_modify[18] = 0x00; /* bTeoPrologue[1] */
1303   pin_modify[19] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
1304   pin_modify[20] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
1305   pin_modify[21] = 0x00; /* ulDataLength */
1306   pin_modify[22] = 0x00; /* ulDataLength */
1307   pin_modify[23] = 0x00; /* ulDataLength */
1308   pin_modify[24] = class; /* abData[0] */
1309   pin_modify[25] = ins; /* abData[1] */
1310   pin_modify[26] = p0; /* abData[2] */
1311   pin_modify[27] = p1; /* abData[3] */
1312   pin_modify[28] = 2 * pininfo->fixedlen; /* abData[4] */
1313   if (pininfo->fixedlen)
1314     memset (&pin_modify[29], 0xff, 2 * pininfo->fixedlen);
1315   else if (no_lc)
1316     len--;
1317
1318   if (DBG_CARD_IO)
1319     log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
1320                class, ins, p0, p1, len, (int)pininfo->maxlen);
1321
1322   sw = control_pcsc (slot, reader_table[slot].pcsc.modify_ioctl,
1323                      pin_modify, len, result, &resultlen);
1324   xfree (pin_modify);
1325   if (sw || resultlen < 2)
1326     {
1327       log_error ("control_pcsc failed: %d\n", sw);
1328       return sw? sw : SW_HOST_INCOMPLETE_CARD_RESPONSE;
1329     }
1330   sw = (result[resultlen-2] << 8) | result[resultlen-1];
1331   if (DBG_CARD_IO)
1332     log_debug (" response: sw=%04X  datalen=%d\n", sw, (unsigned int)resultlen);
1333   return sw;
1334 }
1335 \f
1336 #ifdef HAVE_LIBUSB
1337 /*
1338      Internal CCID driver interface.
1339  */
1340
1341
1342 static void
1343 dump_ccid_reader_status (int slot)
1344 {
1345   log_info ("reader slot %d: using ccid driver\n", slot);
1346 }
1347
1348 static int
1349 close_ccid_reader (int slot)
1350 {
1351   ccid_close_reader (reader_table[slot].ccid.handle);
1352   return 0;
1353 }
1354
1355
1356 static int
1357 reset_ccid_reader (int slot)
1358 {
1359   int err;
1360   reader_table_t slotp = reader_table + slot;
1361   unsigned char atr[33];
1362   size_t atrlen;
1363
1364   err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1365   if (err)
1366     return err;
1367   /* If the reset was successful, update the ATR. */
1368   assert (sizeof slotp->atr >= sizeof atr);
1369   slotp->atrlen = atrlen;
1370   memcpy (slotp->atr, atr, atrlen);
1371   dump_reader_status (slot);
1372   return 0;
1373 }
1374
1375
1376 static int
1377 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
1378 {
1379   reader_table_t slotp = reader_table + slot;
1380
1381   return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
1382 }
1383
1384
1385 static int
1386 get_status_ccid (int slot, unsigned int *status, int on_wire)
1387 {
1388   int rc;
1389   int bits;
1390
1391   rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits, on_wire);
1392   if (rc)
1393     return rc;
1394
1395   if (bits == 0)
1396     *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1397   else if (bits == 1)
1398     *status = APDU_CARD_PRESENT;
1399   else
1400     *status = 0;
1401
1402   return 0;
1403 }
1404
1405
1406 /* Actually send the APDU of length APDULEN to SLOT and return a
1407    maximum of *BUFLEN data in BUFFER, the actual returned size will be
1408    set to BUFLEN.  Returns: Internal CCID driver error code. */
1409 static int
1410 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1411                 unsigned char *buffer, size_t *buflen,
1412                 pininfo_t *pininfo)
1413 {
1414   long err;
1415   size_t maxbuflen;
1416
1417   /* If we don't have an ATR, we need to reset the reader first. */
1418   if (!reader_table[slot].atrlen
1419       && (err = reset_ccid_reader (slot)))
1420     return err;
1421
1422   if (DBG_CARD_IO)
1423     log_printhex (" raw apdu:", apdu, apdulen);
1424
1425   maxbuflen = *buflen;
1426   if (pininfo)
1427     err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1428                                   apdu, apdulen, pininfo,
1429                                   buffer, maxbuflen, buflen);
1430   else
1431     err = ccid_transceive (reader_table[slot].ccid.handle,
1432                            apdu, apdulen,
1433                            buffer, maxbuflen, buflen);
1434   if (err)
1435     log_error ("ccid_transceive failed: (0x%lx)\n",
1436                err);
1437
1438   return err;
1439 }
1440
1441
1442 /* Check whether the CCID reader supports the ISO command code COMMAND
1443    on the pinpad.  Return 0 on success.  For a description of the pin
1444    parameters, see ccid-driver.c */
1445 static int
1446 check_ccid_pinpad (int slot, int command, pininfo_t *pininfo)
1447 {
1448   unsigned char apdu[] = { 0, 0, 0, 0x81 };
1449
1450   apdu[1] = command;
1451   return ccid_transceive_secure (reader_table[slot].ccid.handle, apdu,
1452                                  sizeof apdu, pininfo, NULL, 0, NULL);
1453 }
1454
1455
1456 static int
1457 ccid_pinpad_operation (int slot, int class, int ins, int p0, int p1,
1458                        pininfo_t *pininfo)
1459 {
1460   unsigned char apdu[4];
1461   int err, sw;
1462   unsigned char result[2];
1463   size_t resultlen = 2;
1464
1465   apdu[0] = class;
1466   apdu[1] = ins;
1467   apdu[2] = p0;
1468   apdu[3] = p1;
1469   err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1470                                 apdu, sizeof apdu, pininfo,
1471                                 result, 2, &resultlen);
1472   if (err)
1473     return err;
1474
1475   if (resultlen < 2)
1476     return SW_HOST_INCOMPLETE_CARD_RESPONSE;
1477
1478   sw = (result[resultlen-2] << 8) | result[resultlen-1];
1479   return sw;
1480 }
1481
1482
1483 /* Open the reader and try to read an ATR.  */
1484 static int
1485 open_ccid_reader (struct dev_list *dl)
1486 {
1487   int err;
1488   int slot;
1489   int require_get_status;
1490   reader_table_t slotp;
1491
1492   slot = new_reader_slot ();
1493   if (slot == -1)
1494     return -1;
1495   slotp = reader_table + slot;
1496
1497   err = ccid_open_reader (dl->portstr, dl->idx, dl->ccid_table,
1498                           &slotp->ccid.handle, &slotp->rdrname);
1499   if (!err)
1500     err = ccid_get_atr (slotp->ccid.handle,
1501                         slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1502   if (err)
1503     {
1504       slotp->used = 0;
1505       unlock_slot (slot);
1506       return -1;
1507     }
1508
1509   require_get_status = ccid_require_get_status (slotp->ccid.handle);
1510
1511   reader_table[slot].close_reader = close_ccid_reader;
1512   reader_table[slot].reset_reader = reset_ccid_reader;
1513   reader_table[slot].get_status_reader = get_status_ccid;
1514   reader_table[slot].send_apdu_reader = send_apdu_ccid;
1515   reader_table[slot].check_pinpad = check_ccid_pinpad;
1516   reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1517   reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
1518   reader_table[slot].pinpad_verify = ccid_pinpad_operation;
1519   reader_table[slot].pinpad_modify = ccid_pinpad_operation;
1520   /* Our CCID reader code does not support T=0 at all, thus reset the
1521      flag.  */
1522   reader_table[slot].is_t0 = 0;
1523   reader_table[slot].require_get_status = require_get_status;
1524
1525   dump_reader_status (slot);
1526   unlock_slot (slot);
1527   return slot;
1528 }
1529 #endif /* HAVE_LIBUSB */
1530 \f
1531 #ifdef USE_G10CODE_RAPDU
1532 /*
1533      The Remote APDU Interface.
1534
1535      This uses the Remote APDU protocol to contact a reader.
1536
1537      The port number is actually an index into the list of ports as
1538      returned via the protocol.
1539  */
1540
1541
1542 static int
1543 rapdu_status_to_sw (int status)
1544 {
1545   int rc;
1546
1547   switch (status)
1548     {
1549     case RAPDU_STATUS_SUCCESS:  rc = 0; break;
1550
1551     case RAPDU_STATUS_INVCMD:
1552     case RAPDU_STATUS_INVPROT:
1553     case RAPDU_STATUS_INVSEQ:
1554     case RAPDU_STATUS_INVCOOKIE:
1555     case RAPDU_STATUS_INVREADER:  rc = SW_HOST_INV_VALUE;  break;
1556
1557     case RAPDU_STATUS_TIMEOUT:  rc = SW_HOST_CARD_IO_ERROR; break;
1558     case RAPDU_STATUS_CARDIO:   rc = SW_HOST_CARD_IO_ERROR; break;
1559     case RAPDU_STATUS_NOCARD:   rc = SW_HOST_NO_CARD; break;
1560     case RAPDU_STATUS_CARDCHG:  rc = SW_HOST_NO_CARD; break;
1561     case RAPDU_STATUS_BUSY:     rc = SW_HOST_BUSY; break;
1562     case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1563
1564     default: rc = SW_HOST_GENERAL_ERROR; break;
1565     }
1566
1567   return rc;
1568 }
1569
1570
1571
1572 static int
1573 close_rapdu_reader (int slot)
1574 {
1575   rapdu_release (reader_table[slot].rapdu.handle);
1576   return 0;
1577 }
1578
1579
1580 static int
1581 reset_rapdu_reader (int slot)
1582 {
1583   int err;
1584   reader_table_t slotp;
1585   rapdu_msg_t msg = NULL;
1586
1587   slotp = reader_table + slot;
1588
1589   err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1590   if (err)
1591     {
1592       log_error ("sending rapdu command RESET failed: %s\n",
1593                 err < 0 ? strerror (errno): rapdu_strerror (err));
1594       rapdu_msg_release (msg);
1595       return rapdu_status_to_sw (err);
1596     }
1597   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1598   if (err)
1599     {
1600       log_error ("receiving rapdu message failed: %s\n",
1601                 err < 0 ? strerror (errno): rapdu_strerror (err));
1602       rapdu_msg_release (msg);
1603       return rapdu_status_to_sw (err);
1604     }
1605   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1606     {
1607       int sw = rapdu_status_to_sw (msg->cmd);
1608       log_error ("rapdu command RESET failed: %s\n",
1609                  rapdu_strerror (msg->cmd));
1610       rapdu_msg_release (msg);
1611       return sw;
1612     }
1613   if (msg->datalen > DIM (slotp->atr))
1614     {
1615       log_error ("ATR returned by the RAPDU layer is too large\n");
1616       rapdu_msg_release (msg);
1617       return SW_HOST_INV_VALUE;
1618     }
1619   slotp->atrlen = msg->datalen;
1620   memcpy (slotp->atr, msg->data, msg->datalen);
1621
1622   rapdu_msg_release (msg);
1623   return 0;
1624 }
1625
1626
1627 static int
1628 my_rapdu_get_status (int slot, unsigned int *status, int on_wire)
1629 {
1630   int err;
1631   reader_table_t slotp;
1632   rapdu_msg_t msg = NULL;
1633   int oldslot;
1634
1635   (void)on_wire;
1636   slotp = reader_table + slot;
1637
1638   oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
1639   err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
1640   rapdu_set_reader (slotp->rapdu.handle, oldslot);
1641   if (err)
1642     {
1643       log_error ("sending rapdu command GET_STATUS failed: %s\n",
1644                 err < 0 ? strerror (errno): rapdu_strerror (err));
1645       return rapdu_status_to_sw (err);
1646     }
1647   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1648   if (err)
1649     {
1650       log_error ("receiving rapdu message failed: %s\n",
1651                 err < 0 ? strerror (errno): rapdu_strerror (err));
1652       rapdu_msg_release (msg);
1653       return rapdu_status_to_sw (err);
1654     }
1655   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1656     {
1657       int sw = rapdu_status_to_sw (msg->cmd);
1658       log_error ("rapdu command GET_STATUS failed: %s\n",
1659                  rapdu_strerror (msg->cmd));
1660       rapdu_msg_release (msg);
1661       return sw;
1662     }
1663   *status = msg->data[0];
1664
1665   rapdu_msg_release (msg);
1666   return 0;
1667 }
1668
1669
1670 /* Actually send the APDU of length APDULEN to SLOT and return a
1671    maximum of *BUFLEN data in BUFFER, the actual returned size will be
1672    set to BUFLEN.  Returns: APDU error code. */
1673 static int
1674 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1675                     unsigned char *buffer, size_t *buflen,
1676                     pininfo_t *pininfo)
1677 {
1678   int err;
1679   reader_table_t slotp;
1680   rapdu_msg_t msg = NULL;
1681   size_t maxlen = *buflen;
1682
1683   slotp = reader_table + slot;
1684
1685   *buflen = 0;
1686   if (DBG_CARD_IO)
1687     log_printhex ("  APDU_data:", apdu, apdulen);
1688
1689   if (apdulen < 4)
1690     {
1691       log_error ("rapdu_send_apdu: APDU is too short\n");
1692       return SW_HOST_INV_VALUE;
1693     }
1694
1695   err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
1696   if (err)
1697     {
1698       log_error ("sending rapdu command APDU failed: %s\n",
1699                 err < 0 ? strerror (errno): rapdu_strerror (err));
1700       rapdu_msg_release (msg);
1701       return rapdu_status_to_sw (err);
1702     }
1703   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1704   if (err)
1705     {
1706       log_error ("receiving rapdu message failed: %s\n",
1707                 err < 0 ? strerror (errno): rapdu_strerror (err));
1708       rapdu_msg_release (msg);
1709       return rapdu_status_to_sw (err);
1710     }
1711   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1712     {
1713       int sw = rapdu_status_to_sw (msg->cmd);
1714       log_error ("rapdu command APDU failed: %s\n",
1715                  rapdu_strerror (msg->cmd));
1716       rapdu_msg_release (msg);
1717       return sw;
1718     }
1719
1720   if (msg->datalen > maxlen)
1721     {
1722       log_error ("rapdu response apdu too large\n");
1723       rapdu_msg_release (msg);
1724       return SW_HOST_INV_VALUE;
1725     }
1726
1727   *buflen = msg->datalen;
1728   memcpy (buffer, msg->data, msg->datalen);
1729
1730   rapdu_msg_release (msg);
1731   return 0;
1732 }
1733
1734 static int
1735 open_rapdu_reader (int portno,
1736                    const unsigned char *cookie, size_t length,
1737                    int (*readfnc) (void *opaque,
1738                                    void *buffer, size_t size),
1739                    void *readfnc_value,
1740                    int (*writefnc) (void *opaque,
1741                                     const void *buffer, size_t size),
1742                    void *writefnc_value,
1743                    void (*closefnc) (void *opaque),
1744                    void *closefnc_value)
1745 {
1746   int err;
1747   int slot;
1748   reader_table_t slotp;
1749   rapdu_msg_t msg = NULL;
1750
1751   slot = new_reader_slot ();
1752   if (slot == -1)
1753     return -1;
1754   slotp = reader_table + slot;
1755
1756   slotp->rapdu.handle = rapdu_new ();
1757   if (!slotp->rapdu.handle)
1758     {
1759       slotp->used = 0;
1760       unlock_slot (slot);
1761       return -1;
1762     }
1763
1764   rapdu_set_reader (slotp->rapdu.handle, portno);
1765
1766   rapdu_set_iofunc (slotp->rapdu.handle,
1767                     readfnc, readfnc_value,
1768                     writefnc, writefnc_value,
1769                     closefnc, closefnc_value);
1770   rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
1771
1772   /* First try to get the current ATR, but if the card is inactive
1773      issue a reset instead.  */
1774   err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
1775   if (err == RAPDU_STATUS_NEEDRESET)
1776     err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1777   if (err)
1778     {
1779       log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
1780                 err < 0 ? strerror (errno): rapdu_strerror (err));
1781       goto failure;
1782     }
1783   err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1784   if (err)
1785     {
1786       log_info ("receiving rapdu message failed: %s\n",
1787                 err < 0 ? strerror (errno): rapdu_strerror (err));
1788       goto failure;
1789     }
1790   if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1791     {
1792       log_info ("rapdu command GET ATR failed: %s\n",
1793                  rapdu_strerror (msg->cmd));
1794       goto failure;
1795     }
1796   if (msg->datalen > DIM (slotp->atr))
1797     {
1798       log_error ("ATR returned by the RAPDU layer is too large\n");
1799       goto failure;
1800     }
1801   slotp->atrlen = msg->datalen;
1802   memcpy (slotp->atr, msg->data, msg->datalen);
1803
1804   reader_table[slot].close_reader = close_rapdu_reader;
1805   reader_table[slot].reset_reader = reset_rapdu_reader;
1806   reader_table[slot].get_status_reader = my_rapdu_get_status;
1807   reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
1808   reader_table[slot].check_pinpad = NULL;
1809   reader_table[slot].dump_status_reader = NULL;
1810   reader_table[slot].pinpad_verify = NULL;
1811   reader_table[slot].pinpad_modify = NULL;
1812
1813   dump_reader_status (slot);
1814   rapdu_msg_release (msg);
1815   unlock_slot (slot);
1816   return slot;
1817
1818  failure:
1819   rapdu_msg_release (msg);
1820   rapdu_release (slotp->rapdu.handle);
1821   slotp->used = 0;
1822   unlock_slot (slot);
1823   return -1;
1824 }
1825
1826 #endif /*USE_G10CODE_RAPDU*/
1827
1828
1829 \f
1830 /*
1831        Driver Access
1832  */
1833 gpg_error_t
1834 apdu_dev_list_start (const char *portstr, struct dev_list **l_p)
1835 {
1836   struct dev_list *dl = xtrymalloc (sizeof (struct dev_list));
1837
1838   *l_p = NULL;
1839   if (!dl)
1840     return gpg_error_from_syserror ();
1841
1842   dl->portstr = portstr;
1843   dl->idx = 0;
1844
1845   npth_mutex_lock (&reader_table_lock);
1846
1847 #ifdef HAVE_LIBUSB
1848   if (opt.disable_ccid)
1849     {
1850       dl->ccid_table = NULL;
1851       dl->idx_max = 1;
1852     }
1853   else
1854     {
1855       gpg_error_t err;
1856
1857       err = ccid_dev_scan (&dl->idx_max, &dl->ccid_table);
1858       if (err)
1859         return err;
1860
1861       if (dl->idx_max == 0)
1862         {
1863           /* If a CCID reader specification has been given, the user does
1864              not want a fallback to other drivers. */
1865           if (portstr && strlen (portstr) > 5 && portstr[4] == ':')
1866             {
1867               if (DBG_READER)
1868                 log_debug ("leave: apdu_open_reader => slot=-1 (no ccid)\n");
1869
1870               xfree (dl);
1871               npth_mutex_unlock (&reader_table_lock);
1872               return gpg_error (GPG_ERR_ENODEV);
1873             }
1874           else
1875             dl->idx_max = 1;
1876         }
1877     }
1878 #else
1879   dl->ccid_table = NULL;
1880   dl->idx_max = 1;
1881 #endif /* HAVE_LIBUSB */
1882
1883   *l_p = dl;
1884   return 0;
1885 }
1886
1887 void
1888 apdu_dev_list_finish (struct dev_list *dl)
1889 {
1890 #ifdef HAVE_LIBUSB
1891   if (dl->ccid_table)
1892     ccid_dev_scan_finish (dl->ccid_table, dl->idx_max);
1893 #endif
1894   xfree (dl);
1895   npth_mutex_unlock (&reader_table_lock);
1896 }
1897
1898
1899 /* Open the reader and return an internal slot number or -1 on
1900    error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
1901    the first USB reader.  For PC/SC the first listed reader). */
1902 static int
1903 apdu_open_one_reader (const char *portstr)
1904 {
1905   static int pcsc_api_loaded;
1906   int slot;
1907
1908   if (DBG_READER)
1909     log_debug ("enter: apdu_open_reader: portstr=%s\n", portstr);
1910
1911   /* Lets try the PC/SC API */
1912   if (!pcsc_api_loaded)
1913     {
1914       void *handle;
1915
1916       handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
1917       if (!handle)
1918         {
1919           log_error ("apdu_open_reader: failed to open driver '%s': %s\n",
1920                      opt.pcsc_driver, dlerror ());
1921           return -1;
1922         }
1923
1924       pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
1925       pcsc_release_context   = dlsym (handle, "SCardReleaseContext");
1926       pcsc_list_readers      = dlsym (handle, "SCardListReaders");
1927 #if defined(_WIN32) || defined(__CYGWIN__)
1928       if (!pcsc_list_readers)
1929         pcsc_list_readers    = dlsym (handle, "SCardListReadersA");
1930 #endif
1931       pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
1932 #if defined(_WIN32) || defined(__CYGWIN__)
1933       if (!pcsc_get_status_change)
1934         pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
1935 #endif
1936       pcsc_connect           = dlsym (handle, "SCardConnect");
1937 #if defined(_WIN32) || defined(__CYGWIN__)
1938       if (!pcsc_connect)
1939         pcsc_connect         = dlsym (handle, "SCardConnectA");
1940 #endif
1941       pcsc_reconnect         = dlsym (handle, "SCardReconnect");
1942 #if defined(_WIN32) || defined(__CYGWIN__)
1943       if (!pcsc_reconnect)
1944         pcsc_reconnect       = dlsym (handle, "SCardReconnectA");
1945 #endif
1946       pcsc_disconnect        = dlsym (handle, "SCardDisconnect");
1947       pcsc_status            = dlsym (handle, "SCardStatus");
1948 #if defined(_WIN32) || defined(__CYGWIN__)
1949       if (!pcsc_status)
1950         pcsc_status          = dlsym (handle, "SCardStatusA");
1951 #endif
1952       pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
1953       pcsc_end_transaction   = dlsym (handle, "SCardEndTransaction");
1954       pcsc_transmit          = dlsym (handle, "SCardTransmit");
1955       pcsc_set_timeout       = dlsym (handle, "SCardSetTimeout");
1956       pcsc_control           = dlsym (handle, "SCardControl");
1957
1958       if (!pcsc_establish_context
1959           || !pcsc_release_context
1960           || !pcsc_list_readers
1961           || !pcsc_get_status_change
1962           || !pcsc_connect
1963           || !pcsc_reconnect
1964           || !pcsc_disconnect
1965           || !pcsc_status
1966           || !pcsc_begin_transaction
1967           || !pcsc_end_transaction
1968           || !pcsc_transmit
1969           || !pcsc_control
1970           /* || !pcsc_set_timeout */)
1971         {
1972           /* Note that set_timeout is currently not used and also not
1973              available under Windows. */
1974           log_error ("apdu_open_reader: invalid PC/SC driver "
1975                      "(%d%d%d%d%d%d%d%d%d%d%d%d%d)\n",
1976                      !!pcsc_establish_context,
1977                      !!pcsc_release_context,
1978                      !!pcsc_list_readers,
1979                      !!pcsc_get_status_change,
1980                      !!pcsc_connect,
1981                      !!pcsc_reconnect,
1982                      !!pcsc_disconnect,
1983                      !!pcsc_status,
1984                      !!pcsc_begin_transaction,
1985                      !!pcsc_end_transaction,
1986                      !!pcsc_transmit,
1987                      !!pcsc_set_timeout,
1988                      !!pcsc_control );
1989           dlclose (handle);
1990           return -1;
1991         }
1992       pcsc_api_loaded = 1;
1993     }
1994
1995   slot = open_pcsc_reader (portstr);
1996
1997   if (DBG_READER)
1998     log_debug ("leave: apdu_open_reader => slot=%d [pc/sc]\n", slot);
1999   return slot;
2000 }
2001
2002 int
2003 apdu_open_reader (struct dev_list *dl, int app_empty)
2004 {
2005   int slot;
2006
2007 #ifdef HAVE_LIBUSB
2008   if (dl->ccid_table)
2009     { /* CCID readers.  */
2010       int readerno;
2011
2012       /* See whether we want to use the reader ID string or a reader
2013          number. A readerno of -1 indicates that the reader ID string is
2014          to be used. */
2015       if (dl->portstr && strchr (dl->portstr, ':'))
2016         readerno = -1; /* We want to use the readerid.  */
2017       else if (dl->portstr)
2018         {
2019           readerno = atoi (dl->portstr);
2020           if (readerno < 0)
2021             {
2022               return -1;
2023             }
2024         }
2025       else
2026         readerno = 0;  /* Default. */
2027
2028       if (readerno > 0)
2029         { /* Use single, the specific reader.  */
2030           if (readerno >= dl->idx_max)
2031             return -1;
2032
2033           dl->idx = readerno;
2034           dl->portstr = NULL;
2035           slot = open_ccid_reader (dl);
2036           dl->idx = dl->idx_max;
2037           if (slot >= 0)
2038             return slot;
2039           else
2040             return -1;
2041         }
2042
2043       while (dl->idx < dl->idx_max)
2044         {
2045           unsigned int bai = ccid_get_BAI (dl->idx, dl->ccid_table);
2046
2047           if (DBG_READER)
2048             log_debug ("apdu_open_reader: BAI=%x\n", bai);
2049
2050           /* Check identity by BAI against already opened HANDLEs.  */
2051           for (slot = 0; slot < MAX_READER; slot++)
2052             if (reader_table[slot].used
2053                 && reader_table[slot].ccid.handle
2054                 && ccid_compare_BAI (reader_table[slot].ccid.handle, bai))
2055               break;
2056
2057           if (slot == MAX_READER)
2058             { /* Found a new device.  */
2059               if (DBG_READER)
2060                 log_debug ("apdu_open_reader: new device=%x\n", bai);
2061
2062               slot = open_ccid_reader (dl);
2063
2064               dl->idx++;
2065               if (slot >= 0)
2066                 return slot;
2067               else
2068                 {
2069                   /* Skip this reader.  */
2070                   log_error ("ccid open error: skip\n");
2071                   continue;
2072                 }
2073             }
2074           else
2075             dl->idx++;
2076         }
2077
2078       /* Not found.  Try one for PC/SC, only when it's the initial scan.  */
2079       if (app_empty && dl->idx == dl->idx_max)
2080         {
2081           dl->idx++;
2082           slot = apdu_open_one_reader (dl->portstr);
2083         }
2084       else
2085         slot = -1;
2086     }
2087   else
2088 #endif
2089     { /* PC/SC readers.  */
2090       if (app_empty && dl->idx == 0)
2091         {
2092           dl->idx++;
2093           slot = apdu_open_one_reader (dl->portstr);
2094         }
2095       else
2096         slot = -1;
2097     }
2098
2099   return slot;
2100 }
2101
2102
2103 /* Open an remote reader and return an internal slot number or -1 on
2104    error. This function is an alternative to apdu_open_reader and used
2105    with remote readers only.  Note that the supplied CLOSEFNC will
2106    only be called once and the slot will not be valid afther this.
2107
2108    If PORTSTR is NULL we default to the first available port.
2109 */
2110 int
2111 apdu_open_remote_reader (const char *portstr,
2112                          const unsigned char *cookie, size_t length,
2113                          int (*readfnc) (void *opaque,
2114                                          void *buffer, size_t size),
2115                          void *readfnc_value,
2116                          int (*writefnc) (void *opaque,
2117                                           const void *buffer, size_t size),
2118                          void *writefnc_value,
2119                          void (*closefnc) (void *opaque),
2120                          void *closefnc_value)
2121 {
2122 #ifdef USE_G10CODE_RAPDU
2123   return open_rapdu_reader (portstr? atoi (portstr) : 0,
2124                             cookie, length,
2125                             readfnc, readfnc_value,
2126                             writefnc, writefnc_value,
2127                             closefnc, closefnc_value);
2128 #else
2129   (void)portstr;
2130   (void)cookie;
2131   (void)length;
2132   (void)readfnc;
2133   (void)readfnc_value;
2134   (void)writefnc;
2135   (void)writefnc_value;
2136   (void)closefnc;
2137   (void)closefnc_value;
2138 #ifdef _WIN32
2139   errno = ENOENT;
2140 #else
2141   errno = ENOSYS;
2142 #endif
2143   return -1;
2144 #endif
2145 }
2146
2147
2148 int
2149 apdu_close_reader (int slot)
2150 {
2151   int sw;
2152
2153   if (DBG_READER)
2154     log_debug ("enter: apdu_close_reader: slot=%d\n", slot);
2155
2156   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2157     {
2158       if (DBG_READER)
2159         log_debug ("leave: apdu_close_reader => SW_HOST_NO_DRIVER\n");
2160       return SW_HOST_NO_DRIVER;
2161     }
2162   sw = apdu_disconnect (slot);
2163   if (sw)
2164     {
2165       /*
2166        * When the reader/token was removed it might come here.
2167        * It should go through to call CLOSE_READER even if we got an error.
2168        */
2169       if (DBG_READER)
2170         log_debug ("apdu_close_reader => 0x%x (apdu_disconnect)\n", sw);
2171     }
2172   if (reader_table[slot].close_reader)
2173     {
2174       sw = reader_table[slot].close_reader (slot);
2175       reader_table[slot].used = 0;
2176       if (DBG_READER)
2177         log_debug ("leave: apdu_close_reader => 0x%x (close_reader)\n", sw);
2178       return sw;
2179     }
2180   xfree (reader_table[slot].rdrname);
2181   reader_table[slot].rdrname = NULL;
2182   reader_table[slot].used = 0;
2183   if (DBG_READER)
2184     log_debug ("leave: apdu_close_reader => SW_HOST_NOT_SUPPORTED\n");
2185   return SW_HOST_NOT_SUPPORTED;
2186 }
2187
2188
2189 /* Function suitable for a cleanup function to close all reader.  It
2190    should not be used if the reader will be opened again.  The reason
2191    for implementing this to properly close USB devices so that they
2192    will startup the next time without error. */
2193 void
2194 apdu_prepare_exit (void)
2195 {
2196   static int sentinel;
2197   int slot;
2198
2199   if (!sentinel)
2200     {
2201       sentinel = 1;
2202       npth_mutex_lock (&reader_table_lock);
2203       for (slot = 0; slot < MAX_READER; slot++)
2204         if (reader_table[slot].used)
2205           {
2206             apdu_disconnect (slot);
2207             if (reader_table[slot].close_reader)
2208               reader_table[slot].close_reader (slot);
2209             xfree (reader_table[slot].rdrname);
2210             reader_table[slot].rdrname = NULL;
2211             reader_table[slot].used = 0;
2212           }
2213       npth_mutex_unlock (&reader_table_lock);
2214       sentinel = 0;
2215     }
2216 }
2217
2218
2219 /* Enumerate all readers and return information on whether this reader
2220    is in use.  The caller should start with SLOT set to 0 and
2221    increment it with each call until an error is returned. */
2222 int
2223 apdu_enum_reader (int slot, int *used)
2224 {
2225   if (slot < 0 || slot >= MAX_READER)
2226     return SW_HOST_NO_DRIVER;
2227   *used = reader_table[slot].used;
2228   return 0;
2229 }
2230
2231
2232 /* Connect a card.  This is used to power up the card and make sure
2233    that an ATR is available.  Depending on the reader backend it may
2234    return an error for an inactive card or if no card is available.
2235    Return -1 on error.  Return 1 if reader requires get_status to
2236    watch card removal.  Return 0 if it's a token (always with a card),
2237    or it supports INTERRUPT endpoint to watch card removal.
2238   */
2239 int
2240 apdu_connect (int slot)
2241 {
2242   int sw = 0;
2243   unsigned int status = 0;
2244
2245   if (DBG_READER)
2246     log_debug ("enter: apdu_connect: slot=%d\n", slot);
2247
2248   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2249     {
2250       if (DBG_READER)
2251         log_debug ("leave: apdu_connect => SW_HOST_NO_DRIVER\n");
2252       return -1;
2253     }
2254
2255   /* Only if the access method provides a connect function we use it.
2256      If not, we expect that the card has been implicitly connected by
2257      apdu_open_reader.  */
2258   if (reader_table[slot].connect_card)
2259     {
2260       sw = lock_slot (slot);
2261       if (!sw)
2262         {
2263           sw = reader_table[slot].connect_card (slot);
2264           unlock_slot (slot);
2265         }
2266     }
2267
2268   /* We need to call apdu_get_status_internal, so that the last-status
2269      machinery gets setup properly even if a card is inserted while
2270      scdaemon is fired up and apdu_get_status has not yet been called.
2271      Without that we would force a reset of the card with the next
2272      call to apdu_get_status.  */
2273   if (!sw)
2274     sw = apdu_get_status_internal (slot, 1, &status, 1);
2275
2276   if (sw)
2277     ;
2278   else if (!(status & APDU_CARD_PRESENT))
2279     sw = SW_HOST_NO_CARD;
2280   else if ((status & APDU_CARD_PRESENT) && !(status & APDU_CARD_ACTIVE))
2281     sw = SW_HOST_CARD_INACTIVE;
2282
2283   if (sw == SW_HOST_CARD_INACTIVE)
2284     {
2285       /* Try power it up again.  */
2286       sw = apdu_reset (slot);
2287     }
2288
2289   if (DBG_READER)
2290     log_debug ("leave: apdu_connect => sw=0x%x\n", sw);
2291
2292   if (sw)
2293     return -1;
2294
2295   return reader_table[slot].require_get_status;
2296 }
2297
2298
2299 int
2300 apdu_disconnect (int slot)
2301 {
2302   int sw;
2303
2304   if (DBG_READER)
2305     log_debug ("enter: apdu_disconnect: slot=%d\n", slot);
2306
2307   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2308     {
2309       if (DBG_READER)
2310         log_debug ("leave: apdu_disconnect => SW_HOST_NO_DRIVER\n");
2311       return SW_HOST_NO_DRIVER;
2312     }
2313
2314   if (reader_table[slot].disconnect_card)
2315     {
2316       sw = lock_slot (slot);
2317       if (!sw)
2318         {
2319           sw = reader_table[slot].disconnect_card (slot);
2320           unlock_slot (slot);
2321         }
2322     }
2323   else
2324     sw = 0;
2325
2326   if (DBG_READER)
2327     log_debug ("leave: apdu_disconnect => sw=0x%x\n", sw);
2328   return sw;
2329 }
2330
2331
2332 /* Set the progress callback of SLOT to CB and its args to CB_ARG.  If
2333    CB is NULL the progress callback is removed.  */
2334 int
2335 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
2336 {
2337   int sw;
2338
2339   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2340     return SW_HOST_NO_DRIVER;
2341
2342   if (reader_table[slot].set_progress_cb)
2343     {
2344       sw = lock_slot (slot);
2345       if (!sw)
2346         {
2347           sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
2348           unlock_slot (slot);
2349         }
2350     }
2351   else
2352     sw = 0;
2353   return sw;
2354 }
2355
2356
2357 /* Do a reset for the card in reader at SLOT. */
2358 int
2359 apdu_reset (int slot)
2360 {
2361   int sw;
2362
2363   if (DBG_READER)
2364     log_debug ("enter: apdu_reset: slot=%d\n", slot);
2365
2366   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2367     {
2368       if (DBG_READER)
2369         log_debug ("leave: apdu_reset => SW_HOST_NO_DRIVER\n");
2370       return SW_HOST_NO_DRIVER;
2371     }
2372
2373   if ((sw = lock_slot (slot)))
2374     {
2375       if (DBG_READER)
2376         log_debug ("leave: apdu_reset => sw=0x%x (lock_slot)\n", sw);
2377       return sw;
2378     }
2379
2380   if (reader_table[slot].reset_reader)
2381     sw = reader_table[slot].reset_reader (slot);
2382
2383   unlock_slot (slot);
2384   if (DBG_READER)
2385     log_debug ("leave: apdu_reset => sw=0x%x\n", sw);
2386   return sw;
2387 }
2388
2389
2390 /* Return the ATR or NULL if none is available.  On success the length
2391    of the ATR is stored at ATRLEN.  The caller must free the returned
2392    value.  */
2393 unsigned char *
2394 apdu_get_atr (int slot, size_t *atrlen)
2395 {
2396   unsigned char *buf;
2397
2398   if (DBG_READER)
2399     log_debug ("enter: apdu_get_atr: slot=%d\n", slot);
2400
2401   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2402     {
2403       if (DBG_READER)
2404         log_debug ("leave: apdu_get_atr => NULL (bad slot)\n");
2405       return NULL;
2406     }
2407   if (!reader_table[slot].atrlen)
2408     {
2409       if (DBG_READER)
2410         log_debug ("leave: apdu_get_atr => NULL (no ATR)\n");
2411       return NULL;
2412     }
2413
2414   buf = xtrymalloc (reader_table[slot].atrlen);
2415   if (!buf)
2416     {
2417       if (DBG_READER)
2418         log_debug ("leave: apdu_get_atr => NULL (out of core)\n");
2419       return NULL;
2420     }
2421   memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2422   *atrlen = reader_table[slot].atrlen;
2423   if (DBG_READER)
2424     log_debug ("leave: apdu_get_atr => atrlen=%zu\n", *atrlen);
2425   return buf;
2426 }
2427
2428
2429
2430 /* Retrieve the status for SLOT. The function does only wait for the
2431    card to become available if HANG is set to true. On success the
2432    bits in STATUS will be set to
2433
2434      APDU_CARD_USABLE  (bit 0) = card present and usable
2435      APDU_CARD_PRESENT (bit 1) = card present
2436      APDU_CARD_ACTIVE  (bit 2) = card active
2437                        (bit 3) = card access locked [not yet implemented]
2438
2439    For most applications, testing bit 0 is sufficient.
2440 */
2441 static int
2442 apdu_get_status_internal (int slot, int hang, unsigned int *status, int on_wire)
2443 {
2444   int sw;
2445   unsigned int s = 0;
2446
2447   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2448     return SW_HOST_NO_DRIVER;
2449
2450   if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2451     return sw;
2452
2453   if (reader_table[slot].get_status_reader)
2454     sw = reader_table[slot].get_status_reader (slot, &s, on_wire);
2455
2456   unlock_slot (slot);
2457
2458   if (sw)
2459     {
2460       if (on_wire)
2461         reader_table[slot].atrlen = 0;
2462       s = 0;
2463     }
2464
2465   if (status)
2466     *status = s;
2467   return sw;
2468 }
2469
2470
2471 /* See above for a description.  */
2472 int
2473 apdu_get_status (int slot, int hang, unsigned int *status)
2474 {
2475   int sw;
2476
2477   if (DBG_READER)
2478     log_debug ("enter: apdu_get_status: slot=%d hang=%d\n", slot, hang);
2479   sw = apdu_get_status_internal (slot, hang, status, 0);
2480   if (DBG_READER)
2481     {
2482       if (status)
2483         log_debug ("leave: apdu_get_status => sw=0x%x status=%u\n",
2484                    sw, *status);
2485       else
2486         log_debug ("leave: apdu_get_status => sw=0x%x\n", sw);
2487     }
2488   return sw;
2489 }
2490
2491
2492 /* Check whether the reader supports the ISO command code COMMAND on
2493    the pinpad.  Return 0 on success.  For a description of the pin
2494    parameters, see ccid-driver.c */
2495 int
2496 apdu_check_pinpad (int slot, int command, pininfo_t *pininfo)
2497 {
2498   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2499     return SW_HOST_NO_DRIVER;
2500
2501   if (opt.enable_pinpad_varlen)
2502     pininfo->fixedlen = 0;
2503
2504   if (reader_table[slot].check_pinpad)
2505     {
2506       int sw;
2507
2508       if ((sw = lock_slot (slot)))
2509         return sw;
2510
2511       sw = reader_table[slot].check_pinpad (slot, command, pininfo);
2512       unlock_slot (slot);
2513       return sw;
2514     }
2515   else
2516     return SW_HOST_NOT_SUPPORTED;
2517 }
2518
2519
2520 int
2521 apdu_pinpad_verify (int slot, int class, int ins, int p0, int p1,
2522                     pininfo_t *pininfo)
2523 {
2524   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2525     return SW_HOST_NO_DRIVER;
2526
2527   if (reader_table[slot].pinpad_verify)
2528     {
2529       int sw;
2530
2531       if ((sw = lock_slot (slot)))
2532         return sw;
2533
2534       sw = reader_table[slot].pinpad_verify (slot, class, ins, p0, p1,
2535                                              pininfo);
2536       unlock_slot (slot);
2537       return sw;
2538     }
2539   else
2540     return SW_HOST_NOT_SUPPORTED;
2541 }
2542
2543
2544 int
2545 apdu_pinpad_modify (int slot, int class, int ins, int p0, int p1,
2546                     pininfo_t *pininfo)
2547 {
2548   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2549     return SW_HOST_NO_DRIVER;
2550
2551   if (reader_table[slot].pinpad_modify)
2552     {
2553       int sw;
2554
2555       if ((sw = lock_slot (slot)))
2556         return sw;
2557
2558       sw = reader_table[slot].pinpad_modify (slot, class, ins, p0, p1,
2559                                              pininfo);
2560       unlock_slot (slot);
2561       return sw;
2562     }
2563   else
2564     return SW_HOST_NOT_SUPPORTED;
2565 }
2566
2567
2568 /* Dispatcher for the actual send_apdu function. Note, that this
2569    function should be called in locked state. */
2570 static int
2571 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2572            unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
2573 {
2574   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2575     return SW_HOST_NO_DRIVER;
2576
2577   if (reader_table[slot].send_apdu_reader)
2578     return reader_table[slot].send_apdu_reader (slot,
2579                                                 apdu, apdulen,
2580                                                 buffer, buflen,
2581                                                 pininfo);
2582   else
2583     return SW_HOST_NOT_SUPPORTED;
2584 }
2585
2586
2587 /* Core APDU tranceiver function. Parameters are described at
2588    apdu_send_le with the exception of PININFO which indicates pinpad
2589    related operations if not NULL.  If EXTENDED_MODE is not 0
2590    command chaining or extended length will be used according to these
2591    values:
2592        n < 0 := Use command chaining with the data part limited to -n
2593                 in each chunk.  If -1 is used a default value is used.
2594       n == 0 := No extended mode or command chaining.
2595       n == 1 := Use extended length for input and output without a
2596                 length limit.
2597        n > 1 := Use extended length with up to N bytes.
2598
2599 */
2600 static int
2601 send_le (int slot, int class, int ins, int p0, int p1,
2602          int lc, const char *data, int le,
2603          unsigned char **retbuf, size_t *retbuflen,
2604          pininfo_t *pininfo, int extended_mode)
2605 {
2606 #define SHORT_RESULT_BUFFER_SIZE 258
2607   /* We allocate 8 extra bytes as a safety margin towards a driver bug.  */
2608   unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
2609   unsigned char *result_buffer = NULL;
2610   size_t result_buffer_size;
2611   unsigned char *result;
2612   size_t resultlen;
2613   unsigned char short_apdu_buffer[5+256+1];
2614   unsigned char *apdu_buffer = NULL;
2615   size_t apdu_buffer_size;
2616   unsigned char *apdu;
2617   size_t apdulen;
2618   int sw;
2619   long rc; /* We need a long here due to PC/SC. */
2620   int did_exact_length_hack = 0;
2621   int use_chaining = 0;
2622   int use_extended_length = 0;
2623   int lc_chunk;
2624
2625   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2626     return SW_HOST_NO_DRIVER;
2627
2628   if (DBG_CARD_IO)
2629     log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
2630                class, ins, p0, p1, lc, le, extended_mode);
2631
2632   if (lc != -1 && (lc > 255 || lc < 0))
2633     {
2634       /* Data does not fit into an APDU.  What we do now depends on
2635          the EXTENDED_MODE parameter.  */
2636       if (!extended_mode)
2637         return SW_WRONG_LENGTH; /* No way to send such an APDU.  */
2638       else if (extended_mode > 0)
2639         use_extended_length = 1;
2640       else if (extended_mode < 0)
2641         {
2642           /* Send APDU using chaining mode.  */
2643           if (lc > 16384)
2644             return SW_WRONG_LENGTH;   /* Sanity check.  */
2645           if ((class&0xf0) != 0)
2646             return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0.  */
2647           use_chaining = extended_mode == -1? 255 : -extended_mode;
2648           use_chaining &= 0xff;
2649         }
2650       else
2651         return SW_HOST_INV_VALUE;
2652     }
2653   else if (lc == -1 && extended_mode > 0)
2654     use_extended_length = 1;
2655
2656   if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
2657     {
2658       /* Expected Data does not fit into an APDU.  What we do now
2659          depends on the EXTENDED_MODE parameter.  Note that a check
2660          for command chaining does not make sense because we are
2661          looking at Le.  */
2662       if (!extended_mode)
2663         return SW_WRONG_LENGTH; /* No way to send such an APDU.  */
2664       else if (use_extended_length)
2665         ; /* We are already using extended length.  */
2666       else if (extended_mode > 0)
2667         use_extended_length = 1;
2668       else
2669         return SW_HOST_INV_VALUE;
2670     }
2671
2672   if ((!data && lc != -1) || (data && lc == -1))
2673     return SW_HOST_INV_VALUE;
2674
2675   if (use_extended_length)
2676     {
2677       if (reader_table[slot].is_t0)
2678         return SW_HOST_NOT_SUPPORTED;
2679
2680       /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le.  */
2681       apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2682       apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
2683       if (!apdu_buffer)
2684         return SW_HOST_OUT_OF_CORE;
2685       apdu = apdu_buffer;
2686     }
2687   else
2688     {
2689       apdu_buffer_size = sizeof short_apdu_buffer;
2690       apdu = short_apdu_buffer;
2691     }
2692
2693   if (use_extended_length && (le > 256 || le < 0))
2694     {
2695       /* Two more bytes are needed for status bytes.  */
2696       result_buffer_size = le < 0? 4096 : (le + 2);
2697       result_buffer = xtrymalloc (result_buffer_size);
2698       if (!result_buffer)
2699         {
2700           xfree (apdu_buffer);
2701           return SW_HOST_OUT_OF_CORE;
2702         }
2703       result = result_buffer;
2704     }
2705   else
2706     {
2707       result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2708       result = short_result_buffer;
2709     }
2710 #undef SHORT_RESULT_BUFFER_SIZE
2711
2712   if ((sw = lock_slot (slot)))
2713     {
2714       xfree (apdu_buffer);
2715       xfree (result_buffer);
2716       return sw;
2717     }
2718
2719   do
2720     {
2721       if (use_extended_length)
2722         {
2723           use_chaining = 0;
2724           apdulen = 0;
2725           apdu[apdulen++] = class;
2726           apdu[apdulen++] = ins;
2727           apdu[apdulen++] = p0;
2728           apdu[apdulen++] = p1;
2729           if (lc > 0)
2730             {
2731               apdu[apdulen++] = 0;  /* Z byte: Extended length marker.  */
2732               apdu[apdulen++] = ((lc >> 8) & 0xff);
2733               apdu[apdulen++] = (lc & 0xff);
2734               memcpy (apdu+apdulen, data, lc);
2735               data += lc;
2736               apdulen += lc;
2737             }
2738           if (le != -1)
2739             {
2740               if (lc <= 0)
2741                 apdu[apdulen++] = 0;  /* Z byte: Extended length marker.  */
2742               apdu[apdulen++] = ((le >> 8) & 0xff);
2743               apdu[apdulen++] = (le & 0xff);
2744             }
2745         }
2746       else
2747         {
2748           apdulen = 0;
2749           apdu[apdulen] = class;
2750           if (use_chaining && lc > 255)
2751             {
2752               apdu[apdulen] |= 0x10;
2753               assert (use_chaining < 256);
2754               lc_chunk = use_chaining;
2755               lc -= use_chaining;
2756             }
2757           else
2758             {
2759               use_chaining = 0;
2760               lc_chunk = lc;
2761             }
2762           apdulen++;
2763           apdu[apdulen++] = ins;
2764           apdu[apdulen++] = p0;
2765           apdu[apdulen++] = p1;
2766           if (lc_chunk != -1)
2767             {
2768               apdu[apdulen++] = lc_chunk;
2769               memcpy (apdu+apdulen, data, lc_chunk);
2770               data += lc_chunk;
2771               apdulen += lc_chunk;
2772               /* T=0 does not allow the use of Lc together with Le;
2773                  thus disable Le in this case.  */
2774               if (reader_table[slot].is_t0)
2775                 le = -1;
2776             }
2777           if (le != -1 && !use_chaining)
2778             apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
2779         }
2780
2781     exact_length_hack:
2782       /* As a safeguard don't pass any garbage to the driver.  */
2783       assert (apdulen <= apdu_buffer_size);
2784       memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
2785       resultlen = result_buffer_size;
2786       rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
2787       if (rc || resultlen < 2)
2788         {
2789           log_info ("apdu_send_simple(%d) failed: %s\n",
2790                     slot, apdu_strerror (rc));
2791           unlock_slot (slot);
2792           xfree (apdu_buffer);
2793           xfree (result_buffer);
2794           return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2795         }
2796       sw = (result[resultlen-2] << 8) | result[resultlen-1];
2797       if (!use_extended_length
2798           && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
2799         {
2800           apdu[apdulen-1] = (sw & 0x00ff);
2801           did_exact_length_hack = 1;
2802           goto exact_length_hack;
2803         }
2804     }
2805   while (use_chaining && sw == SW_SUCCESS);
2806
2807   if (apdu_buffer)
2808     {
2809       xfree (apdu_buffer);
2810       apdu_buffer = NULL;
2811     }
2812
2813   /* Store away the returned data but strip the statusword. */
2814   resultlen -= 2;
2815   if (DBG_CARD_IO)
2816     {
2817       log_debug (" response: sw=%04X  datalen=%d\n",
2818                  sw, (unsigned int)resultlen);
2819       if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2820         log_printhex ("    dump: ", result, resultlen);
2821     }
2822
2823   if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2824     {
2825       if (retbuf)
2826         {
2827           *retbuf = xtrymalloc (resultlen? resultlen : 1);
2828           if (!*retbuf)
2829             {
2830               unlock_slot (slot);
2831               xfree (result_buffer);
2832               return SW_HOST_OUT_OF_CORE;
2833             }
2834           *retbuflen = resultlen;
2835           memcpy (*retbuf, result, resultlen);
2836         }
2837     }
2838   else if ((sw & 0xff00) == SW_MORE_DATA)
2839     {
2840       unsigned char *p = NULL, *tmp;
2841       size_t bufsize = 4096;
2842
2843       /* It is likely that we need to return much more data, so we
2844          start off with a large buffer. */
2845       if (retbuf)
2846         {
2847           *retbuf = p = xtrymalloc (bufsize);
2848           if (!*retbuf)
2849             {
2850               unlock_slot (slot);
2851               xfree (result_buffer);
2852               return SW_HOST_OUT_OF_CORE;
2853             }
2854           assert (resultlen < bufsize);
2855           memcpy (p, result, resultlen);
2856           p += resultlen;
2857         }
2858
2859       do
2860         {
2861           int len = (sw & 0x00ff);
2862
2863           if (DBG_CARD_IO)
2864             log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2865                        slot, len);
2866           apdu_buffer_size = sizeof short_apdu_buffer;
2867           apdu = short_apdu_buffer;
2868           apdulen = 0;
2869           apdu[apdulen++] = class;
2870           apdu[apdulen++] = 0xC0;
2871           apdu[apdulen++] = 0;
2872           apdu[apdulen++] = 0;
2873           apdu[apdulen++] = len;
2874           assert (apdulen <= apdu_buffer_size);
2875           memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
2876           resultlen = result_buffer_size;
2877           rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2878           if (rc || resultlen < 2)
2879             {
2880               log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2881                          slot, apdu_strerror (rc));
2882               unlock_slot (slot);
2883               xfree (result_buffer);
2884               return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2885             }
2886           sw = (result[resultlen-2] << 8) | result[resultlen-1];
2887           resultlen -= 2;
2888           if (DBG_CARD_IO)
2889             {
2890               log_debug ("     more: sw=%04X  datalen=%d\n",
2891                          sw, (unsigned int)resultlen);
2892               if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2893                 log_printhex ("     dump: ", result, resultlen);
2894             }
2895
2896           if ((sw & 0xff00) == SW_MORE_DATA
2897               || sw == SW_SUCCESS
2898               || sw == SW_EOF_REACHED )
2899             {
2900               if (retbuf && resultlen)
2901                 {
2902                   if (p - *retbuf + resultlen > bufsize)
2903                     {
2904                       bufsize += resultlen > 4096? resultlen: 4096;
2905                       tmp = xtryrealloc (*retbuf, bufsize);
2906                       if (!tmp)
2907                         {
2908                           unlock_slot (slot);
2909                           xfree (result_buffer);
2910                           return SW_HOST_OUT_OF_CORE;
2911                         }
2912                       p = tmp + (p - *retbuf);
2913                       *retbuf = tmp;
2914                     }
2915                   memcpy (p, result, resultlen);
2916                   p += resultlen;
2917                 }
2918             }
2919           else
2920             log_info ("apdu_send_simple(%d) "
2921                       "got unexpected status %04X from get response\n",
2922                       slot, sw);
2923         }
2924       while ((sw & 0xff00) == SW_MORE_DATA);
2925
2926       if (retbuf)
2927         {
2928           *retbuflen = p - *retbuf;
2929           tmp = xtryrealloc (*retbuf, *retbuflen);
2930           if (tmp)
2931             *retbuf = tmp;
2932         }
2933     }
2934
2935   unlock_slot (slot);
2936   xfree (result_buffer);
2937
2938   if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2939     log_printhex ("      dump: ", *retbuf, *retbuflen);
2940
2941   return sw;
2942 }
2943
2944 /* Send an APDU to the card in SLOT.  The APDU is created from all
2945    given parameters: CLASS, INS, P0, P1, LC, DATA, LE.  A value of -1
2946    for LC won't sent this field and the data field; in this case DATA
2947    must also be passed as NULL.  If EXTENDED_MODE is not 0 command
2948    chaining or extended length will be used; see send_le for details.
2949    The return value is the status word or -1 for an invalid SLOT or
2950    other non card related error.  If RETBUF is not NULL, it will
2951    receive an allocated buffer with the returned data.  The length of
2952    that data will be put into *RETBUFLEN.  The caller is responsible
2953    for releasing the buffer even in case of errors.  */
2954 int
2955 apdu_send_le(int slot, int extended_mode,
2956              int class, int ins, int p0, int p1,
2957              int lc, const char *data, int le,
2958              unsigned char **retbuf, size_t *retbuflen)
2959 {
2960   return send_le (slot, class, ins, p0, p1,
2961                   lc, data, le,
2962                   retbuf, retbuflen,
2963                   NULL, extended_mode);
2964 }
2965
2966
2967 /* Send an APDU to the card in SLOT.  The APDU is created from all
2968    given parameters: CLASS, INS, P0, P1, LC, DATA.  A value of -1 for
2969    LC won't sent this field and the data field; in this case DATA must
2970    also be passed as NULL.  If EXTENDED_MODE is not 0 command chaining
2971    or extended length will be used; see send_le for details.  The
2972    return value is the status word or -1 for an invalid SLOT or other
2973    non card related error.  If RETBUF is not NULL, it will receive an
2974    allocated buffer with the returned data.  The length of that data
2975    will be put into *RETBUFLEN.  The caller is responsible for
2976    releasing the buffer even in case of errors.  */
2977 int
2978 apdu_send (int slot, int extended_mode,
2979            int class, int ins, int p0, int p1,
2980            int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2981 {
2982   return send_le (slot, class, ins, p0, p1, lc, data, 256,
2983                   retbuf, retbuflen, NULL, extended_mode);
2984 }
2985
2986 /* Send an APDU to the card in SLOT.  The APDU is created from all
2987    given parameters: CLASS, INS, P0, P1, LC, DATA.  A value of -1 for
2988    LC won't sent this field and the data field; in this case DATA must
2989    also be passed as NULL.  If EXTENDED_MODE is not 0 command chaining
2990    or extended length will be used; see send_le for details.  The
2991    return value is the status word or -1 for an invalid SLOT or other
2992    non card related error.  No data will be returned.  */
2993 int
2994 apdu_send_simple (int slot, int extended_mode,
2995                   int class, int ins, int p0, int p1,
2996                   int lc, const char *data)
2997 {
2998   return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
2999                   extended_mode);
3000 }
3001
3002
3003 /* This is a more generic version of the apdu sending routine.  It
3004    takes an already formatted APDU in APDUDATA or length APDUDATALEN
3005    and returns with an APDU including the status word.  With
3006    HANDLE_MORE set to true this function will handle the MORE DATA
3007    status and return all APDUs concatenated with one status word at
3008    the end.  If EXTENDED_LENGTH is != 0 extended lengths are allowed
3009    with a max. result data length of EXTENDED_LENGTH bytes.  The
3010    function does not return a regular status word but 0 on success.
3011    If the slot is locked, the function returns immediately with an
3012    error.  */
3013 int
3014 apdu_send_direct (int slot, size_t extended_length,
3015                   const unsigned char *apdudata, size_t apdudatalen,
3016                   int handle_more,
3017                   unsigned char **retbuf, size_t *retbuflen)
3018 {
3019 #define SHORT_RESULT_BUFFER_SIZE 258
3020   unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3021   unsigned char *result_buffer = NULL;
3022   size_t result_buffer_size;
3023   unsigned char *result;
3024   size_t resultlen;
3025   unsigned char short_apdu_buffer[5+256+10];
3026   unsigned char *apdu_buffer = NULL;
3027   unsigned char *apdu;
3028   size_t apdulen;
3029   int sw;
3030   long rc; /* we need a long here due to PC/SC. */
3031   int class;
3032
3033   if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3034     return SW_HOST_NO_DRIVER;
3035
3036   if (apdudatalen > 65535)
3037     return SW_HOST_INV_VALUE;
3038
3039   if (apdudatalen > sizeof short_apdu_buffer - 5)
3040     {
3041       apdu_buffer = xtrymalloc (apdudatalen + 5);
3042       if (!apdu_buffer)
3043         return SW_HOST_OUT_OF_CORE;
3044       apdu = apdu_buffer;
3045     }
3046   else
3047     {
3048       apdu = short_apdu_buffer;
3049     }
3050   apdulen = apdudatalen;
3051   memcpy (apdu, apdudata, apdudatalen);
3052   class = apdulen? *apdu : 0;
3053
3054   if (extended_length >= 256 && extended_length <= 65536)
3055     {
3056       result_buffer_size = extended_length;
3057       result_buffer = xtrymalloc (result_buffer_size + 10);
3058       if (!result_buffer)
3059         {
3060           xfree (apdu_buffer);
3061           return SW_HOST_OUT_OF_CORE;
3062         }
3063       result = result_buffer;
3064     }
3065   else
3066     {
3067       result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3068       result = short_result_buffer;
3069     }
3070 #undef SHORT_RESULT_BUFFER_SIZE
3071
3072   if ((sw = trylock_slot (slot)))
3073     {
3074       xfree (apdu_buffer);
3075       xfree (result_buffer);
3076       return sw;
3077     }
3078
3079   resultlen = result_buffer_size;
3080   rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3081   xfree (apdu_buffer);
3082   apdu_buffer = NULL;
3083   if (rc || resultlen < 2)
3084     {
3085       log_error ("apdu_send_direct(%d) failed: %s\n",
3086                  slot, apdu_strerror (rc));
3087       unlock_slot (slot);
3088       xfree (result_buffer);
3089       return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3090     }
3091   sw = (result[resultlen-2] << 8) | result[resultlen-1];
3092   /* Store away the returned data but strip the statusword. */
3093   resultlen -= 2;
3094   if (DBG_CARD_IO)
3095     {
3096       log_debug (" response: sw=%04X  datalen=%d\n",
3097                  sw, (unsigned int)resultlen);
3098       if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3099         log_printhex ("     dump: ", result, resultlen);
3100     }
3101
3102   if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3103     {
3104       unsigned char *p = NULL, *tmp;
3105       size_t bufsize = 4096;
3106
3107       /* It is likely that we need to return much more data, so we
3108          start off with a large buffer. */
3109       if (retbuf)
3110         {
3111           *retbuf = p = xtrymalloc (bufsize + 2);
3112           if (!*retbuf)
3113             {
3114               unlock_slot (slot);
3115               xfree (result_buffer);
3116               return SW_HOST_OUT_OF_CORE;
3117             }
3118           assert (resultlen < bufsize);
3119           memcpy (p, result, resultlen);
3120           p += resultlen;
3121         }
3122
3123       do
3124         {
3125           int len = (sw & 0x00ff);
3126
3127           if (DBG_CARD_IO)
3128             log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3129                        slot, len);
3130           apdu = short_apdu_buffer;
3131           apdulen = 0;
3132           apdu[apdulen++] = class;
3133           apdu[apdulen++] = 0xC0;
3134           apdu[apdulen++] = 0;
3135           apdu[apdulen++] = 0;
3136           apdu[apdulen++] = len;
3137           memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
3138           resultlen = result_buffer_size;
3139           rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3140           if (rc || resultlen < 2)
3141             {
3142               log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3143                          slot, apdu_strerror (rc));
3144               unlock_slot (slot);
3145               xfree (result_buffer);
3146               return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3147             }
3148           sw = (result[resultlen-2] << 8) | result[resultlen-1];
3149           resultlen -= 2;
3150           if (DBG_CARD_IO)
3151             {
3152               log_debug ("     more: sw=%04X  datalen=%d\n",
3153                          sw, (unsigned int)resultlen);
3154               if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3155                 log_printhex ("     dump: ", result, resultlen);
3156             }
3157
3158           if ((sw & 0xff00) == SW_MORE_DATA
3159               || sw == SW_SUCCESS
3160               || sw == SW_EOF_REACHED )
3161             {
3162               if (retbuf && resultlen)
3163                 {
3164                   if (p - *retbuf + resultlen > bufsize)
3165                     {
3166                       bufsize += resultlen > 4096? resultlen: 4096;
3167                       tmp = xtryrealloc (*retbuf, bufsize + 2);
3168                       if (!tmp)
3169                         {
3170                           unlock_slot (slot);
3171                           xfree (result_buffer);
3172                           return SW_HOST_OUT_OF_CORE;
3173                         }
3174                       p = tmp + (p - *retbuf);
3175                       *retbuf = tmp;
3176                     }
3177                   memcpy (p, result, resultlen);
3178                   p += resultlen;
3179                 }
3180             }
3181           else
3182             log_info ("apdu_send_direct(%d) "
3183                       "got unexpected status %04X from get response\n",
3184                       slot, sw);
3185         }
3186       while ((sw & 0xff00) == SW_MORE_DATA);
3187
3188       if (retbuf)
3189         {
3190           *retbuflen = p - *retbuf;
3191           tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3192           if (tmp)
3193             *retbuf = tmp;
3194         }
3195     }
3196   else
3197     {
3198       if (retbuf)
3199         {
3200           *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3201           if (!*retbuf)
3202             {
3203               unlock_slot (slot);
3204               xfree (result_buffer);
3205               return SW_HOST_OUT_OF_CORE;
3206             }
3207           *retbuflen = resultlen;
3208           memcpy (*retbuf, result, resultlen);
3209         }
3210     }
3211
3212   unlock_slot (slot);
3213   xfree (result_buffer);
3214
3215   /* Append the status word.  Note that we reserved the two extra
3216      bytes while allocating the buffer.  */
3217   if (retbuf)
3218     {
3219       (*retbuf)[(*retbuflen)++] = (sw >> 8);
3220       (*retbuf)[(*retbuflen)++] = sw;
3221     }
3222
3223   if (DBG_CARD_IO && retbuf)
3224     log_printhex ("      dump: ", *retbuf, *retbuflen);
3225
3226   return 0;
3227 }
3228
3229
3230 const char *
3231 apdu_get_reader_name (int slot)
3232 {
3233   return reader_table[slot].rdrname;
3234 }
3235
3236 gpg_error_t
3237 apdu_init (void)
3238 {
3239 #ifdef USE_NPTH
3240   gpg_error_t err;
3241   int i;
3242
3243   if (npth_mutex_init (&reader_table_lock, NULL))
3244     goto leave;
3245
3246   for (i = 0; i < MAX_READER; i++)
3247     if (npth_mutex_init (&reader_table[i].lock, NULL))
3248       goto leave;
3249
3250   /* All done well.  */
3251   return 0;
3252
3253  leave:
3254   err = gpg_error_from_syserror ();
3255   log_error ("apdu: error initializing mutex: %s\n", gpg_strerror (err));
3256   return err;
3257 #endif /*USE_NPTH*/
3258   return 0;
3259 }