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
58 #else /* GNUPG_MAJOR_VERSION != 1 */
61 #endif /* GNUPG_MAJOR_VERSION != 1 */
66 #define CCID_DRIVER_INCLUDE_USB_IDS 1
67 #include "ccid-driver.h"
70 struct ccid_dev_table *ccid_table;
76 /* Due to conflicting use of threading libraries we usually can't link
77 against libpcsclite if we are using Pth. Instead we use a wrapper
78 program. Note that with nPth there is no need for a wrapper. */
79 #ifdef USE_PTH /* Right, plain old Pth. */
80 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
81 #define NEED_PCSC_WRAPPER 1
86 #define MAX_READER 4 /* Number of readers we support concurrently. */
89 #if defined(_WIN32) || defined(__CYGWIN__)
90 #define DLSTDCALL __stdcall
95 #if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
96 typedef unsigned int pcsc_dword_t;
98 typedef unsigned long pcsc_dword_t;
101 /* A structure to collect information pertaining to one reader
103 struct reader_table_s {
104 int used; /* True if slot is used. */
105 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
107 /* Function pointers intialized to the various backends. */
108 int (*connect_card)(int);
109 int (*disconnect_card)(int);
110 int (*close_reader)(int);
111 int (*reset_reader)(int);
112 int (*get_status_reader)(int, unsigned int *);
113 int (*send_apdu_reader)(int,unsigned char *,size_t,
114 unsigned char *, size_t *, pininfo_t *);
115 int (*check_pinpad)(int, int, pininfo_t *);
116 void (*dump_status_reader)(int);
117 int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
118 int (*pinpad_verify)(int, int, int, int, int, pininfo_t *);
119 int (*pinpad_modify)(int, int, int, int, int, pininfo_t *);
122 ccid_driver_t handle;
127 pcsc_dword_t protocol;
128 pcsc_dword_t verify_ioctl;
129 pcsc_dword_t modify_ioctl;
132 #ifdef NEED_PCSC_WRAPPER
136 #endif /*NEED_PCSC_WRAPPER*/
138 #ifdef USE_G10CODE_RAPDU
142 #endif /*USE_G10CODE_RAPDU*/
143 char *rdrname; /* Name of the connected reader or NULL if unknown. */
144 int is_t0; /* True if we know that we are running T=0. */
145 int is_spr532; /* True if we know that the reader is a SPR532. */
146 int pinpad_varlen_supported; /* True if we know that the reader
147 supports variable length pinpad
149 unsigned char atr[33];
150 size_t atrlen; /* A zero length indicates that the ATR has
151 not yet been read; i.e. the card is not
157 typedef struct reader_table_s *reader_table_t;
159 /* A global table to keep track of active readers. */
160 static struct reader_table_s reader_table[MAX_READER];
163 static npth_mutex_t reader_table_lock;
167 /* ct API function pointer. */
168 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
169 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
170 unsigned char *sad, unsigned short lc,
171 unsigned char *cmd, unsigned short *lr,
173 static char (* DLSTDCALL CT_close) (unsigned short ctn);
175 /* PC/SC constants and function pointer. */
176 #define PCSC_SCOPE_USER 0
177 #define PCSC_SCOPE_TERMINAL 1
178 #define PCSC_SCOPE_SYSTEM 2
179 #define PCSC_SCOPE_GLOBAL 3
181 #define PCSC_PROTOCOL_T0 1
182 #define PCSC_PROTOCOL_T1 2
183 #ifdef HAVE_W32_SYSTEM
184 # define PCSC_PROTOCOL_RAW 0x00010000 /* The active protocol. */
186 # define PCSC_PROTOCOL_RAW 4
189 #define PCSC_SHARE_EXCLUSIVE 1
190 #define PCSC_SHARE_SHARED 2
191 #define PCSC_SHARE_DIRECT 3
193 #define PCSC_LEAVE_CARD 0
194 #define PCSC_RESET_CARD 1
195 #define PCSC_UNPOWER_CARD 2
196 #define PCSC_EJECT_CARD 3
198 #ifdef HAVE_W32_SYSTEM
199 # define PCSC_UNKNOWN 0x0000 /* The driver is not aware of the status. */
200 # define PCSC_ABSENT 0x0001 /* Card is absent. */
201 # define PCSC_PRESENT 0x0002 /* Card is present. */
202 # define PCSC_SWALLOWED 0x0003 /* Card is present and electrical connected. */
203 # define PCSC_POWERED 0x0004 /* Card is powered. */
204 # define PCSC_NEGOTIABLE 0x0005 /* Card is awaiting PTS. */
205 # define PCSC_SPECIFIC 0x0006 /* Card is ready for use. */
207 # define PCSC_UNKNOWN 0x0001
208 # define PCSC_ABSENT 0x0002 /* Card is absent. */
209 # define PCSC_PRESENT 0x0004 /* Card is present. */
210 # define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
211 # define PCSC_POWERED 0x0010 /* Card is powered. */
212 # define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
213 # define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
216 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
217 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
218 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
219 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
220 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
221 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
222 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
223 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
224 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
225 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
226 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
227 #ifdef HAVE_W32_SYSTEM
228 # define PCSC_STATE_UNPOWERED 0x0400 /* Card not powerred up. */
231 /* Some PC/SC error codes. */
232 #define PCSC_E_CANCELLED 0x80100002
233 #define PCSC_E_CANT_DISPOSE 0x8010000E
234 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
235 #define PCSC_E_INVALID_ATR 0x80100015
236 #define PCSC_E_INVALID_HANDLE 0x80100003
237 #define PCSC_E_INVALID_PARAMETER 0x80100004
238 #define PCSC_E_INVALID_TARGET 0x80100005
239 #define PCSC_E_INVALID_VALUE 0x80100011
240 #define PCSC_E_NO_MEMORY 0x80100006
241 #define PCSC_E_UNKNOWN_READER 0x80100009
242 #define PCSC_E_TIMEOUT 0x8010000A
243 #define PCSC_E_SHARING_VIOLATION 0x8010000B
244 #define PCSC_E_NO_SMARTCARD 0x8010000C
245 #define PCSC_E_UNKNOWN_CARD 0x8010000D
246 #define PCSC_E_PROTO_MISMATCH 0x8010000F
247 #define PCSC_E_NOT_READY 0x80100010
248 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
249 #define PCSC_E_NOT_TRANSACTED 0x80100016
250 #define PCSC_E_READER_UNAVAILABLE 0x80100017
251 #define PCSC_E_NO_SERVICE 0x8010001D
252 #define PCSC_E_SERVICE_STOPPED 0x8010001E
253 #define PCSC_W_REMOVED_CARD 0x80100069
255 /* Fix pcsc-lite ABI incompatibilty. */
256 #ifndef SCARD_CTL_CODE
258 #include <winioctl.h>
259 #define SCARD_CTL_CODE(code) CTL_CODE(FILE_DEVICE_SMARTCARD, (code), \
260 METHOD_BUFFERED, FILE_ANY_ACCESS)
262 #define SCARD_CTL_CODE(code) (0x42000000 + (code))
266 #define CM_IOCTL_GET_FEATURE_REQUEST SCARD_CTL_CODE(3400)
267 #define CM_IOCTL_VENDOR_IFD_EXCHANGE SCARD_CTL_CODE(1)
268 #define FEATURE_VERIFY_PIN_DIRECT 0x06
269 #define FEATURE_MODIFY_PIN_DIRECT 0x07
270 #define FEATURE_GET_TLV_PROPERTIES 0x12
272 #define PCSCv2_PART10_PROPERTY_bEntryValidationCondition 2
273 #define PCSCv2_PART10_PROPERTY_bTimeOut2 3
274 #define PCSCv2_PART10_PROPERTY_bMinPINSize 6
275 #define PCSCv2_PART10_PROPERTY_bMaxPINSize 7
276 #define PCSCv2_PART10_PROPERTY_wIdVendor 11
277 #define PCSCv2_PART10_PROPERTY_wIdProduct 12
280 /* The PC/SC error is defined as a long as per specs. Due to left
281 shifts bit 31 will get sign extended. We use this mask to fix
283 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
286 struct pcsc_io_request_s
288 unsigned long protocol;
289 unsigned long pci_len;
292 typedef struct pcsc_io_request_s *pcsc_io_request_t;
298 struct pcsc_readerstate_s
302 pcsc_dword_t current_state;
303 pcsc_dword_t event_state;
305 unsigned char atr[33];
312 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
314 long (* DLSTDCALL pcsc_establish_context) (pcsc_dword_t scope,
315 const void *reserved1,
316 const void *reserved2,
318 long (* DLSTDCALL pcsc_release_context) (long context);
319 long (* DLSTDCALL pcsc_list_readers) (long context,
321 char *readers, pcsc_dword_t*readerslen);
322 long (* DLSTDCALL pcsc_get_status_change) (long context,
323 pcsc_dword_t timeout,
324 pcsc_readerstate_t readerstates,
325 pcsc_dword_t nreaderstates);
326 long (* DLSTDCALL pcsc_connect) (long context,
328 pcsc_dword_t share_mode,
329 pcsc_dword_t preferred_protocols,
331 pcsc_dword_t *r_active_protocol);
332 long (* DLSTDCALL pcsc_reconnect) (long card,
333 pcsc_dword_t share_mode,
334 pcsc_dword_t preferred_protocols,
335 pcsc_dword_t initialization,
336 pcsc_dword_t *r_active_protocol);
337 long (* DLSTDCALL pcsc_disconnect) (long card,
338 pcsc_dword_t disposition);
339 long (* DLSTDCALL pcsc_status) (long card,
340 char *reader, pcsc_dword_t *readerlen,
341 pcsc_dword_t *r_state,
342 pcsc_dword_t *r_protocol,
343 unsigned char *atr, pcsc_dword_t *atrlen);
344 long (* DLSTDCALL pcsc_begin_transaction) (long card);
345 long (* DLSTDCALL pcsc_end_transaction) (long card,
346 pcsc_dword_t disposition);
347 long (* DLSTDCALL pcsc_transmit) (long card,
348 const pcsc_io_request_t send_pci,
349 const unsigned char *send_buffer,
350 pcsc_dword_t send_len,
351 pcsc_io_request_t recv_pci,
352 unsigned char *recv_buffer,
353 pcsc_dword_t *recv_len);
354 long (* DLSTDCALL pcsc_set_timeout) (long context,
355 pcsc_dword_t timeout);
356 long (* DLSTDCALL pcsc_control) (long card,
357 pcsc_dword_t control_code,
358 const void *send_buffer,
359 pcsc_dword_t send_len,
361 pcsc_dword_t recv_len,
362 pcsc_dword_t *bytes_returned);
366 static int pcsc_vendor_specific_init (int slot);
367 static int pcsc_get_status (int slot, unsigned int *status);
368 static int reset_pcsc_reader (int slot);
369 static int apdu_get_status_internal (int slot, int hang, int no_atr_reset,
370 unsigned int *status);
371 static int check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo);
372 static int pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
374 static int pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
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].pinpad_verify = pcsc_pinpad_verify;
468 reader_table[reader].pinpad_modify = pcsc_pinpad_modify;
470 reader_table[reader].is_t0 = 1;
471 reader_table[reader].is_spr532 = 0;
472 reader_table[reader].pinpad_varlen_supported = 0;
473 #ifdef NEED_PCSC_WRAPPER
474 reader_table[reader].pcsc.req_fd = -1;
475 reader_table[reader].pcsc.rsp_fd = -1;
476 reader_table[reader].pcsc.pid = (pid_t)(-1);
478 reader_table[reader].pcsc.verify_ioctl = 0;
479 reader_table[reader].pcsc.modify_ioctl = 0;
480 reader_table[reader].pcsc.pinmin = -1;
481 reader_table[reader].pcsc.pinmax = -1;
488 dump_reader_status (int slot)
493 if (reader_table[slot].dump_status_reader)
494 reader_table[slot].dump_status_reader (slot);
496 if (reader_table[slot].atrlen)
498 log_info ("slot %d: ATR=", slot);
499 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
506 host_sw_string (long err)
510 case 0: return "okay";
511 case SW_HOST_OUT_OF_CORE: return "out of core";
512 case SW_HOST_INV_VALUE: return "invalid value";
513 case SW_HOST_NO_DRIVER: return "no driver";
514 case SW_HOST_NOT_SUPPORTED: return "not supported";
515 case SW_HOST_LOCKING_FAILED: return "locking failed";
516 case SW_HOST_BUSY: return "busy";
517 case SW_HOST_NO_CARD: return "no card";
518 case SW_HOST_CARD_INACTIVE: return "card inactive";
519 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
520 case SW_HOST_GENERAL_ERROR: return "general error";
521 case SW_HOST_NO_READER: return "no reader";
522 case SW_HOST_ABORTED: return "aborted";
523 case SW_HOST_NO_PINPAD: return "no pinpad";
524 case SW_HOST_ALREADY_CONNECTED: return "already connected";
525 default: return "unknown host status error";
531 apdu_strerror (int rc)
535 case SW_EOF_REACHED : return "eof reached";
536 case SW_EEPROM_FAILURE : return "eeprom failure";
537 case SW_WRONG_LENGTH : return "wrong length";
538 case SW_CHV_WRONG : return "CHV wrong";
539 case SW_CHV_BLOCKED : return "CHV blocked";
540 case SW_REF_DATA_INV : return "referenced data invalidated";
541 case SW_USE_CONDITIONS : return "use conditions not satisfied";
542 case SW_BAD_PARAMETER : return "bad parameter";
543 case SW_NOT_SUPPORTED : return "not supported";
544 case SW_FILE_NOT_FOUND : return "file not found";
545 case SW_RECORD_NOT_FOUND:return "record not found";
546 case SW_REF_NOT_FOUND : return "reference not found";
547 case SW_NOT_ENOUGH_MEMORY: return "not enough memory space in the file";
548 case SW_INCONSISTENT_LC: return "Lc inconsistent with TLV structure.";
549 case SW_INCORRECT_P0_P1: return "incorrect parameters P0,P1";
550 case SW_BAD_LC : return "Lc inconsistent with P0,P1";
551 case SW_BAD_P0_P1 : return "bad P0,P1";
552 case SW_INS_NOT_SUP : return "instruction not supported";
553 case SW_CLA_NOT_SUP : return "class not supported";
554 case SW_SUCCESS : return "success";
556 if ((rc & ~0x00ff) == SW_MORE_DATA)
557 return "more data available";
558 if ( (rc & 0x10000) )
559 return host_sw_string (rc);
560 return "unknown status error";
571 ct_error_string (long err)
575 case 0: return "okay";
576 case -1: return "invalid data";
577 case -8: return "ct error";
578 case -10: return "transmission error";
579 case -11: return "memory allocation error";
580 case -128: return "HTSI error";
581 default: return "unknown CT-API error";
586 /* Wait for the card in SLOT and activate it. Return a status word
587 error or 0 on success. */
589 ct_activate_card (int slot)
592 unsigned char dad[1], sad[1], cmd[11], buf[256];
593 unsigned short buflen;
595 /* Check whether card has been inserted. */
596 dad[0] = 1; /* Destination address: CT. */
597 sad[0] = 2; /* Source address: Host. */
599 cmd[0] = 0x20; /* Class byte. */
600 cmd[1] = 0x13; /* Request status. */
601 cmd[2] = 0x00; /* From kernel. */
602 cmd[3] = 0x80; /* Return card's DO. */
607 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
608 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
610 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
611 slot, ct_error_string (rc));
612 return SW_HOST_CARD_IO_ERROR;
615 /* Connected, now activate the card. */
616 dad[0] = 1; /* Destination address: CT. */
617 sad[0] = 2; /* Source address: Host. */
619 cmd[0] = 0x20; /* Class byte. */
620 cmd[1] = 0x12; /* Request ICC. */
621 cmd[2] = 0x01; /* From first interface. */
622 cmd[3] = 0x01; /* Return card's ATR. */
627 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
628 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
630 log_error ("ct_activate_card(%d): activation failed: %s\n",
631 slot, ct_error_string (rc));
633 log_printhex (" received data:", buf, buflen);
634 return SW_HOST_CARD_IO_ERROR;
637 /* Store the type and the ATR. */
638 if (buflen - 2 > DIM (reader_table[0].atr))
640 log_error ("ct_activate_card(%d): ATR too long\n", slot);
641 return SW_HOST_CARD_IO_ERROR;
644 memcpy (reader_table[slot].atr, buf, buflen - 2);
645 reader_table[slot].atrlen = buflen - 2;
651 close_ct_reader (int slot)
658 reset_ct_reader (int slot)
660 /* FIXME: Check is this is sufficient do do a reset. */
661 return ct_activate_card (slot);
666 ct_get_status (int slot, unsigned int *status)
669 /* The status we returned is wrong but we don't care because ctAPI
670 is not anymore required. */
671 *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
675 /* Actually send the APDU of length APDULEN to SLOT and return a
676 maximum of *BUFLEN data in BUFFER, the actual returned size will be
677 set to BUFLEN. Returns: CT API error code. */
679 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
680 unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
683 unsigned char dad[1], sad[1];
684 unsigned short ctbuflen;
688 /* If we don't have an ATR, we need to reset the reader first. */
689 if (!reader_table[slot].atrlen
690 && (rc = reset_ct_reader (slot)))
693 dad[0] = 0; /* Destination address: Card. */
694 sad[0] = 2; /* Source address: Host. */
697 log_printhex (" CT_data:", apdu, apdulen);
698 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
701 return rc? SW_HOST_CARD_IO_ERROR: 0;
706 /* Open a reader and return an internal handle for it. PORT is a
707 non-negative value with the port number of the reader. USB readers
708 do have port numbers starting at 32769. */
710 open_ct_reader (int port)
714 if (port < 0 || port > 0xffff)
716 log_error ("open_ct_reader: invalid port %d requested\n", port);
719 reader = new_reader_slot ();
722 reader_table[reader].port = port;
724 rc = CT_init (reader, (unsigned short)port);
727 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
728 port, ct_error_string (rc));
729 reader_table[reader].used = 0;
730 unlock_slot (reader);
734 /* Only try to activate the card. */
735 rc = ct_activate_card (reader);
738 reader_table[reader].atrlen = 0;
742 reader_table[reader].close_reader = close_ct_reader;
743 reader_table[reader].reset_reader = reset_ct_reader;
744 reader_table[reader].get_status_reader = ct_get_status;
745 reader_table[reader].send_apdu_reader = ct_send_apdu;
746 reader_table[reader].check_pinpad = NULL;
747 reader_table[reader].dump_status_reader = NULL;
748 reader_table[reader].pinpad_verify = NULL;
749 reader_table[reader].pinpad_modify = NULL;
751 dump_reader_status (reader);
752 unlock_slot (reader);
761 #ifdef NEED_PCSC_WRAPPER
763 writen (int fd, const void *buf, size_t nbytes)
765 size_t nleft = nbytes;
768 /* log_printhex (" writen:", buf, nbytes); */
773 nwritten = npth_write (fd, buf, nleft);
775 nwritten = write (fd, buf, nleft);
777 if (nwritten < 0 && errno == EINTR)
782 buf = (const char*)buf + nwritten;
787 /* Read up to BUFLEN bytes from FD and return the number of bytes
788 actually read in NREAD. Returns -1 on error or 0 on success. */
790 readn (int fd, void *buf, size_t buflen, size_t *nread)
792 size_t nleft = buflen;
794 /* void *orig_buf = buf; */
799 # ifdef HAVE_W32_SYSTEM
800 # error Cannot use npth_read here because it expects a system HANDLE.
802 n = npth_read (fd, buf, nleft);
804 n = read (fd, buf, nleft);
806 if (n < 0 && errno == EINTR)
809 return -1; /* read error. */
813 buf = (char*)buf + n;
816 *nread = buflen - nleft;
818 /* log_printhex (" readn:", orig_buf, *nread); */
822 #endif /*NEED_PCSC_WRAPPER*/
825 pcsc_error_string (long err)
831 if ((err & 0x80100000) != 0x80100000)
832 return "invalid PC/SC error code";
836 case 0x0002: s = "cancelled"; break;
837 case 0x000e: s = "can't dispose"; break;
838 case 0x0008: s = "insufficient buffer"; break;
839 case 0x0015: s = "invalid ATR"; break;
840 case 0x0003: s = "invalid handle"; break;
841 case 0x0004: s = "invalid parameter"; break;
842 case 0x0005: s = "invalid target"; break;
843 case 0x0011: s = "invalid value"; break;
844 case 0x0006: s = "no memory"; break;
845 case 0x0013: s = "comm error"; break;
846 case 0x0001: s = "internal error"; break;
847 case 0x0014: s = "unknown error"; break;
848 case 0x0007: s = "waited too long"; break;
849 case 0x0009: s = "unknown reader"; break;
850 case 0x000a: s = "timeout"; break;
851 case 0x000b: s = "sharing violation"; break;
852 case 0x000c: s = "no smartcard"; break;
853 case 0x000d: s = "unknown card"; break;
854 case 0x000f: s = "proto mismatch"; break;
855 case 0x0010: s = "not ready"; break;
856 case 0x0012: s = "system cancelled"; break;
857 case 0x0016: s = "not transacted"; break;
858 case 0x0017: s = "reader unavailable"; break;
859 case 0x0065: s = "unsupported card"; break;
860 case 0x0066: s = "unresponsive card"; break;
861 case 0x0067: s = "unpowered card"; break;
862 case 0x0068: s = "reset card"; break;
863 case 0x0069: s = "removed card"; break;
864 case 0x006a: s = "inserted card"; break;
865 case 0x001f: s = "unsupported feature"; break;
866 case 0x0019: s = "PCI too small"; break;
867 case 0x001a: s = "reader unsupported"; break;
868 case 0x001b: s = "duplicate reader"; break;
869 case 0x001c: s = "card unsupported"; break;
870 case 0x001d: s = "no service"; break;
871 case 0x001e: s = "service stopped"; break;
872 default: s = "unknown PC/SC error code"; break;
877 /* Map PC/SC error codes to our special host status words. */
879 pcsc_error_to_sw (long ec)
883 switch ( PCSC_ERR_MASK (ec) )
885 case 0: rc = 0; break;
887 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
888 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
889 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
890 case PCSC_E_NO_SERVICE:
891 case PCSC_E_SERVICE_STOPPED:
892 case PCSC_E_UNKNOWN_READER: rc = SW_HOST_NO_READER; break;
893 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
894 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
895 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
897 case PCSC_E_INVALID_TARGET:
898 case PCSC_E_INVALID_VALUE:
899 case PCSC_E_INVALID_HANDLE:
900 case PCSC_E_INVALID_PARAMETER:
901 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
903 default: rc = SW_HOST_GENERAL_ERROR; break;
910 dump_pcsc_reader_status (int slot)
912 if (reader_table[slot].pcsc.card)
914 log_info ("reader slot %d: active protocol:", slot);
915 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
917 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
919 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
924 log_info ("reader slot %d: not connected\n", slot);
928 #ifndef NEED_PCSC_WRAPPER
930 pcsc_get_status_direct (int slot, unsigned int *status)
933 struct pcsc_readerstate_s rdrstates[1];
935 memset (rdrstates, 0, sizeof *rdrstates);
936 rdrstates[0].reader = reader_table[slot].rdrname;
937 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
938 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
941 if (err == PCSC_E_TIMEOUT)
942 err = 0; /* Timeout is no error error here. */
945 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
946 pcsc_error_string (err), err);
947 return pcsc_error_to_sw (err);
951 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
952 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
953 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
954 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
955 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
956 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
957 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
958 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
959 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
960 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
961 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
964 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
966 *status |= APDU_CARD_PRESENT;
967 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
968 *status |= APDU_CARD_ACTIVE;
970 #ifndef HAVE_W32_SYSTEM
971 /* We indicate a useful card if it is not in use by another
972 application. This is because we only use exclusive access
974 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
975 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
976 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
977 *status |= APDU_CARD_USABLE;
979 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
980 time when we are the only user (SCM SCR335) under Windows. */
981 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
982 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
983 *status |= APDU_CARD_USABLE;
988 #endif /*!NEED_PCSC_WRAPPER*/
991 #ifdef NEED_PCSC_WRAPPER
993 pcsc_get_status_wrapped (int slot, unsigned int *status)
996 reader_table_t slotp;
997 size_t len, full_len;
999 unsigned char msgbuf[9];
1000 unsigned char buffer[16];
1001 int sw = SW_HOST_CARD_IO_ERROR;
1003 slotp = reader_table + slot;
1005 if (slotp->pcsc.req_fd == -1
1006 || slotp->pcsc.rsp_fd == -1
1007 || slotp->pcsc.pid == (pid_t)(-1) )
1009 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1013 msgbuf[0] = 0x04; /* STATUS command. */
1015 msgbuf[1] = (len >> 24);
1016 msgbuf[2] = (len >> 16);
1017 msgbuf[3] = (len >> 8);
1019 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1021 log_error ("error sending PC/SC STATUS request: %s\n",
1023 goto command_failed;
1026 /* Read the response. */
1027 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1029 log_error ("error receiving PC/SC STATUS response: %s\n",
1030 i? strerror (errno) : "premature EOF");
1031 goto command_failed;
1033 len = buf_to_size_t (msgbuf+1);
1034 if (msgbuf[0] != 0x81 || len < 4)
1036 log_error ("invalid response header from PC/SC received\n");
1037 goto command_failed;
1039 len -= 4; /* Already read the error code. */
1040 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1043 log_error ("pcsc_status failed: %s (0x%lx)\n",
1044 pcsc_error_string (err), err);
1045 /* This is a proper error code, so return immediately. */
1046 return pcsc_error_to_sw (err);
1051 /* The current version returns 3 words but we allow also for old
1052 versions returning only 2 words. */
1053 n = 12 < len ? 12 : len;
1054 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
1055 || (len != 8 && len != 12))
1057 log_error ("error receiving PC/SC STATUS response: %s\n",
1058 i? strerror (errno) : "premature EOF");
1059 goto command_failed;
1062 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
1066 /* Newer versions of the wrapper might send more status bytes.
1070 unsigned char dummybuf[128];
1072 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1073 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1075 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1076 i? strerror (errno) : "premature EOF");
1077 goto command_failed;
1082 /* We are lucky: The wrapper already returns the data in the
1084 *status = buffer[3];
1088 close (slotp->pcsc.req_fd);
1089 close (slotp->pcsc.rsp_fd);
1090 slotp->pcsc.req_fd = -1;
1091 slotp->pcsc.rsp_fd = -1;
1092 if (slotp->pcsc.pid != -1)
1093 kill (slotp->pcsc.pid, SIGTERM);
1094 slotp->pcsc.pid = (pid_t)(-1);
1098 #endif /*NEED_PCSC_WRAPPER*/
1102 pcsc_get_status (int slot, unsigned int *status)
1104 #ifdef NEED_PCSC_WRAPPER
1105 return pcsc_get_status_wrapped (slot, status);
1107 return pcsc_get_status_direct (slot, status);
1112 #ifndef NEED_PCSC_WRAPPER
1114 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
1115 unsigned char *buffer, size_t *buflen,
1119 struct pcsc_io_request_s send_pci;
1120 pcsc_dword_t recv_len;
1124 if (!reader_table[slot].atrlen
1125 && (err = reset_pcsc_reader (slot)))
1129 log_printhex (" PCSC_data:", apdu, apdulen);
1131 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1132 send_pci.protocol = PCSC_PROTOCOL_T1;
1134 send_pci.protocol = PCSC_PROTOCOL_T0;
1135 send_pci.pci_len = sizeof send_pci;
1137 err = pcsc_transmit (reader_table[slot].pcsc.card,
1138 &send_pci, apdu, apdulen,
1139 NULL, buffer, &recv_len);
1142 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1143 pcsc_error_string (err), err);
1145 return pcsc_error_to_sw (err);
1147 #endif /*!NEED_PCSC_WRAPPER*/
1150 #ifdef NEED_PCSC_WRAPPER
1152 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1153 unsigned char *buffer, size_t *buflen,
1157 reader_table_t slotp;
1158 size_t len, full_len;
1160 unsigned char msgbuf[9];
1161 int sw = SW_HOST_CARD_IO_ERROR;
1165 if (!reader_table[slot].atrlen
1166 && (err = reset_pcsc_reader (slot)))
1170 log_printhex (" PCSC_data:", apdu, apdulen);
1172 slotp = reader_table + slot;
1174 if (slotp->pcsc.req_fd == -1
1175 || slotp->pcsc.rsp_fd == -1
1176 || slotp->pcsc.pid == (pid_t)(-1) )
1178 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1182 msgbuf[0] = 0x03; /* TRANSMIT command. */
1184 msgbuf[1] = (len >> 24);
1185 msgbuf[2] = (len >> 16);
1186 msgbuf[3] = (len >> 8);
1188 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1189 || writen (slotp->pcsc.req_fd, apdu, len))
1191 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1193 goto command_failed;
1196 /* Read the response. */
1197 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1199 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1200 i? strerror (errno) : "premature EOF");
1201 goto command_failed;
1203 len = buf_to_size_t (msgbuf+1);
1204 if (msgbuf[0] != 0x81 || len < 4)
1206 log_error ("invalid response header from PC/SC received\n");
1207 goto command_failed;
1209 len -= 4; /* Already read the error code. */
1210 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1213 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1214 pcsc_error_string (err), err);
1215 return pcsc_error_to_sw (err);
1220 n = *buflen < len ? *buflen : len;
1221 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1223 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1224 i? strerror (errno) : "premature EOF");
1225 goto command_failed;
1232 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1233 err = SW_HOST_INV_VALUE;
1235 /* We need to read any rest of the response, to keep the
1236 protocol running. */
1239 unsigned char dummybuf[128];
1241 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1242 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1244 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1245 i? strerror (errno) : "premature EOF");
1246 goto command_failed;
1254 close (slotp->pcsc.req_fd);
1255 close (slotp->pcsc.rsp_fd);
1256 slotp->pcsc.req_fd = -1;
1257 slotp->pcsc.rsp_fd = -1;
1258 if (slotp->pcsc.pid != -1)
1259 kill (slotp->pcsc.pid, SIGTERM);
1260 slotp->pcsc.pid = (pid_t)(-1);
1264 #endif /*NEED_PCSC_WRAPPER*/
1267 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1268 *BUFLEN data in BUFFER, the actual returned size will be stored at
1269 BUFLEN. Returns: A status word. */
1271 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1272 unsigned char *buffer, size_t *buflen,
1275 #ifdef NEED_PCSC_WRAPPER
1276 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1278 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1283 #ifndef NEED_PCSC_WRAPPER
1285 control_pcsc_direct (int slot, pcsc_dword_t ioctl_code,
1286 const unsigned char *cntlbuf, size_t len,
1287 unsigned char *buffer, pcsc_dword_t *buflen)
1291 err = pcsc_control (reader_table[slot].pcsc.card, ioctl_code,
1292 cntlbuf, len, buffer, buflen? *buflen:0, buflen);
1295 log_error ("pcsc_control failed: %s (0x%lx)\n",
1296 pcsc_error_string (err), err);
1297 return pcsc_error_to_sw (err);
1302 #endif /*!NEED_PCSC_WRAPPER*/
1305 #ifdef NEED_PCSC_WRAPPER
1307 control_pcsc_wrapped (int slot, pcsc_dword_t ioctl_code,
1308 const unsigned char *cntlbuf, size_t len,
1309 unsigned char *buffer, pcsc_dword_t *buflen)
1311 long err = PCSC_E_NOT_TRANSACTED;
1312 reader_table_t slotp;
1313 unsigned char msgbuf[9];
1317 slotp = reader_table + slot;
1319 msgbuf[0] = 0x06; /* CONTROL command. */
1320 msgbuf[1] = ((len + 4) >> 24);
1321 msgbuf[2] = ((len + 4) >> 16);
1322 msgbuf[3] = ((len + 4) >> 8);
1323 msgbuf[4] = ((len + 4) );
1324 msgbuf[5] = (ioctl_code >> 24);
1325 msgbuf[6] = (ioctl_code >> 16);
1326 msgbuf[7] = (ioctl_code >> 8);
1327 msgbuf[8] = (ioctl_code );
1328 if ( writen (slotp->pcsc.req_fd, msgbuf, 9)
1329 || writen (slotp->pcsc.req_fd, cntlbuf, len))
1331 log_error ("error sending PC/SC CONTROL request: %s\n",
1333 goto command_failed;
1336 /* Read the response. */
1337 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1339 log_error ("error receiving PC/SC CONTROL response: %s\n",
1340 i? strerror (errno) : "premature EOF");
1341 goto command_failed;
1343 len = buf32_to_size_t (msgbuf+1);
1344 if (msgbuf[0] != 0x81 || len < 4)
1346 log_error ("invalid response header from PC/SC received\n");
1347 goto command_failed;
1349 len -= 4; /* Already read the error code. */
1350 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1353 log_error ("pcsc_control failed: %s (0x%lx)\n",
1354 pcsc_error_string (err), err);
1355 return pcsc_error_to_sw (err);
1361 n = *buflen < len ? *buflen : len;
1364 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1366 log_error ("error receiving PC/SC CONTROL response: %s\n",
1367 i? strerror (errno) : "premature EOF");
1368 goto command_failed;
1376 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1377 err = PCSC_E_INVALID_VALUE;
1379 /* We need to read any rest of the response, to keep the
1380 protocol running. */
1383 unsigned char dummybuf[128];
1385 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1386 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1388 log_error ("error receiving PC/SC CONTROL response: %s\n",
1389 i? strerror (errno) : "premature EOF");
1390 goto command_failed;
1399 close (slotp->pcsc.req_fd);
1400 close (slotp->pcsc.rsp_fd);
1401 slotp->pcsc.req_fd = -1;
1402 slotp->pcsc.rsp_fd = -1;
1403 if (slotp->pcsc.pid != -1)
1404 kill (slotp->pcsc.pid, SIGTERM);
1405 slotp->pcsc.pid = (pid_t)(-1);
1407 return pcsc_error_to_sw (err);
1409 #endif /*NEED_PCSC_WRAPPER*/
1413 /* Do some control with the value of IOCTL_CODE to the card inserted
1414 to SLOT. Input buffer is specified by CNTLBUF of length LEN.
1415 Output buffer is specified by BUFFER of length *BUFLEN, and the
1416 actual output size will be stored at BUFLEN. Returns: A status word.
1417 This routine is used for PIN pad input support. */
1419 control_pcsc (int slot, pcsc_dword_t ioctl_code,
1420 const unsigned char *cntlbuf, size_t len,
1421 unsigned char *buffer, pcsc_dword_t *buflen)
1423 #ifdef NEED_PCSC_WRAPPER
1424 return control_pcsc_wrapped (slot, ioctl_code, cntlbuf, len, buffer, buflen);
1426 return control_pcsc_direct (slot, ioctl_code, cntlbuf, len, buffer, buflen);
1431 #ifndef NEED_PCSC_WRAPPER
1433 close_pcsc_reader_direct (int slot)
1435 pcsc_release_context (reader_table[slot].pcsc.context);
1438 #endif /*!NEED_PCSC_WRAPPER*/
1441 #ifdef NEED_PCSC_WRAPPER
1443 close_pcsc_reader_wrapped (int slot)
1446 reader_table_t slotp;
1449 unsigned char msgbuf[9];
1451 slotp = reader_table + slot;
1453 if (slotp->pcsc.req_fd == -1
1454 || slotp->pcsc.rsp_fd == -1
1455 || slotp->pcsc.pid == (pid_t)(-1) )
1457 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1461 msgbuf[0] = 0x02; /* CLOSE command. */
1463 msgbuf[1] = (len >> 24);
1464 msgbuf[2] = (len >> 16);
1465 msgbuf[3] = (len >> 8);
1467 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1469 log_error ("error sending PC/SC CLOSE request: %s\n",
1471 goto command_failed;
1474 /* Read the response. */
1475 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1477 log_error ("error receiving PC/SC CLOSE response: %s\n",
1478 i? strerror (errno) : "premature EOF");
1479 goto command_failed;
1481 len = buf32_to_size_t (msgbuf+1);
1482 if (msgbuf[0] != 0x81 || len < 4)
1484 log_error ("invalid response header from PC/SC received\n");
1485 goto command_failed;
1487 len -= 4; /* Already read the error code. */
1488 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1490 log_error ("pcsc_close failed: %s (0x%lx)\n",
1491 pcsc_error_string (err), err);
1493 /* We will close the wrapper in any case - errors are merely
1497 close (slotp->pcsc.req_fd);
1498 close (slotp->pcsc.rsp_fd);
1499 slotp->pcsc.req_fd = -1;
1500 slotp->pcsc.rsp_fd = -1;
1501 if (slotp->pcsc.pid != -1)
1502 kill (slotp->pcsc.pid, SIGTERM);
1503 slotp->pcsc.pid = (pid_t)(-1);
1507 #endif /*NEED_PCSC_WRAPPER*/
1511 close_pcsc_reader (int slot)
1513 #ifdef NEED_PCSC_WRAPPER
1514 return close_pcsc_reader_wrapped (slot);
1516 return close_pcsc_reader_direct (slot);
1521 /* Connect a PC/SC card. */
1522 #ifndef NEED_PCSC_WRAPPER
1524 connect_pcsc_card (int slot)
1528 assert (slot >= 0 && slot < MAX_READER);
1530 if (reader_table[slot].pcsc.card)
1531 return SW_HOST_ALREADY_CONNECTED;
1533 reader_table[slot].atrlen = 0;
1534 reader_table[slot].is_t0 = 0;
1536 err = pcsc_connect (reader_table[slot].pcsc.context,
1537 reader_table[slot].rdrname,
1538 PCSC_SHARE_EXCLUSIVE,
1539 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1540 &reader_table[slot].pcsc.card,
1541 &reader_table[slot].pcsc.protocol);
1544 reader_table[slot].pcsc.card = 0;
1545 if (err != PCSC_E_NO_SMARTCARD)
1546 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1547 pcsc_error_string (err), err);
1552 pcsc_dword_t readerlen, atrlen;
1553 pcsc_dword_t card_state, card_protocol;
1555 pcsc_vendor_specific_init (slot);
1557 atrlen = DIM (reader_table[0].atr);
1558 readerlen = sizeof reader -1 ;
1559 err = pcsc_status (reader_table[slot].pcsc.card,
1561 &card_state, &card_protocol,
1562 reader_table[slot].atr, &atrlen);
1564 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1565 pcsc_error_string (err), err, (long unsigned int)readerlen);
1568 if (atrlen > DIM (reader_table[0].atr))
1569 log_bug ("ATR returned by pcsc_status is too large\n");
1570 reader_table[slot].atrlen = atrlen;
1571 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1575 dump_reader_status (slot);
1576 return pcsc_error_to_sw (err);
1578 #endif /*!NEED_PCSC_WRAPPER*/
1581 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1582 is not connected. */
1583 #ifndef NEED_PCSC_WRAPPER
1585 disconnect_pcsc_card (int slot)
1589 assert (slot >= 0 && slot < MAX_READER);
1591 if (!reader_table[slot].pcsc.card)
1594 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1597 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1598 pcsc_error_string (err), err);
1599 return SW_HOST_CARD_IO_ERROR;
1601 reader_table[slot].pcsc.card = 0;
1604 #endif /*!NEED_PCSC_WRAPPER*/
1607 #ifndef NEED_PCSC_WRAPPER
1609 reset_pcsc_reader_direct (int slot)
1613 sw = disconnect_pcsc_card (slot);
1615 sw = connect_pcsc_card (slot);
1619 #endif /*NEED_PCSC_WRAPPER*/
1622 #ifdef NEED_PCSC_WRAPPER
1624 reset_pcsc_reader_wrapped (int slot)
1627 reader_table_t slotp;
1630 unsigned char msgbuf[9];
1631 unsigned int dummy_status;
1632 int sw = SW_HOST_CARD_IO_ERROR;
1634 slotp = reader_table + slot;
1636 if (slotp->pcsc.req_fd == -1
1637 || slotp->pcsc.rsp_fd == -1
1638 || slotp->pcsc.pid == (pid_t)(-1) )
1640 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1644 msgbuf[0] = 0x05; /* RESET command. */
1646 msgbuf[1] = (len >> 24);
1647 msgbuf[2] = (len >> 16);
1648 msgbuf[3] = (len >> 8);
1650 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1652 log_error ("error sending PC/SC RESET request: %s\n",
1654 goto command_failed;
1657 /* Read the response. */
1658 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1660 log_error ("error receiving PC/SC RESET response: %s\n",
1661 i? strerror (errno) : "premature EOF");
1662 goto command_failed;
1664 len = buf32_to_size_t (msgbuf+1);
1665 if (msgbuf[0] != 0x81 || len < 4)
1667 log_error ("invalid response header from PC/SC received\n");
1668 goto command_failed;
1670 len -= 4; /* Already read the error code. */
1671 if (len > DIM (slotp->atr))
1673 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1674 (unsigned long)len);
1675 sw = SW_HOST_GENERAL_ERROR;
1676 goto command_failed;
1678 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1681 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1682 pcsc_error_string (err), err);
1683 /* If the error code is no smart card, we should not considere
1684 this a major error and close the wrapper. */
1685 sw = pcsc_error_to_sw (err);
1686 if (err == PCSC_E_NO_SMARTCARD)
1688 goto command_failed;
1691 /* The open function may return a zero for the ATR length to
1692 indicate that no card is present. */
1696 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1698 log_error ("error receiving PC/SC RESET response: %s\n",
1699 i? strerror (errno) : "premature EOF");
1700 goto command_failed;
1703 slotp->atrlen = len;
1705 /* Read the status so that IS_T0 will be set. */
1706 pcsc_get_status (slot, &dummy_status);
1711 close (slotp->pcsc.req_fd);
1712 close (slotp->pcsc.rsp_fd);
1713 slotp->pcsc.req_fd = -1;
1714 slotp->pcsc.rsp_fd = -1;
1715 if (slotp->pcsc.pid != -1)
1716 kill (slotp->pcsc.pid, SIGTERM);
1717 slotp->pcsc.pid = (pid_t)(-1);
1721 #endif /* !NEED_PCSC_WRAPPER */
1724 /* Send an PC/SC reset command and return a status word on error or 0
1727 reset_pcsc_reader (int slot)
1729 #ifdef NEED_PCSC_WRAPPER
1730 return reset_pcsc_reader_wrapped (slot);
1732 return reset_pcsc_reader_direct (slot);
1737 /* Examine reader specific parameters and initialize. This is mostly
1738 for pinpad input. Called at opening the connection to the reader. */
1740 pcsc_vendor_specific_init (int slot)
1742 unsigned char buf[256];
1747 pcsc_dword_t get_tlv_ioctl = (pcsc_dword_t)-1;
1751 sw = control_pcsc (slot, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, &len);
1754 log_error ("pcsc_vendor_specific_init: GET_FEATURE_REQUEST failed: %d\n",
1756 return SW_NOT_SUPPORTED;
1761 while (p < buf + len)
1763 unsigned char code = *p++;
1770 v = buf16_to_uint (p);
1772 v = buf32_to_uint (p);
1774 if (code == FEATURE_VERIFY_PIN_DIRECT)
1775 reader_table[slot].pcsc.verify_ioctl = v;
1776 else if (code == FEATURE_MODIFY_PIN_DIRECT)
1777 reader_table[slot].pcsc.modify_ioctl = v;
1778 else if (code == FEATURE_GET_TLV_PROPERTIES)
1782 log_debug ("feature: code=%02X, len=%d, v=%02X\n", code, l, v);
1788 if (get_tlv_ioctl == (pcsc_dword_t)-1)
1791 * For system which doesn't support GET_TLV_PROPERTIES,
1792 * we put some heuristics here.
1794 if (reader_table[slot].rdrname)
1796 if (strstr (reader_table[slot].rdrname, "SPRx32"))
1798 reader_table[slot].is_spr532 = 1;
1799 reader_table[slot].pinpad_varlen_supported = 1;
1801 else if (strstr (reader_table[slot].rdrname, "ST-2xxx"))
1803 reader_table[slot].pcsc.pinmax = 15;
1804 reader_table[slot].pinpad_varlen_supported = 1;
1806 else if (strstr (reader_table[slot].rdrname, "cyberJack")
1807 || strstr (reader_table[slot].rdrname, "DIGIPASS")
1808 || strstr (reader_table[slot].rdrname, "Gnuk")
1809 || strstr (reader_table[slot].rdrname, "KAAN"))
1810 reader_table[slot].pinpad_varlen_supported = 1;
1817 sw = control_pcsc (slot, get_tlv_ioctl, NULL, 0, buf, &len);
1820 log_error ("pcsc_vendor_specific_init: GET_TLV_IOCTL failed: %d\n", sw);
1821 return SW_NOT_SUPPORTED;
1825 while (p < buf + len)
1827 unsigned char tag = *p++;
1831 /* Umm... here is little endian, while the encoding above is big. */
1835 v = (((unsigned int)p[1] << 8) | p[0]);
1837 v = (((unsigned int)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
1839 if (tag == PCSCv2_PART10_PROPERTY_bMinPINSize)
1840 reader_table[slot].pcsc.pinmin = v;
1841 else if (tag == PCSCv2_PART10_PROPERTY_bMaxPINSize)
1842 reader_table[slot].pcsc.pinmax = v;
1843 else if (tag == PCSCv2_PART10_PROPERTY_wIdVendor)
1845 else if (tag == PCSCv2_PART10_PROPERTY_wIdProduct)
1849 log_debug ("TLV properties: tag=%02X, len=%d, v=%08X\n", tag, l, v);
1854 if (vendor == VENDOR_VEGA && product == VEGA_ALPHA)
1857 * Please read the comment of ccid_vendor_specific_init in
1860 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1861 sw = control_pcsc (slot, CM_IOCTL_VENDOR_IFD_EXCHANGE,
1862 cmd, sizeof (cmd), NULL, 0);
1864 return SW_NOT_SUPPORTED;
1866 else if (vendor == VENDOR_SCM && product == SCM_SPR532) /* SCM SPR532 */
1868 reader_table[slot].is_spr532 = 1;
1869 reader_table[slot].pinpad_varlen_supported = 1;
1871 else if (vendor == 0x046a)
1873 /* Cherry ST-2xxx (product == 0x003e) supports TPDU level
1874 * exchange. Other products which only support short APDU level
1875 * exchange only work with shorter keys like RSA 1024.
1877 reader_table[slot].pcsc.pinmax = 15;
1878 reader_table[slot].pinpad_varlen_supported = 1;
1880 else if (vendor == 0x0c4b /* Tested with Reiner cyberJack GO */
1881 || vendor == 0x1a44 /* Tested with Vasco DIGIPASS 920 */
1882 || vendor == 0x234b /* Tested with FSIJ Gnuk Token */
1883 || vendor == 0x0d46 /* Tested with KAAN Advanced??? */)
1884 reader_table[slot].pinpad_varlen_supported = 1;
1890 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1891 error or a slot number for the reader. */
1892 #ifndef NEED_PCSC_WRAPPER
1894 open_pcsc_reader_direct (const char *portstr)
1899 char *rdrname = NULL;
1900 pcsc_dword_t nreader;
1903 slot = new_reader_slot ();
1907 /* Fixme: Allocating a context for each slot is not required. One
1908 global context should be sufficient. */
1909 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1910 &reader_table[slot].pcsc.context);
1913 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1914 pcsc_error_string (err), err);
1915 reader_table[slot].used = 0;
1920 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1921 NULL, NULL, &nreader);
1924 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1927 log_error ("error allocating memory for reader list\n");
1928 pcsc_release_context (reader_table[slot].pcsc.context);
1929 reader_table[slot].used = 0;
1931 return -1 /*SW_HOST_OUT_OF_CORE*/;
1933 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1934 NULL, list, &nreader);
1938 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1939 pcsc_error_string (err), err);
1940 pcsc_release_context (reader_table[slot].pcsc.context);
1941 reader_table[slot].used = 0;
1952 log_info ("detected reader '%s'\n", p);
1953 if (nreader < (strlen (p)+1))
1955 log_error ("invalid response from pcsc_list_readers\n");
1958 if (!rdrname && portstr && !strncmp (p, portstr, strlen (portstr)))
1960 nreader -= strlen (p)+1;
1961 p += strlen (p) + 1;
1967 reader_table[slot].rdrname = xtrystrdup (rdrname);
1968 if (!reader_table[slot].rdrname)
1970 log_error ("error allocating memory for reader name\n");
1971 pcsc_release_context (reader_table[slot].pcsc.context);
1972 reader_table[slot].used = 0;
1979 reader_table[slot].pcsc.card = 0;
1980 reader_table[slot].atrlen = 0;
1982 reader_table[slot].connect_card = connect_pcsc_card;
1983 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1984 reader_table[slot].close_reader = close_pcsc_reader;
1985 reader_table[slot].reset_reader = reset_pcsc_reader;
1986 reader_table[slot].get_status_reader = pcsc_get_status;
1987 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1988 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1990 dump_reader_status (slot);
1994 #endif /*!NEED_PCSC_WRAPPER */
1997 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1998 needed to cope with different thread models and other peculiarities
2000 #ifdef NEED_PCSC_WRAPPER
2002 open_pcsc_reader_wrapped (const char *portstr)
2005 reader_table_t slotp;
2006 int fd, rp[2], wp[2];
2010 unsigned char msgbuf[9];
2012 unsigned int dummy_status;
2014 /* Note that we use the constant and not the function because this
2015 code won't be be used under Windows. */
2016 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
2018 if (access (wrapperpgm, X_OK))
2020 log_error ("can't run PC/SC access module '%s': %s\n",
2021 wrapperpgm, strerror (errno));
2025 slot = new_reader_slot ();
2028 slotp = reader_table + slot;
2030 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
2031 the common directy but implement it directly so that this file
2032 may still be source copied. */
2034 if (pipe (rp) == -1)
2036 log_error ("error creating a pipe: %s\n", strerror (errno));
2041 if (pipe (wp) == -1)
2043 log_error ("error creating a pipe: %s\n", strerror (errno));
2054 log_error ("error forking process: %s\n", strerror (errno));
2063 slotp->pcsc.pid = pid;
2075 _exit (0); /* Immediate exit this parent, so that the child
2076 gets cleaned up by the init process. */
2078 /* Connect our pipes. */
2079 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
2080 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
2081 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
2082 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
2084 /* Send stderr to the bit bucket. */
2085 fd = open ("/dev/null", O_WRONLY);
2087 log_fatal ("can't open '/dev/null': %s", strerror (errno));
2088 if (fd != 2 && dup2 (fd, 2) == -1)
2089 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
2091 /* Close all other files. */
2092 close_all_fds (3, NULL);
2097 "1", /* API version */
2098 opt.pcsc_driver, /* Name of the PC/SC library. */
2108 slotp->pcsc.req_fd = wp[1];
2109 slotp->pcsc.rsp_fd = rp[0];
2111 /* Wait for the intermediate child to terminate. */
2113 #define WAIT npth_waitpid
2115 #define WAIT waitpid
2117 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
2121 /* Now send the open request. */
2122 msgbuf[0] = 0x01; /* OPEN command. */
2123 len = portstr? strlen (portstr):0;
2124 msgbuf[1] = (len >> 24);
2125 msgbuf[2] = (len >> 16);
2126 msgbuf[3] = (len >> 8);
2128 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
2129 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
2131 log_error ("error sending PC/SC OPEN request: %s\n",
2133 goto command_failed;
2135 /* Read the response. */
2136 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
2138 log_error ("error receiving PC/SC OPEN response: %s\n",
2139 i? strerror (errno) : "premature EOF");
2140 goto command_failed;
2142 len = buf32_to_size_t (msgbuf+1);
2143 if (msgbuf[0] != 0x81 || len < 4)
2145 log_error ("invalid response header from PC/SC received\n");
2146 goto command_failed;
2148 len -= 4; /* Already read the error code. */
2149 if (len > DIM (slotp->atr))
2151 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
2152 (unsigned long)len);
2153 goto command_failed;
2155 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
2158 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
2159 goto command_failed;
2162 /* The open request may return a zero for the ATR length to
2163 indicate that no card is present. */
2167 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
2169 log_error ("error receiving PC/SC OPEN response: %s\n",
2170 i? strerror (errno) : "premature EOF");
2171 goto command_failed;
2174 slotp->atrlen = len;
2176 reader_table[slot].close_reader = close_pcsc_reader;
2177 reader_table[slot].reset_reader = reset_pcsc_reader;
2178 reader_table[slot].get_status_reader = pcsc_get_status;
2179 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
2180 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
2182 pcsc_vendor_specific_init (slot);
2184 /* Read the status so that IS_T0 will be set. */
2185 pcsc_get_status (slot, &dummy_status);
2187 dump_reader_status (slot);
2192 close (slotp->pcsc.req_fd);
2193 close (slotp->pcsc.rsp_fd);
2194 slotp->pcsc.req_fd = -1;
2195 slotp->pcsc.rsp_fd = -1;
2196 if (slotp->pcsc.pid != -1)
2197 kill (slotp->pcsc.pid, SIGTERM);
2198 slotp->pcsc.pid = (pid_t)(-1);
2201 /* There is no way to return SW. */
2205 #endif /*NEED_PCSC_WRAPPER*/
2209 open_pcsc_reader (const char *portstr)
2211 #ifdef NEED_PCSC_WRAPPER
2212 return open_pcsc_reader_wrapped (portstr);
2214 return open_pcsc_reader_direct (portstr);
2219 /* Check whether the reader supports the ISO command code COMMAND
2220 on the pinpad. Return 0 on success. */
2222 check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo)
2226 if (reader_table[slot].pcsc.pinmin >= 0)
2227 pininfo->minlen = reader_table[slot].pcsc.pinmin;
2229 if (reader_table[slot].pcsc.pinmax >= 0)
2230 pininfo->maxlen = reader_table[slot].pcsc.pinmax;
2232 if (!pininfo->minlen)
2233 pininfo->minlen = 1;
2234 if (!pininfo->maxlen)
2235 pininfo->maxlen = 15;
2237 if ((command == ISO7816_VERIFY && reader_table[slot].pcsc.verify_ioctl != 0)
2238 || (command == ISO7816_CHANGE_REFERENCE_DATA
2239 && reader_table[slot].pcsc.modify_ioctl != 0))
2240 r = 0; /* Success */
2242 r = SW_NOT_SUPPORTED;
2245 log_debug ("check_pcsc_pinpad: command=%02X, r=%d\n",
2246 (unsigned int)command, r);
2248 if (reader_table[slot].pinpad_varlen_supported)
2249 pininfo->fixedlen = 0;
2254 #define PIN_VERIFY_STRUCTURE_SIZE 24
2256 pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
2260 unsigned char *pin_verify;
2261 int len = PIN_VERIFY_STRUCTURE_SIZE + pininfo->fixedlen;
2263 * The result buffer is only expected to have two-byte result on
2264 * return. However, some implementation uses this buffer for lower
2265 * layer too and it assumes that there is enough space for lower
2266 * layer communication. Such an implementation fails for TPDU
2267 * readers with "insufficient buffer", as it needs header and
2268 * trailer. Six is the number for header + result + trailer (TPDU).
2270 unsigned char result[6];
2271 pcsc_dword_t resultlen = 6;
2274 if (!reader_table[slot].atrlen
2275 && (sw = reset_pcsc_reader (slot)))
2278 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
2279 return SW_NOT_SUPPORTED;
2281 pin_verify = xtrymalloc (len);
2283 return SW_HOST_OUT_OF_CORE;
2285 no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
2287 pin_verify[0] = 0x00; /* bTimeOut */
2288 pin_verify[1] = 0x00; /* bTimeOut2 */
2289 pin_verify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2290 pin_verify[3] = pininfo->fixedlen; /* bmPINBlockString */
2291 pin_verify[4] = 0x00; /* bmPINLengthFormat */
2292 pin_verify[5] = pininfo->maxlen; /* wPINMaxExtraDigit */
2293 pin_verify[6] = pininfo->minlen; /* wPINMaxExtraDigit */
2294 pin_verify[7] = 0x02; /* bEntryValidationCondition: Validation key pressed */
2295 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
2296 pin_verify[7] |= 0x01; /* Max size reached. */
2297 pin_verify[8] = 0x01; /* bNumberMessage: One message */
2298 pin_verify[9] = 0x09; /* wLangId: 0x0409: US English */
2299 pin_verify[10] = 0x04; /* wLangId: 0x0409: US English */
2300 pin_verify[11] = 0x00; /* bMsgIndex */
2301 pin_verify[12] = 0x00; /* bTeoPrologue[0] */
2302 pin_verify[13] = 0x00; /* bTeoPrologue[1] */
2303 pin_verify[14] = pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
2304 pin_verify[15] = pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
2305 pin_verify[16] = 0x00; /* ulDataLength */
2306 pin_verify[17] = 0x00; /* ulDataLength */
2307 pin_verify[18] = 0x00; /* ulDataLength */
2308 pin_verify[19] = class; /* abData[0] */
2309 pin_verify[20] = ins; /* abData[1] */
2310 pin_verify[21] = p0; /* abData[2] */
2311 pin_verify[22] = p1; /* abData[3] */
2312 pin_verify[23] = pininfo->fixedlen; /* abData[4] */
2313 if (pininfo->fixedlen)
2314 memset (&pin_verify[24], 0xff, pininfo->fixedlen);
2319 log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
2320 class, ins, p0, p1, len, pininfo->maxlen);
2322 sw = control_pcsc (slot, reader_table[slot].pcsc.verify_ioctl,
2323 pin_verify, len, result, &resultlen);
2325 if (sw || resultlen < 2)
2327 log_error ("control_pcsc failed: %d\n", sw);
2328 return sw? sw: SW_HOST_INCOMPLETE_CARD_RESPONSE;
2330 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2332 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
2337 #define PIN_MODIFY_STRUCTURE_SIZE 29
2339 pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
2343 unsigned char *pin_modify;
2344 int len = PIN_MODIFY_STRUCTURE_SIZE + 2 * pininfo->fixedlen;
2345 unsigned char result[6]; /* See the comment at pinpad_verify. */
2346 pcsc_dword_t resultlen = 6;
2349 if (!reader_table[slot].atrlen
2350 && (sw = reset_pcsc_reader (slot)))
2353 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
2354 return SW_NOT_SUPPORTED;
2356 pin_modify = xtrymalloc (len);
2358 return SW_HOST_OUT_OF_CORE;
2360 no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
2362 pin_modify[0] = 0x00; /* bTimeOut */
2363 pin_modify[1] = 0x00; /* bTimeOut2 */
2364 pin_modify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2365 pin_modify[3] = pininfo->fixedlen; /* bmPINBlockString */
2366 pin_modify[4] = 0x00; /* bmPINLengthFormat */
2367 pin_modify[5] = 0x00; /* bInsertionOffsetOld */
2368 pin_modify[6] = pininfo->fixedlen; /* bInsertionOffsetNew */
2369 pin_modify[7] = pininfo->maxlen; /* wPINMaxExtraDigit */
2370 pin_modify[8] = pininfo->minlen; /* wPINMaxExtraDigit */
2371 pin_modify[9] = (p0 == 0 ? 0x03 : 0x01);
2373 * 0x00: new PIN once
2374 * 0x01: new PIN twice (confirmation)
2375 * 0x02: old PIN and new PIN once
2376 * 0x03: old PIN and new PIN twice (confirmation)
2378 pin_modify[10] = 0x02; /* bEntryValidationCondition: Validation key pressed */
2379 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
2380 pin_modify[10] |= 0x01; /* Max size reached. */
2381 pin_modify[11] = 0x03; /* bNumberMessage: Three messages */
2382 pin_modify[12] = 0x09; /* wLangId: 0x0409: US English */
2383 pin_modify[13] = 0x04; /* wLangId: 0x0409: US English */
2384 pin_modify[14] = 0x00; /* bMsgIndex1 */
2385 pin_modify[15] = 0x01; /* bMsgIndex2 */
2386 pin_modify[16] = 0x02; /* bMsgIndex3 */
2387 pin_modify[17] = 0x00; /* bTeoPrologue[0] */
2388 pin_modify[18] = 0x00; /* bTeoPrologue[1] */
2389 pin_modify[19] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
2390 pin_modify[20] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
2391 pin_modify[21] = 0x00; /* ulDataLength */
2392 pin_modify[22] = 0x00; /* ulDataLength */
2393 pin_modify[23] = 0x00; /* ulDataLength */
2394 pin_modify[24] = class; /* abData[0] */
2395 pin_modify[25] = ins; /* abData[1] */
2396 pin_modify[26] = p0; /* abData[2] */
2397 pin_modify[27] = p1; /* abData[3] */
2398 pin_modify[28] = 2 * pininfo->fixedlen; /* abData[4] */
2399 if (pininfo->fixedlen)
2400 memset (&pin_modify[29], 0xff, 2 * pininfo->fixedlen);
2405 log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
2406 class, ins, p0, p1, len, (int)pininfo->maxlen);
2408 sw = control_pcsc (slot, reader_table[slot].pcsc.modify_ioctl,
2409 pin_modify, len, result, &resultlen);
2411 if (sw || resultlen < 2)
2413 log_error ("control_pcsc failed: %d\n", sw);
2414 return sw? sw : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2416 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2418 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
2424 Internal CCID driver interface.
2429 dump_ccid_reader_status (int slot)
2431 log_info ("reader slot %d: using ccid driver\n", slot);
2435 close_ccid_reader (int slot)
2437 ccid_close_reader (reader_table[slot].ccid.handle);
2443 reset_ccid_reader (int slot)
2446 reader_table_t slotp = reader_table + slot;
2447 unsigned char atr[33];
2450 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
2453 /* If the reset was successful, update the ATR. */
2454 assert (sizeof slotp->atr >= sizeof atr);
2455 slotp->atrlen = atrlen;
2456 memcpy (slotp->atr, atr, atrlen);
2457 dump_reader_status (slot);
2463 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
2465 reader_table_t slotp = reader_table + slot;
2467 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
2472 get_status_ccid (int slot, unsigned int *status)
2477 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
2482 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
2484 *status = APDU_CARD_PRESENT;
2492 /* Actually send the APDU of length APDULEN to SLOT and return a
2493 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2494 set to BUFLEN. Returns: Internal CCID driver error code. */
2496 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
2497 unsigned char *buffer, size_t *buflen,
2503 /* If we don't have an ATR, we need to reset the reader first. */
2504 if (!reader_table[slot].atrlen
2505 && (err = reset_ccid_reader (slot)))
2509 log_printhex (" raw apdu:", apdu, apdulen);
2511 maxbuflen = *buflen;
2513 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
2514 apdu, apdulen, pininfo,
2515 buffer, maxbuflen, buflen);
2517 err = ccid_transceive (reader_table[slot].ccid.handle,
2519 buffer, maxbuflen, buflen);
2521 log_error ("ccid_transceive failed: (0x%lx)\n",
2528 /* Check whether the CCID reader supports the ISO command code COMMAND
2529 on the pinpad. Return 0 on success. For a description of the pin
2530 parameters, see ccid-driver.c */
2532 check_ccid_pinpad (int slot, int command, pininfo_t *pininfo)
2534 unsigned char apdu[] = { 0, 0, 0, 0x81 };
2537 return ccid_transceive_secure (reader_table[slot].ccid.handle, apdu,
2538 sizeof apdu, pininfo, NULL, 0, NULL);
2543 ccid_pinpad_operation (int slot, int class, int ins, int p0, int p1,
2546 unsigned char apdu[4];
2548 unsigned char result[2];
2549 size_t resultlen = 2;
2555 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
2556 apdu, sizeof apdu, pininfo,
2557 result, 2, &resultlen);
2562 return SW_HOST_INCOMPLETE_CARD_RESPONSE;
2564 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2569 /* Open the reader and try to read an ATR. */
2571 open_ccid_reader (struct dev_list *dl)
2575 reader_table_t slotp;
2577 slot = new_reader_slot ();
2580 slotp = reader_table + slot;
2582 err = ccid_open_reader (dl->portstr, dl->idx, dl->ccid_table,
2583 &slotp->ccid.handle, &slotp->rdrname);
2591 err = ccid_get_atr (slotp->ccid.handle,
2592 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
2599 reader_table[slot].close_reader = close_ccid_reader;
2600 reader_table[slot].reset_reader = reset_ccid_reader;
2601 reader_table[slot].get_status_reader = get_status_ccid;
2602 reader_table[slot].send_apdu_reader = send_apdu_ccid;
2603 reader_table[slot].check_pinpad = check_ccid_pinpad;
2604 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
2605 reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
2606 reader_table[slot].pinpad_verify = ccid_pinpad_operation;
2607 reader_table[slot].pinpad_modify = ccid_pinpad_operation;
2608 /* Our CCID reader code does not support T=0 at all, thus reset the
2610 reader_table[slot].is_t0 = 0;
2612 dump_reader_status (slot);
2616 #endif /* HAVE_LIBUSB */
2618 #ifdef USE_G10CODE_RAPDU
2620 The Remote APDU Interface.
2622 This uses the Remote APDU protocol to contact a reader.
2624 The port number is actually an index into the list of ports as
2625 returned via the protocol.
2630 rapdu_status_to_sw (int status)
2636 case RAPDU_STATUS_SUCCESS: rc = 0; break;
2638 case RAPDU_STATUS_INVCMD:
2639 case RAPDU_STATUS_INVPROT:
2640 case RAPDU_STATUS_INVSEQ:
2641 case RAPDU_STATUS_INVCOOKIE:
2642 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
2644 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
2645 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
2646 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
2647 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
2648 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2649 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2651 default: rc = SW_HOST_GENERAL_ERROR; break;
2660 close_rapdu_reader (int slot)
2662 rapdu_release (reader_table[slot].rapdu.handle);
2668 reset_rapdu_reader (int slot)
2671 reader_table_t slotp;
2672 rapdu_msg_t msg = NULL;
2674 slotp = reader_table + slot;
2676 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2679 log_error ("sending rapdu command RESET failed: %s\n",
2680 err < 0 ? strerror (errno): rapdu_strerror (err));
2681 rapdu_msg_release (msg);
2682 return rapdu_status_to_sw (err);
2684 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2687 log_error ("receiving rapdu message failed: %s\n",
2688 err < 0 ? strerror (errno): rapdu_strerror (err));
2689 rapdu_msg_release (msg);
2690 return rapdu_status_to_sw (err);
2692 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2694 int sw = rapdu_status_to_sw (msg->cmd);
2695 log_error ("rapdu command RESET failed: %s\n",
2696 rapdu_strerror (msg->cmd));
2697 rapdu_msg_release (msg);
2700 if (msg->datalen > DIM (slotp->atr))
2702 log_error ("ATR returned by the RAPDU layer is too large\n");
2703 rapdu_msg_release (msg);
2704 return SW_HOST_INV_VALUE;
2706 slotp->atrlen = msg->datalen;
2707 memcpy (slotp->atr, msg->data, msg->datalen);
2709 rapdu_msg_release (msg);
2715 my_rapdu_get_status (int slot, unsigned int *status)
2718 reader_table_t slotp;
2719 rapdu_msg_t msg = NULL;
2722 slotp = reader_table + slot;
2724 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2725 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2726 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2729 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2730 err < 0 ? strerror (errno): rapdu_strerror (err));
2731 return rapdu_status_to_sw (err);
2733 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2736 log_error ("receiving rapdu message failed: %s\n",
2737 err < 0 ? strerror (errno): rapdu_strerror (err));
2738 rapdu_msg_release (msg);
2739 return rapdu_status_to_sw (err);
2741 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2743 int sw = rapdu_status_to_sw (msg->cmd);
2744 log_error ("rapdu command GET_STATUS failed: %s\n",
2745 rapdu_strerror (msg->cmd));
2746 rapdu_msg_release (msg);
2749 *status = msg->data[0];
2751 rapdu_msg_release (msg);
2756 /* Actually send the APDU of length APDULEN to SLOT and return a
2757 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2758 set to BUFLEN. Returns: APDU error code. */
2760 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2761 unsigned char *buffer, size_t *buflen,
2765 reader_table_t slotp;
2766 rapdu_msg_t msg = NULL;
2767 size_t maxlen = *buflen;
2769 slotp = reader_table + slot;
2773 log_printhex (" APDU_data:", apdu, apdulen);
2777 log_error ("rapdu_send_apdu: APDU is too short\n");
2778 return SW_HOST_INV_VALUE;
2781 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2784 log_error ("sending rapdu command APDU failed: %s\n",
2785 err < 0 ? strerror (errno): rapdu_strerror (err));
2786 rapdu_msg_release (msg);
2787 return rapdu_status_to_sw (err);
2789 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2792 log_error ("receiving rapdu message failed: %s\n",
2793 err < 0 ? strerror (errno): rapdu_strerror (err));
2794 rapdu_msg_release (msg);
2795 return rapdu_status_to_sw (err);
2797 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2799 int sw = rapdu_status_to_sw (msg->cmd);
2800 log_error ("rapdu command APDU failed: %s\n",
2801 rapdu_strerror (msg->cmd));
2802 rapdu_msg_release (msg);
2806 if (msg->datalen > maxlen)
2808 log_error ("rapdu response apdu too large\n");
2809 rapdu_msg_release (msg);
2810 return SW_HOST_INV_VALUE;
2813 *buflen = msg->datalen;
2814 memcpy (buffer, msg->data, msg->datalen);
2816 rapdu_msg_release (msg);
2821 open_rapdu_reader (int portno,
2822 const unsigned char *cookie, size_t length,
2823 int (*readfnc) (void *opaque,
2824 void *buffer, size_t size),
2825 void *readfnc_value,
2826 int (*writefnc) (void *opaque,
2827 const void *buffer, size_t size),
2828 void *writefnc_value,
2829 void (*closefnc) (void *opaque),
2830 void *closefnc_value)
2834 reader_table_t slotp;
2835 rapdu_msg_t msg = NULL;
2837 slot = new_reader_slot ();
2840 slotp = reader_table + slot;
2842 slotp->rapdu.handle = rapdu_new ();
2843 if (!slotp->rapdu.handle)
2850 rapdu_set_reader (slotp->rapdu.handle, portno);
2852 rapdu_set_iofunc (slotp->rapdu.handle,
2853 readfnc, readfnc_value,
2854 writefnc, writefnc_value,
2855 closefnc, closefnc_value);
2856 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2858 /* First try to get the current ATR, but if the card is inactive
2859 issue a reset instead. */
2860 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2861 if (err == RAPDU_STATUS_NEEDRESET)
2862 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2865 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2866 err < 0 ? strerror (errno): rapdu_strerror (err));
2869 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2872 log_info ("receiving rapdu message failed: %s\n",
2873 err < 0 ? strerror (errno): rapdu_strerror (err));
2876 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2878 log_info ("rapdu command GET ATR failed: %s\n",
2879 rapdu_strerror (msg->cmd));
2882 if (msg->datalen > DIM (slotp->atr))
2884 log_error ("ATR returned by the RAPDU layer is too large\n");
2887 slotp->atrlen = msg->datalen;
2888 memcpy (slotp->atr, msg->data, msg->datalen);
2890 reader_table[slot].close_reader = close_rapdu_reader;
2891 reader_table[slot].reset_reader = reset_rapdu_reader;
2892 reader_table[slot].get_status_reader = my_rapdu_get_status;
2893 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2894 reader_table[slot].check_pinpad = NULL;
2895 reader_table[slot].dump_status_reader = NULL;
2896 reader_table[slot].pinpad_verify = NULL;
2897 reader_table[slot].pinpad_modify = NULL;
2899 dump_reader_status (slot);
2900 rapdu_msg_release (msg);
2905 rapdu_msg_release (msg);
2906 rapdu_release (slotp->rapdu.handle);
2912 #endif /*USE_G10CODE_RAPDU*/
2920 apdu_dev_list_start (const char *portstr, struct dev_list **l_p)
2922 struct dev_list *dl = xtrymalloc (sizeof (struct dev_list));
2926 return gpg_error_from_syserror ();
2928 dl->portstr = portstr;
2931 npth_mutex_lock (&reader_table_lock);
2934 if (opt.disable_ccid)
2936 dl->ccid_table = NULL;
2943 err = ccid_dev_scan (&dl->idx_max, &dl->ccid_table);
2947 if (dl->idx_max == 0)
2949 /* If a CCID reader specification has been given, the user does
2950 not want a fallback to other drivers. */
2951 if (portstr && strlen (portstr) > 5 && portstr[4] == ':')
2954 log_debug ("leave: apdu_open_reader => slot=-1 (no ccid)\n");
2957 npth_mutex_unlock (&reader_table_lock);
2958 return gpg_error (GPG_ERR_ENODEV);
2965 dl->ccid_table = NULL;
2967 #endif /* HAVE_LIBUSB */
2974 apdu_dev_list_finish (struct dev_list *dl)
2978 ccid_dev_scan_finish (dl->ccid_table, dl->idx_max);
2981 npth_mutex_unlock (&reader_table_lock);
2985 /* Open the reader and return an internal slot number or -1 on
2986 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2987 the first USB reader. For PC/SC the first listed reader). */
2989 apdu_open_one_reader (const char *portstr)
2991 static int pcsc_api_loaded, ct_api_loaded;
2995 log_debug ("enter: apdu_open_reader: portstr=%s\n", portstr);
2997 if (opt.ctapi_driver && *opt.ctapi_driver)
2999 int port = portstr? atoi (portstr) : 32768;
3005 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
3008 log_error ("apdu_open_reader: failed to open driver: %s\n",
3012 CT_init = dlsym (handle, "CT_init");
3013 CT_data = dlsym (handle, "CT_data");
3014 CT_close = dlsym (handle, "CT_close");
3015 if (!CT_init || !CT_data || !CT_close)
3017 log_error ("apdu_open_reader: invalid CT-API driver\n");
3023 return open_ct_reader (port);
3026 /* No ctAPI configured, so lets try the PC/SC API */
3027 if (!pcsc_api_loaded)
3029 #ifndef NEED_PCSC_WRAPPER
3032 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
3035 log_error ("apdu_open_reader: failed to open driver '%s': %s\n",
3036 opt.pcsc_driver, dlerror ());
3040 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
3041 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
3042 pcsc_list_readers = dlsym (handle, "SCardListReaders");
3043 #if defined(_WIN32) || defined(__CYGWIN__)
3044 if (!pcsc_list_readers)
3045 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
3047 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
3048 #if defined(_WIN32) || defined(__CYGWIN__)
3049 if (!pcsc_get_status_change)
3050 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
3052 pcsc_connect = dlsym (handle, "SCardConnect");
3053 #if defined(_WIN32) || defined(__CYGWIN__)
3055 pcsc_connect = dlsym (handle, "SCardConnectA");
3057 pcsc_reconnect = dlsym (handle, "SCardReconnect");
3058 #if defined(_WIN32) || defined(__CYGWIN__)
3059 if (!pcsc_reconnect)
3060 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
3062 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
3063 pcsc_status = dlsym (handle, "SCardStatus");
3064 #if defined(_WIN32) || defined(__CYGWIN__)
3066 pcsc_status = dlsym (handle, "SCardStatusA");
3068 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
3069 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
3070 pcsc_transmit = dlsym (handle, "SCardTransmit");
3071 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
3072 pcsc_control = dlsym (handle, "SCardControl");
3074 if (!pcsc_establish_context
3075 || !pcsc_release_context
3076 || !pcsc_list_readers
3077 || !pcsc_get_status_change
3082 || !pcsc_begin_transaction
3083 || !pcsc_end_transaction
3086 /* || !pcsc_set_timeout */)
3088 /* Note that set_timeout is currently not used and also not
3089 available under Windows. */
3090 log_error ("apdu_open_reader: invalid PC/SC driver "
3091 "(%d%d%d%d%d%d%d%d%d%d%d%d%d)\n",
3092 !!pcsc_establish_context,
3093 !!pcsc_release_context,
3094 !!pcsc_list_readers,
3095 !!pcsc_get_status_change,
3100 !!pcsc_begin_transaction,
3101 !!pcsc_end_transaction,
3108 #endif /*!NEED_PCSC_WRAPPER*/
3109 pcsc_api_loaded = 1;
3112 slot = open_pcsc_reader (portstr);
3115 log_debug ("leave: apdu_open_reader => slot=%d [pc/sc]\n", slot);
3120 apdu_open_reader (struct dev_list *dl)
3126 { /* CCID readers. */
3129 /* See whether we want to use the reader ID string or a reader
3130 number. A readerno of -1 indicates that the reader ID string is
3132 if (dl->portstr && strchr (dl->portstr, ':'))
3133 readerno = -1; /* We want to use the readerid. */
3134 else if (dl->portstr)
3136 readerno = atoi (dl->portstr);
3143 readerno = 0; /* Default. */
3146 { /* Use single, the specific reader. */
3147 if (readerno >= dl->idx_max)
3152 slot = open_ccid_reader (dl);
3153 dl->idx = dl->idx_max;
3160 while (dl->idx < dl->idx_max)
3162 unsigned int bai = ccid_get_BAI (dl->idx, dl->ccid_table);
3165 log_debug ("apdu_open_reader: BAI=%x\n", bai);
3167 /* Check identity by BAI against already opened HANDLEs. */
3168 for (slot = 0; slot < MAX_READER; slot++)
3169 if (reader_table[slot].used
3170 && ccid_compare_BAI (reader_table[slot].ccid.handle, bai))
3173 if (slot == MAX_READER)
3174 { /* Found a new device. */
3176 log_debug ("apdu_open_reader: new device=%x\n", bai);
3178 slot = open_ccid_reader (dl);
3185 /* Skip this reader. */
3186 log_error ("ccid open error: skip\n");
3198 { /* PC/SC readers. */
3202 slot = apdu_open_one_reader (dl->portstr);
3212 /* Open an remote reader and return an internal slot number or -1 on
3213 error. This function is an alternative to apdu_open_reader and used
3214 with remote readers only. Note that the supplied CLOSEFNC will
3215 only be called once and the slot will not be valid afther this.
3217 If PORTSTR is NULL we default to the first available port.
3220 apdu_open_remote_reader (const char *portstr,
3221 const unsigned char *cookie, size_t length,
3222 int (*readfnc) (void *opaque,
3223 void *buffer, size_t size),
3224 void *readfnc_value,
3225 int (*writefnc) (void *opaque,
3226 const void *buffer, size_t size),
3227 void *writefnc_value,
3228 void (*closefnc) (void *opaque),
3229 void *closefnc_value)
3231 #ifdef USE_G10CODE_RAPDU
3232 return open_rapdu_reader (portstr? atoi (portstr) : 0,
3234 readfnc, readfnc_value,
3235 writefnc, writefnc_value,
3236 closefnc, closefnc_value);
3242 (void)readfnc_value;
3244 (void)writefnc_value;
3246 (void)closefnc_value;
3258 apdu_close_reader (int slot)
3263 log_debug ("enter: apdu_close_reader: slot=%d\n", slot);
3265 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3268 log_debug ("leave: apdu_close_reader => SW_HOST_NO_DRIVER\n");
3269 return SW_HOST_NO_DRIVER;
3271 sw = apdu_disconnect (slot);
3275 * When the reader/token was removed it might come here.
3276 * It should go through to call CLOSE_READER even if we got an error.
3279 log_debug ("apdu_close_reader => 0x%x (apdu_disconnect)\n", sw);
3281 if (reader_table[slot].close_reader)
3283 sw = reader_table[slot].close_reader (slot);
3284 reader_table[slot].used = 0;
3286 log_debug ("leave: apdu_close_reader => 0x%x (close_reader)\n", sw);
3289 xfree (reader_table[slot].rdrname);
3290 reader_table[slot].rdrname = NULL;
3291 reader_table[slot].used = 0;
3293 log_debug ("leave: apdu_close_reader => SW_HOST_NOT_SUPPORTED\n");
3294 return SW_HOST_NOT_SUPPORTED;
3298 /* Function suitable for a cleanup function to close all reader. It
3299 should not be used if the reader will be opened again. The reason
3300 for implementing this to properly close USB devices so that they
3301 will startup the next time without error. */
3303 apdu_prepare_exit (void)
3305 static int sentinel;
3311 npth_mutex_lock (&reader_table_lock);
3312 for (slot = 0; slot < MAX_READER; slot++)
3313 if (reader_table[slot].used)
3315 apdu_disconnect (slot);
3316 if (reader_table[slot].close_reader)
3317 reader_table[slot].close_reader (slot);
3318 xfree (reader_table[slot].rdrname);
3319 reader_table[slot].rdrname = NULL;
3320 reader_table[slot].used = 0;
3322 npth_mutex_unlock (&reader_table_lock);
3328 /* Enumerate all readers and return information on whether this reader
3329 is in use. The caller should start with SLOT set to 0 and
3330 increment it with each call until an error is returned. */
3332 apdu_enum_reader (int slot, int *used)
3334 if (slot < 0 || slot >= MAX_READER)
3335 return SW_HOST_NO_DRIVER;
3336 *used = reader_table[slot].used;
3341 /* Connect a card. This is used to power up the card and make sure
3342 that an ATR is available. Depending on the reader backend it may
3343 return an error for an inactive card or if no card is
3346 apdu_connect (int slot)
3349 unsigned int status = 0;
3352 log_debug ("enter: apdu_connect: slot=%d\n", slot);
3354 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3357 log_debug ("leave: apdu_connect => SW_HOST_NO_DRIVER\n");
3358 return SW_HOST_NO_DRIVER;
3361 /* Only if the access method provides a connect function we use it.
3362 If not, we expect that the card has been implicitly connected by
3363 apdu_open_reader. */
3364 if (reader_table[slot].connect_card)
3366 sw = lock_slot (slot);
3369 sw = reader_table[slot].connect_card (slot);
3374 /* We need to call apdu_get_status_internal, so that the last-status
3375 machinery gets setup properly even if a card is inserted while
3376 scdaemon is fired up and apdu_get_status has not yet been called.
3377 Without that we would force a reset of the card with the next
3378 call to apdu_get_status. */
3380 sw = apdu_get_status_internal (slot, 1, 1, &status);
3384 else if (!(status & APDU_CARD_PRESENT))
3385 sw = SW_HOST_NO_CARD;
3386 else if ((status & APDU_CARD_PRESENT) && !(status & APDU_CARD_ACTIVE))
3387 sw = SW_HOST_CARD_INACTIVE;
3390 log_debug ("leave: apdu_connect => sw=0x%x\n", sw);
3397 apdu_disconnect (int slot)
3402 log_debug ("enter: apdu_disconnect: slot=%d\n", slot);
3404 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3407 log_debug ("leave: apdu_disconnect => SW_HOST_NO_DRIVER\n");
3408 return SW_HOST_NO_DRIVER;
3411 if (reader_table[slot].disconnect_card)
3413 sw = lock_slot (slot);
3416 sw = reader_table[slot].disconnect_card (slot);
3424 log_debug ("leave: apdu_disconnect => sw=0x%x\n", sw);
3429 /* Set the progress callback of SLOT to CB and its args to CB_ARG. If
3430 CB is NULL the progress callback is removed. */
3432 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
3436 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3437 return SW_HOST_NO_DRIVER;
3439 if (reader_table[slot].set_progress_cb)
3441 sw = lock_slot (slot);
3444 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
3454 /* Do a reset for the card in reader at SLOT. */
3456 apdu_reset (int slot)
3461 log_debug ("enter: apdu_reset: slot=%d\n", slot);
3463 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3466 log_debug ("leave: apdu_reset => SW_HOST_NO_DRIVER\n");
3467 return SW_HOST_NO_DRIVER;
3470 if ((sw = lock_slot (slot)))
3473 log_debug ("leave: apdu_reset => sw=0x%x (lock_slot)\n", sw);
3477 if (reader_table[slot].reset_reader)
3478 sw = reader_table[slot].reset_reader (slot);
3482 log_debug ("leave: apdu_reset => sw=0x%x\n", sw);
3487 /* Return the ATR or NULL if none is available. On success the length
3488 of the ATR is stored at ATRLEN. The caller must free the returned
3491 apdu_get_atr (int slot, size_t *atrlen)
3496 log_debug ("enter: apdu_get_atr: slot=%d\n", slot);
3498 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3501 log_debug ("leave: apdu_get_atr => NULL (bad slot)\n");
3504 if (!reader_table[slot].atrlen)
3507 log_debug ("leave: apdu_get_atr => NULL (no ATR)\n");
3511 buf = xtrymalloc (reader_table[slot].atrlen);
3515 log_debug ("leave: apdu_get_atr => NULL (out of core)\n");
3518 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
3519 *atrlen = reader_table[slot].atrlen;
3521 log_debug ("leave: apdu_get_atr => atrlen=%zu\n", *atrlen);
3527 /* Retrieve the status for SLOT. The function does only wait for the
3528 card to become available if HANG is set to true. On success the
3529 bits in STATUS will be set to
3531 APDU_CARD_USABLE (bit 0) = card present and usable
3532 APDU_CARD_PRESENT (bit 1) = card present
3533 APDU_CARD_ACTIVE (bit 2) = card active
3534 (bit 3) = card access locked [not yet implemented]
3536 For must applications, testing bit 0 is sufficient.
3539 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
3540 unsigned int *status)
3545 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3546 return SW_HOST_NO_DRIVER;
3548 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
3551 if (reader_table[slot].get_status_reader)
3552 sw = reader_table[slot].get_status_reader (slot, &s);
3559 reader_table[slot].atrlen = 0;
3569 /* See above for a description. */
3571 apdu_get_status (int slot, int hang, unsigned int *status)
3576 log_debug ("enter: apdu_get_status: slot=%d hang=%d\n", slot, hang);
3577 sw = apdu_get_status_internal (slot, hang, 0, status);
3581 log_debug ("leave: apdu_get_status => sw=0x%x status=%u\n",
3584 log_debug ("leave: apdu_get_status => sw=0x%x\n", sw);
3590 /* Check whether the reader supports the ISO command code COMMAND on
3591 the pinpad. Return 0 on success. For a description of the pin
3592 parameters, see ccid-driver.c */
3594 apdu_check_pinpad (int slot, int command, pininfo_t *pininfo)
3596 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3597 return SW_HOST_NO_DRIVER;
3599 if (opt.enable_pinpad_varlen)
3600 pininfo->fixedlen = 0;
3602 if (reader_table[slot].check_pinpad)
3606 if ((sw = lock_slot (slot)))
3609 sw = reader_table[slot].check_pinpad (slot, command, pininfo);
3614 return SW_HOST_NOT_SUPPORTED;
3619 apdu_pinpad_verify (int slot, int class, int ins, int p0, int p1,
3622 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3623 return SW_HOST_NO_DRIVER;
3625 if (reader_table[slot].pinpad_verify)
3629 if ((sw = lock_slot (slot)))
3632 sw = reader_table[slot].pinpad_verify (slot, class, ins, p0, p1,
3638 return SW_HOST_NOT_SUPPORTED;
3643 apdu_pinpad_modify (int slot, int class, int ins, int p0, int p1,
3646 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3647 return SW_HOST_NO_DRIVER;
3649 if (reader_table[slot].pinpad_modify)
3653 if ((sw = lock_slot (slot)))
3656 sw = reader_table[slot].pinpad_modify (slot, class, ins, p0, p1,
3662 return SW_HOST_NOT_SUPPORTED;
3666 /* Dispatcher for the actual send_apdu function. Note, that this
3667 function should be called in locked state. */
3669 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
3670 unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
3672 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3673 return SW_HOST_NO_DRIVER;
3675 if (reader_table[slot].send_apdu_reader)
3676 return reader_table[slot].send_apdu_reader (slot,
3681 return SW_HOST_NOT_SUPPORTED;
3685 /* Core APDU tranceiver function. Parameters are described at
3686 apdu_send_le with the exception of PININFO which indicates pinpad
3687 related operations if not NULL. If EXTENDED_MODE is not 0
3688 command chaining or extended length will be used according to these
3690 n < 0 := Use command chaining with the data part limited to -n
3691 in each chunk. If -1 is used a default value is used.
3692 n == 0 := No extended mode or command chaining.
3693 n == 1 := Use extended length for input and output without a
3695 n > 1 := Use extended length with up to N bytes.
3699 send_le (int slot, int class, int ins, int p0, int p1,
3700 int lc, const char *data, int le,
3701 unsigned char **retbuf, size_t *retbuflen,
3702 pininfo_t *pininfo, int extended_mode)
3704 #define SHORT_RESULT_BUFFER_SIZE 258
3705 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
3706 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3707 unsigned char *result_buffer = NULL;
3708 size_t result_buffer_size;
3709 unsigned char *result;
3711 unsigned char short_apdu_buffer[5+256+1];
3712 unsigned char *apdu_buffer = NULL;
3713 size_t apdu_buffer_size;
3714 unsigned char *apdu;
3717 long rc; /* We need a long here due to PC/SC. */
3718 int did_exact_length_hack = 0;
3719 int use_chaining = 0;
3720 int use_extended_length = 0;
3723 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3724 return SW_HOST_NO_DRIVER;
3727 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
3728 class, ins, p0, p1, lc, le, extended_mode);
3730 if (lc != -1 && (lc > 255 || lc < 0))
3732 /* Data does not fit into an APDU. What we do now depends on
3733 the EXTENDED_MODE parameter. */
3735 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
3736 else if (extended_mode > 0)
3737 use_extended_length = 1;
3738 else if (extended_mode < 0)
3740 /* Send APDU using chaining mode. */
3742 return SW_WRONG_LENGTH; /* Sanity check. */
3743 if ((class&0xf0) != 0)
3744 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
3745 use_chaining = extended_mode == -1? 255 : -extended_mode;
3746 use_chaining &= 0xff;
3749 return SW_HOST_INV_VALUE;
3751 else if (lc == -1 && extended_mode > 0)
3752 use_extended_length = 1;
3754 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
3756 /* Expected Data does not fit into an APDU. What we do now
3757 depends on the EXTENDED_MODE parameter. Note that a check
3758 for command chaining does not make sense because we are
3761 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
3762 else if (use_extended_length)
3763 ; /* We are already using extended length. */
3764 else if (extended_mode > 0)
3765 use_extended_length = 1;
3767 return SW_HOST_INV_VALUE;
3770 if ((!data && lc != -1) || (data && lc == -1))
3771 return SW_HOST_INV_VALUE;
3773 if (use_extended_length)
3775 if (reader_table[slot].is_t0)
3776 return SW_HOST_NOT_SUPPORTED;
3778 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
3779 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
3780 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
3782 return SW_HOST_OUT_OF_CORE;
3787 apdu_buffer_size = sizeof short_apdu_buffer;
3788 apdu = short_apdu_buffer;
3791 if (use_extended_length && (le > 256 || le < 0))
3793 /* Two more bytes are needed for status bytes. */
3794 result_buffer_size = le < 0? 4096 : (le + 2);
3795 result_buffer = xtrymalloc (result_buffer_size);
3798 xfree (apdu_buffer);
3799 return SW_HOST_OUT_OF_CORE;
3801 result = result_buffer;
3805 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3806 result = short_result_buffer;
3808 #undef SHORT_RESULT_BUFFER_SIZE
3810 if ((sw = lock_slot (slot)))
3812 xfree (apdu_buffer);
3813 xfree (result_buffer);
3819 if (use_extended_length)
3823 apdu[apdulen++] = class;
3824 apdu[apdulen++] = ins;
3825 apdu[apdulen++] = p0;
3826 apdu[apdulen++] = p1;
3829 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3830 apdu[apdulen++] = ((lc >> 8) & 0xff);
3831 apdu[apdulen++] = (lc & 0xff);
3832 memcpy (apdu+apdulen, data, lc);
3839 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3840 apdu[apdulen++] = ((le >> 8) & 0xff);
3841 apdu[apdulen++] = (le & 0xff);
3847 apdu[apdulen] = class;
3848 if (use_chaining && lc > 255)
3850 apdu[apdulen] |= 0x10;
3851 assert (use_chaining < 256);
3852 lc_chunk = use_chaining;
3861 apdu[apdulen++] = ins;
3862 apdu[apdulen++] = p0;
3863 apdu[apdulen++] = p1;
3866 apdu[apdulen++] = lc_chunk;
3867 memcpy (apdu+apdulen, data, lc_chunk);
3869 apdulen += lc_chunk;
3870 /* T=0 does not allow the use of Lc together with Le;
3871 thus disable Le in this case. */
3872 if (reader_table[slot].is_t0)
3875 if (le != -1 && !use_chaining)
3876 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3880 /* As a safeguard don't pass any garbage to the driver. */
3881 assert (apdulen <= apdu_buffer_size);
3882 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3883 resultlen = result_buffer_size;
3884 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3885 if (rc || resultlen < 2)
3887 log_info ("apdu_send_simple(%d) failed: %s\n",
3888 slot, apdu_strerror (rc));
3890 xfree (apdu_buffer);
3891 xfree (result_buffer);
3892 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3894 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3895 if (!use_extended_length
3896 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3898 apdu[apdulen-1] = (sw & 0x00ff);
3899 did_exact_length_hack = 1;
3900 goto exact_length_hack;
3903 while (use_chaining && sw == SW_SUCCESS);
3907 xfree (apdu_buffer);
3909 apdu_buffer_size = 0;
3912 /* Store away the returned data but strip the statusword. */
3916 log_debug (" response: sw=%04X datalen=%d\n",
3917 sw, (unsigned int)resultlen);
3918 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3919 log_printhex (" dump: ", result, resultlen);
3922 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3926 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3930 xfree (result_buffer);
3931 return SW_HOST_OUT_OF_CORE;
3933 *retbuflen = resultlen;
3934 memcpy (*retbuf, result, resultlen);
3937 else if ((sw & 0xff00) == SW_MORE_DATA)
3939 unsigned char *p = NULL, *tmp;
3940 size_t bufsize = 4096;
3942 /* It is likely that we need to return much more data, so we
3943 start off with a large buffer. */
3946 *retbuf = p = xtrymalloc (bufsize);
3950 xfree (result_buffer);
3951 return SW_HOST_OUT_OF_CORE;
3953 assert (resultlen < bufsize);
3954 memcpy (p, result, resultlen);
3960 int len = (sw & 0x00ff);
3963 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3965 apdu_buffer_size = sizeof short_apdu_buffer;
3966 apdu = short_apdu_buffer;
3968 apdu[apdulen++] = class;
3969 apdu[apdulen++] = 0xC0;
3970 apdu[apdulen++] = 0;
3971 apdu[apdulen++] = 0;
3972 apdu[apdulen++] = len;
3973 assert (apdulen <= apdu_buffer_size);
3974 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3975 resultlen = result_buffer_size;
3976 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3977 if (rc || resultlen < 2)
3979 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3980 slot, apdu_strerror (rc));
3982 xfree (result_buffer);
3983 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3985 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3989 log_debug (" more: sw=%04X datalen=%d\n",
3990 sw, (unsigned int)resultlen);
3991 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3992 log_printhex (" dump: ", result, resultlen);
3995 if ((sw & 0xff00) == SW_MORE_DATA
3997 || sw == SW_EOF_REACHED )
3999 if (retbuf && resultlen)
4001 if (p - *retbuf + resultlen > bufsize)
4003 bufsize += resultlen > 4096? resultlen: 4096;
4004 tmp = xtryrealloc (*retbuf, bufsize);
4008 xfree (result_buffer);
4009 return SW_HOST_OUT_OF_CORE;
4011 p = tmp + (p - *retbuf);
4014 memcpy (p, result, resultlen);
4019 log_info ("apdu_send_simple(%d) "
4020 "got unexpected status %04X from get response\n",
4023 while ((sw & 0xff00) == SW_MORE_DATA);
4027 *retbuflen = p - *retbuf;
4028 tmp = xtryrealloc (*retbuf, *retbuflen);
4035 xfree (result_buffer);
4037 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
4038 log_printhex (" dump: ", *retbuf, *retbuflen);
4043 /* Send an APDU to the card in SLOT. The APDU is created from all
4044 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
4045 for LC won't sent this field and the data field; in this case DATA
4046 must also be passed as NULL. If EXTENDED_MODE is not 0 command
4047 chaining or extended length will be used; see send_le for details.
4048 The return value is the status word or -1 for an invalid SLOT or
4049 other non card related error. If RETBUF is not NULL, it will
4050 receive an allocated buffer with the returned data. The length of
4051 that data will be put into *RETBUFLEN. The caller is responsible
4052 for releasing the buffer even in case of errors. */
4054 apdu_send_le(int slot, int extended_mode,
4055 int class, int ins, int p0, int p1,
4056 int lc, const char *data, int le,
4057 unsigned char **retbuf, size_t *retbuflen)
4059 return send_le (slot, class, ins, p0, p1,
4062 NULL, extended_mode);
4066 /* Send an APDU to the card in SLOT. The APDU is created from all
4067 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
4068 LC won't sent this field and the data field; in this case DATA must
4069 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
4070 or extended length will be used; see send_le for details. The
4071 return value is the status word or -1 for an invalid SLOT or other
4072 non card related error. If RETBUF is not NULL, it will receive an
4073 allocated buffer with the returned data. The length of that data
4074 will be put into *RETBUFLEN. The caller is responsible for
4075 releasing the buffer even in case of errors. */
4077 apdu_send (int slot, int extended_mode,
4078 int class, int ins, int p0, int p1,
4079 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
4081 return send_le (slot, class, ins, p0, p1, lc, data, 256,
4082 retbuf, retbuflen, NULL, extended_mode);
4085 /* Send an APDU to the card in SLOT. The APDU is created from all
4086 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
4087 LC won't sent this field and the data field; in this case DATA must
4088 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
4089 or extended length will be used; see send_le for details. The
4090 return value is the status word or -1 for an invalid SLOT or other
4091 non card related error. No data will be returned. */
4093 apdu_send_simple (int slot, int extended_mode,
4094 int class, int ins, int p0, int p1,
4095 int lc, const char *data)
4097 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
4102 /* This is a more generic version of the apdu sending routine. It
4103 takes an already formatted APDU in APDUDATA or length APDUDATALEN
4104 and returns with an APDU including the status word. With
4105 HANDLE_MORE set to true this function will handle the MORE DATA
4106 status and return all APDUs concatenated with one status word at
4107 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
4108 with a max. result data length of EXTENDED_LENGTH bytes. The
4109 function does not return a regular status word but 0 on success.
4110 If the slot is locked, the function returns immediately with an
4113 apdu_send_direct (int slot, size_t extended_length,
4114 const unsigned char *apdudata, size_t apdudatalen,
4116 unsigned char **retbuf, size_t *retbuflen)
4118 #define SHORT_RESULT_BUFFER_SIZE 258
4119 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
4120 unsigned char *result_buffer = NULL;
4121 size_t result_buffer_size;
4122 unsigned char *result;
4124 unsigned char short_apdu_buffer[5+256+10];
4125 unsigned char *apdu_buffer = NULL;
4126 unsigned char *apdu;
4129 long rc; /* we need a long here due to PC/SC. */
4132 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
4133 return SW_HOST_NO_DRIVER;
4135 if (apdudatalen > 65535)
4136 return SW_HOST_INV_VALUE;
4138 if (apdudatalen > sizeof short_apdu_buffer - 5)
4140 apdu_buffer = xtrymalloc (apdudatalen + 5);
4142 return SW_HOST_OUT_OF_CORE;
4147 apdu = short_apdu_buffer;
4149 apdulen = apdudatalen;
4150 memcpy (apdu, apdudata, apdudatalen);
4151 class = apdulen? *apdu : 0;
4153 if (extended_length >= 256 && extended_length <= 65536)
4155 result_buffer_size = extended_length;
4156 result_buffer = xtrymalloc (result_buffer_size + 10);
4159 xfree (apdu_buffer);
4160 return SW_HOST_OUT_OF_CORE;
4162 result = result_buffer;
4166 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
4167 result = short_result_buffer;
4169 #undef SHORT_RESULT_BUFFER_SIZE
4171 if ((sw = trylock_slot (slot)))
4173 xfree (apdu_buffer);
4174 xfree (result_buffer);
4178 resultlen = result_buffer_size;
4179 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
4180 xfree (apdu_buffer);
4182 if (rc || resultlen < 2)
4184 log_error ("apdu_send_direct(%d) failed: %s\n",
4185 slot, apdu_strerror (rc));
4187 xfree (result_buffer);
4188 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
4190 sw = (result[resultlen-2] << 8) | result[resultlen-1];
4191 /* Store away the returned data but strip the statusword. */
4195 log_debug (" response: sw=%04X datalen=%d\n",
4196 sw, (unsigned int)resultlen);
4197 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
4198 log_printhex (" dump: ", result, resultlen);
4201 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
4203 unsigned char *p = NULL, *tmp;
4204 size_t bufsize = 4096;
4206 /* It is likely that we need to return much more data, so we
4207 start off with a large buffer. */
4210 *retbuf = p = xtrymalloc (bufsize + 2);
4214 xfree (result_buffer);
4215 return SW_HOST_OUT_OF_CORE;
4217 assert (resultlen < bufsize);
4218 memcpy (p, result, resultlen);
4224 int len = (sw & 0x00ff);
4227 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
4229 apdu = short_apdu_buffer;
4231 apdu[apdulen++] = class;
4232 apdu[apdulen++] = 0xC0;
4233 apdu[apdulen++] = 0;
4234 apdu[apdulen++] = 0;
4235 apdu[apdulen++] = len;
4236 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
4237 resultlen = result_buffer_size;
4238 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
4239 if (rc || resultlen < 2)
4241 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
4242 slot, apdu_strerror (rc));
4244 xfree (result_buffer);
4245 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
4247 sw = (result[resultlen-2] << 8) | result[resultlen-1];
4251 log_debug (" more: sw=%04X datalen=%d\n",
4252 sw, (unsigned int)resultlen);
4253 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
4254 log_printhex (" dump: ", result, resultlen);
4257 if ((sw & 0xff00) == SW_MORE_DATA
4259 || sw == SW_EOF_REACHED )
4261 if (retbuf && resultlen)
4263 if (p - *retbuf + resultlen > bufsize)
4265 bufsize += resultlen > 4096? resultlen: 4096;
4266 tmp = xtryrealloc (*retbuf, bufsize + 2);
4270 xfree (result_buffer);
4271 return SW_HOST_OUT_OF_CORE;
4273 p = tmp + (p - *retbuf);
4276 memcpy (p, result, resultlen);
4281 log_info ("apdu_send_direct(%d) "
4282 "got unexpected status %04X from get response\n",
4285 while ((sw & 0xff00) == SW_MORE_DATA);
4289 *retbuflen = p - *retbuf;
4290 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
4299 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
4303 xfree (result_buffer);
4304 return SW_HOST_OUT_OF_CORE;
4306 *retbuflen = resultlen;
4307 memcpy (*retbuf, result, resultlen);
4312 xfree (result_buffer);
4314 /* Append the status word. Note that we reserved the two extra
4315 bytes while allocating the buffer. */
4318 (*retbuf)[(*retbuflen)++] = (sw >> 8);
4319 (*retbuf)[(*retbuflen)++] = sw;
4322 if (DBG_CARD_IO && retbuf)
4323 log_printhex (" dump: ", *retbuf, *retbuflen);
4330 apdu_get_reader_name (int slot)
4332 return reader_table[slot].rdrname;
4342 if (npth_mutex_init (&reader_table_lock, NULL))
4345 for (i = 0; i < MAX_READER; i++)
4346 if (npth_mutex_init (&reader_table[i].lock, NULL))
4349 /* All done well. */
4353 err = gpg_error_from_syserror ();
4354 log_error ("apdu: error initializing mutex: %s\n", gpg_strerror (err));