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