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.
5 * This file is part of GnuPG.
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.
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.
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/>.
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. */
39 /* If requested include the definitions for the remote APDU protocol
41 #ifdef USE_G10CODE_RAPDU
43 #endif /*USE_G10CODE_RAPDU*/
45 #if defined(GNUPG_SCD_MAIN_HEADER)
46 #include GNUPG_SCD_MAIN_HEADER
47 #elif GNUPG_MAJOR_VERSION == 1
48 /* This is used with GnuPG version < 1.9. The code has been source
49 copied from the current GnuPG >= 1.9 and is maintained over
51 #include "../common/options.h"
54 #include "../common/util.h"
55 #include "../common/i18n.h"
58 #else /* GNUPG_MAJOR_VERSION != 1 */
60 #include "../common/exechelp.h"
61 #endif /* GNUPG_MAJOR_VERSION != 1 */
62 #include "../common/host2net.h"
66 #define CCID_DRIVER_INCLUDE_USB_IDS 1
67 #include "ccid-driver.h"
70 struct ccid_dev_table *ccid_table;
76 #define MAX_READER 4 /* Number of readers we support concurrently. */
79 #if defined(_WIN32) || defined(__CYGWIN__)
80 #define DLSTDCALL __stdcall
85 #if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
86 typedef unsigned int pcsc_dword_t;
88 typedef unsigned long pcsc_dword_t;
91 /* A structure to collect information pertaining to one reader
93 struct reader_table_s {
94 int used; /* True if slot is used. */
95 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
97 /* Function pointers initialized to the various backends. */
98 int (*connect_card)(int);
99 int (*disconnect_card)(int);
100 int (*close_reader)(int);
101 int (*reset_reader)(int);
102 int (*get_status_reader)(int, unsigned int *, int);
103 int (*send_apdu_reader)(int,unsigned char *,size_t,
104 unsigned char *, size_t *, pininfo_t *);
105 int (*check_pinpad)(int, int, pininfo_t *);
106 void (*dump_status_reader)(int);
107 int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
108 int (*pinpad_verify)(int, int, int, int, int, pininfo_t *);
109 int (*pinpad_modify)(int, int, int, int, int, pininfo_t *);
112 ccid_driver_t handle;
117 pcsc_dword_t protocol;
118 pcsc_dword_t verify_ioctl;
119 pcsc_dword_t modify_ioctl;
123 #ifdef USE_G10CODE_RAPDU
127 #endif /*USE_G10CODE_RAPDU*/
128 char *rdrname; /* Name of the connected reader or NULL if unknown. */
129 unsigned int is_t0:1; /* True if we know that we are running T=0. */
130 unsigned int is_spr532:1; /* True if we know that the reader is a SPR532. */
131 unsigned int pinpad_varlen_supported:1; /* True if we know that the reader
132 supports variable length pinpad
134 unsigned int require_get_status:1;
135 unsigned char atr[33];
136 size_t atrlen; /* A zero length indicates that the ATR has
137 not yet been read; i.e. the card is not
143 typedef struct reader_table_s *reader_table_t;
145 /* A global table to keep track of active readers. */
146 static struct reader_table_s reader_table[MAX_READER];
149 static npth_mutex_t reader_table_lock;
153 /* PC/SC constants and function pointer. */
154 #define PCSC_SCOPE_USER 0
155 #define PCSC_SCOPE_TERMINAL 1
156 #define PCSC_SCOPE_SYSTEM 2
157 #define PCSC_SCOPE_GLOBAL 3
159 #define PCSC_PROTOCOL_T0 1
160 #define PCSC_PROTOCOL_T1 2
161 #ifdef HAVE_W32_SYSTEM
162 # define PCSC_PROTOCOL_RAW 0x00010000 /* The active protocol. */
164 # define PCSC_PROTOCOL_RAW 4
167 #define PCSC_SHARE_EXCLUSIVE 1
168 #define PCSC_SHARE_SHARED 2
169 #define PCSC_SHARE_DIRECT 3
171 #define PCSC_LEAVE_CARD 0
172 #define PCSC_RESET_CARD 1
173 #define PCSC_UNPOWER_CARD 2
174 #define PCSC_EJECT_CARD 3
176 #ifdef HAVE_W32_SYSTEM
177 # define PCSC_UNKNOWN 0x0000 /* The driver is not aware of the status. */
178 # define PCSC_ABSENT 0x0001 /* Card is absent. */
179 # define PCSC_PRESENT 0x0002 /* Card is present. */
180 # define PCSC_SWALLOWED 0x0003 /* Card is present and electrical connected. */
181 # define PCSC_POWERED 0x0004 /* Card is powered. */
182 # define PCSC_NEGOTIABLE 0x0005 /* Card is awaiting PTS. */
183 # define PCSC_SPECIFIC 0x0006 /* Card is ready for use. */
185 # define PCSC_UNKNOWN 0x0001
186 # define PCSC_ABSENT 0x0002 /* Card is absent. */
187 # define PCSC_PRESENT 0x0004 /* Card is present. */
188 # define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
189 # define PCSC_POWERED 0x0010 /* Card is powered. */
190 # define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
191 # define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
194 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
195 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
196 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
197 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
198 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
199 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
200 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
201 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
202 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
203 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
204 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
205 #ifdef HAVE_W32_SYSTEM
206 # define PCSC_STATE_UNPOWERED 0x0400 /* Card not powerred up. */
209 /* Some PC/SC error codes. */
210 #define PCSC_E_CANCELLED 0x80100002
211 #define PCSC_E_CANT_DISPOSE 0x8010000E
212 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
213 #define PCSC_E_INVALID_ATR 0x80100015
214 #define PCSC_E_INVALID_HANDLE 0x80100003
215 #define PCSC_E_INVALID_PARAMETER 0x80100004
216 #define PCSC_E_INVALID_TARGET 0x80100005
217 #define PCSC_E_INVALID_VALUE 0x80100011
218 #define PCSC_E_NO_MEMORY 0x80100006
219 #define PCSC_E_UNKNOWN_READER 0x80100009
220 #define PCSC_E_TIMEOUT 0x8010000A
221 #define PCSC_E_SHARING_VIOLATION 0x8010000B
222 #define PCSC_E_NO_SMARTCARD 0x8010000C
223 #define PCSC_E_UNKNOWN_CARD 0x8010000D
224 #define PCSC_E_PROTO_MISMATCH 0x8010000F
225 #define PCSC_E_NOT_READY 0x80100010
226 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
227 #define PCSC_E_NOT_TRANSACTED 0x80100016
228 #define PCSC_E_READER_UNAVAILABLE 0x80100017
229 #define PCSC_E_NO_SERVICE 0x8010001D
230 #define PCSC_E_SERVICE_STOPPED 0x8010001E
231 #define PCSC_W_REMOVED_CARD 0x80100069
233 /* Fix pcsc-lite ABI incompatibility. */
234 #ifndef SCARD_CTL_CODE
236 #include <winioctl.h>
237 #define SCARD_CTL_CODE(code) CTL_CODE(FILE_DEVICE_SMARTCARD, (code), \
238 METHOD_BUFFERED, FILE_ANY_ACCESS)
240 #define SCARD_CTL_CODE(code) (0x42000000 + (code))
244 #define CM_IOCTL_GET_FEATURE_REQUEST SCARD_CTL_CODE(3400)
245 #define CM_IOCTL_VENDOR_IFD_EXCHANGE SCARD_CTL_CODE(1)
246 #define FEATURE_VERIFY_PIN_DIRECT 0x06
247 #define FEATURE_MODIFY_PIN_DIRECT 0x07
248 #define FEATURE_GET_TLV_PROPERTIES 0x12
250 #define PCSCv2_PART10_PROPERTY_bEntryValidationCondition 2
251 #define PCSCv2_PART10_PROPERTY_bTimeOut2 3
252 #define PCSCv2_PART10_PROPERTY_bMinPINSize 6
253 #define PCSCv2_PART10_PROPERTY_bMaxPINSize 7
254 #define PCSCv2_PART10_PROPERTY_wIdVendor 11
255 #define PCSCv2_PART10_PROPERTY_wIdProduct 12
258 /* The PC/SC error is defined as a long as per specs. Due to left
259 shifts bit 31 will get sign extended. We use this mask to fix
261 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
264 struct pcsc_io_request_s
266 unsigned long protocol;
267 unsigned long pci_len;
270 typedef struct pcsc_io_request_s *pcsc_io_request_t;
276 struct pcsc_readerstate_s
280 pcsc_dword_t current_state;
281 pcsc_dword_t event_state;
283 unsigned char atr[33];
290 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
292 long (* DLSTDCALL pcsc_establish_context) (pcsc_dword_t scope,
293 const void *reserved1,
294 const void *reserved2,
296 long (* DLSTDCALL pcsc_release_context) (long context);
297 long (* DLSTDCALL pcsc_list_readers) (long context,
299 char *readers, pcsc_dword_t*readerslen);
300 long (* DLSTDCALL pcsc_get_status_change) (long context,
301 pcsc_dword_t timeout,
302 pcsc_readerstate_t readerstates,
303 pcsc_dword_t nreaderstates);
304 long (* DLSTDCALL pcsc_connect) (long context,
306 pcsc_dword_t share_mode,
307 pcsc_dword_t preferred_protocols,
309 pcsc_dword_t *r_active_protocol);
310 long (* DLSTDCALL pcsc_reconnect) (long card,
311 pcsc_dword_t share_mode,
312 pcsc_dword_t preferred_protocols,
313 pcsc_dword_t initialization,
314 pcsc_dword_t *r_active_protocol);
315 long (* DLSTDCALL pcsc_disconnect) (long card,
316 pcsc_dword_t disposition);
317 long (* DLSTDCALL pcsc_status) (long card,
318 char *reader, pcsc_dword_t *readerlen,
319 pcsc_dword_t *r_state,
320 pcsc_dword_t *r_protocol,
321 unsigned char *atr, pcsc_dword_t *atrlen);
322 long (* DLSTDCALL pcsc_begin_transaction) (long card);
323 long (* DLSTDCALL pcsc_end_transaction) (long card,
324 pcsc_dword_t disposition);
325 long (* DLSTDCALL pcsc_transmit) (long card,
326 const pcsc_io_request_t send_pci,
327 const unsigned char *send_buffer,
328 pcsc_dword_t send_len,
329 pcsc_io_request_t recv_pci,
330 unsigned char *recv_buffer,
331 pcsc_dword_t *recv_len);
332 long (* DLSTDCALL pcsc_set_timeout) (long context,
333 pcsc_dword_t timeout);
334 long (* DLSTDCALL pcsc_control) (long card,
335 pcsc_dword_t control_code,
336 const void *send_buffer,
337 pcsc_dword_t send_len,
339 pcsc_dword_t recv_len,
340 pcsc_dword_t *bytes_returned);
344 static int pcsc_vendor_specific_init (int slot);
345 static int pcsc_get_status (int slot, unsigned int *status, int on_wire);
346 static int reset_pcsc_reader (int slot);
347 static int apdu_get_status_internal (int slot, int hang, unsigned int *status,
349 static int check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo);
350 static int pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
352 static int pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
367 err = npth_mutex_lock (&reader_table[slot].lock);
370 log_error ("failed to acquire apdu lock: %s\n", strerror (err));
371 return SW_HOST_LOCKING_FAILED;
378 trylock_slot (int slot)
383 err = npth_mutex_trylock (&reader_table[slot].lock);
388 log_error ("failed to acquire apdu lock: %s\n", strerror (err));
389 return SW_HOST_LOCKING_FAILED;
396 unlock_slot (int slot)
401 err = npth_mutex_unlock (&reader_table[slot].lock);
403 log_error ("failed to release apdu lock: %s\n", strerror (errno));
408 /* Find an unused reader slot for PORTSTR and put it into the reader
409 table. Return -1 on error or the index into the reader table.
410 Acquire slot's lock on successful return. Caller needs to unlock it. */
412 new_reader_slot (void)
416 for (i=0; i < MAX_READER; i++)
417 if (!reader_table[i].used)
420 reader_table[reader].used = 1;
426 log_error ("new_reader_slot: out of slots\n");
430 if (lock_slot (reader))
432 reader_table[reader].used = 0;
436 reader_table[reader].connect_card = NULL;
437 reader_table[reader].disconnect_card = NULL;
438 reader_table[reader].close_reader = NULL;
439 reader_table[reader].reset_reader = NULL;
440 reader_table[reader].get_status_reader = NULL;
441 reader_table[reader].send_apdu_reader = NULL;
442 reader_table[reader].check_pinpad = check_pcsc_pinpad;
443 reader_table[reader].dump_status_reader = NULL;
444 reader_table[reader].set_progress_cb = NULL;
445 reader_table[reader].pinpad_verify = pcsc_pinpad_verify;
446 reader_table[reader].pinpad_modify = pcsc_pinpad_modify;
448 reader_table[reader].is_t0 = 1;
449 reader_table[reader].is_spr532 = 0;
450 reader_table[reader].pinpad_varlen_supported = 0;
451 reader_table[reader].require_get_status = 1;
452 reader_table[reader].pcsc.verify_ioctl = 0;
453 reader_table[reader].pcsc.modify_ioctl = 0;
454 reader_table[reader].pcsc.pinmin = -1;
455 reader_table[reader].pcsc.pinmax = -1;
462 dump_reader_status (int slot)
467 if (reader_table[slot].dump_status_reader)
468 reader_table[slot].dump_status_reader (slot);
470 if (reader_table[slot].atrlen)
472 log_info ("slot %d: ATR=", slot);
473 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
480 host_sw_string (long err)
484 case 0: return "okay";
485 case SW_HOST_OUT_OF_CORE: return "out of core";
486 case SW_HOST_INV_VALUE: return "invalid value";
487 case SW_HOST_NO_DRIVER: return "no driver";
488 case SW_HOST_NOT_SUPPORTED: return "not supported";
489 case SW_HOST_LOCKING_FAILED: return "locking failed";
490 case SW_HOST_BUSY: return "busy";
491 case SW_HOST_NO_CARD: return "no card";
492 case SW_HOST_CARD_INACTIVE: return "card inactive";
493 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
494 case SW_HOST_GENERAL_ERROR: return "general error";
495 case SW_HOST_NO_READER: return "no reader";
496 case SW_HOST_ABORTED: return "aborted";
497 case SW_HOST_NO_PINPAD: return "no pinpad";
498 case SW_HOST_ALREADY_CONNECTED: return "already connected";
499 default: return "unknown host status error";
505 apdu_strerror (int rc)
509 case SW_EOF_REACHED : return "eof reached";
510 case SW_EEPROM_FAILURE : return "eeprom failure";
511 case SW_WRONG_LENGTH : return "wrong length";
512 case SW_CHV_WRONG : return "CHV wrong";
513 case SW_CHV_BLOCKED : return "CHV blocked";
514 case SW_REF_DATA_INV : return "referenced data invalidated";
515 case SW_USE_CONDITIONS : return "use conditions not satisfied";
516 case SW_BAD_PARAMETER : return "bad parameter";
517 case SW_NOT_SUPPORTED : return "not supported";
518 case SW_FILE_NOT_FOUND : return "file not found";
519 case SW_RECORD_NOT_FOUND:return "record not found";
520 case SW_REF_NOT_FOUND : return "reference not found";
521 case SW_NOT_ENOUGH_MEMORY: return "not enough memory space in the file";
522 case SW_INCONSISTENT_LC: return "Lc inconsistent with TLV structure.";
523 case SW_INCORRECT_P0_P1: return "incorrect parameters P0,P1";
524 case SW_BAD_LC : return "Lc inconsistent with P0,P1";
525 case SW_BAD_P0_P1 : return "bad P0,P1";
526 case SW_INS_NOT_SUP : return "instruction not supported";
527 case SW_CLA_NOT_SUP : return "class not supported";
528 case SW_SUCCESS : return "success";
530 if ((rc & ~0x00ff) == SW_MORE_DATA)
531 return "more data available";
532 if ( (rc & 0x10000) )
533 return host_sw_string (rc);
534 return "unknown status error";
543 pcsc_error_string (long err)
549 if ((err & 0x80100000) != 0x80100000)
550 return "invalid PC/SC error code";
554 case 0x0002: s = "cancelled"; break;
555 case 0x000e: s = "can't dispose"; break;
556 case 0x0008: s = "insufficient buffer"; break;
557 case 0x0015: s = "invalid ATR"; break;
558 case 0x0003: s = "invalid handle"; break;
559 case 0x0004: s = "invalid parameter"; break;
560 case 0x0005: s = "invalid target"; break;
561 case 0x0011: s = "invalid value"; break;
562 case 0x0006: s = "no memory"; break;
563 case 0x0013: s = "comm error"; break;
564 case 0x0001: s = "internal error"; break;
565 case 0x0014: s = "unknown error"; break;
566 case 0x0007: s = "waited too long"; break;
567 case 0x0009: s = "unknown reader"; break;
568 case 0x000a: s = "timeout"; break;
569 case 0x000b: s = "sharing violation"; break;
570 case 0x000c: s = "no smartcard"; break;
571 case 0x000d: s = "unknown card"; break;
572 case 0x000f: s = "proto mismatch"; break;
573 case 0x0010: s = "not ready"; break;
574 case 0x0012: s = "system cancelled"; break;
575 case 0x0016: s = "not transacted"; break;
576 case 0x0017: s = "reader unavailable"; break;
577 case 0x0065: s = "unsupported card"; break;
578 case 0x0066: s = "unresponsive card"; break;
579 case 0x0067: s = "unpowered card"; break;
580 case 0x0068: s = "reset card"; break;
581 case 0x0069: s = "removed card"; break;
582 case 0x006a: s = "inserted card"; break;
583 case 0x001f: s = "unsupported feature"; break;
584 case 0x0019: s = "PCI too small"; break;
585 case 0x001a: s = "reader unsupported"; break;
586 case 0x001b: s = "duplicate reader"; break;
587 case 0x001c: s = "card unsupported"; break;
588 case 0x001d: s = "no service"; break;
589 case 0x001e: s = "service stopped"; break;
590 default: s = "unknown PC/SC error code"; break;
595 /* Map PC/SC error codes to our special host status words. */
597 pcsc_error_to_sw (long ec)
601 switch ( PCSC_ERR_MASK (ec) )
603 case 0: rc = 0; break;
605 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
606 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
607 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
608 case PCSC_E_NO_SERVICE:
609 case PCSC_E_SERVICE_STOPPED:
610 case PCSC_E_UNKNOWN_READER: rc = SW_HOST_NO_READER; break;
611 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
612 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
613 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
615 case PCSC_E_INVALID_TARGET:
616 case PCSC_E_INVALID_VALUE:
617 case PCSC_E_INVALID_HANDLE:
618 case PCSC_E_INVALID_PARAMETER:
619 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
621 default: rc = SW_HOST_GENERAL_ERROR; break;
628 dump_pcsc_reader_status (int slot)
630 if (reader_table[slot].pcsc.card)
632 log_info ("reader slot %d: active protocol:", slot);
633 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
635 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
637 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
642 log_info ("reader slot %d: not connected\n", slot);
647 pcsc_get_status (int slot, unsigned int *status, int on_wire)
650 struct pcsc_readerstate_s rdrstates[1];
653 memset (rdrstates, 0, sizeof *rdrstates);
654 rdrstates[0].reader = reader_table[slot].rdrname;
655 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
656 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
659 if (err == PCSC_E_TIMEOUT)
660 err = 0; /* Timeout is no error error here. */
663 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
664 pcsc_error_string (err), err);
665 return pcsc_error_to_sw (err);
669 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
670 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
671 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
672 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
673 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
674 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
675 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
676 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
677 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
678 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
679 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
682 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
684 *status |= APDU_CARD_PRESENT;
685 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
686 *status |= APDU_CARD_ACTIVE;
688 #ifndef HAVE_W32_SYSTEM
689 /* We indicate a useful card if it is not in use by another
690 application. This is because we only use exclusive access
692 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
693 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
694 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
695 *status |= APDU_CARD_USABLE;
697 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
698 time when we are the only user (SCM SCR335) under Windows. */
699 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
700 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
701 *status |= APDU_CARD_USABLE;
708 /* Send the APDU of length APDULEN to SLOT and return a maximum of
709 *BUFLEN data in BUFFER, the actual returned size will be stored at
710 BUFLEN. Returns: A status word. */
712 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
713 unsigned char *buffer, size_t *buflen,
717 struct pcsc_io_request_s send_pci;
718 pcsc_dword_t recv_len;
722 if (!reader_table[slot].atrlen
723 && (err = reset_pcsc_reader (slot)))
727 log_printhex (" PCSC_data:", apdu, apdulen);
729 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
730 send_pci.protocol = PCSC_PROTOCOL_T1;
732 send_pci.protocol = PCSC_PROTOCOL_T0;
733 send_pci.pci_len = sizeof send_pci;
735 err = pcsc_transmit (reader_table[slot].pcsc.card,
736 &send_pci, apdu, apdulen,
737 NULL, buffer, &recv_len);
740 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
741 pcsc_error_string (err), err);
743 return pcsc_error_to_sw (err);
747 /* Do some control with the value of IOCTL_CODE to the card inserted
748 to SLOT. Input buffer is specified by CNTLBUF of length LEN.
749 Output buffer is specified by BUFFER of length *BUFLEN, and the
750 actual output size will be stored at BUFLEN. Returns: A status word.
751 This routine is used for PIN pad input support. */
753 control_pcsc (int slot, pcsc_dword_t ioctl_code,
754 const unsigned char *cntlbuf, size_t len,
755 unsigned char *buffer, pcsc_dword_t *buflen)
759 err = pcsc_control (reader_table[slot].pcsc.card, ioctl_code,
760 cntlbuf, len, buffer, buflen? *buflen:0, buflen);
763 log_error ("pcsc_control failed: %s (0x%lx)\n",
764 pcsc_error_string (err), err);
765 return pcsc_error_to_sw (err);
773 close_pcsc_reader (int slot)
775 pcsc_release_context (reader_table[slot].pcsc.context);
780 /* Connect a PC/SC card. */
782 connect_pcsc_card (int slot)
786 assert (slot >= 0 && slot < MAX_READER);
788 if (reader_table[slot].pcsc.card)
789 return SW_HOST_ALREADY_CONNECTED;
791 reader_table[slot].atrlen = 0;
792 reader_table[slot].is_t0 = 0;
794 err = pcsc_connect (reader_table[slot].pcsc.context,
795 reader_table[slot].rdrname,
796 PCSC_SHARE_EXCLUSIVE,
797 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
798 &reader_table[slot].pcsc.card,
799 &reader_table[slot].pcsc.protocol);
802 reader_table[slot].pcsc.card = 0;
803 if (err != PCSC_E_NO_SMARTCARD)
804 log_error ("pcsc_connect failed: %s (0x%lx)\n",
805 pcsc_error_string (err), err);
810 pcsc_dword_t readerlen, atrlen;
811 pcsc_dword_t card_state, card_protocol;
813 pcsc_vendor_specific_init (slot);
815 atrlen = DIM (reader_table[0].atr);
816 readerlen = sizeof reader -1 ;
817 err = pcsc_status (reader_table[slot].pcsc.card,
819 &card_state, &card_protocol,
820 reader_table[slot].atr, &atrlen);
822 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
823 pcsc_error_string (err), err, (long unsigned int)readerlen);
826 if (atrlen > DIM (reader_table[0].atr))
827 log_bug ("ATR returned by pcsc_status is too large\n");
828 reader_table[slot].atrlen = atrlen;
829 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
833 dump_reader_status (slot);
834 return pcsc_error_to_sw (err);
839 disconnect_pcsc_card (int slot)
843 assert (slot >= 0 && slot < MAX_READER);
845 if (!reader_table[slot].pcsc.card)
848 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
851 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
852 pcsc_error_string (err), err);
853 return SW_HOST_CARD_IO_ERROR;
855 reader_table[slot].pcsc.card = 0;
860 /* Send an PC/SC reset command and return a status word on error or 0
863 reset_pcsc_reader (int slot)
867 sw = disconnect_pcsc_card (slot);
869 sw = connect_pcsc_card (slot);
875 /* Examine reader specific parameters and initialize. This is mostly
876 for pinpad input. Called at opening the connection to the reader. */
878 pcsc_vendor_specific_init (int slot)
880 unsigned char buf[256];
885 pcsc_dword_t get_tlv_ioctl = (pcsc_dword_t)-1;
889 sw = control_pcsc (slot, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, &len);
892 log_error ("pcsc_vendor_specific_init: GET_FEATURE_REQUEST failed: %d\n",
894 return SW_NOT_SUPPORTED;
899 while (p < buf + len)
901 unsigned char code = *p++;
908 v = buf16_to_uint (p);
910 v = buf32_to_uint (p);
912 if (code == FEATURE_VERIFY_PIN_DIRECT)
913 reader_table[slot].pcsc.verify_ioctl = v;
914 else if (code == FEATURE_MODIFY_PIN_DIRECT)
915 reader_table[slot].pcsc.modify_ioctl = v;
916 else if (code == FEATURE_GET_TLV_PROPERTIES)
920 log_debug ("feature: code=%02X, len=%d, v=%02X\n", code, l, v);
926 if (get_tlv_ioctl == (pcsc_dword_t)-1)
929 * For system which doesn't support GET_TLV_PROPERTIES,
930 * we put some heuristics here.
932 if (reader_table[slot].rdrname)
934 if (strstr (reader_table[slot].rdrname, "SPRx32"))
936 reader_table[slot].is_spr532 = 1;
937 reader_table[slot].pinpad_varlen_supported = 1;
939 else if (strstr (reader_table[slot].rdrname, "ST-2xxx"))
941 reader_table[slot].pcsc.pinmax = 15;
942 reader_table[slot].pinpad_varlen_supported = 1;
944 else if (strstr (reader_table[slot].rdrname, "cyberJack")
945 || strstr (reader_table[slot].rdrname, "DIGIPASS")
946 || strstr (reader_table[slot].rdrname, "Gnuk")
947 || strstr (reader_table[slot].rdrname, "KAAN"))
948 reader_table[slot].pinpad_varlen_supported = 1;
955 sw = control_pcsc (slot, get_tlv_ioctl, NULL, 0, buf, &len);
958 log_error ("pcsc_vendor_specific_init: GET_TLV_IOCTL failed: %d\n", sw);
959 return SW_NOT_SUPPORTED;
963 while (p < buf + len)
965 unsigned char tag = *p++;
969 /* Umm... here is little endian, while the encoding above is big. */
973 v = (((unsigned int)p[1] << 8) | p[0]);
975 v = (((unsigned int)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
977 if (tag == PCSCv2_PART10_PROPERTY_bMinPINSize)
978 reader_table[slot].pcsc.pinmin = v;
979 else if (tag == PCSCv2_PART10_PROPERTY_bMaxPINSize)
980 reader_table[slot].pcsc.pinmax = v;
981 else if (tag == PCSCv2_PART10_PROPERTY_wIdVendor)
983 else if (tag == PCSCv2_PART10_PROPERTY_wIdProduct)
987 log_debug ("TLV properties: tag=%02X, len=%d, v=%08X\n", tag, l, v);
992 if (vendor == VENDOR_VEGA && product == VEGA_ALPHA)
995 * Please read the comment of ccid_vendor_specific_init in
998 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
999 sw = control_pcsc (slot, CM_IOCTL_VENDOR_IFD_EXCHANGE,
1000 cmd, sizeof (cmd), NULL, 0);
1002 return SW_NOT_SUPPORTED;
1004 else if (vendor == VENDOR_SCM && product == SCM_SPR532) /* SCM SPR532 */
1006 reader_table[slot].is_spr532 = 1;
1007 reader_table[slot].pinpad_varlen_supported = 1;
1009 else if (vendor == 0x046a)
1011 /* Cherry ST-2xxx (product == 0x003e) supports TPDU level
1012 * exchange. Other products which only support short APDU level
1013 * exchange only work with shorter keys like RSA 1024.
1015 reader_table[slot].pcsc.pinmax = 15;
1016 reader_table[slot].pinpad_varlen_supported = 1;
1018 else if (vendor == 0x0c4b /* Tested with Reiner cyberJack GO */
1019 || vendor == 0x1a44 /* Tested with Vasco DIGIPASS 920 */
1020 || vendor == 0x234b /* Tested with FSIJ Gnuk Token */
1021 || vendor == 0x0d46 /* Tested with KAAN Advanced??? */)
1022 reader_table[slot].pinpad_varlen_supported = 1;
1028 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1029 error or a slot number for the reader. */
1031 open_pcsc_reader (const char *portstr)
1036 char *rdrname = NULL;
1037 pcsc_dword_t nreader;
1040 slot = new_reader_slot ();
1044 /* Fixme: Allocating a context for each slot is not required. One
1045 global context should be sufficient. */
1046 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1047 &reader_table[slot].pcsc.context);
1050 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1051 pcsc_error_string (err), err);
1052 reader_table[slot].used = 0;
1057 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1058 NULL, NULL, &nreader);
1061 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1064 log_error ("error allocating memory for reader list\n");
1065 pcsc_release_context (reader_table[slot].pcsc.context);
1066 reader_table[slot].used = 0;
1068 return -1 /*SW_HOST_OUT_OF_CORE*/;
1070 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1071 NULL, list, &nreader);
1075 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1076 pcsc_error_string (err), err);
1077 pcsc_release_context (reader_table[slot].pcsc.context);
1078 reader_table[slot].used = 0;
1089 log_info ("detected reader '%s'\n", p);
1090 if (nreader < (strlen (p)+1))
1092 log_error ("invalid response from pcsc_list_readers\n");
1095 if (!rdrname && portstr && !strncmp (p, portstr, strlen (portstr)))
1097 nreader -= strlen (p)+1;
1098 p += strlen (p) + 1;
1104 reader_table[slot].rdrname = xtrystrdup (rdrname);
1105 if (!reader_table[slot].rdrname)
1107 log_error ("error allocating memory for reader name\n");
1108 pcsc_release_context (reader_table[slot].pcsc.context);
1109 reader_table[slot].used = 0;
1116 reader_table[slot].pcsc.card = 0;
1117 reader_table[slot].atrlen = 0;
1119 reader_table[slot].connect_card = connect_pcsc_card;
1120 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1121 reader_table[slot].close_reader = close_pcsc_reader;
1122 reader_table[slot].reset_reader = reset_pcsc_reader;
1123 reader_table[slot].get_status_reader = pcsc_get_status;
1124 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1125 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1127 dump_reader_status (slot);
1133 /* Check whether the reader supports the ISO command code COMMAND
1134 on the pinpad. Return 0 on success. */
1136 check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo)
1140 if (reader_table[slot].pcsc.pinmin >= 0)
1141 pininfo->minlen = reader_table[slot].pcsc.pinmin;
1143 if (reader_table[slot].pcsc.pinmax >= 0)
1144 pininfo->maxlen = reader_table[slot].pcsc.pinmax;
1146 if (!pininfo->minlen)
1147 pininfo->minlen = 1;
1148 if (!pininfo->maxlen)
1149 pininfo->maxlen = 15;
1151 if ((command == ISO7816_VERIFY && reader_table[slot].pcsc.verify_ioctl != 0)
1152 || (command == ISO7816_CHANGE_REFERENCE_DATA
1153 && reader_table[slot].pcsc.modify_ioctl != 0))
1154 r = 0; /* Success */
1156 r = SW_NOT_SUPPORTED;
1159 log_debug ("check_pcsc_pinpad: command=%02X, r=%d\n",
1160 (unsigned int)command, r);
1162 if (reader_table[slot].pinpad_varlen_supported)
1163 pininfo->fixedlen = 0;
1168 #define PIN_VERIFY_STRUCTURE_SIZE 24
1170 pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
1174 unsigned char *pin_verify;
1175 int len = PIN_VERIFY_STRUCTURE_SIZE + pininfo->fixedlen;
1177 * The result buffer is only expected to have two-byte result on
1178 * return. However, some implementation uses this buffer for lower
1179 * layer too and it assumes that there is enough space for lower
1180 * layer communication. Such an implementation fails for TPDU
1181 * readers with "insufficient buffer", as it needs header and
1182 * trailer. Six is the number for header + result + trailer (TPDU).
1184 unsigned char result[6];
1185 pcsc_dword_t resultlen = 6;
1188 if (!reader_table[slot].atrlen
1189 && (sw = reset_pcsc_reader (slot)))
1192 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
1193 return SW_NOT_SUPPORTED;
1195 pin_verify = xtrymalloc (len);
1197 return SW_HOST_OUT_OF_CORE;
1199 no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
1201 pin_verify[0] = 0x00; /* bTimeOut */
1202 pin_verify[1] = 0x00; /* bTimeOut2 */
1203 pin_verify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
1204 pin_verify[3] = pininfo->fixedlen; /* bmPINBlockString */
1205 pin_verify[4] = 0x00; /* bmPINLengthFormat */
1206 pin_verify[5] = pininfo->maxlen; /* wPINMaxExtraDigit */
1207 pin_verify[6] = pininfo->minlen; /* wPINMaxExtraDigit */
1208 pin_verify[7] = 0x02; /* bEntryValidationCondition: Validation key pressed */
1209 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
1210 pin_verify[7] |= 0x01; /* Max size reached. */
1211 pin_verify[8] = 0x01; /* bNumberMessage: One message */
1212 pin_verify[9] = 0x09; /* wLangId: 0x0409: US English */
1213 pin_verify[10] = 0x04; /* wLangId: 0x0409: US English */
1214 pin_verify[11] = 0x00; /* bMsgIndex */
1215 pin_verify[12] = 0x00; /* bTeoPrologue[0] */
1216 pin_verify[13] = 0x00; /* bTeoPrologue[1] */
1217 pin_verify[14] = pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
1218 pin_verify[15] = pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
1219 pin_verify[16] = 0x00; /* ulDataLength */
1220 pin_verify[17] = 0x00; /* ulDataLength */
1221 pin_verify[18] = 0x00; /* ulDataLength */
1222 pin_verify[19] = class; /* abData[0] */
1223 pin_verify[20] = ins; /* abData[1] */
1224 pin_verify[21] = p0; /* abData[2] */
1225 pin_verify[22] = p1; /* abData[3] */
1226 pin_verify[23] = pininfo->fixedlen; /* abData[4] */
1227 if (pininfo->fixedlen)
1228 memset (&pin_verify[24], 0xff, pininfo->fixedlen);
1233 log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
1234 class, ins, p0, p1, len, pininfo->maxlen);
1236 sw = control_pcsc (slot, reader_table[slot].pcsc.verify_ioctl,
1237 pin_verify, len, result, &resultlen);
1239 if (sw || resultlen < 2)
1241 log_error ("control_pcsc failed: %d\n", sw);
1242 return sw? sw: SW_HOST_INCOMPLETE_CARD_RESPONSE;
1244 sw = (result[resultlen-2] << 8) | result[resultlen-1];
1246 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
1251 #define PIN_MODIFY_STRUCTURE_SIZE 29
1253 pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
1257 unsigned char *pin_modify;
1258 int len = PIN_MODIFY_STRUCTURE_SIZE + 2 * pininfo->fixedlen;
1259 unsigned char result[6]; /* See the comment at pinpad_verify. */
1260 pcsc_dword_t resultlen = 6;
1263 if (!reader_table[slot].atrlen
1264 && (sw = reset_pcsc_reader (slot)))
1267 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
1268 return SW_NOT_SUPPORTED;
1270 pin_modify = xtrymalloc (len);
1272 return SW_HOST_OUT_OF_CORE;
1274 no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
1276 pin_modify[0] = 0x00; /* bTimeOut */
1277 pin_modify[1] = 0x00; /* bTimeOut2 */
1278 pin_modify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
1279 pin_modify[3] = pininfo->fixedlen; /* bmPINBlockString */
1280 pin_modify[4] = 0x00; /* bmPINLengthFormat */
1281 pin_modify[5] = 0x00; /* bInsertionOffsetOld */
1282 pin_modify[6] = pininfo->fixedlen; /* bInsertionOffsetNew */
1283 pin_modify[7] = pininfo->maxlen; /* wPINMaxExtraDigit */
1284 pin_modify[8] = pininfo->minlen; /* wPINMaxExtraDigit */
1285 pin_modify[9] = (p0 == 0 ? 0x03 : 0x01);
1287 * 0x00: new PIN once
1288 * 0x01: new PIN twice (confirmation)
1289 * 0x02: old PIN and new PIN once
1290 * 0x03: old PIN and new PIN twice (confirmation)
1292 pin_modify[10] = 0x02; /* bEntryValidationCondition: Validation key pressed */
1293 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
1294 pin_modify[10] |= 0x01; /* Max size reached. */
1295 pin_modify[11] = 0x03; /* bNumberMessage: Three messages */
1296 pin_modify[12] = 0x09; /* wLangId: 0x0409: US English */
1297 pin_modify[13] = 0x04; /* wLangId: 0x0409: US English */
1298 pin_modify[14] = 0x00; /* bMsgIndex1 */
1299 pin_modify[15] = 0x01; /* bMsgIndex2 */
1300 pin_modify[16] = 0x02; /* bMsgIndex3 */
1301 pin_modify[17] = 0x00; /* bTeoPrologue[0] */
1302 pin_modify[18] = 0x00; /* bTeoPrologue[1] */
1303 pin_modify[19] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
1304 pin_modify[20] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
1305 pin_modify[21] = 0x00; /* ulDataLength */
1306 pin_modify[22] = 0x00; /* ulDataLength */
1307 pin_modify[23] = 0x00; /* ulDataLength */
1308 pin_modify[24] = class; /* abData[0] */
1309 pin_modify[25] = ins; /* abData[1] */
1310 pin_modify[26] = p0; /* abData[2] */
1311 pin_modify[27] = p1; /* abData[3] */
1312 pin_modify[28] = 2 * pininfo->fixedlen; /* abData[4] */
1313 if (pininfo->fixedlen)
1314 memset (&pin_modify[29], 0xff, 2 * pininfo->fixedlen);
1319 log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
1320 class, ins, p0, p1, len, (int)pininfo->maxlen);
1322 sw = control_pcsc (slot, reader_table[slot].pcsc.modify_ioctl,
1323 pin_modify, len, result, &resultlen);
1325 if (sw || resultlen < 2)
1327 log_error ("control_pcsc failed: %d\n", sw);
1328 return sw? sw : SW_HOST_INCOMPLETE_CARD_RESPONSE;
1330 sw = (result[resultlen-2] << 8) | result[resultlen-1];
1332 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
1338 Internal CCID driver interface.
1343 dump_ccid_reader_status (int slot)
1345 log_info ("reader slot %d: using ccid driver\n", slot);
1349 close_ccid_reader (int slot)
1351 ccid_close_reader (reader_table[slot].ccid.handle);
1357 reset_ccid_reader (int slot)
1360 reader_table_t slotp = reader_table + slot;
1361 unsigned char atr[33];
1364 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1367 /* If the reset was successful, update the ATR. */
1368 assert (sizeof slotp->atr >= sizeof atr);
1369 slotp->atrlen = atrlen;
1370 memcpy (slotp->atr, atr, atrlen);
1371 dump_reader_status (slot);
1377 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
1379 reader_table_t slotp = reader_table + slot;
1381 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
1386 get_status_ccid (int slot, unsigned int *status, int on_wire)
1391 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits, on_wire);
1396 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1398 *status = APDU_CARD_PRESENT;
1406 /* Actually send the APDU of length APDULEN to SLOT and return a
1407 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1408 set to BUFLEN. Returns: Internal CCID driver error code. */
1410 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1411 unsigned char *buffer, size_t *buflen,
1417 /* If we don't have an ATR, we need to reset the reader first. */
1418 if (!reader_table[slot].atrlen
1419 && (err = reset_ccid_reader (slot)))
1423 log_printhex (" raw apdu:", apdu, apdulen);
1425 maxbuflen = *buflen;
1427 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1428 apdu, apdulen, pininfo,
1429 buffer, maxbuflen, buflen);
1431 err = ccid_transceive (reader_table[slot].ccid.handle,
1433 buffer, maxbuflen, buflen);
1435 log_error ("ccid_transceive failed: (0x%lx)\n",
1442 /* Check whether the CCID reader supports the ISO command code COMMAND
1443 on the pinpad. Return 0 on success. For a description of the pin
1444 parameters, see ccid-driver.c */
1446 check_ccid_pinpad (int slot, int command, pininfo_t *pininfo)
1448 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1451 return ccid_transceive_secure (reader_table[slot].ccid.handle, apdu,
1452 sizeof apdu, pininfo, NULL, 0, NULL);
1457 ccid_pinpad_operation (int slot, int class, int ins, int p0, int p1,
1460 unsigned char apdu[4];
1462 unsigned char result[2];
1463 size_t resultlen = 2;
1469 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1470 apdu, sizeof apdu, pininfo,
1471 result, 2, &resultlen);
1476 return SW_HOST_INCOMPLETE_CARD_RESPONSE;
1478 sw = (result[resultlen-2] << 8) | result[resultlen-1];
1483 /* Open the reader and try to read an ATR. */
1485 open_ccid_reader (struct dev_list *dl)
1489 int require_get_status;
1490 reader_table_t slotp;
1492 slot = new_reader_slot ();
1495 slotp = reader_table + slot;
1497 err = ccid_open_reader (dl->portstr, dl->idx, dl->ccid_table,
1498 &slotp->ccid.handle, &slotp->rdrname);
1500 err = ccid_get_atr (slotp->ccid.handle,
1501 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1509 require_get_status = ccid_require_get_status (slotp->ccid.handle);
1511 reader_table[slot].close_reader = close_ccid_reader;
1512 reader_table[slot].reset_reader = reset_ccid_reader;
1513 reader_table[slot].get_status_reader = get_status_ccid;
1514 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1515 reader_table[slot].check_pinpad = check_ccid_pinpad;
1516 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1517 reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
1518 reader_table[slot].pinpad_verify = ccid_pinpad_operation;
1519 reader_table[slot].pinpad_modify = ccid_pinpad_operation;
1520 /* Our CCID reader code does not support T=0 at all, thus reset the
1522 reader_table[slot].is_t0 = 0;
1523 reader_table[slot].require_get_status = require_get_status;
1525 dump_reader_status (slot);
1529 #endif /* HAVE_LIBUSB */
1531 #ifdef USE_G10CODE_RAPDU
1533 The Remote APDU Interface.
1535 This uses the Remote APDU protocol to contact a reader.
1537 The port number is actually an index into the list of ports as
1538 returned via the protocol.
1543 rapdu_status_to_sw (int status)
1549 case RAPDU_STATUS_SUCCESS: rc = 0; break;
1551 case RAPDU_STATUS_INVCMD:
1552 case RAPDU_STATUS_INVPROT:
1553 case RAPDU_STATUS_INVSEQ:
1554 case RAPDU_STATUS_INVCOOKIE:
1555 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
1557 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
1558 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
1559 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
1560 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
1561 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
1562 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
1564 default: rc = SW_HOST_GENERAL_ERROR; break;
1573 close_rapdu_reader (int slot)
1575 rapdu_release (reader_table[slot].rapdu.handle);
1581 reset_rapdu_reader (int slot)
1584 reader_table_t slotp;
1585 rapdu_msg_t msg = NULL;
1587 slotp = reader_table + slot;
1589 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1592 log_error ("sending rapdu command RESET failed: %s\n",
1593 err < 0 ? strerror (errno): rapdu_strerror (err));
1594 rapdu_msg_release (msg);
1595 return rapdu_status_to_sw (err);
1597 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1600 log_error ("receiving rapdu message failed: %s\n",
1601 err < 0 ? strerror (errno): rapdu_strerror (err));
1602 rapdu_msg_release (msg);
1603 return rapdu_status_to_sw (err);
1605 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1607 int sw = rapdu_status_to_sw (msg->cmd);
1608 log_error ("rapdu command RESET failed: %s\n",
1609 rapdu_strerror (msg->cmd));
1610 rapdu_msg_release (msg);
1613 if (msg->datalen > DIM (slotp->atr))
1615 log_error ("ATR returned by the RAPDU layer is too large\n");
1616 rapdu_msg_release (msg);
1617 return SW_HOST_INV_VALUE;
1619 slotp->atrlen = msg->datalen;
1620 memcpy (slotp->atr, msg->data, msg->datalen);
1622 rapdu_msg_release (msg);
1628 my_rapdu_get_status (int slot, unsigned int *status, int on_wire)
1631 reader_table_t slotp;
1632 rapdu_msg_t msg = NULL;
1636 slotp = reader_table + slot;
1638 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
1639 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
1640 rapdu_set_reader (slotp->rapdu.handle, oldslot);
1643 log_error ("sending rapdu command GET_STATUS failed: %s\n",
1644 err < 0 ? strerror (errno): rapdu_strerror (err));
1645 return rapdu_status_to_sw (err);
1647 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1650 log_error ("receiving rapdu message failed: %s\n",
1651 err < 0 ? strerror (errno): rapdu_strerror (err));
1652 rapdu_msg_release (msg);
1653 return rapdu_status_to_sw (err);
1655 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1657 int sw = rapdu_status_to_sw (msg->cmd);
1658 log_error ("rapdu command GET_STATUS failed: %s\n",
1659 rapdu_strerror (msg->cmd));
1660 rapdu_msg_release (msg);
1663 *status = msg->data[0];
1665 rapdu_msg_release (msg);
1670 /* Actually send the APDU of length APDULEN to SLOT and return a
1671 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1672 set to BUFLEN. Returns: APDU error code. */
1674 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1675 unsigned char *buffer, size_t *buflen,
1679 reader_table_t slotp;
1680 rapdu_msg_t msg = NULL;
1681 size_t maxlen = *buflen;
1683 slotp = reader_table + slot;
1687 log_printhex (" APDU_data:", apdu, apdulen);
1691 log_error ("rapdu_send_apdu: APDU is too short\n");
1692 return SW_HOST_INV_VALUE;
1695 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
1698 log_error ("sending rapdu command APDU failed: %s\n",
1699 err < 0 ? strerror (errno): rapdu_strerror (err));
1700 rapdu_msg_release (msg);
1701 return rapdu_status_to_sw (err);
1703 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1706 log_error ("receiving rapdu message failed: %s\n",
1707 err < 0 ? strerror (errno): rapdu_strerror (err));
1708 rapdu_msg_release (msg);
1709 return rapdu_status_to_sw (err);
1711 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1713 int sw = rapdu_status_to_sw (msg->cmd);
1714 log_error ("rapdu command APDU failed: %s\n",
1715 rapdu_strerror (msg->cmd));
1716 rapdu_msg_release (msg);
1720 if (msg->datalen > maxlen)
1722 log_error ("rapdu response apdu too large\n");
1723 rapdu_msg_release (msg);
1724 return SW_HOST_INV_VALUE;
1727 *buflen = msg->datalen;
1728 memcpy (buffer, msg->data, msg->datalen);
1730 rapdu_msg_release (msg);
1735 open_rapdu_reader (int portno,
1736 const unsigned char *cookie, size_t length,
1737 int (*readfnc) (void *opaque,
1738 void *buffer, size_t size),
1739 void *readfnc_value,
1740 int (*writefnc) (void *opaque,
1741 const void *buffer, size_t size),
1742 void *writefnc_value,
1743 void (*closefnc) (void *opaque),
1744 void *closefnc_value)
1748 reader_table_t slotp;
1749 rapdu_msg_t msg = NULL;
1751 slot = new_reader_slot ();
1754 slotp = reader_table + slot;
1756 slotp->rapdu.handle = rapdu_new ();
1757 if (!slotp->rapdu.handle)
1764 rapdu_set_reader (slotp->rapdu.handle, portno);
1766 rapdu_set_iofunc (slotp->rapdu.handle,
1767 readfnc, readfnc_value,
1768 writefnc, writefnc_value,
1769 closefnc, closefnc_value);
1770 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
1772 /* First try to get the current ATR, but if the card is inactive
1773 issue a reset instead. */
1774 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
1775 if (err == RAPDU_STATUS_NEEDRESET)
1776 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
1779 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
1780 err < 0 ? strerror (errno): rapdu_strerror (err));
1783 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1786 log_info ("receiving rapdu message failed: %s\n",
1787 err < 0 ? strerror (errno): rapdu_strerror (err));
1790 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1792 log_info ("rapdu command GET ATR failed: %s\n",
1793 rapdu_strerror (msg->cmd));
1796 if (msg->datalen > DIM (slotp->atr))
1798 log_error ("ATR returned by the RAPDU layer is too large\n");
1801 slotp->atrlen = msg->datalen;
1802 memcpy (slotp->atr, msg->data, msg->datalen);
1804 reader_table[slot].close_reader = close_rapdu_reader;
1805 reader_table[slot].reset_reader = reset_rapdu_reader;
1806 reader_table[slot].get_status_reader = my_rapdu_get_status;
1807 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
1808 reader_table[slot].check_pinpad = NULL;
1809 reader_table[slot].dump_status_reader = NULL;
1810 reader_table[slot].pinpad_verify = NULL;
1811 reader_table[slot].pinpad_modify = NULL;
1813 dump_reader_status (slot);
1814 rapdu_msg_release (msg);
1819 rapdu_msg_release (msg);
1820 rapdu_release (slotp->rapdu.handle);
1826 #endif /*USE_G10CODE_RAPDU*/
1834 apdu_dev_list_start (const char *portstr, struct dev_list **l_p)
1836 struct dev_list *dl = xtrymalloc (sizeof (struct dev_list));
1840 return gpg_error_from_syserror ();
1842 dl->portstr = portstr;
1845 npth_mutex_lock (&reader_table_lock);
1848 if (opt.disable_ccid)
1850 dl->ccid_table = NULL;
1857 err = ccid_dev_scan (&dl->idx_max, &dl->ccid_table);
1861 if (dl->idx_max == 0)
1863 /* If a CCID reader specification has been given, the user does
1864 not want a fallback to other drivers. */
1865 if (portstr && strlen (portstr) > 5 && portstr[4] == ':')
1868 log_debug ("leave: apdu_open_reader => slot=-1 (no ccid)\n");
1871 npth_mutex_unlock (&reader_table_lock);
1872 return gpg_error (GPG_ERR_ENODEV);
1879 dl->ccid_table = NULL;
1881 #endif /* HAVE_LIBUSB */
1888 apdu_dev_list_finish (struct dev_list *dl)
1892 ccid_dev_scan_finish (dl->ccid_table, dl->idx_max);
1895 npth_mutex_unlock (&reader_table_lock);
1899 /* Open the reader and return an internal slot number or -1 on
1900 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
1901 the first USB reader. For PC/SC the first listed reader). */
1903 apdu_open_one_reader (const char *portstr)
1905 static int pcsc_api_loaded;
1909 log_debug ("enter: apdu_open_reader: portstr=%s\n", portstr);
1911 /* Lets try the PC/SC API */
1912 if (!pcsc_api_loaded)
1916 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
1919 log_error ("apdu_open_reader: failed to open driver '%s': %s\n",
1920 opt.pcsc_driver, dlerror ());
1924 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
1925 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
1926 pcsc_list_readers = dlsym (handle, "SCardListReaders");
1927 #if defined(_WIN32) || defined(__CYGWIN__)
1928 if (!pcsc_list_readers)
1929 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
1931 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
1932 #if defined(_WIN32) || defined(__CYGWIN__)
1933 if (!pcsc_get_status_change)
1934 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
1936 pcsc_connect = dlsym (handle, "SCardConnect");
1937 #if defined(_WIN32) || defined(__CYGWIN__)
1939 pcsc_connect = dlsym (handle, "SCardConnectA");
1941 pcsc_reconnect = dlsym (handle, "SCardReconnect");
1942 #if defined(_WIN32) || defined(__CYGWIN__)
1943 if (!pcsc_reconnect)
1944 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
1946 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
1947 pcsc_status = dlsym (handle, "SCardStatus");
1948 #if defined(_WIN32) || defined(__CYGWIN__)
1950 pcsc_status = dlsym (handle, "SCardStatusA");
1952 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
1953 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
1954 pcsc_transmit = dlsym (handle, "SCardTransmit");
1955 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
1956 pcsc_control = dlsym (handle, "SCardControl");
1958 if (!pcsc_establish_context
1959 || !pcsc_release_context
1960 || !pcsc_list_readers
1961 || !pcsc_get_status_change
1966 || !pcsc_begin_transaction
1967 || !pcsc_end_transaction
1970 /* || !pcsc_set_timeout */)
1972 /* Note that set_timeout is currently not used and also not
1973 available under Windows. */
1974 log_error ("apdu_open_reader: invalid PC/SC driver "
1975 "(%d%d%d%d%d%d%d%d%d%d%d%d%d)\n",
1976 !!pcsc_establish_context,
1977 !!pcsc_release_context,
1978 !!pcsc_list_readers,
1979 !!pcsc_get_status_change,
1984 !!pcsc_begin_transaction,
1985 !!pcsc_end_transaction,
1992 pcsc_api_loaded = 1;
1995 slot = open_pcsc_reader (portstr);
1998 log_debug ("leave: apdu_open_reader => slot=%d [pc/sc]\n", slot);
2003 apdu_open_reader (struct dev_list *dl, int app_empty)
2009 { /* CCID readers. */
2012 /* See whether we want to use the reader ID string or a reader
2013 number. A readerno of -1 indicates that the reader ID string is
2015 if (dl->portstr && strchr (dl->portstr, ':'))
2016 readerno = -1; /* We want to use the readerid. */
2017 else if (dl->portstr)
2019 readerno = atoi (dl->portstr);
2026 readerno = 0; /* Default. */
2029 { /* Use single, the specific reader. */
2030 if (readerno >= dl->idx_max)
2035 slot = open_ccid_reader (dl);
2036 dl->idx = dl->idx_max;
2043 while (dl->idx < dl->idx_max)
2045 unsigned int bai = ccid_get_BAI (dl->idx, dl->ccid_table);
2048 log_debug ("apdu_open_reader: BAI=%x\n", bai);
2050 /* Check identity by BAI against already opened HANDLEs. */
2051 for (slot = 0; slot < MAX_READER; slot++)
2052 if (reader_table[slot].used
2053 && reader_table[slot].ccid.handle
2054 && ccid_compare_BAI (reader_table[slot].ccid.handle, bai))
2057 if (slot == MAX_READER)
2058 { /* Found a new device. */
2060 log_debug ("apdu_open_reader: new device=%x\n", bai);
2062 slot = open_ccid_reader (dl);
2069 /* Skip this reader. */
2070 log_error ("ccid open error: skip\n");
2078 /* Not found. Try one for PC/SC, only when it's the initial scan. */
2079 if (app_empty && dl->idx == dl->idx_max)
2082 slot = apdu_open_one_reader (dl->portstr);
2089 { /* PC/SC readers. */
2090 if (app_empty && dl->idx == 0)
2093 slot = apdu_open_one_reader (dl->portstr);
2103 /* Open an remote reader and return an internal slot number or -1 on
2104 error. This function is an alternative to apdu_open_reader and used
2105 with remote readers only. Note that the supplied CLOSEFNC will
2106 only be called once and the slot will not be valid afther this.
2108 If PORTSTR is NULL we default to the first available port.
2111 apdu_open_remote_reader (const char *portstr,
2112 const unsigned char *cookie, size_t length,
2113 int (*readfnc) (void *opaque,
2114 void *buffer, size_t size),
2115 void *readfnc_value,
2116 int (*writefnc) (void *opaque,
2117 const void *buffer, size_t size),
2118 void *writefnc_value,
2119 void (*closefnc) (void *opaque),
2120 void *closefnc_value)
2122 #ifdef USE_G10CODE_RAPDU
2123 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2125 readfnc, readfnc_value,
2126 writefnc, writefnc_value,
2127 closefnc, closefnc_value);
2133 (void)readfnc_value;
2135 (void)writefnc_value;
2137 (void)closefnc_value;
2149 apdu_close_reader (int slot)
2154 log_debug ("enter: apdu_close_reader: slot=%d\n", slot);
2156 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2159 log_debug ("leave: apdu_close_reader => SW_HOST_NO_DRIVER\n");
2160 return SW_HOST_NO_DRIVER;
2162 sw = apdu_disconnect (slot);
2166 * When the reader/token was removed it might come here.
2167 * It should go through to call CLOSE_READER even if we got an error.
2170 log_debug ("apdu_close_reader => 0x%x (apdu_disconnect)\n", sw);
2172 if (reader_table[slot].close_reader)
2174 sw = reader_table[slot].close_reader (slot);
2175 reader_table[slot].used = 0;
2177 log_debug ("leave: apdu_close_reader => 0x%x (close_reader)\n", sw);
2180 xfree (reader_table[slot].rdrname);
2181 reader_table[slot].rdrname = NULL;
2182 reader_table[slot].used = 0;
2184 log_debug ("leave: apdu_close_reader => SW_HOST_NOT_SUPPORTED\n");
2185 return SW_HOST_NOT_SUPPORTED;
2189 /* Function suitable for a cleanup function to close all reader. It
2190 should not be used if the reader will be opened again. The reason
2191 for implementing this to properly close USB devices so that they
2192 will startup the next time without error. */
2194 apdu_prepare_exit (void)
2196 static int sentinel;
2202 npth_mutex_lock (&reader_table_lock);
2203 for (slot = 0; slot < MAX_READER; slot++)
2204 if (reader_table[slot].used)
2206 apdu_disconnect (slot);
2207 if (reader_table[slot].close_reader)
2208 reader_table[slot].close_reader (slot);
2209 xfree (reader_table[slot].rdrname);
2210 reader_table[slot].rdrname = NULL;
2211 reader_table[slot].used = 0;
2213 npth_mutex_unlock (&reader_table_lock);
2219 /* Enumerate all readers and return information on whether this reader
2220 is in use. The caller should start with SLOT set to 0 and
2221 increment it with each call until an error is returned. */
2223 apdu_enum_reader (int slot, int *used)
2225 if (slot < 0 || slot >= MAX_READER)
2226 return SW_HOST_NO_DRIVER;
2227 *used = reader_table[slot].used;
2232 /* Connect a card. This is used to power up the card and make sure
2233 that an ATR is available. Depending on the reader backend it may
2234 return an error for an inactive card or if no card is available.
2235 Return -1 on error. Return 1 if reader requires get_status to
2236 watch card removal. Return 0 if it's a token (always with a card),
2237 or it supports INTERRUPT endpoint to watch card removal.
2240 apdu_connect (int slot)
2243 unsigned int status = 0;
2246 log_debug ("enter: apdu_connect: slot=%d\n", slot);
2248 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2251 log_debug ("leave: apdu_connect => SW_HOST_NO_DRIVER\n");
2255 /* Only if the access method provides a connect function we use it.
2256 If not, we expect that the card has been implicitly connected by
2257 apdu_open_reader. */
2258 if (reader_table[slot].connect_card)
2260 sw = lock_slot (slot);
2263 sw = reader_table[slot].connect_card (slot);
2268 /* We need to call apdu_get_status_internal, so that the last-status
2269 machinery gets setup properly even if a card is inserted while
2270 scdaemon is fired up and apdu_get_status has not yet been called.
2271 Without that we would force a reset of the card with the next
2272 call to apdu_get_status. */
2274 sw = apdu_get_status_internal (slot, 1, &status, 1);
2278 else if (!(status & APDU_CARD_PRESENT))
2279 sw = SW_HOST_NO_CARD;
2280 else if ((status & APDU_CARD_PRESENT) && !(status & APDU_CARD_ACTIVE))
2281 sw = SW_HOST_CARD_INACTIVE;
2283 if (sw == SW_HOST_CARD_INACTIVE)
2285 /* Try power it up again. */
2286 sw = apdu_reset (slot);
2290 log_debug ("leave: apdu_connect => sw=0x%x\n", sw);
2295 return reader_table[slot].require_get_status;
2300 apdu_disconnect (int slot)
2305 log_debug ("enter: apdu_disconnect: slot=%d\n", slot);
2307 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2310 log_debug ("leave: apdu_disconnect => SW_HOST_NO_DRIVER\n");
2311 return SW_HOST_NO_DRIVER;
2314 if (reader_table[slot].disconnect_card)
2316 sw = lock_slot (slot);
2319 sw = reader_table[slot].disconnect_card (slot);
2327 log_debug ("leave: apdu_disconnect => sw=0x%x\n", sw);
2332 /* Set the progress callback of SLOT to CB and its args to CB_ARG. If
2333 CB is NULL the progress callback is removed. */
2335 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
2339 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2340 return SW_HOST_NO_DRIVER;
2342 if (reader_table[slot].set_progress_cb)
2344 sw = lock_slot (slot);
2347 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
2357 /* Do a reset for the card in reader at SLOT. */
2359 apdu_reset (int slot)
2364 log_debug ("enter: apdu_reset: slot=%d\n", slot);
2366 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2369 log_debug ("leave: apdu_reset => SW_HOST_NO_DRIVER\n");
2370 return SW_HOST_NO_DRIVER;
2373 if ((sw = lock_slot (slot)))
2376 log_debug ("leave: apdu_reset => sw=0x%x (lock_slot)\n", sw);
2380 if (reader_table[slot].reset_reader)
2381 sw = reader_table[slot].reset_reader (slot);
2385 log_debug ("leave: apdu_reset => sw=0x%x\n", sw);
2390 /* Return the ATR or NULL if none is available. On success the length
2391 of the ATR is stored at ATRLEN. The caller must free the returned
2394 apdu_get_atr (int slot, size_t *atrlen)
2399 log_debug ("enter: apdu_get_atr: slot=%d\n", slot);
2401 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2404 log_debug ("leave: apdu_get_atr => NULL (bad slot)\n");
2407 if (!reader_table[slot].atrlen)
2410 log_debug ("leave: apdu_get_atr => NULL (no ATR)\n");
2414 buf = xtrymalloc (reader_table[slot].atrlen);
2418 log_debug ("leave: apdu_get_atr => NULL (out of core)\n");
2421 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2422 *atrlen = reader_table[slot].atrlen;
2424 log_debug ("leave: apdu_get_atr => atrlen=%zu\n", *atrlen);
2430 /* Retrieve the status for SLOT. The function does only wait for the
2431 card to become available if HANG is set to true. On success the
2432 bits in STATUS will be set to
2434 APDU_CARD_USABLE (bit 0) = card present and usable
2435 APDU_CARD_PRESENT (bit 1) = card present
2436 APDU_CARD_ACTIVE (bit 2) = card active
2437 (bit 3) = card access locked [not yet implemented]
2439 For most applications, testing bit 0 is sufficient.
2442 apdu_get_status_internal (int slot, int hang, unsigned int *status, int on_wire)
2447 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2448 return SW_HOST_NO_DRIVER;
2450 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2453 if (reader_table[slot].get_status_reader)
2454 sw = reader_table[slot].get_status_reader (slot, &s, on_wire);
2461 reader_table[slot].atrlen = 0;
2471 /* See above for a description. */
2473 apdu_get_status (int slot, int hang, unsigned int *status)
2478 log_debug ("enter: apdu_get_status: slot=%d hang=%d\n", slot, hang);
2479 sw = apdu_get_status_internal (slot, hang, status, 0);
2483 log_debug ("leave: apdu_get_status => sw=0x%x status=%u\n",
2486 log_debug ("leave: apdu_get_status => sw=0x%x\n", sw);
2492 /* Check whether the reader supports the ISO command code COMMAND on
2493 the pinpad. Return 0 on success. For a description of the pin
2494 parameters, see ccid-driver.c */
2496 apdu_check_pinpad (int slot, int command, pininfo_t *pininfo)
2498 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2499 return SW_HOST_NO_DRIVER;
2501 if (opt.enable_pinpad_varlen)
2502 pininfo->fixedlen = 0;
2504 if (reader_table[slot].check_pinpad)
2508 if ((sw = lock_slot (slot)))
2511 sw = reader_table[slot].check_pinpad (slot, command, pininfo);
2516 return SW_HOST_NOT_SUPPORTED;
2521 apdu_pinpad_verify (int slot, int class, int ins, int p0, int p1,
2524 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2525 return SW_HOST_NO_DRIVER;
2527 if (reader_table[slot].pinpad_verify)
2531 if ((sw = lock_slot (slot)))
2534 sw = reader_table[slot].pinpad_verify (slot, class, ins, p0, p1,
2540 return SW_HOST_NOT_SUPPORTED;
2545 apdu_pinpad_modify (int slot, int class, int ins, int p0, int p1,
2548 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2549 return SW_HOST_NO_DRIVER;
2551 if (reader_table[slot].pinpad_modify)
2555 if ((sw = lock_slot (slot)))
2558 sw = reader_table[slot].pinpad_modify (slot, class, ins, p0, p1,
2564 return SW_HOST_NOT_SUPPORTED;
2568 /* Dispatcher for the actual send_apdu function. Note, that this
2569 function should be called in locked state. */
2571 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2572 unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
2574 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2575 return SW_HOST_NO_DRIVER;
2577 if (reader_table[slot].send_apdu_reader)
2578 return reader_table[slot].send_apdu_reader (slot,
2583 return SW_HOST_NOT_SUPPORTED;
2587 /* Core APDU tranceiver function. Parameters are described at
2588 apdu_send_le with the exception of PININFO which indicates pinpad
2589 related operations if not NULL. If EXTENDED_MODE is not 0
2590 command chaining or extended length will be used according to these
2592 n < 0 := Use command chaining with the data part limited to -n
2593 in each chunk. If -1 is used a default value is used.
2594 n == 0 := No extended mode or command chaining.
2595 n == 1 := Use extended length for input and output without a
2597 n > 1 := Use extended length with up to N bytes.
2601 send_le (int slot, int class, int ins, int p0, int p1,
2602 int lc, const char *data, int le,
2603 unsigned char **retbuf, size_t *retbuflen,
2604 pininfo_t *pininfo, int extended_mode)
2606 #define SHORT_RESULT_BUFFER_SIZE 258
2607 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
2608 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
2609 unsigned char *result_buffer = NULL;
2610 size_t result_buffer_size;
2611 unsigned char *result;
2613 unsigned char short_apdu_buffer[5+256+1];
2614 unsigned char *apdu_buffer = NULL;
2615 size_t apdu_buffer_size;
2616 unsigned char *apdu;
2619 long rc; /* We need a long here due to PC/SC. */
2620 int did_exact_length_hack = 0;
2621 int use_chaining = 0;
2622 int use_extended_length = 0;
2625 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2626 return SW_HOST_NO_DRIVER;
2629 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
2630 class, ins, p0, p1, lc, le, extended_mode);
2632 if (lc != -1 && (lc > 255 || lc < 0))
2634 /* Data does not fit into an APDU. What we do now depends on
2635 the EXTENDED_MODE parameter. */
2637 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2638 else if (extended_mode > 0)
2639 use_extended_length = 1;
2640 else if (extended_mode < 0)
2642 /* Send APDU using chaining mode. */
2644 return SW_WRONG_LENGTH; /* Sanity check. */
2645 if ((class&0xf0) != 0)
2646 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
2647 use_chaining = extended_mode == -1? 255 : -extended_mode;
2648 use_chaining &= 0xff;
2651 return SW_HOST_INV_VALUE;
2653 else if (lc == -1 && extended_mode > 0)
2654 use_extended_length = 1;
2656 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
2658 /* Expected Data does not fit into an APDU. What we do now
2659 depends on the EXTENDED_MODE parameter. Note that a check
2660 for command chaining does not make sense because we are
2663 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2664 else if (use_extended_length)
2665 ; /* We are already using extended length. */
2666 else if (extended_mode > 0)
2667 use_extended_length = 1;
2669 return SW_HOST_INV_VALUE;
2672 if ((!data && lc != -1) || (data && lc == -1))
2673 return SW_HOST_INV_VALUE;
2675 if (use_extended_length)
2677 if (reader_table[slot].is_t0)
2678 return SW_HOST_NOT_SUPPORTED;
2680 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
2681 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2682 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
2684 return SW_HOST_OUT_OF_CORE;
2689 apdu_buffer_size = sizeof short_apdu_buffer;
2690 apdu = short_apdu_buffer;
2693 if (use_extended_length && (le > 256 || le < 0))
2695 /* Two more bytes are needed for status bytes. */
2696 result_buffer_size = le < 0? 4096 : (le + 2);
2697 result_buffer = xtrymalloc (result_buffer_size);
2700 xfree (apdu_buffer);
2701 return SW_HOST_OUT_OF_CORE;
2703 result = result_buffer;
2707 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2708 result = short_result_buffer;
2710 #undef SHORT_RESULT_BUFFER_SIZE
2712 if ((sw = lock_slot (slot)))
2714 xfree (apdu_buffer);
2715 xfree (result_buffer);
2721 if (use_extended_length)
2725 apdu[apdulen++] = class;
2726 apdu[apdulen++] = ins;
2727 apdu[apdulen++] = p0;
2728 apdu[apdulen++] = p1;
2731 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
2732 apdu[apdulen++] = ((lc >> 8) & 0xff);
2733 apdu[apdulen++] = (lc & 0xff);
2734 memcpy (apdu+apdulen, data, lc);
2741 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
2742 apdu[apdulen++] = ((le >> 8) & 0xff);
2743 apdu[apdulen++] = (le & 0xff);
2749 apdu[apdulen] = class;
2750 if (use_chaining && lc > 255)
2752 apdu[apdulen] |= 0x10;
2753 assert (use_chaining < 256);
2754 lc_chunk = use_chaining;
2763 apdu[apdulen++] = ins;
2764 apdu[apdulen++] = p0;
2765 apdu[apdulen++] = p1;
2768 apdu[apdulen++] = lc_chunk;
2769 memcpy (apdu+apdulen, data, lc_chunk);
2771 apdulen += lc_chunk;
2772 /* T=0 does not allow the use of Lc together with Le;
2773 thus disable Le in this case. */
2774 if (reader_table[slot].is_t0)
2777 if (le != -1 && !use_chaining)
2778 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
2782 /* As a safeguard don't pass any garbage to the driver. */
2783 assert (apdulen <= apdu_buffer_size);
2784 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
2785 resultlen = result_buffer_size;
2786 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
2787 if (rc || resultlen < 2)
2789 log_info ("apdu_send_simple(%d) failed: %s\n",
2790 slot, apdu_strerror (rc));
2792 xfree (apdu_buffer);
2793 xfree (result_buffer);
2794 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2796 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2797 if (!use_extended_length
2798 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
2800 apdu[apdulen-1] = (sw & 0x00ff);
2801 did_exact_length_hack = 1;
2802 goto exact_length_hack;
2805 while (use_chaining && sw == SW_SUCCESS);
2809 xfree (apdu_buffer);
2813 /* Store away the returned data but strip the statusword. */
2817 log_debug (" response: sw=%04X datalen=%d\n",
2818 sw, (unsigned int)resultlen);
2819 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
2820 log_printhex (" dump: ", result, resultlen);
2823 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2827 *retbuf = xtrymalloc (resultlen? resultlen : 1);
2831 xfree (result_buffer);
2832 return SW_HOST_OUT_OF_CORE;
2834 *retbuflen = resultlen;
2835 memcpy (*retbuf, result, resultlen);
2838 else if ((sw & 0xff00) == SW_MORE_DATA)
2840 unsigned char *p = NULL, *tmp;
2841 size_t bufsize = 4096;
2843 /* It is likely that we need to return much more data, so we
2844 start off with a large buffer. */
2847 *retbuf = p = xtrymalloc (bufsize);
2851 xfree (result_buffer);
2852 return SW_HOST_OUT_OF_CORE;
2854 assert (resultlen < bufsize);
2855 memcpy (p, result, resultlen);
2861 int len = (sw & 0x00ff);
2864 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
2866 apdu_buffer_size = sizeof short_apdu_buffer;
2867 apdu = short_apdu_buffer;
2869 apdu[apdulen++] = class;
2870 apdu[apdulen++] = 0xC0;
2871 apdu[apdulen++] = 0;
2872 apdu[apdulen++] = 0;
2873 apdu[apdulen++] = len;
2874 assert (apdulen <= apdu_buffer_size);
2875 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
2876 resultlen = result_buffer_size;
2877 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
2878 if (rc || resultlen < 2)
2880 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
2881 slot, apdu_strerror (rc));
2883 xfree (result_buffer);
2884 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2886 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2890 log_debug (" more: sw=%04X datalen=%d\n",
2891 sw, (unsigned int)resultlen);
2892 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
2893 log_printhex (" dump: ", result, resultlen);
2896 if ((sw & 0xff00) == SW_MORE_DATA
2898 || sw == SW_EOF_REACHED )
2900 if (retbuf && resultlen)
2902 if (p - *retbuf + resultlen > bufsize)
2904 bufsize += resultlen > 4096? resultlen: 4096;
2905 tmp = xtryrealloc (*retbuf, bufsize);
2909 xfree (result_buffer);
2910 return SW_HOST_OUT_OF_CORE;
2912 p = tmp + (p - *retbuf);
2915 memcpy (p, result, resultlen);
2920 log_info ("apdu_send_simple(%d) "
2921 "got unexpected status %04X from get response\n",
2924 while ((sw & 0xff00) == SW_MORE_DATA);
2928 *retbuflen = p - *retbuf;
2929 tmp = xtryrealloc (*retbuf, *retbuflen);
2936 xfree (result_buffer);
2938 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
2939 log_printhex (" dump: ", *retbuf, *retbuflen);
2944 /* Send an APDU to the card in SLOT. The APDU is created from all
2945 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
2946 for LC won't sent this field and the data field; in this case DATA
2947 must also be passed as NULL. If EXTENDED_MODE is not 0 command
2948 chaining or extended length will be used; see send_le for details.
2949 The return value is the status word or -1 for an invalid SLOT or
2950 other non card related error. If RETBUF is not NULL, it will
2951 receive an allocated buffer with the returned data. The length of
2952 that data will be put into *RETBUFLEN. The caller is responsible
2953 for releasing the buffer even in case of errors. */
2955 apdu_send_le(int slot, int extended_mode,
2956 int class, int ins, int p0, int p1,
2957 int lc, const char *data, int le,
2958 unsigned char **retbuf, size_t *retbuflen)
2960 return send_le (slot, class, ins, p0, p1,
2963 NULL, extended_mode);
2967 /* Send an APDU to the card in SLOT. The APDU is created from all
2968 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2969 LC won't sent this field and the data field; in this case DATA must
2970 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
2971 or extended length will be used; see send_le for details. The
2972 return value is the status word or -1 for an invalid SLOT or other
2973 non card related error. If RETBUF is not NULL, it will receive an
2974 allocated buffer with the returned data. The length of that data
2975 will be put into *RETBUFLEN. The caller is responsible for
2976 releasing the buffer even in case of errors. */
2978 apdu_send (int slot, int extended_mode,
2979 int class, int ins, int p0, int p1,
2980 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
2982 return send_le (slot, class, ins, p0, p1, lc, data, 256,
2983 retbuf, retbuflen, NULL, extended_mode);
2986 /* Send an APDU to the card in SLOT. The APDU is created from all
2987 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
2988 LC won't sent this field and the data field; in this case DATA must
2989 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
2990 or extended length will be used; see send_le for details. The
2991 return value is the status word or -1 for an invalid SLOT or other
2992 non card related error. No data will be returned. */
2994 apdu_send_simple (int slot, int extended_mode,
2995 int class, int ins, int p0, int p1,
2996 int lc, const char *data)
2998 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
3003 /* This is a more generic version of the apdu sending routine. It
3004 takes an already formatted APDU in APDUDATA or length APDUDATALEN
3005 and returns with an APDU including the status word. With
3006 HANDLE_MORE set to true this function will handle the MORE DATA
3007 status and return all APDUs concatenated with one status word at
3008 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
3009 with a max. result data length of EXTENDED_LENGTH bytes. The
3010 function does not return a regular status word but 0 on success.
3011 If the slot is locked, the function returns immediately with an
3014 apdu_send_direct (int slot, size_t extended_length,
3015 const unsigned char *apdudata, size_t apdudatalen,
3017 unsigned char **retbuf, size_t *retbuflen)
3019 #define SHORT_RESULT_BUFFER_SIZE 258
3020 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3021 unsigned char *result_buffer = NULL;
3022 size_t result_buffer_size;
3023 unsigned char *result;
3025 unsigned char short_apdu_buffer[5+256+10];
3026 unsigned char *apdu_buffer = NULL;
3027 unsigned char *apdu;
3030 long rc; /* we need a long here due to PC/SC. */
3033 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3034 return SW_HOST_NO_DRIVER;
3036 if (apdudatalen > 65535)
3037 return SW_HOST_INV_VALUE;
3039 if (apdudatalen > sizeof short_apdu_buffer - 5)
3041 apdu_buffer = xtrymalloc (apdudatalen + 5);
3043 return SW_HOST_OUT_OF_CORE;
3048 apdu = short_apdu_buffer;
3050 apdulen = apdudatalen;
3051 memcpy (apdu, apdudata, apdudatalen);
3052 class = apdulen? *apdu : 0;
3054 if (extended_length >= 256 && extended_length <= 65536)
3056 result_buffer_size = extended_length;
3057 result_buffer = xtrymalloc (result_buffer_size + 10);
3060 xfree (apdu_buffer);
3061 return SW_HOST_OUT_OF_CORE;
3063 result = result_buffer;
3067 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3068 result = short_result_buffer;
3070 #undef SHORT_RESULT_BUFFER_SIZE
3072 if ((sw = trylock_slot (slot)))
3074 xfree (apdu_buffer);
3075 xfree (result_buffer);
3079 resultlen = result_buffer_size;
3080 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3081 xfree (apdu_buffer);
3083 if (rc || resultlen < 2)
3085 log_error ("apdu_send_direct(%d) failed: %s\n",
3086 slot, apdu_strerror (rc));
3088 xfree (result_buffer);
3089 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3091 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3092 /* Store away the returned data but strip the statusword. */
3096 log_debug (" response: sw=%04X datalen=%d\n",
3097 sw, (unsigned int)resultlen);
3098 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3099 log_printhex (" dump: ", result, resultlen);
3102 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3104 unsigned char *p = NULL, *tmp;
3105 size_t bufsize = 4096;
3107 /* It is likely that we need to return much more data, so we
3108 start off with a large buffer. */
3111 *retbuf = p = xtrymalloc (bufsize + 2);
3115 xfree (result_buffer);
3116 return SW_HOST_OUT_OF_CORE;
3118 assert (resultlen < bufsize);
3119 memcpy (p, result, resultlen);
3125 int len = (sw & 0x00ff);
3128 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3130 apdu = short_apdu_buffer;
3132 apdu[apdulen++] = class;
3133 apdu[apdulen++] = 0xC0;
3134 apdu[apdulen++] = 0;
3135 apdu[apdulen++] = 0;
3136 apdu[apdulen++] = len;
3137 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
3138 resultlen = result_buffer_size;
3139 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3140 if (rc || resultlen < 2)
3142 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3143 slot, apdu_strerror (rc));
3145 xfree (result_buffer);
3146 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3148 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3152 log_debug (" more: sw=%04X datalen=%d\n",
3153 sw, (unsigned int)resultlen);
3154 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3155 log_printhex (" dump: ", result, resultlen);
3158 if ((sw & 0xff00) == SW_MORE_DATA
3160 || sw == SW_EOF_REACHED )
3162 if (retbuf && resultlen)
3164 if (p - *retbuf + resultlen > bufsize)
3166 bufsize += resultlen > 4096? resultlen: 4096;
3167 tmp = xtryrealloc (*retbuf, bufsize + 2);
3171 xfree (result_buffer);
3172 return SW_HOST_OUT_OF_CORE;
3174 p = tmp + (p - *retbuf);
3177 memcpy (p, result, resultlen);
3182 log_info ("apdu_send_direct(%d) "
3183 "got unexpected status %04X from get response\n",
3186 while ((sw & 0xff00) == SW_MORE_DATA);
3190 *retbuflen = p - *retbuf;
3191 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3200 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3204 xfree (result_buffer);
3205 return SW_HOST_OUT_OF_CORE;
3207 *retbuflen = resultlen;
3208 memcpy (*retbuf, result, resultlen);
3213 xfree (result_buffer);
3215 /* Append the status word. Note that we reserved the two extra
3216 bytes while allocating the buffer. */
3219 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3220 (*retbuf)[(*retbuflen)++] = sw;
3223 if (DBG_CARD_IO && retbuf)
3224 log_printhex (" dump: ", *retbuf, *retbuflen);
3231 apdu_get_reader_name (int slot)
3233 return reader_table[slot].rdrname;
3243 if (npth_mutex_init (&reader_table_lock, NULL))
3246 for (i = 0; i < MAX_READER; i++)
3247 if (npth_mutex_init (&reader_table[i].lock, NULL))
3250 /* All done well. */
3254 err = gpg_error_from_syserror ();
3255 log_error ("apdu: error initializing mutex: %s\n", gpg_strerror (err));