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. */
38 /* If requested include the definitions for the remote APDU protocol
40 #ifdef USE_G10CODE_RAPDU
42 #endif /*USE_G10CODE_RAPDU*/
44 #if defined(GNUPG_MAJOR_VERSION)
45 # include "scdaemon.h"
46 # include "../common/exechelp.h"
47 #endif /*GNUPG_MAJOR_VERSION*/
49 #include "../common/host2net.h"
53 #define CCID_DRIVER_INCLUDE_USB_IDS 1
54 #include "ccid-driver.h"
63 #define MAX_READER 16 /* Number of readers we support concurrently. */
64 /* See also MAX_DEVICE in ccid-driver.c. */
67 #if defined(_WIN32) || defined(__CYGWIN__)
68 #define DLSTDCALL __stdcall
73 #if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
74 typedef unsigned int pcsc_dword_t;
76 typedef unsigned long pcsc_dword_t;
79 #ifdef HAVE_W32_SYSTEM
80 #define HANDLE uintptr_t
85 /* PC/SC context to access readers. Shared among all readers. */
86 static struct pcsc_global_data {
89 const char *rdrname[MAX_READER];
92 /* A structure to collect information pertaining to one reader
94 struct reader_table_s {
95 int used; /* True if slot is used. */
96 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
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 *);
114 ccid_driver_t handle;
118 pcsc_dword_t protocol;
119 pcsc_dword_t verify_ioctl;
120 pcsc_dword_t modify_ioctl;
123 pcsc_dword_t current_state;
125 #ifdef USE_G10CODE_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
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
144 typedef struct reader_table_s *reader_table_t;
146 /* A global table to keep track of active readers. */
147 static struct reader_table_s reader_table[MAX_READER];
150 static npth_mutex_t reader_table_lock;
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
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. */
165 # define PCSC_PROTOCOL_RAW 4
168 #define PCSC_SHARE_EXCLUSIVE 1
169 #define PCSC_SHARE_SHARED 2
170 #define PCSC_SHARE_DIRECT 3
172 #define PCSC_LEAVE_CARD 0
173 #define PCSC_RESET_CARD 1
174 #define PCSC_UNPOWER_CARD 2
175 #define PCSC_EJECT_CARD 3
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. */
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. */
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. */
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
236 /* Fix pcsc-lite ABI incompatibility. */
237 #ifndef SCARD_CTL_CODE
239 #include <winioctl.h>
240 #define SCARD_CTL_CODE(code) CTL_CODE(FILE_DEVICE_SMARTCARD, (code), \
241 METHOD_BUFFERED, FILE_ANY_ACCESS)
243 #define SCARD_CTL_CODE(code) (0x42000000 + (code))
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
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
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
264 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
267 struct pcsc_io_request_s
269 #if defined(_WIN32) || defined(__CYGWIN__)
270 pcsc_dword_t protocol;
271 pcsc_dword_t pci_len;
273 unsigned long protocol;
274 unsigned long pci_len;
278 typedef struct pcsc_io_request_s *pcsc_io_request_t;
284 struct pcsc_readerstate_s
288 pcsc_dword_t current_state;
289 pcsc_dword_t event_state;
291 unsigned char atr[33];
298 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
300 long (* DLSTDCALL pcsc_establish_context) (pcsc_dword_t scope,
301 const void *reserved1,
302 const void *reserved2,
304 long (* DLSTDCALL pcsc_release_context) (HANDLE context);
305 long (* DLSTDCALL pcsc_list_readers) (HANDLE context,
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,
314 pcsc_dword_t share_mode,
315 pcsc_dword_t preferred_protocols,
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,
347 pcsc_dword_t recv_len,
348 pcsc_dword_t *bytes_returned);
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,
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,
360 static int pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
369 /* Return true if (BUFFER,LENGTH) consists of only binary zeroes. */
371 all_zero_p (const void *buffer, size_t length)
373 const unsigned char *p;
375 for (p=buffer; length; p++, length--)
389 err = npth_mutex_lock (&reader_table[slot].lock);
392 log_error ("failed to acquire apdu lock: %s\n", strerror (err));
393 return SW_HOST_LOCKING_FAILED;
400 trylock_slot (int slot)
405 err = npth_mutex_trylock (&reader_table[slot].lock);
410 log_error ("failed to acquire apdu lock: %s\n", strerror (err));
411 return SW_HOST_LOCKING_FAILED;
418 unlock_slot (int slot)
423 err = npth_mutex_unlock (&reader_table[slot].lock);
425 log_error ("failed to release apdu lock: %s\n", strerror (errno));
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. */
434 new_reader_slot (void)
438 for (i=0; i < MAX_READER; i++)
439 if (!reader_table[i].used)
442 reader_table[reader].used = 1;
448 log_error ("new_reader_slot: out of slots\n");
452 if (lock_slot (reader))
454 reader_table[reader].used = 0;
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;
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;
485 dump_reader_status (int slot)
490 if (reader_table[slot].dump_status_reader)
491 reader_table[slot].dump_status_reader (slot);
493 if (reader_table[slot].atrlen)
495 log_info ("slot %d: ATR=", slot);
496 log_printhex (reader_table[slot].atr, reader_table[slot].atrlen, "");
503 host_sw_string (long err)
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";
536 apdu_strerror (int rc)
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";
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";
581 pcsc_error_string (long err)
587 if ((err & 0x80100000) != 0x80100000)
588 return "invalid PC/SC error code";
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;
633 /* Map PC/SC error codes to our special host status words. */
635 pcsc_error_to_sw (long ec)
639 switch ( PCSC_ERR_MASK (ec) )
641 case 0: rc = 0; break;
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;
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;
660 default: rc = SW_HOST_GENERAL_ERROR; break;
667 dump_pcsc_reader_status (int slot)
669 if (reader_table[slot].pcsc.card)
671 log_info ("reader slot %d: active protocol:", slot);
672 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
674 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
676 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
681 log_info ("reader slot %d: not connected\n", slot);
686 pcsc_get_status (int slot, unsigned int *status, int on_wire)
689 struct pcsc_readerstate_s rdrstates[1];
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. */
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);
705 if ((rdrstates[0].event_state & PCSC_STATE_CHANGED))
706 reader_table[slot].pcsc.current_state =
707 (rdrstates[0].event_state & ~PCSC_STATE_CHANGED);
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":"" );
724 if ( (reader_table[slot].pcsc.current_state & PCSC_STATE_PRESENT) )
726 *status |= APDU_CARD_PRESENT;
727 if ( !(reader_table[slot].pcsc.current_state & PCSC_STATE_MUTE) )
728 *status |= APDU_CARD_ACTIVE;
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
734 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
735 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
737 || !(reader_table[slot].pcsc.current_state & PCSC_STATE_INUSE)))
738 *status |= APDU_CARD_USABLE;
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;
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;
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. */
759 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
760 unsigned char *buffer, size_t *buflen,
764 struct pcsc_io_request_s send_pci;
765 pcsc_dword_t recv_len;
769 if (!reader_table[slot].atrlen
770 && (err = reset_pcsc_reader (slot)))
774 log_printhex (apdu, apdulen, " PCSC_data:");
776 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
777 send_pci.protocol = PCSC_PROTOCOL_T1;
779 send_pci.protocol = PCSC_PROTOCOL_T0;
780 send_pci.pci_len = sizeof send_pci;
782 err = pcsc_transmit (reader_table[slot].pcsc.card,
783 &send_pci, apdu, apdulen,
784 NULL, buffer, &recv_len);
787 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
788 pcsc_error_string (err), err);
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)
794 reader_table[slot].pcsc.current_state = PCSC_STATE_UNAWARE;
795 scd_kick_the_loop ();
798 return pcsc_error_to_sw (err);
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. */
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)
814 err = pcsc_control (reader_table[slot].pcsc.card, ioctl_code,
815 cntlbuf, len, buffer, buflen? *buflen:0, buflen);
818 log_error ("pcsc_control failed: %s (0x%lx)\n",
819 pcsc_error_string (err), err);
820 return pcsc_error_to_sw (err);
828 close_pcsc_reader (int slot)
831 if (--pcsc.count == 0 && npth_mutex_trylock (&reader_table_lock) == 0)
835 pcsc_release_context (pcsc.context);
837 for (i = 0; i < MAX_READER; i++)
838 pcsc.rdrname[i] = NULL;
839 npth_mutex_unlock (&reader_table_lock);
845 /* Connect a PC/SC card. */
847 connect_pcsc_card (int slot)
851 log_assert (slot >= 0 && slot < MAX_READER);
853 if (reader_table[slot].pcsc.card)
854 return SW_HOST_ALREADY_CONNECTED;
856 reader_table[slot].atrlen = 0;
857 reader_table[slot].is_t0 = 0;
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);
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);
875 pcsc_dword_t readerlen, atrlen;
876 pcsc_dword_t card_state, card_protocol;
878 pcsc_vendor_specific_init (slot);
880 atrlen = DIM (reader_table[0].atr);
881 readerlen = sizeof reader - 1;
882 err = pcsc_status (reader_table[slot].pcsc.card,
884 &card_state, &card_protocol,
885 reader_table[slot].atr, &atrlen);
887 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
888 pcsc_error_string (err), err, (long unsigned int)readerlen);
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);
898 dump_reader_status (slot);
899 return pcsc_error_to_sw (err);
904 disconnect_pcsc_card (int slot)
908 log_assert (slot >= 0 && slot < MAX_READER);
910 if (!reader_table[slot].pcsc.card)
913 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
916 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
917 pcsc_error_string (err), err);
918 return SW_HOST_CARD_IO_ERROR;
920 reader_table[slot].pcsc.card = 0;
925 /* Send an PC/SC reset command and return a status word on error or 0
928 reset_pcsc_reader (int slot)
932 sw = disconnect_pcsc_card (slot);
934 sw = connect_pcsc_card (slot);
940 /* Examine reader specific parameters and initialize. This is mostly
941 for pinpad input. Called at opening the connection to the reader. */
943 pcsc_vendor_specific_init (int slot)
945 unsigned char buf[256];
950 pcsc_dword_t get_tlv_ioctl = (pcsc_dword_t)-1;
954 sw = control_pcsc (slot, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, &len);
957 log_error ("pcsc_vendor_specific_init: GET_FEATURE_REQUEST failed: %d\n",
959 return SW_NOT_SUPPORTED;
964 while (p < buf + len)
966 unsigned char code = *p++;
973 v = buf16_to_uint (p);
975 v = buf32_to_uint (p);
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)
985 log_debug ("feature: code=%02X, len=%d, v=%02X\n", code, l, v);
991 if (get_tlv_ioctl == (pcsc_dword_t)-1)
994 * For system which doesn't support GET_TLV_PROPERTIES,
995 * we put some heuristics here.
997 if (reader_table[slot].rdrname)
999 if (strstr (reader_table[slot].rdrname, "SPRx32"))
1001 const unsigned char cmd[] = { '\x80', '\x02', '\x00' };
1002 sw = control_pcsc (slot, CM_IOCTL_VENDOR_IFD_EXCHANGE,
1003 cmd, sizeof (cmd), NULL, 0);
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.
1010 log_debug ("Ignore control_pcsc failure.\n");
1011 reader_table[slot].pinpad_varlen_supported = 1;
1013 else if (strstr (reader_table[slot].rdrname, "ST-2xxx"))
1015 reader_table[slot].pcsc.pinmax = 15;
1016 reader_table[slot].pinpad_varlen_supported = 1;
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;
1030 sw = control_pcsc (slot, get_tlv_ioctl, NULL, 0, buf, &len);
1033 log_error ("pcsc_vendor_specific_init: GET_TLV_IOCTL failed: %d\n", sw);
1034 return SW_NOT_SUPPORTED;
1038 while (p < buf + len)
1040 unsigned char tag = *p++;
1044 /* Umm... here is little endian, while the encoding above is big. */
1048 v = (((unsigned int)p[1] << 8) | p[0]);
1050 v = (((unsigned int)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
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)
1058 else if (tag == PCSCv2_PART10_PROPERTY_wIdProduct)
1062 log_debug ("TLV properties: tag=%02X, len=%d, v=%08X\n", tag, l, v);
1067 if (vendor == VENDOR_VEGA && product == VEGA_ALPHA)
1070 * Please read the comment of ccid_vendor_specific_init in
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);
1077 return SW_NOT_SUPPORTED;
1079 else if (vendor == VENDOR_SCM && product == SCM_SPR532)
1081 const unsigned char cmd[] = { '\x80', '\x02', '\x00' };
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.
1090 log_debug ("Ignore control_pcsc failure.\n");
1091 reader_table[slot].pinpad_varlen_supported = 1;
1093 else if (vendor == VENDOR_CHERRY)
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.
1099 reader_table[slot].pcsc.pinmax = 15;
1100 reader_table[slot].pinpad_varlen_supported = 1;
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;
1116 static int pcsc_api_loaded;
1119 /* Lets try the PC/SC API */
1120 if (!pcsc_api_loaded)
1124 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
1127 log_error ("apdu_open_reader: failed to open driver '%s': %s\n",
1128 opt.pcsc_driver, dlerror ());
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");
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");
1144 pcsc_connect = dlsym (handle, "SCardConnect");
1145 #if defined(_WIN32) || defined(__CYGWIN__)
1147 pcsc_connect = dlsym (handle, "SCardConnectA");
1149 pcsc_reconnect = dlsym (handle, "SCardReconnect");
1150 #if defined(_WIN32) || defined(__CYGWIN__)
1151 if (!pcsc_reconnect)
1152 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
1154 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
1155 pcsc_status = dlsym (handle, "SCardStatus");
1156 #if defined(_WIN32) || defined(__CYGWIN__)
1158 pcsc_status = dlsym (handle, "SCardStatusA");
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");
1166 if (!pcsc_establish_context
1167 || !pcsc_release_context
1168 || !pcsc_list_readers
1169 || !pcsc_get_status_change
1174 || !pcsc_begin_transaction
1175 || !pcsc_end_transaction
1178 /* || !pcsc_set_timeout */)
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,
1192 !!pcsc_begin_transaction,
1193 !!pcsc_end_transaction,
1200 pcsc_api_loaded = 1;
1203 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1207 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1208 pcsc_error_string (err), err);
1215 /* Open the PC/SC reader. Returns -1 on error or a slot number for
1218 open_pcsc_reader (const char *rdrname)
1222 slot = new_reader_slot ();
1226 reader_table[slot].rdrname = xtrystrdup (rdrname);
1227 if (!reader_table[slot].rdrname)
1229 log_error ("error allocating memory for reader name\n");
1230 close_pcsc_reader (0);
1231 reader_table[slot].used = 0;
1236 reader_table[slot].pcsc.card = 0;
1237 reader_table[slot].atrlen = 0;
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;
1248 dump_reader_status (slot);
1254 /* Check whether the reader supports the ISO command code COMMAND
1255 on the pinpad. Return 0 on success. */
1257 check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo)
1261 if (reader_table[slot].pcsc.pinmin >= 0)
1262 pininfo->minlen = reader_table[slot].pcsc.pinmin;
1264 if (reader_table[slot].pcsc.pinmax >= 0)
1265 pininfo->maxlen = reader_table[slot].pcsc.pinmax;
1267 if (!pininfo->minlen)
1268 pininfo->minlen = 1;
1269 if (!pininfo->maxlen)
1270 pininfo->maxlen = 15;
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 */
1277 r = SW_NOT_SUPPORTED;
1280 log_debug ("check_pcsc_pinpad: command=%02X, r=%d\n",
1281 (unsigned int)command, r);
1283 if (reader_table[slot].pinpad_varlen_supported)
1284 pininfo->fixedlen = 0;
1289 #define PIN_VERIFY_STRUCTURE_SIZE 24
1291 pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
1295 unsigned char *pin_verify;
1296 int len = PIN_VERIFY_STRUCTURE_SIZE + pininfo->fixedlen;
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).
1305 unsigned char result[6];
1306 pcsc_dword_t resultlen = 6;
1308 if (!reader_table[slot].atrlen
1309 && (sw = reset_pcsc_reader (slot)))
1312 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
1313 return SW_NOT_SUPPORTED;
1315 pin_verify = xtrymalloc (len);
1317 return SW_HOST_OUT_OF_CORE;
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);
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);
1352 sw = control_pcsc (slot, reader_table[slot].pcsc.verify_ioctl,
1353 pin_verify, len, result, &resultlen);
1355 if (sw || resultlen < 2)
1357 log_error ("control_pcsc failed: %d\n", sw);
1358 return sw? sw: SW_HOST_INCOMPLETE_CARD_RESPONSE;
1360 sw = (result[resultlen-2] << 8) | result[resultlen-1];
1362 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
1367 #define PIN_MODIFY_STRUCTURE_SIZE 29
1369 pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
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;
1378 if (!reader_table[slot].atrlen
1379 && (sw = reset_pcsc_reader (slot)))
1382 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
1383 return SW_NOT_SUPPORTED;
1385 pin_modify = xtrymalloc (len);
1387 return SW_HOST_OUT_OF_CORE;
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);
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)
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);
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);
1433 sw = control_pcsc (slot, reader_table[slot].pcsc.modify_ioctl,
1434 pin_modify, len, result, &resultlen);
1436 if (sw || resultlen < 2)
1438 log_error ("control_pcsc failed: %d\n", sw);
1439 return sw? sw : SW_HOST_INCOMPLETE_CARD_RESPONSE;
1441 sw = (result[resultlen-2] << 8) | result[resultlen-1];
1443 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
1449 Internal CCID driver interface.
1454 dump_ccid_reader_status (int slot)
1456 log_info ("reader slot %d: using ccid driver\n", slot);
1460 close_ccid_reader (int slot)
1462 ccid_close_reader (reader_table[slot].ccid.handle);
1463 reader_table[slot].ccid.handle = NULL;
1469 reset_ccid_reader (int slot)
1472 reader_table_t slotp = reader_table + slot;
1473 unsigned char atr[33];
1476 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
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);
1489 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
1491 reader_table_t slotp = reader_table + slot;
1493 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
1497 set_prompt_cb_ccid_reader (int slot, void (*cb) (void *, int ), void *cb_arg)
1499 reader_table_t slotp = reader_table + slot;
1501 return ccid_set_prompt_cb (slotp->ccid.handle, cb, cb_arg);
1506 get_status_ccid (int slot, unsigned int *status, int on_wire)
1511 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits, on_wire);
1516 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1518 *status = APDU_CARD_PRESENT;
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. */
1530 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1531 unsigned char *buffer, size_t *buflen,
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)))
1543 log_printhex (apdu, apdulen, " raw apdu:");
1545 maxbuflen = *buflen;
1547 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1548 apdu, apdulen, pininfo,
1549 buffer, maxbuflen, buflen);
1551 err = ccid_transceive (reader_table[slot].ccid.handle,
1553 buffer, maxbuflen, buflen);
1555 log_error ("ccid_transceive failed: (0x%lx)\n",
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 */
1566 check_ccid_pinpad (int slot, int command, pininfo_t *pininfo)
1568 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1571 return ccid_transceive_secure (reader_table[slot].ccid.handle, apdu,
1572 sizeof apdu, pininfo, NULL, 0, NULL);
1577 ccid_pinpad_operation (int slot, int class, int ins, int p0, int p1,
1580 unsigned char apdu[4];
1582 unsigned char result[2];
1583 size_t resultlen = 2;
1589 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1590 apdu, sizeof apdu, pininfo,
1591 result, 2, &resultlen);
1596 return SW_HOST_INCOMPLETE_CARD_RESPONSE;
1598 sw = (result[resultlen-2] << 8) | result[resultlen-1];
1603 /* Open the reader and try to read an ATR. */
1605 open_ccid_reader (struct dev_list *dl, int *r_cciderr)
1609 int require_get_status;
1610 reader_table_t slotp;
1614 slot = new_reader_slot ();
1617 slotp = reader_table + slot;
1619 err = ccid_open_reader (dl->portstr, dl->idx, dl->table,
1620 &slotp->ccid.handle, &slotp->rdrname);
1623 err = ccid_get_atr (slotp->ccid.handle,
1624 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1627 ccid_close_reader (slotp->ccid.handle);
1628 slotp->ccid.handle = NULL;
1640 require_get_status = ccid_require_get_status (slotp->ccid.handle);
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
1654 reader_table[slot].is_t0 = 0;
1655 reader_table[slot].require_get_status = require_get_status;
1657 dump_reader_status (slot);
1661 #endif /* HAVE_LIBUSB */
1663 #ifdef USE_G10CODE_RAPDU
1665 The Remote APDU Interface.
1667 This uses the Remote APDU protocol to contact a reader.
1669 The port number is actually an index into the list of ports as
1670 returned via the protocol.
1675 rapdu_status_to_sw (int status)
1681 case RAPDU_STATUS_SUCCESS: rc = 0; break;
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;
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;
1696 default: rc = SW_HOST_GENERAL_ERROR; break;
1705 close_rapdu_reader (int slot)
1707 rapdu_release (reader_table[slot].rapdu.handle);
1713 reset_rapdu_reader (int slot)
1716 reader_table_t slotp;
1717 rapdu_msg_t msg = NULL;
1719 slotp = reader_table + slot;
1721 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
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);
1729 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
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);
1737 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
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);
1745 if (msg->datalen > DIM (slotp->atr))
1747 log_error ("ATR returned by the RAPDU layer is too large\n");
1748 rapdu_msg_release (msg);
1749 return SW_HOST_INV_VALUE;
1751 slotp->atrlen = msg->datalen;
1752 memcpy (slotp->atr, msg->data, msg->datalen);
1754 rapdu_msg_release (msg);
1760 my_rapdu_get_status (int slot, unsigned int *status, int on_wire)
1763 reader_table_t slotp;
1764 rapdu_msg_t msg = NULL;
1768 slotp = reader_table + slot;
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);
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);
1779 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
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);
1787 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
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);
1795 *status = msg->data[0];
1797 rapdu_msg_release (msg);
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. */
1806 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1807 unsigned char *buffer, size_t *buflen,
1811 reader_table_t slotp;
1812 rapdu_msg_t msg = NULL;
1813 size_t maxlen = *buflen;
1815 slotp = reader_table + slot;
1819 log_printhex (apdu, apdulen, " APDU_data:");
1823 log_error ("rapdu_send_apdu: APDU is too short\n");
1824 return SW_HOST_INV_VALUE;
1827 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
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);
1835 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
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);
1843 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
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);
1852 if (msg->datalen > maxlen)
1854 log_error ("rapdu response apdu too large\n");
1855 rapdu_msg_release (msg);
1856 return SW_HOST_INV_VALUE;
1859 *buflen = msg->datalen;
1860 memcpy (buffer, msg->data, msg->datalen);
1862 rapdu_msg_release (msg);
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)
1880 reader_table_t slotp;
1881 rapdu_msg_t msg = NULL;
1883 slot = new_reader_slot ();
1886 slotp = reader_table + slot;
1888 slotp->rapdu.handle = rapdu_new ();
1889 if (!slotp->rapdu.handle)
1896 rapdu_set_reader (slotp->rapdu.handle, portno);
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);
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);
1911 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
1912 err < 0 ? strerror (errno): rapdu_strerror (err));
1915 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
1918 log_info ("receiving rapdu message failed: %s\n",
1919 err < 0 ? strerror (errno): rapdu_strerror (err));
1922 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
1924 log_info ("rapdu command GET ATR failed: %s\n",
1925 rapdu_strerror (msg->cmd));
1928 if (msg->datalen > DIM (slotp->atr))
1930 log_error ("ATR returned by the RAPDU layer is too large\n");
1933 slotp->atrlen = msg->datalen;
1934 memcpy (slotp->atr, msg->data, msg->datalen);
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;
1945 dump_reader_status (slot);
1946 rapdu_msg_release (msg);
1951 rapdu_msg_release (msg);
1952 rapdu_release (slotp->rapdu.handle);
1958 #endif /*USE_G10CODE_RAPDU*/
1966 apdu_dev_list_start (const char *portstr, struct dev_list **l_p)
1968 struct dev_list *dl = xtrymalloc (sizeof (struct dev_list));
1973 return gpg_error_from_syserror ();
1976 dl->portstr = portstr;
1980 npth_mutex_lock (&reader_table_lock);
1983 if (!opt.disable_ccid)
1985 err = ccid_dev_scan (&dl->idx_max, &dl->table);
1988 npth_mutex_unlock (&reader_table_lock);
1992 if (dl->idx_max == 0)
1995 log_debug ("leave: apdu_open_reader => slot=-1 (no ccid)\n");
1998 npth_mutex_unlock (&reader_table_lock);
1999 return gpg_error (GPG_ERR_ENODEV);
2004 { /* PC/SC readers. */
2006 pcsc_dword_t nreader;
2010 if (pcsc_init () < 0)
2012 npth_mutex_unlock (&reader_table_lock);
2013 return gpg_error (GPG_ERR_NO_SERVICE);
2016 r = pcsc_list_readers (pcsc.context, NULL, NULL, &nreader);
2019 p = xtrymalloc (nreader);
2022 err = gpg_error_from_syserror ();
2024 log_error ("error allocating memory for reader list\n");
2025 close_pcsc_reader (0);
2026 npth_mutex_unlock (&reader_table_lock);
2029 r = pcsc_list_readers (pcsc.context, NULL, p, &nreader);
2033 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
2034 pcsc_error_string (r), r);
2036 close_pcsc_reader (0);
2037 npth_mutex_unlock (&reader_table_lock);
2038 return iso7816_map_sw (pcsc_error_to_sw (r));
2051 for (n = 0; n < nreader; n++)
2057 log_error ("invalid response from pcsc_list_readers\n");
2061 log_info ("detected reader '%s'\n", p);
2062 pcsc.rdrname[dl->idx_max] = p;
2066 if (dl->idx_max > MAX_READER)
2068 log_error ("too many readers from pcsc_list_readers\n");
2080 apdu_dev_list_finish (struct dev_list *dl)
2083 if (!opt.disable_ccid)
2086 ccid_dev_scan_finish (dl->table, dl->idx_max);
2090 { /* PC/SC readers. */
2094 for (i = 0; i < MAX_READER; i++)
2095 pcsc.rdrname[i] = NULL;
2097 if (pcsc.count == 0)
2099 pcsc_release_context (pcsc.context);
2104 npth_mutex_unlock (&reader_table_lock);
2109 apdu_open_reader (struct dev_list *dl)
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
2120 if (dl->portstr && strchr (dl->portstr, ':'))
2121 readerno = -1; /* We want to use the readerid. */
2122 else if (dl->portstr)
2124 readerno = atoi (dl->portstr);
2125 if (readerno < 0 || readerno >= dl->idx_max)
2132 readerno = 0; /* Default. */
2135 if (!opt.disable_ccid)
2136 { /* CCID readers. */
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;
2147 while (dl->idx < dl->idx_max)
2149 unsigned int bai = ccid_get_BAI (dl->idx, dl->table);
2152 log_debug ("apdu_open_reader: BAI=%x\n", bai);
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))
2161 if (slot == MAX_READER)
2162 { /* Found a new device. */
2164 log_debug ("apdu_open_reader: new device=%x\n", bai);
2166 slot = open_ccid_reader (dl, &cciderr);
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));
2192 { /* PC/SC readers. */
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;
2201 while (dl->idx < dl->idx_max)
2203 const char *rdrname = pcsc.rdrname[dl->idx];
2206 log_debug ("apdu_open_reader: %s\n", rdrname);
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))
2214 if (slot == MAX_READER)
2215 { /* Found a new device. */
2217 log_debug ("apdu_open_reader: new device=%s\n", rdrname);
2219 /* When reader string is specified, check if it is the one. */
2220 if (readerno < 0 && strcmp (rdrname, dl->portstr) != 0)
2223 slot = open_pcsc_reader (rdrname);
2230 /* Skip this reader. */
2231 log_error ("pcsc open error: skip\n");
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.
2252 If PORTSTR is NULL we default to the first available port.
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)
2266 #ifdef USE_G10CODE_RAPDU
2267 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2269 readfnc, readfnc_value,
2270 writefnc, writefnc_value,
2271 closefnc, closefnc_value);
2277 (void)readfnc_value;
2279 (void)writefnc_value;
2281 (void)closefnc_value;
2293 apdu_close_reader (int slot)
2298 log_debug ("enter: apdu_close_reader: slot=%d\n", slot);
2300 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2303 log_debug ("leave: apdu_close_reader => SW_HOST_NO_DRIVER\n");
2304 return SW_HOST_NO_DRIVER;
2306 sw = apdu_disconnect (slot);
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.
2314 log_debug ("apdu_close_reader => 0x%x (apdu_disconnect)\n", sw);
2316 if (reader_table[slot].close_reader)
2318 sw = reader_table[slot].close_reader (slot);
2319 reader_table[slot].used = 0;
2321 log_debug ("leave: apdu_close_reader => 0x%x (close_reader)\n", sw);
2324 xfree (reader_table[slot].rdrname);
2325 reader_table[slot].rdrname = NULL;
2326 reader_table[slot].used = 0;
2328 log_debug ("leave: apdu_close_reader => SW_HOST_NOT_SUPPORTED\n");
2329 return SW_HOST_NOT_SUPPORTED;
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. */
2338 apdu_prepare_exit (void)
2340 static int sentinel;
2346 npth_mutex_lock (&reader_table_lock);
2347 for (slot = 0; slot < MAX_READER; slot++)
2348 if (reader_table[slot].used)
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;
2357 npth_mutex_unlock (&reader_table_lock);
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. */
2367 apdu_enum_reader (int slot, int *used)
2369 if (slot < 0 || slot >= MAX_READER)
2370 return SW_HOST_NO_DRIVER;
2371 *used = reader_table[slot].used;
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.
2384 apdu_connect (int slot)
2387 unsigned int status = 0;
2390 log_debug ("enter: apdu_connect: slot=%d\n", slot);
2392 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2395 log_debug ("leave: apdu_connect => SW_HOST_NO_DRIVER\n");
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)
2404 sw = lock_slot (slot);
2407 sw = reader_table[slot].connect_card (slot);
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. */
2418 sw = apdu_get_status_internal (slot, 1, &status, 1);
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;
2427 if (sw == SW_HOST_CARD_INACTIVE)
2429 /* Try power it up again. */
2430 sw = apdu_reset (slot);
2434 log_debug ("leave: apdu_connect => sw=0x%x\n", sw);
2439 return reader_table[slot].require_get_status;
2444 apdu_disconnect (int slot)
2449 log_debug ("enter: apdu_disconnect: slot=%d\n", slot);
2451 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2454 log_debug ("leave: apdu_disconnect => SW_HOST_NO_DRIVER\n");
2455 return SW_HOST_NO_DRIVER;
2458 if (reader_table[slot].disconnect_card)
2460 sw = lock_slot (slot);
2463 sw = reader_table[slot].disconnect_card (slot);
2471 log_debug ("leave: apdu_disconnect => sw=0x%x\n", sw);
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. */
2479 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
2483 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2484 return SW_HOST_NO_DRIVER;
2486 if (reader_table[slot].set_progress_cb)
2488 sw = lock_slot (slot);
2491 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
2502 apdu_set_prompt_cb (int slot, void (*cb) (void *, int), void *cb_arg)
2506 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2507 return SW_HOST_NO_DRIVER;
2509 if (reader_table[slot].set_prompt_cb)
2511 sw = lock_slot (slot);
2514 sw = reader_table[slot].set_prompt_cb (slot, cb, cb_arg);
2524 /* Do a reset for the card in reader at SLOT. */
2526 apdu_reset (int slot)
2531 log_debug ("enter: apdu_reset: slot=%d\n", slot);
2533 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2536 log_debug ("leave: apdu_reset => SW_HOST_NO_DRIVER\n");
2537 return SW_HOST_NO_DRIVER;
2540 if ((sw = lock_slot (slot)))
2543 log_debug ("leave: apdu_reset => sw=0x%x (lock_slot)\n", sw);
2547 if (reader_table[slot].reset_reader)
2548 sw = reader_table[slot].reset_reader (slot);
2552 log_debug ("leave: apdu_reset => sw=0x%x\n", sw);
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
2561 apdu_get_atr (int slot, size_t *atrlen)
2566 log_debug ("enter: apdu_get_atr: slot=%d\n", slot);
2568 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2571 log_debug ("leave: apdu_get_atr => NULL (bad slot)\n");
2574 if (!reader_table[slot].atrlen)
2577 log_debug ("leave: apdu_get_atr => NULL (no ATR)\n");
2581 buf = xtrymalloc (reader_table[slot].atrlen);
2585 log_debug ("leave: apdu_get_atr => NULL (out of core)\n");
2588 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2589 *atrlen = reader_table[slot].atrlen;
2591 log_debug ("leave: apdu_get_atr => atrlen=%zu\n", *atrlen);
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
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]
2606 For most applications, testing bit 0 is sufficient.
2609 apdu_get_status_internal (int slot, int hang, unsigned int *status, int on_wire)
2614 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2615 return SW_HOST_NO_DRIVER;
2617 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2620 if (reader_table[slot].get_status_reader)
2621 sw = reader_table[slot].get_status_reader (slot, &s, on_wire);
2628 reader_table[slot].atrlen = 0;
2638 /* See above for a description. */
2640 apdu_get_status (int slot, int hang, unsigned int *status)
2645 log_debug ("enter: apdu_get_status: slot=%d hang=%d\n", slot, hang);
2646 sw = apdu_get_status_internal (slot, hang, status, 0);
2650 log_debug ("leave: apdu_get_status => sw=0x%x status=%u\n",
2653 log_debug ("leave: apdu_get_status => sw=0x%x\n", sw);
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 */
2663 apdu_check_pinpad (int slot, int command, pininfo_t *pininfo)
2665 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2666 return SW_HOST_NO_DRIVER;
2668 if (opt.enable_pinpad_varlen)
2669 pininfo->fixedlen = 0;
2671 if (reader_table[slot].check_pinpad)
2675 if ((sw = lock_slot (slot)))
2678 sw = reader_table[slot].check_pinpad (slot, command, pininfo);
2683 return SW_HOST_NOT_SUPPORTED;
2688 apdu_pinpad_verify (int slot, int class, int ins, int p0, int p1,
2691 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2692 return SW_HOST_NO_DRIVER;
2694 if (reader_table[slot].pinpad_verify)
2698 if ((sw = lock_slot (slot)))
2701 sw = reader_table[slot].pinpad_verify (slot, class, ins, p0, p1,
2707 return SW_HOST_NOT_SUPPORTED;
2712 apdu_pinpad_modify (int slot, int class, int ins, int p0, int p1,
2715 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2716 return SW_HOST_NO_DRIVER;
2718 if (reader_table[slot].pinpad_modify)
2722 if ((sw = lock_slot (slot)))
2725 sw = reader_table[slot].pinpad_modify (slot, class, ins, p0, p1,
2731 return SW_HOST_NOT_SUPPORTED;
2735 /* Dispatcher for the actual send_apdu function. Note, that this
2736 function should be called in locked state. */
2738 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2739 unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
2741 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2742 return SW_HOST_NO_DRIVER;
2744 if (reader_table[slot].send_apdu_reader)
2745 return reader_table[slot].send_apdu_reader (slot,
2750 return SW_HOST_NOT_SUPPORTED;
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
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
2764 n > 1 := Use extended length with up to N bytes.
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)
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;
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;
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;
2792 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2793 return SW_HOST_NO_DRIVER;
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);
2799 if (lc != -1 && (lc > 255 || lc < 0))
2801 /* Data does not fit into an APDU. What we do now depends on
2802 the EXTENDED_MODE parameter. */
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)
2809 /* Send APDU using chaining mode. */
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;
2818 return SW_HOST_INV_VALUE;
2820 else if (lc == -1 && extended_mode > 0)
2821 use_extended_length = 1;
2823 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
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
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;
2836 return SW_HOST_INV_VALUE;
2839 if ((!data && lc != -1) || (data && lc == -1))
2840 return SW_HOST_INV_VALUE;
2842 if (use_extended_length)
2844 if (reader_table[slot].is_t0)
2845 return SW_HOST_NOT_SUPPORTED;
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);
2851 return SW_HOST_OUT_OF_CORE;
2856 apdu_buffer_size = sizeof short_apdu_buffer;
2857 apdu = short_apdu_buffer;
2860 if (use_extended_length && (le > 256 || le < 0))
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);
2867 xfree (apdu_buffer);
2868 return SW_HOST_OUT_OF_CORE;
2870 result = result_buffer;
2874 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2875 result = short_result_buffer;
2877 #undef SHORT_RESULT_BUFFER_SIZE
2879 if ((sw = lock_slot (slot)))
2881 xfree (apdu_buffer);
2882 xfree (result_buffer);
2888 if (use_extended_length)
2892 apdu[apdulen++] = class;
2893 apdu[apdulen++] = ins;
2894 apdu[apdulen++] = p0;
2895 apdu[apdulen++] = p1;
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);
2908 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
2909 apdu[apdulen++] = ((le >> 8) & 0xff);
2910 apdu[apdulen++] = (le & 0xff);
2916 apdu[apdulen] = class;
2917 if (use_chaining && lc > 255)
2919 apdu[apdulen] |= 0x10;
2920 log_assert (use_chaining < 256);
2921 lc_chunk = use_chaining;
2930 apdu[apdulen++] = ins;
2931 apdu[apdulen++] = p0;
2932 apdu[apdulen++] = p1;
2935 apdu[apdulen++] = lc_chunk;
2936 memcpy (apdu+apdulen, 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)
2944 if (le != -1 && !use_chaining)
2945 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
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)
2956 log_info ("apdu_send_simple(%d) failed: %s\n",
2957 slot, apdu_strerror (rc));
2959 xfree (apdu_buffer);
2960 xfree (result_buffer);
2961 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2963 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2964 if (!use_extended_length
2965 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
2967 apdu[apdulen-1] = (sw & 0x00ff);
2968 did_exact_length_hack = 1;
2969 goto exact_length_hack;
2972 while (use_chaining && sw == SW_SUCCESS);
2976 xfree (apdu_buffer);
2980 /* Store away the returned data but strip the statusword. */
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))
2988 if (all_zero_p (result, resultlen))
2989 log_debug (" dump: [all zero]\n");
2991 log_printhex (result, resultlen, " dump:");
2995 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
2999 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3003 xfree (result_buffer);
3004 return SW_HOST_OUT_OF_CORE;
3006 *retbuflen = resultlen;
3007 memcpy (*retbuf, result, resultlen);
3010 else if ((sw & 0xff00) == SW_MORE_DATA)
3012 unsigned char *p = NULL, *tmp;
3013 size_t bufsize = 4096;
3015 /* It is likely that we need to return much more data, so we
3016 start off with a large buffer. */
3019 *retbuf = p = xtrymalloc (bufsize);
3023 xfree (result_buffer);
3024 return SW_HOST_OUT_OF_CORE;
3026 log_assert (resultlen < bufsize);
3027 memcpy (p, result, resultlen);
3033 int len = (sw & 0x00ff);
3036 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3038 apdu_buffer_size = sizeof short_apdu_buffer;
3039 apdu = short_apdu_buffer;
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)
3052 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3053 slot, apdu_strerror (rc));
3055 xfree (result_buffer);
3056 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3058 sw = (result[resultlen-2] << 8) | result[resultlen-1];
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))
3066 if (all_zero_p (result, resultlen))
3067 log_debug ( " dump: [all zero]\n");
3069 log_printhex (result, resultlen, " dump:");
3073 if ((sw & 0xff00) == SW_MORE_DATA
3075 || sw == SW_EOF_REACHED )
3077 if (retbuf && resultlen)
3079 if (p - *retbuf + resultlen > bufsize)
3081 bufsize += resultlen > 4096? resultlen: 4096;
3082 tmp = xtryrealloc (*retbuf, bufsize);
3086 xfree (result_buffer);
3087 return SW_HOST_OUT_OF_CORE;
3089 p = tmp + (p - *retbuf);
3092 memcpy (p, result, resultlen);
3097 log_info ("apdu_send_simple(%d) "
3098 "got unexpected status %04X from get response\n",
3101 while ((sw & 0xff00) == SW_MORE_DATA);
3105 *retbuflen = p - *retbuf;
3106 tmp = xtryrealloc (*retbuf, *retbuflen);
3113 xfree (result_buffer);
3115 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
3117 if (all_zero_p (*retbuf, *retbuflen))
3118 log_debug (" dump: [all zero]\n");
3120 log_printhex (*retbuf, *retbuflen, " dump:");
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. */
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)
3142 return send_le (slot, class, ins, p0, p1,
3145 NULL, extended_mode);
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. */
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)
3164 return send_le (slot, class, ins, p0, p1, lc, data, 256,
3165 retbuf, retbuflen, NULL, extended_mode);
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. */
3176 apdu_send_simple (int slot, int extended_mode,
3177 int class, int ins, int p0, int p1,
3178 int lc, const char *data)
3180 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
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
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. */
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)
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;
3213 unsigned char short_apdu_buffer[5+256+10];
3214 unsigned char *apdu_buffer = NULL;
3215 unsigned char *apdu;
3218 long rc; /* we need a long here due to PC/SC. */
3221 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3222 return SW_HOST_NO_DRIVER;
3224 if (apdudatalen > 65535)
3225 return SW_HOST_INV_VALUE;
3227 if (apdudatalen > sizeof short_apdu_buffer - 5)
3229 apdu_buffer = xtrymalloc (apdudatalen + 5);
3231 return SW_HOST_OUT_OF_CORE;
3236 apdu = short_apdu_buffer;
3238 apdulen = apdudatalen;
3239 memcpy (apdu, apdudata, apdudatalen);
3240 class = apdulen? *apdu : 0;
3242 if (extended_length >= 256 && extended_length <= 65536)
3244 result_buffer_size = extended_length;
3245 result_buffer = xtrymalloc (result_buffer_size + 10);
3248 xfree (apdu_buffer);
3249 return SW_HOST_OUT_OF_CORE;
3251 result = result_buffer;
3255 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3256 result = short_result_buffer;
3258 #undef SHORT_RESULT_BUFFER_SIZE
3260 if ((sw = lock_slot (slot)))
3262 xfree (apdu_buffer);
3263 xfree (result_buffer);
3267 resultlen = result_buffer_size;
3268 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3269 xfree (apdu_buffer);
3271 if (rc || resultlen < 2)
3273 log_error ("apdu_send_direct(%d) failed: %s\n",
3274 slot, apdu_strerror (rc));
3276 xfree (result_buffer);
3277 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3279 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3280 /* Store away the returned data but strip the statusword. */
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: ");
3290 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3292 unsigned char *p = NULL, *tmp;
3293 size_t bufsize = 4096;
3295 /* It is likely that we need to return much more data, so we
3296 start off with a large buffer. */
3299 *retbuf = p = xtrymalloc (bufsize + 2);
3303 xfree (result_buffer);
3304 return SW_HOST_OUT_OF_CORE;
3306 log_assert (resultlen < bufsize);
3307 memcpy (p, result, resultlen);
3313 int len = (sw & 0x00ff);
3316 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3318 apdu = short_apdu_buffer;
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)
3330 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3331 slot, apdu_strerror (rc));
3333 xfree (result_buffer);
3334 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3336 sw = (result[resultlen-2] << 8) | result[resultlen-1];
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: ");
3346 if ((sw & 0xff00) == SW_MORE_DATA
3348 || sw == SW_EOF_REACHED )
3350 if (retbuf && resultlen)
3352 if (p - *retbuf + resultlen > bufsize)
3354 bufsize += resultlen > 4096? resultlen: 4096;
3355 tmp = xtryrealloc (*retbuf, bufsize + 2);
3359 xfree (result_buffer);
3360 return SW_HOST_OUT_OF_CORE;
3362 p = tmp + (p - *retbuf);
3365 memcpy (p, result, resultlen);
3370 log_info ("apdu_send_direct(%d) "
3371 "got unexpected status %04X from get response\n",
3374 while ((sw & 0xff00) == SW_MORE_DATA);
3378 *retbuflen = p - *retbuf;
3379 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3388 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3392 xfree (result_buffer);
3393 return SW_HOST_OUT_OF_CORE;
3395 *retbuflen = resultlen;
3396 memcpy (*retbuf, result, resultlen);
3401 xfree (result_buffer);
3403 /* Append the status word. Note that we reserved the two extra
3404 bytes while allocating the buffer. */
3407 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3408 (*retbuf)[(*retbuflen)++] = sw;
3414 if (DBG_CARD_IO && retbuf)
3415 log_printhex (*retbuf, *retbuflen, " dump: ");
3423 apdu_get_reader_name (int slot)
3425 return reader_table[slot].rdrname;
3437 for (i = 0; i < MAX_READER; i++)
3438 pcsc.rdrname[i] = NULL;
3440 if (npth_mutex_init (&reader_table_lock, NULL))
3443 for (i = 0; i < MAX_READER; i++)
3444 if (npth_mutex_init (&reader_table[i].lock, NULL))
3447 /* All done well. */
3451 err = gpg_error_from_syserror ();
3452 log_error ("apdu: error initializing mutex: %s\n", gpg_strerror (err));