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"
69 /* Due to conflicting use of threading libraries we usually can't link
70 against libpcsclite if we are using Pth. Instead we use a wrapper
71 program. Note that with nPth there is no need for a wrapper. */
72 #ifdef USE_PTH /* Right, plain old Pth. */
73 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
74 #define NEED_PCSC_WRAPPER 1
79 #define MAX_READER 4 /* Number of readers we support concurrently. */
82 #if defined(_WIN32) || defined(__CYGWIN__)
83 #define DLSTDCALL __stdcall
88 #if defined(__APPLE__) || defined(_WIN32) || defined(__CYGWIN__)
89 typedef unsigned int pcsc_dword_t;
91 typedef unsigned long pcsc_dword_t;
94 /* A structure to collect information pertaining to one reader
96 struct reader_table_s {
97 int used; /* True if slot is used. */
98 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
100 /* Function pointers intialized to the various backends. */
101 int (*connect_card)(int);
102 int (*disconnect_card)(int);
103 int (*close_reader)(int);
104 int (*reset_reader)(int);
105 int (*get_status_reader)(int, unsigned int *);
106 int (*send_apdu_reader)(int,unsigned char *,size_t,
107 unsigned char *, size_t *, pininfo_t *);
108 int (*check_pinpad)(int, int, pininfo_t *);
109 void (*dump_status_reader)(int);
110 int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
111 int (*pinpad_verify)(int, int, int, int, int, pininfo_t *);
112 int (*pinpad_modify)(int, int, int, int, int, pininfo_t *);
115 ccid_driver_t handle;
120 pcsc_dword_t protocol;
121 pcsc_dword_t verify_ioctl;
122 pcsc_dword_t modify_ioctl;
125 #ifdef NEED_PCSC_WRAPPER
129 #endif /*NEED_PCSC_WRAPPER*/
131 #ifdef USE_G10CODE_RAPDU
135 #endif /*USE_G10CODE_RAPDU*/
136 char *rdrname; /* Name of the connected reader or NULL if unknown. */
137 int any_status; /* True if we have seen any status. */
140 int is_t0; /* True if we know that we are running T=0. */
141 int is_spr532; /* True if we know that the reader is a SPR532. */
142 int pinpad_varlen_supported; /* True if we know that the reader
143 supports variable length pinpad
145 unsigned char atr[33];
146 size_t atrlen; /* A zero length indicates that the ATR has
147 not yet been read; i.e. the card is not
149 unsigned int change_counter;
151 int lock_initialized;
155 typedef struct reader_table_s *reader_table_t;
157 /* A global table to keep track of active readers. */
158 static struct reader_table_s reader_table[MAX_READER];
161 /* ct API function pointer. */
162 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
163 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
164 unsigned char *sad, unsigned short lc,
165 unsigned char *cmd, unsigned short *lr,
167 static char (* DLSTDCALL CT_close) (unsigned short ctn);
169 /* PC/SC constants and function pointer. */
170 #define PCSC_SCOPE_USER 0
171 #define PCSC_SCOPE_TERMINAL 1
172 #define PCSC_SCOPE_SYSTEM 2
173 #define PCSC_SCOPE_GLOBAL 3
175 #define PCSC_PROTOCOL_T0 1
176 #define PCSC_PROTOCOL_T1 2
177 #ifdef HAVE_W32_SYSTEM
178 # define PCSC_PROTOCOL_RAW 0x00010000 /* The active protocol. */
180 # define PCSC_PROTOCOL_RAW 4
183 #define PCSC_SHARE_EXCLUSIVE 1
184 #define PCSC_SHARE_SHARED 2
185 #define PCSC_SHARE_DIRECT 3
187 #define PCSC_LEAVE_CARD 0
188 #define PCSC_RESET_CARD 1
189 #define PCSC_UNPOWER_CARD 2
190 #define PCSC_EJECT_CARD 3
192 #ifdef HAVE_W32_SYSTEM
193 # define PCSC_UNKNOWN 0x0000 /* The driver is not aware of the status. */
194 # define PCSC_ABSENT 0x0001 /* Card is absent. */
195 # define PCSC_PRESENT 0x0002 /* Card is present. */
196 # define PCSC_SWALLOWED 0x0003 /* Card is present and electrical connected. */
197 # define PCSC_POWERED 0x0004 /* Card is powered. */
198 # define PCSC_NEGOTIABLE 0x0005 /* Card is awaiting PTS. */
199 # define PCSC_SPECIFIC 0x0006 /* Card is ready for use. */
201 # define PCSC_UNKNOWN 0x0001
202 # define PCSC_ABSENT 0x0002 /* Card is absent. */
203 # define PCSC_PRESENT 0x0004 /* Card is present. */
204 # define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
205 # define PCSC_POWERED 0x0010 /* Card is powered. */
206 # define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
207 # define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
210 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
211 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
212 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
213 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
214 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
215 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
216 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
217 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
218 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
219 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
220 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
221 #ifdef HAVE_W32_SYSTEM
222 # define PCSC_STATE_UNPOWERED 0x0400 /* Card not powerred up. */
225 /* Some PC/SC error codes. */
226 #define PCSC_E_CANCELLED 0x80100002
227 #define PCSC_E_CANT_DISPOSE 0x8010000E
228 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
229 #define PCSC_E_INVALID_ATR 0x80100015
230 #define PCSC_E_INVALID_HANDLE 0x80100003
231 #define PCSC_E_INVALID_PARAMETER 0x80100004
232 #define PCSC_E_INVALID_TARGET 0x80100005
233 #define PCSC_E_INVALID_VALUE 0x80100011
234 #define PCSC_E_NO_MEMORY 0x80100006
235 #define PCSC_E_UNKNOWN_READER 0x80100009
236 #define PCSC_E_TIMEOUT 0x8010000A
237 #define PCSC_E_SHARING_VIOLATION 0x8010000B
238 #define PCSC_E_NO_SMARTCARD 0x8010000C
239 #define PCSC_E_UNKNOWN_CARD 0x8010000D
240 #define PCSC_E_PROTO_MISMATCH 0x8010000F
241 #define PCSC_E_NOT_READY 0x80100010
242 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
243 #define PCSC_E_NOT_TRANSACTED 0x80100016
244 #define PCSC_E_READER_UNAVAILABLE 0x80100017
245 #define PCSC_E_NO_SERVICE 0x8010001D
246 #define PCSC_E_SERVICE_STOPPED 0x8010001E
247 #define PCSC_W_REMOVED_CARD 0x80100069
249 /* Fix pcsc-lite ABI incompatibilty. */
250 #ifndef SCARD_CTL_CODE
252 #include <winioctl.h>
253 #define SCARD_CTL_CODE(code) CTL_CODE(FILE_DEVICE_SMARTCARD, (code), \
254 METHOD_BUFFERED, FILE_ANY_ACCESS)
256 #define SCARD_CTL_CODE(code) (0x42000000 + (code))
260 #define CM_IOCTL_GET_FEATURE_REQUEST SCARD_CTL_CODE(3400)
261 #define CM_IOCTL_VENDOR_IFD_EXCHANGE SCARD_CTL_CODE(1)
262 #define FEATURE_VERIFY_PIN_DIRECT 0x06
263 #define FEATURE_MODIFY_PIN_DIRECT 0x07
264 #define FEATURE_GET_TLV_PROPERTIES 0x12
266 #define PCSCv2_PART10_PROPERTY_bEntryValidationCondition 2
267 #define PCSCv2_PART10_PROPERTY_bTimeOut2 3
268 #define PCSCv2_PART10_PROPERTY_bMinPINSize 6
269 #define PCSCv2_PART10_PROPERTY_bMaxPINSize 7
270 #define PCSCv2_PART10_PROPERTY_wIdVendor 11
271 #define PCSCv2_PART10_PROPERTY_wIdProduct 12
274 /* The PC/SC error is defined as a long as per specs. Due to left
275 shifts bit 31 will get sign extended. We use this mask to fix
277 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
280 struct pcsc_io_request_s
282 unsigned long protocol;
283 unsigned long pci_len;
286 typedef struct pcsc_io_request_s *pcsc_io_request_t;
292 struct pcsc_readerstate_s
296 pcsc_dword_t current_state;
297 pcsc_dword_t event_state;
299 unsigned char atr[33];
306 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
308 long (* DLSTDCALL pcsc_establish_context) (pcsc_dword_t scope,
309 const void *reserved1,
310 const void *reserved2,
312 long (* DLSTDCALL pcsc_release_context) (long context);
313 long (* DLSTDCALL pcsc_list_readers) (long context,
315 char *readers, pcsc_dword_t*readerslen);
316 long (* DLSTDCALL pcsc_get_status_change) (long context,
317 pcsc_dword_t timeout,
318 pcsc_readerstate_t readerstates,
319 pcsc_dword_t nreaderstates);
320 long (* DLSTDCALL pcsc_connect) (long context,
322 pcsc_dword_t share_mode,
323 pcsc_dword_t preferred_protocols,
325 pcsc_dword_t *r_active_protocol);
326 long (* DLSTDCALL pcsc_reconnect) (long card,
327 pcsc_dword_t share_mode,
328 pcsc_dword_t preferred_protocols,
329 pcsc_dword_t initialization,
330 pcsc_dword_t *r_active_protocol);
331 long (* DLSTDCALL pcsc_disconnect) (long card,
332 pcsc_dword_t disposition);
333 long (* DLSTDCALL pcsc_status) (long card,
334 char *reader, pcsc_dword_t *readerlen,
335 pcsc_dword_t *r_state,
336 pcsc_dword_t *r_protocol,
337 unsigned char *atr, pcsc_dword_t *atrlen);
338 long (* DLSTDCALL pcsc_begin_transaction) (long card);
339 long (* DLSTDCALL pcsc_end_transaction) (long card,
340 pcsc_dword_t disposition);
341 long (* DLSTDCALL pcsc_transmit) (long card,
342 const pcsc_io_request_t send_pci,
343 const unsigned char *send_buffer,
344 pcsc_dword_t send_len,
345 pcsc_io_request_t recv_pci,
346 unsigned char *recv_buffer,
347 pcsc_dword_t *recv_len);
348 long (* DLSTDCALL pcsc_set_timeout) (long context,
349 pcsc_dword_t timeout);
350 long (* DLSTDCALL pcsc_control) (long card,
351 pcsc_dword_t control_code,
352 const void *send_buffer,
353 pcsc_dword_t send_len,
355 pcsc_dword_t recv_len,
356 pcsc_dword_t *bytes_returned);
360 static int pcsc_vendor_specific_init (int slot);
361 static int pcsc_get_status (int slot, unsigned int *status);
362 static int reset_pcsc_reader (int slot);
363 static int apdu_get_status_internal (int slot, int hang, int no_atr_reset,
364 unsigned int *status,
365 unsigned int *changed);
366 static int check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo);
367 static int pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
369 static int pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
384 err = npth_mutex_lock (&reader_table[slot].lock);
387 log_error ("failed to acquire apdu lock: %s\n", strerror (err));
388 return SW_HOST_LOCKING_FAILED;
395 trylock_slot (int slot)
400 err = npth_mutex_trylock (&reader_table[slot].lock);
405 log_error ("failed to acquire apdu lock: %s\n", strerror (err));
406 return SW_HOST_LOCKING_FAILED;
413 unlock_slot (int slot)
418 err = npth_mutex_unlock (&reader_table[slot].lock);
420 log_error ("failed to release apdu lock: %s\n", strerror (errno));
425 /* Find an unused reader slot for PORTSTR and put it into the reader
426 table. Return -1 on error or the index into the reader table.
427 Acquire slot's lock on successful return. Caller needs to unlock it. */
429 new_reader_slot (void)
434 for (i=0; i < MAX_READER; i++)
436 if (!reader_table[i].used && reader == -1)
441 log_error ("new_reader_slot: out of slots\n");
445 if (!reader_table[reader].lock_initialized)
447 err = npth_mutex_init (&reader_table[reader].lock, NULL);
450 log_error ("error initializing mutex: %s\n", strerror (err));
453 reader_table[reader].lock_initialized = 1;
456 if (lock_slot (reader))
458 log_error ("error locking mutex: %s\n", strerror (errno));
461 reader_table[reader].connect_card = NULL;
462 reader_table[reader].disconnect_card = NULL;
463 reader_table[reader].close_reader = NULL;
464 reader_table[reader].reset_reader = NULL;
465 reader_table[reader].get_status_reader = NULL;
466 reader_table[reader].send_apdu_reader = NULL;
467 reader_table[reader].check_pinpad = check_pcsc_pinpad;
468 reader_table[reader].dump_status_reader = NULL;
469 reader_table[reader].set_progress_cb = NULL;
470 reader_table[reader].pinpad_verify = pcsc_pinpad_verify;
471 reader_table[reader].pinpad_modify = pcsc_pinpad_modify;
473 reader_table[reader].used = 1;
474 reader_table[reader].any_status = 0;
475 reader_table[reader].last_status = 0;
476 reader_table[reader].is_t0 = 1;
477 reader_table[reader].is_spr532 = 0;
478 reader_table[reader].pinpad_varlen_supported = 0;
479 #ifdef NEED_PCSC_WRAPPER
480 reader_table[reader].pcsc.req_fd = -1;
481 reader_table[reader].pcsc.rsp_fd = -1;
482 reader_table[reader].pcsc.pid = (pid_t)(-1);
484 reader_table[reader].pcsc.verify_ioctl = 0;
485 reader_table[reader].pcsc.modify_ioctl = 0;
486 reader_table[reader].pcsc.pinmin = -1;
487 reader_table[reader].pcsc.pinmax = -1;
494 dump_reader_status (int slot)
499 if (reader_table[slot].dump_status_reader)
500 reader_table[slot].dump_status_reader (slot);
502 if (reader_table[slot].status != -1
503 && reader_table[slot].atrlen)
505 log_info ("slot %d: ATR=", slot);
506 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
513 host_sw_string (long err)
517 case 0: return "okay";
518 case SW_HOST_OUT_OF_CORE: return "out of core";
519 case SW_HOST_INV_VALUE: return "invalid value";
520 case SW_HOST_NO_DRIVER: return "no driver";
521 case SW_HOST_NOT_SUPPORTED: return "not supported";
522 case SW_HOST_LOCKING_FAILED: return "locking failed";
523 case SW_HOST_BUSY: return "busy";
524 case SW_HOST_NO_CARD: return "no card";
525 case SW_HOST_CARD_INACTIVE: return "card inactive";
526 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
527 case SW_HOST_GENERAL_ERROR: return "general error";
528 case SW_HOST_NO_READER: return "no reader";
529 case SW_HOST_ABORTED: return "aborted";
530 case SW_HOST_NO_PINPAD: return "no pinpad";
531 case SW_HOST_ALREADY_CONNECTED: return "already connected";
532 default: return "unknown host status error";
538 apdu_strerror (int rc)
542 case SW_EOF_REACHED : return "eof reached";
543 case SW_EEPROM_FAILURE : return "eeprom failure";
544 case SW_WRONG_LENGTH : return "wrong length";
545 case SW_CHV_WRONG : return "CHV wrong";
546 case SW_CHV_BLOCKED : return "CHV blocked";
547 case SW_REF_DATA_INV : return "referenced data invalidated";
548 case SW_USE_CONDITIONS : return "use conditions not satisfied";
549 case SW_BAD_PARAMETER : return "bad parameter";
550 case SW_NOT_SUPPORTED : return "not supported";
551 case SW_FILE_NOT_FOUND : return "file not found";
552 case SW_RECORD_NOT_FOUND:return "record not found";
553 case SW_REF_NOT_FOUND : return "reference not found";
554 case SW_NOT_ENOUGH_MEMORY: return "not enough memory space in the file";
555 case SW_INCONSISTENT_LC: return "Lc inconsistent with TLV structure.";
556 case SW_INCORRECT_P0_P1: return "incorrect parameters P0,P1";
557 case SW_BAD_LC : return "Lc inconsistent with P0,P1";
558 case SW_BAD_P0_P1 : return "bad P0,P1";
559 case SW_INS_NOT_SUP : return "instruction not supported";
560 case SW_CLA_NOT_SUP : return "class not supported";
561 case SW_SUCCESS : return "success";
563 if ((rc & ~0x00ff) == SW_MORE_DATA)
564 return "more data available";
565 if ( (rc & 0x10000) )
566 return host_sw_string (rc);
567 return "unknown status error";
578 ct_error_string (long err)
582 case 0: return "okay";
583 case -1: return "invalid data";
584 case -8: return "ct error";
585 case -10: return "transmission error";
586 case -11: return "memory allocation error";
587 case -128: return "HTSI error";
588 default: return "unknown CT-API error";
594 ct_dump_reader_status (int slot)
596 log_info ("reader slot %d: %s\n", slot,
597 reader_table[slot].status == 1? "Processor ICC present" :
598 reader_table[slot].status == 0? "Memory ICC present" :
603 /* Wait for the card in SLOT and activate it. Return a status word
604 error or 0 on success. */
606 ct_activate_card (int slot)
609 unsigned char dad[1], sad[1], cmd[11], buf[256];
610 unsigned short buflen;
612 /* Check whether card has been inserted. */
613 dad[0] = 1; /* Destination address: CT. */
614 sad[0] = 2; /* Source address: Host. */
616 cmd[0] = 0x20; /* Class byte. */
617 cmd[1] = 0x13; /* Request status. */
618 cmd[2] = 0x00; /* From kernel. */
619 cmd[3] = 0x80; /* Return card's DO. */
624 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
625 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
627 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
628 slot, ct_error_string (rc));
629 return SW_HOST_CARD_IO_ERROR;
632 /* Connected, now activate the card. */
633 dad[0] = 1; /* Destination address: CT. */
634 sad[0] = 2; /* Source address: Host. */
636 cmd[0] = 0x20; /* Class byte. */
637 cmd[1] = 0x12; /* Request ICC. */
638 cmd[2] = 0x01; /* From first interface. */
639 cmd[3] = 0x01; /* Return card's ATR. */
644 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
645 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
647 log_error ("ct_activate_card(%d): activation failed: %s\n",
648 slot, ct_error_string (rc));
650 log_printhex (" received data:", buf, buflen);
651 return SW_HOST_CARD_IO_ERROR;
654 /* Store the type and the ATR. */
655 if (buflen - 2 > DIM (reader_table[0].atr))
657 log_error ("ct_activate_card(%d): ATR too long\n", slot);
658 return SW_HOST_CARD_IO_ERROR;
661 reader_table[slot].status = buf[buflen - 1];
662 memcpy (reader_table[slot].atr, buf, buflen - 2);
663 reader_table[slot].atrlen = buflen - 2;
669 close_ct_reader (int slot)
672 reader_table[slot].used = 0;
677 reset_ct_reader (int slot)
679 /* FIXME: Check is this is sufficient do do a reset. */
680 return ct_activate_card (slot);
685 ct_get_status (int slot, unsigned int *status)
688 /* The status we returned is wrong but we don't care because ctAPI
689 is not anymore required. */
690 *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
694 /* Actually send the APDU of length APDULEN to SLOT and return a
695 maximum of *BUFLEN data in BUFFER, the actual returned size will be
696 set to BUFLEN. Returns: CT API error code. */
698 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
699 unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
702 unsigned char dad[1], sad[1];
703 unsigned short ctbuflen;
707 /* If we don't have an ATR, we need to reset the reader first. */
708 if (!reader_table[slot].atrlen
709 && (rc = reset_ct_reader (slot)))
712 dad[0] = 0; /* Destination address: Card. */
713 sad[0] = 2; /* Source address: Host. */
716 log_printhex (" CT_data:", apdu, apdulen);
717 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
720 return rc? SW_HOST_CARD_IO_ERROR: 0;
725 /* Open a reader and return an internal handle for it. PORT is a
726 non-negative value with the port number of the reader. USB readers
727 do have port numbers starting at 32769. */
729 open_ct_reader (int port)
733 if (port < 0 || port > 0xffff)
735 log_error ("open_ct_reader: invalid port %d requested\n", port);
738 reader = new_reader_slot ();
741 reader_table[reader].port = port;
743 rc = CT_init (reader, (unsigned short)port);
746 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
747 port, ct_error_string (rc));
748 reader_table[reader].used = 0;
749 unlock_slot (reader);
753 /* Only try to activate the card. */
754 rc = ct_activate_card (reader);
757 reader_table[reader].atrlen = 0;
761 reader_table[reader].close_reader = close_ct_reader;
762 reader_table[reader].reset_reader = reset_ct_reader;
763 reader_table[reader].get_status_reader = ct_get_status;
764 reader_table[reader].send_apdu_reader = ct_send_apdu;
765 reader_table[reader].check_pinpad = NULL;
766 reader_table[reader].dump_status_reader = ct_dump_reader_status;
767 reader_table[reader].pinpad_verify = NULL;
768 reader_table[reader].pinpad_modify = NULL;
770 dump_reader_status (reader);
771 unlock_slot (reader);
780 #ifdef NEED_PCSC_WRAPPER
782 writen (int fd, const void *buf, size_t nbytes)
784 size_t nleft = nbytes;
787 /* log_printhex (" writen:", buf, nbytes); */
792 nwritten = npth_write (fd, buf, nleft);
794 nwritten = write (fd, buf, nleft);
796 if (nwritten < 0 && errno == EINTR)
801 buf = (const char*)buf + nwritten;
806 /* Read up to BUFLEN bytes from FD and return the number of bytes
807 actually read in NREAD. Returns -1 on error or 0 on success. */
809 readn (int fd, void *buf, size_t buflen, size_t *nread)
811 size_t nleft = buflen;
813 /* void *orig_buf = buf; */
818 # ifdef HAVE_W32_SYSTEM
819 # error Cannot use npth_read here because it expects a system HANDLE.
821 n = npth_read (fd, buf, nleft);
823 n = read (fd, buf, nleft);
825 if (n < 0 && errno == EINTR)
828 return -1; /* read error. */
832 buf = (char*)buf + n;
835 *nread = buflen - nleft;
837 /* log_printhex (" readn:", orig_buf, *nread); */
841 #endif /*NEED_PCSC_WRAPPER*/
844 pcsc_error_string (long err)
850 if ((err & 0x80100000) != 0x80100000)
851 return "invalid PC/SC error code";
855 case 0x0002: s = "cancelled"; break;
856 case 0x000e: s = "can't dispose"; break;
857 case 0x0008: s = "insufficient buffer"; break;
858 case 0x0015: s = "invalid ATR"; break;
859 case 0x0003: s = "invalid handle"; break;
860 case 0x0004: s = "invalid parameter"; break;
861 case 0x0005: s = "invalid target"; break;
862 case 0x0011: s = "invalid value"; break;
863 case 0x0006: s = "no memory"; break;
864 case 0x0013: s = "comm error"; break;
865 case 0x0001: s = "internal error"; break;
866 case 0x0014: s = "unknown error"; break;
867 case 0x0007: s = "waited too long"; break;
868 case 0x0009: s = "unknown reader"; break;
869 case 0x000a: s = "timeout"; break;
870 case 0x000b: s = "sharing violation"; break;
871 case 0x000c: s = "no smartcard"; break;
872 case 0x000d: s = "unknown card"; break;
873 case 0x000f: s = "proto mismatch"; break;
874 case 0x0010: s = "not ready"; break;
875 case 0x0012: s = "system cancelled"; break;
876 case 0x0016: s = "not transacted"; break;
877 case 0x0017: s = "reader unavailable"; break;
878 case 0x0065: s = "unsupported card"; break;
879 case 0x0066: s = "unresponsive card"; break;
880 case 0x0067: s = "unpowered card"; break;
881 case 0x0068: s = "reset card"; break;
882 case 0x0069: s = "removed card"; break;
883 case 0x006a: s = "inserted card"; break;
884 case 0x001f: s = "unsupported feature"; break;
885 case 0x0019: s = "PCI too small"; break;
886 case 0x001a: s = "reader unsupported"; break;
887 case 0x001b: s = "duplicate reader"; break;
888 case 0x001c: s = "card unsupported"; break;
889 case 0x001d: s = "no service"; break;
890 case 0x001e: s = "service stopped"; break;
891 default: s = "unknown PC/SC error code"; break;
896 /* Map PC/SC error codes to our special host status words. */
898 pcsc_error_to_sw (long ec)
902 switch ( PCSC_ERR_MASK (ec) )
904 case 0: rc = 0; break;
906 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
907 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
908 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
909 case PCSC_E_NO_SERVICE:
910 case PCSC_E_SERVICE_STOPPED:
911 case PCSC_E_UNKNOWN_READER: rc = SW_HOST_NO_READER; break;
912 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
913 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
914 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
916 case PCSC_E_INVALID_TARGET:
917 case PCSC_E_INVALID_VALUE:
918 case PCSC_E_INVALID_HANDLE:
919 case PCSC_E_INVALID_PARAMETER:
920 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
922 default: rc = SW_HOST_GENERAL_ERROR; break;
929 dump_pcsc_reader_status (int slot)
931 if (reader_table[slot].pcsc.card)
933 log_info ("reader slot %d: active protocol:", slot);
934 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
936 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
938 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
943 log_info ("reader slot %d: not connected\n", slot);
947 #ifndef NEED_PCSC_WRAPPER
949 pcsc_get_status_direct (int slot, unsigned int *status)
952 struct pcsc_readerstate_s rdrstates[1];
954 memset (rdrstates, 0, sizeof *rdrstates);
955 rdrstates[0].reader = reader_table[slot].rdrname;
956 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
957 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
960 if (err == PCSC_E_TIMEOUT)
961 err = 0; /* Timeout is no error error here. */
964 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
965 pcsc_error_string (err), err);
966 return pcsc_error_to_sw (err);
970 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
971 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
972 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
973 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
974 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
975 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
976 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
977 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
978 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
979 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
980 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
983 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
985 *status |= APDU_CARD_PRESENT;
986 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
987 *status |= APDU_CARD_ACTIVE;
989 #ifndef HAVE_W32_SYSTEM
990 /* We indicate a useful card if it is not in use by another
991 application. This is because we only use exclusive access
993 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
994 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
995 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
996 *status |= APDU_CARD_USABLE;
998 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
999 time when we are the only user (SCM SCR335) under Windows. */
1000 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
1001 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
1002 *status |= APDU_CARD_USABLE;
1007 #endif /*!NEED_PCSC_WRAPPER*/
1010 #ifdef NEED_PCSC_WRAPPER
1012 pcsc_get_status_wrapped (int slot, unsigned int *status)
1015 reader_table_t slotp;
1016 size_t len, full_len;
1018 unsigned char msgbuf[9];
1019 unsigned char buffer[16];
1020 int sw = SW_HOST_CARD_IO_ERROR;
1022 slotp = reader_table + slot;
1024 if (slotp->pcsc.req_fd == -1
1025 || slotp->pcsc.rsp_fd == -1
1026 || slotp->pcsc.pid == (pid_t)(-1) )
1028 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1032 msgbuf[0] = 0x04; /* STATUS command. */
1034 msgbuf[1] = (len >> 24);
1035 msgbuf[2] = (len >> 16);
1036 msgbuf[3] = (len >> 8);
1038 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1040 log_error ("error sending PC/SC STATUS request: %s\n",
1042 goto command_failed;
1045 /* Read the response. */
1046 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1048 log_error ("error receiving PC/SC STATUS response: %s\n",
1049 i? strerror (errno) : "premature EOF");
1050 goto command_failed;
1052 len = buf_to_size_t (msgbuf+1);
1053 if (msgbuf[0] != 0x81 || len < 4)
1055 log_error ("invalid response header from PC/SC received\n");
1056 goto command_failed;
1058 len -= 4; /* Already read the error code. */
1059 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1062 log_error ("pcsc_status failed: %s (0x%lx)\n",
1063 pcsc_error_string (err), err);
1064 /* This is a proper error code, so return immediately. */
1065 return pcsc_error_to_sw (err);
1070 /* The current version returns 3 words but we allow also for old
1071 versions returning only 2 words. */
1072 n = 12 < len ? 12 : len;
1073 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
1074 || (len != 8 && len != 12))
1076 log_error ("error receiving PC/SC STATUS response: %s\n",
1077 i? strerror (errno) : "premature EOF");
1078 goto command_failed;
1081 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
1085 /* Newer versions of the wrapper might send more status bytes.
1089 unsigned char dummybuf[128];
1091 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1092 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1094 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1095 i? strerror (errno) : "premature EOF");
1096 goto command_failed;
1101 /* We are lucky: The wrapper already returns the data in the
1103 *status = buffer[3];
1107 close (slotp->pcsc.req_fd);
1108 close (slotp->pcsc.rsp_fd);
1109 slotp->pcsc.req_fd = -1;
1110 slotp->pcsc.rsp_fd = -1;
1111 if (slotp->pcsc.pid != -1)
1112 kill (slotp->pcsc.pid, SIGTERM);
1113 slotp->pcsc.pid = (pid_t)(-1);
1117 #endif /*NEED_PCSC_WRAPPER*/
1121 pcsc_get_status (int slot, unsigned int *status)
1123 #ifdef NEED_PCSC_WRAPPER
1124 return pcsc_get_status_wrapped (slot, status);
1126 return pcsc_get_status_direct (slot, status);
1131 #ifndef NEED_PCSC_WRAPPER
1133 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
1134 unsigned char *buffer, size_t *buflen,
1138 struct pcsc_io_request_s send_pci;
1139 pcsc_dword_t recv_len;
1143 if (!reader_table[slot].atrlen
1144 && (err = reset_pcsc_reader (slot)))
1148 log_printhex (" PCSC_data:", apdu, apdulen);
1150 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1151 send_pci.protocol = PCSC_PROTOCOL_T1;
1153 send_pci.protocol = PCSC_PROTOCOL_T0;
1154 send_pci.pci_len = sizeof send_pci;
1156 err = pcsc_transmit (reader_table[slot].pcsc.card,
1157 &send_pci, apdu, apdulen,
1158 NULL, buffer, &recv_len);
1161 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1162 pcsc_error_string (err), err);
1164 return pcsc_error_to_sw (err);
1166 #endif /*!NEED_PCSC_WRAPPER*/
1169 #ifdef NEED_PCSC_WRAPPER
1171 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1172 unsigned char *buffer, size_t *buflen,
1176 reader_table_t slotp;
1177 size_t len, full_len;
1179 unsigned char msgbuf[9];
1180 int sw = SW_HOST_CARD_IO_ERROR;
1184 if (!reader_table[slot].atrlen
1185 && (err = reset_pcsc_reader (slot)))
1189 log_printhex (" PCSC_data:", apdu, apdulen);
1191 slotp = reader_table + slot;
1193 if (slotp->pcsc.req_fd == -1
1194 || slotp->pcsc.rsp_fd == -1
1195 || slotp->pcsc.pid == (pid_t)(-1) )
1197 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1201 msgbuf[0] = 0x03; /* TRANSMIT command. */
1203 msgbuf[1] = (len >> 24);
1204 msgbuf[2] = (len >> 16);
1205 msgbuf[3] = (len >> 8);
1207 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1208 || writen (slotp->pcsc.req_fd, apdu, len))
1210 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1212 goto command_failed;
1215 /* Read the response. */
1216 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1218 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1219 i? strerror (errno) : "premature EOF");
1220 goto command_failed;
1222 len = buf_to_size_t (msgbuf+1);
1223 if (msgbuf[0] != 0x81 || len < 4)
1225 log_error ("invalid response header from PC/SC received\n");
1226 goto command_failed;
1228 len -= 4; /* Already read the error code. */
1229 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1232 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1233 pcsc_error_string (err), err);
1234 return pcsc_error_to_sw (err);
1239 n = *buflen < len ? *buflen : len;
1240 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1242 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1243 i? strerror (errno) : "premature EOF");
1244 goto command_failed;
1251 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1252 err = SW_HOST_INV_VALUE;
1254 /* We need to read any rest of the response, to keep the
1255 protocol running. */
1258 unsigned char dummybuf[128];
1260 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1261 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1263 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1264 i? strerror (errno) : "premature EOF");
1265 goto command_failed;
1273 close (slotp->pcsc.req_fd);
1274 close (slotp->pcsc.rsp_fd);
1275 slotp->pcsc.req_fd = -1;
1276 slotp->pcsc.rsp_fd = -1;
1277 if (slotp->pcsc.pid != -1)
1278 kill (slotp->pcsc.pid, SIGTERM);
1279 slotp->pcsc.pid = (pid_t)(-1);
1283 #endif /*NEED_PCSC_WRAPPER*/
1286 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1287 *BUFLEN data in BUFFER, the actual returned size will be stored at
1288 BUFLEN. Returns: A status word. */
1290 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1291 unsigned char *buffer, size_t *buflen,
1294 #ifdef NEED_PCSC_WRAPPER
1295 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1297 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1302 #ifndef NEED_PCSC_WRAPPER
1304 control_pcsc_direct (int slot, pcsc_dword_t ioctl_code,
1305 const unsigned char *cntlbuf, size_t len,
1306 unsigned char *buffer, pcsc_dword_t *buflen)
1310 err = pcsc_control (reader_table[slot].pcsc.card, ioctl_code,
1311 cntlbuf, len, buffer, buflen? *buflen:0, buflen);
1314 log_error ("pcsc_control failed: %s (0x%lx)\n",
1315 pcsc_error_string (err), err);
1316 return pcsc_error_to_sw (err);
1321 #endif /*!NEED_PCSC_WRAPPER*/
1324 #ifdef NEED_PCSC_WRAPPER
1326 control_pcsc_wrapped (int slot, pcsc_dword_t ioctl_code,
1327 const unsigned char *cntlbuf, size_t len,
1328 unsigned char *buffer, pcsc_dword_t *buflen)
1330 long err = PCSC_E_NOT_TRANSACTED;
1331 reader_table_t slotp;
1332 unsigned char msgbuf[9];
1336 slotp = reader_table + slot;
1338 msgbuf[0] = 0x06; /* CONTROL command. */
1339 msgbuf[1] = ((len + 4) >> 24);
1340 msgbuf[2] = ((len + 4) >> 16);
1341 msgbuf[3] = ((len + 4) >> 8);
1342 msgbuf[4] = ((len + 4) );
1343 msgbuf[5] = (ioctl_code >> 24);
1344 msgbuf[6] = (ioctl_code >> 16);
1345 msgbuf[7] = (ioctl_code >> 8);
1346 msgbuf[8] = (ioctl_code );
1347 if ( writen (slotp->pcsc.req_fd, msgbuf, 9)
1348 || writen (slotp->pcsc.req_fd, cntlbuf, len))
1350 log_error ("error sending PC/SC CONTROL request: %s\n",
1352 goto command_failed;
1355 /* Read the response. */
1356 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1358 log_error ("error receiving PC/SC CONTROL response: %s\n",
1359 i? strerror (errno) : "premature EOF");
1360 goto command_failed;
1362 len = buf32_to_size_t (msgbuf+1);
1363 if (msgbuf[0] != 0x81 || len < 4)
1365 log_error ("invalid response header from PC/SC received\n");
1366 goto command_failed;
1368 len -= 4; /* Already read the error code. */
1369 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1372 log_error ("pcsc_control failed: %s (0x%lx)\n",
1373 pcsc_error_string (err), err);
1374 return pcsc_error_to_sw (err);
1380 n = *buflen < len ? *buflen : len;
1383 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1385 log_error ("error receiving PC/SC CONTROL response: %s\n",
1386 i? strerror (errno) : "premature EOF");
1387 goto command_failed;
1395 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1396 err = PCSC_E_INVALID_VALUE;
1398 /* We need to read any rest of the response, to keep the
1399 protocol running. */
1402 unsigned char dummybuf[128];
1404 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1405 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1407 log_error ("error receiving PC/SC CONTROL response: %s\n",
1408 i? strerror (errno) : "premature EOF");
1409 goto command_failed;
1418 close (slotp->pcsc.req_fd);
1419 close (slotp->pcsc.rsp_fd);
1420 slotp->pcsc.req_fd = -1;
1421 slotp->pcsc.rsp_fd = -1;
1422 if (slotp->pcsc.pid != -1)
1423 kill (slotp->pcsc.pid, SIGTERM);
1424 slotp->pcsc.pid = (pid_t)(-1);
1426 return pcsc_error_to_sw (err);
1428 #endif /*NEED_PCSC_WRAPPER*/
1432 /* Do some control with the value of IOCTL_CODE to the card inserted
1433 to SLOT. Input buffer is specified by CNTLBUF of length LEN.
1434 Output buffer is specified by BUFFER of length *BUFLEN, and the
1435 actual output size will be stored at BUFLEN. Returns: A status word.
1436 This routine is used for PIN pad input support. */
1438 control_pcsc (int slot, pcsc_dword_t ioctl_code,
1439 const unsigned char *cntlbuf, size_t len,
1440 unsigned char *buffer, pcsc_dword_t *buflen)
1442 #ifdef NEED_PCSC_WRAPPER
1443 return control_pcsc_wrapped (slot, ioctl_code, cntlbuf, len, buffer, buflen);
1445 return control_pcsc_direct (slot, ioctl_code, cntlbuf, len, buffer, buflen);
1450 #ifndef NEED_PCSC_WRAPPER
1452 close_pcsc_reader_direct (int slot)
1454 pcsc_release_context (reader_table[slot].pcsc.context);
1455 xfree (reader_table[slot].rdrname);
1456 reader_table[slot].rdrname = NULL;
1457 reader_table[slot].used = 0;
1460 #endif /*!NEED_PCSC_WRAPPER*/
1463 #ifdef NEED_PCSC_WRAPPER
1465 close_pcsc_reader_wrapped (int slot)
1468 reader_table_t slotp;
1471 unsigned char msgbuf[9];
1473 slotp = reader_table + slot;
1475 if (slotp->pcsc.req_fd == -1
1476 || slotp->pcsc.rsp_fd == -1
1477 || slotp->pcsc.pid == (pid_t)(-1) )
1479 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1483 msgbuf[0] = 0x02; /* CLOSE command. */
1485 msgbuf[1] = (len >> 24);
1486 msgbuf[2] = (len >> 16);
1487 msgbuf[3] = (len >> 8);
1489 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1491 log_error ("error sending PC/SC CLOSE request: %s\n",
1493 goto command_failed;
1496 /* Read the response. */
1497 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1499 log_error ("error receiving PC/SC CLOSE response: %s\n",
1500 i? strerror (errno) : "premature EOF");
1501 goto command_failed;
1503 len = buf32_to_size_t (msgbuf+1);
1504 if (msgbuf[0] != 0x81 || len < 4)
1506 log_error ("invalid response header from PC/SC received\n");
1507 goto command_failed;
1509 len -= 4; /* Already read the error code. */
1510 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1512 log_error ("pcsc_close failed: %s (0x%lx)\n",
1513 pcsc_error_string (err), err);
1515 /* We will close the wrapper in any case - errors are merely
1519 close (slotp->pcsc.req_fd);
1520 close (slotp->pcsc.rsp_fd);
1521 slotp->pcsc.req_fd = -1;
1522 slotp->pcsc.rsp_fd = -1;
1523 if (slotp->pcsc.pid != -1)
1524 kill (slotp->pcsc.pid, SIGTERM);
1525 slotp->pcsc.pid = (pid_t)(-1);
1529 #endif /*NEED_PCSC_WRAPPER*/
1533 close_pcsc_reader (int slot)
1535 #ifdef NEED_PCSC_WRAPPER
1536 return close_pcsc_reader_wrapped (slot);
1538 return close_pcsc_reader_direct (slot);
1543 /* Connect a PC/SC card. */
1544 #ifndef NEED_PCSC_WRAPPER
1546 connect_pcsc_card (int slot)
1550 assert (slot >= 0 && slot < MAX_READER);
1552 if (reader_table[slot].pcsc.card)
1553 return SW_HOST_ALREADY_CONNECTED;
1555 reader_table[slot].atrlen = 0;
1556 reader_table[slot].last_status = 0;
1557 reader_table[slot].is_t0 = 0;
1559 err = pcsc_connect (reader_table[slot].pcsc.context,
1560 reader_table[slot].rdrname,
1561 PCSC_SHARE_EXCLUSIVE,
1562 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1563 &reader_table[slot].pcsc.card,
1564 &reader_table[slot].pcsc.protocol);
1567 reader_table[slot].pcsc.card = 0;
1568 if (err != PCSC_E_NO_SMARTCARD)
1569 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1570 pcsc_error_string (err), err);
1575 pcsc_dword_t readerlen, atrlen;
1576 pcsc_dword_t card_state, card_protocol;
1578 pcsc_vendor_specific_init (slot);
1580 atrlen = DIM (reader_table[0].atr);
1581 readerlen = sizeof reader -1 ;
1582 err = pcsc_status (reader_table[slot].pcsc.card,
1584 &card_state, &card_protocol,
1585 reader_table[slot].atr, &atrlen);
1587 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1588 pcsc_error_string (err), err, (long unsigned int)readerlen);
1591 if (atrlen > DIM (reader_table[0].atr))
1592 log_bug ("ATR returned by pcsc_status is too large\n");
1593 reader_table[slot].atrlen = atrlen;
1594 /* If we got to here we know that a card is present
1595 and usable. Remember this. */
1596 reader_table[slot].last_status = ( APDU_CARD_USABLE
1598 | APDU_CARD_ACTIVE);
1599 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1603 dump_reader_status (slot);
1604 return pcsc_error_to_sw (err);
1606 #endif /*!NEED_PCSC_WRAPPER*/
1609 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1610 is not connected. */
1611 #ifndef NEED_PCSC_WRAPPER
1613 disconnect_pcsc_card (int slot)
1617 assert (slot >= 0 && slot < MAX_READER);
1619 if (!reader_table[slot].pcsc.card)
1622 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1625 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1626 pcsc_error_string (err), err);
1627 return SW_HOST_CARD_IO_ERROR;
1629 reader_table[slot].pcsc.card = 0;
1632 #endif /*!NEED_PCSC_WRAPPER*/
1635 #ifndef NEED_PCSC_WRAPPER
1637 reset_pcsc_reader_direct (int slot)
1641 sw = disconnect_pcsc_card (slot);
1643 sw = connect_pcsc_card (slot);
1647 #endif /*NEED_PCSC_WRAPPER*/
1650 #ifdef NEED_PCSC_WRAPPER
1652 reset_pcsc_reader_wrapped (int slot)
1655 reader_table_t slotp;
1658 unsigned char msgbuf[9];
1659 unsigned int dummy_status;
1660 int sw = SW_HOST_CARD_IO_ERROR;
1662 slotp = reader_table + slot;
1664 if (slotp->pcsc.req_fd == -1
1665 || slotp->pcsc.rsp_fd == -1
1666 || slotp->pcsc.pid == (pid_t)(-1) )
1668 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1672 msgbuf[0] = 0x05; /* RESET command. */
1674 msgbuf[1] = (len >> 24);
1675 msgbuf[2] = (len >> 16);
1676 msgbuf[3] = (len >> 8);
1678 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1680 log_error ("error sending PC/SC RESET request: %s\n",
1682 goto command_failed;
1685 /* Read the response. */
1686 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1688 log_error ("error receiving PC/SC RESET response: %s\n",
1689 i? strerror (errno) : "premature EOF");
1690 goto command_failed;
1692 len = buf32_to_size_t (msgbuf+1);
1693 if (msgbuf[0] != 0x81 || len < 4)
1695 log_error ("invalid response header from PC/SC received\n");
1696 goto command_failed;
1698 len -= 4; /* Already read the error code. */
1699 if (len > DIM (slotp->atr))
1701 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1702 (unsigned long)len);
1703 sw = SW_HOST_GENERAL_ERROR;
1704 goto command_failed;
1706 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
1709 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1710 pcsc_error_string (err), err);
1711 /* If the error code is no smart card, we should not considere
1712 this a major error and close the wrapper. */
1713 sw = pcsc_error_to_sw (err);
1714 if (err == PCSC_E_NO_SMARTCARD)
1716 goto command_failed;
1719 /* The open function may return a zero for the ATR length to
1720 indicate that no card is present. */
1724 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1726 log_error ("error receiving PC/SC RESET response: %s\n",
1727 i? strerror (errno) : "premature EOF");
1728 goto command_failed;
1731 slotp->atrlen = len;
1733 /* Read the status so that IS_T0 will be set. */
1734 pcsc_get_status (slot, &dummy_status);
1739 close (slotp->pcsc.req_fd);
1740 close (slotp->pcsc.rsp_fd);
1741 slotp->pcsc.req_fd = -1;
1742 slotp->pcsc.rsp_fd = -1;
1743 if (slotp->pcsc.pid != -1)
1744 kill (slotp->pcsc.pid, SIGTERM);
1745 slotp->pcsc.pid = (pid_t)(-1);
1749 #endif /* !NEED_PCSC_WRAPPER */
1752 /* Send an PC/SC reset command and return a status word on error or 0
1755 reset_pcsc_reader (int slot)
1757 #ifdef NEED_PCSC_WRAPPER
1758 return reset_pcsc_reader_wrapped (slot);
1760 return reset_pcsc_reader_direct (slot);
1765 /* Examine reader specific parameters and initialize. This is mostly
1766 for pinpad input. Called at opening the connection to the reader. */
1768 pcsc_vendor_specific_init (int slot)
1770 unsigned char buf[256];
1775 pcsc_dword_t get_tlv_ioctl = (pcsc_dword_t)-1;
1779 sw = control_pcsc (slot, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, &len);
1782 log_error ("pcsc_vendor_specific_init: GET_FEATURE_REQUEST failed: %d\n",
1784 return SW_NOT_SUPPORTED;
1789 while (p < buf + len)
1791 unsigned char code = *p++;
1798 v = buf16_to_uint (p);
1800 v = buf32_to_uint (p);
1802 if (code == FEATURE_VERIFY_PIN_DIRECT)
1803 reader_table[slot].pcsc.verify_ioctl = v;
1804 else if (code == FEATURE_MODIFY_PIN_DIRECT)
1805 reader_table[slot].pcsc.modify_ioctl = v;
1806 else if (code == FEATURE_GET_TLV_PROPERTIES)
1810 log_debug ("feature: code=%02X, len=%d, v=%02X\n", code, l, v);
1816 if (get_tlv_ioctl == (pcsc_dword_t)-1)
1819 * For system which doesn't support GET_TLV_PROPERTIES,
1820 * we put some heuristics here.
1822 if (reader_table[slot].rdrname)
1824 if (strstr (reader_table[slot].rdrname, "SPRx32"))
1826 reader_table[slot].is_spr532 = 1;
1827 reader_table[slot].pinpad_varlen_supported = 1;
1829 else if (strstr (reader_table[slot].rdrname, "ST-2xxx"))
1831 reader_table[slot].pcsc.pinmax = 15;
1832 reader_table[slot].pinpad_varlen_supported = 1;
1834 else if (strstr (reader_table[slot].rdrname, "cyberJack")
1835 || strstr (reader_table[slot].rdrname, "DIGIPASS")
1836 || strstr (reader_table[slot].rdrname, "Gnuk")
1837 || strstr (reader_table[slot].rdrname, "KAAN"))
1838 reader_table[slot].pinpad_varlen_supported = 1;
1845 sw = control_pcsc (slot, get_tlv_ioctl, NULL, 0, buf, &len);
1848 log_error ("pcsc_vendor_specific_init: GET_TLV_IOCTL failed: %d\n", sw);
1849 return SW_NOT_SUPPORTED;
1853 while (p < buf + len)
1855 unsigned char tag = *p++;
1859 /* Umm... here is little endian, while the encoding above is big. */
1863 v = (((unsigned int)p[1] << 8) | p[0]);
1865 v = (((unsigned int)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
1867 if (tag == PCSCv2_PART10_PROPERTY_bMinPINSize)
1868 reader_table[slot].pcsc.pinmin = v;
1869 else if (tag == PCSCv2_PART10_PROPERTY_bMaxPINSize)
1870 reader_table[slot].pcsc.pinmax = v;
1871 else if (tag == PCSCv2_PART10_PROPERTY_wIdVendor)
1873 else if (tag == PCSCv2_PART10_PROPERTY_wIdProduct)
1877 log_debug ("TLV properties: tag=%02X, len=%d, v=%08X\n", tag, l, v);
1882 if (vendor == VENDOR_VEGA && product == VEGA_ALPHA)
1885 * Please read the comment of ccid_vendor_specific_init in
1888 const unsigned char cmd[] = { '\xb5', '\x01', '\x00', '\x03', '\x00' };
1889 sw = control_pcsc (slot, CM_IOCTL_VENDOR_IFD_EXCHANGE,
1890 cmd, sizeof (cmd), NULL, 0);
1892 return SW_NOT_SUPPORTED;
1894 else if (vendor == VENDOR_SCM && product == SCM_SPR532) /* SCM SPR532 */
1896 reader_table[slot].is_spr532 = 1;
1897 reader_table[slot].pinpad_varlen_supported = 1;
1899 else if (vendor == 0x046a)
1901 /* Cherry ST-2xxx (product == 0x003e) supports TPDU level
1902 * exchange. Other products which only support short APDU level
1903 * exchange only work with shorter keys like RSA 1024.
1905 reader_table[slot].pcsc.pinmax = 15;
1906 reader_table[slot].pinpad_varlen_supported = 1;
1908 else if (vendor == 0x0c4b /* Tested with Reiner cyberJack GO */
1909 || vendor == 0x1a44 /* Tested with Vasco DIGIPASS 920 */
1910 || vendor == 0x234b /* Tested with FSIJ Gnuk Token */
1911 || vendor == 0x0d46 /* Tested with KAAN Advanced??? */)
1912 reader_table[slot].pinpad_varlen_supported = 1;
1918 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1919 error or a slot number for the reader. */
1920 #ifndef NEED_PCSC_WRAPPER
1922 open_pcsc_reader_direct (const char *portstr)
1927 char *rdrname = NULL;
1928 pcsc_dword_t nreader;
1931 slot = new_reader_slot ();
1935 /* Fixme: Allocating a context for each slot is not required. One
1936 global context should be sufficient. */
1937 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1938 &reader_table[slot].pcsc.context);
1941 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1942 pcsc_error_string (err), err);
1943 reader_table[slot].used = 0;
1948 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1949 NULL, NULL, &nreader);
1952 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1955 log_error ("error allocating memory for reader list\n");
1956 pcsc_release_context (reader_table[slot].pcsc.context);
1957 reader_table[slot].used = 0;
1959 return -1 /*SW_HOST_OUT_OF_CORE*/;
1961 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1962 NULL, list, &nreader);
1966 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1967 pcsc_error_string (err), err);
1968 pcsc_release_context (reader_table[slot].pcsc.context);
1969 reader_table[slot].used = 0;
1980 log_info ("detected reader '%s'\n", p);
1981 if (nreader < (strlen (p)+1))
1983 log_error ("invalid response from pcsc_list_readers\n");
1986 if (!rdrname && portstr && !strncmp (p, portstr, strlen (portstr)))
1988 nreader -= strlen (p)+1;
1989 p += strlen (p) + 1;
1995 reader_table[slot].rdrname = xtrystrdup (rdrname);
1996 if (!reader_table[slot].rdrname)
1998 log_error ("error allocating memory for reader name\n");
1999 pcsc_release_context (reader_table[slot].pcsc.context);
2000 reader_table[slot].used = 0;
2007 reader_table[slot].pcsc.card = 0;
2008 reader_table[slot].atrlen = 0;
2009 reader_table[slot].last_status = 0;
2011 reader_table[slot].connect_card = connect_pcsc_card;
2012 reader_table[slot].disconnect_card = disconnect_pcsc_card;
2013 reader_table[slot].close_reader = close_pcsc_reader;
2014 reader_table[slot].reset_reader = reset_pcsc_reader;
2015 reader_table[slot].get_status_reader = pcsc_get_status;
2016 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
2017 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
2019 dump_reader_status (slot);
2023 #endif /*!NEED_PCSC_WRAPPER */
2026 /* Open the PC/SC reader using the pcsc_wrapper program. This is
2027 needed to cope with different thread models and other peculiarities
2029 #ifdef NEED_PCSC_WRAPPER
2031 open_pcsc_reader_wrapped (const char *portstr)
2034 reader_table_t slotp;
2035 int fd, rp[2], wp[2];
2039 unsigned char msgbuf[9];
2041 unsigned int dummy_status;
2043 /* Note that we use the constant and not the function because this
2044 code won't be be used under Windows. */
2045 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
2047 if (access (wrapperpgm, X_OK))
2049 log_error ("can't run PC/SC access module '%s': %s\n",
2050 wrapperpgm, strerror (errno));
2054 slot = new_reader_slot ();
2057 slotp = reader_table + slot;
2059 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
2060 the common directy but implement it directly so that this file
2061 may still be source copied. */
2063 if (pipe (rp) == -1)
2065 log_error ("error creating a pipe: %s\n", strerror (errno));
2070 if (pipe (wp) == -1)
2072 log_error ("error creating a pipe: %s\n", strerror (errno));
2083 log_error ("error forking process: %s\n", strerror (errno));
2092 slotp->pcsc.pid = pid;
2104 _exit (0); /* Immediate exit this parent, so that the child
2105 gets cleaned up by the init process. */
2107 /* Connect our pipes. */
2108 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
2109 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
2110 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
2111 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
2113 /* Send stderr to the bit bucket. */
2114 fd = open ("/dev/null", O_WRONLY);
2116 log_fatal ("can't open '/dev/null': %s", strerror (errno));
2117 if (fd != 2 && dup2 (fd, 2) == -1)
2118 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
2120 /* Close all other files. */
2121 close_all_fds (3, NULL);
2126 "1", /* API version */
2127 opt.pcsc_driver, /* Name of the PC/SC library. */
2137 slotp->pcsc.req_fd = wp[1];
2138 slotp->pcsc.rsp_fd = rp[0];
2140 /* Wait for the intermediate child to terminate. */
2142 #define WAIT npth_waitpid
2144 #define WAIT waitpid
2146 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
2150 /* Now send the open request. */
2151 msgbuf[0] = 0x01; /* OPEN command. */
2152 len = portstr? strlen (portstr):0;
2153 msgbuf[1] = (len >> 24);
2154 msgbuf[2] = (len >> 16);
2155 msgbuf[3] = (len >> 8);
2157 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
2158 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
2160 log_error ("error sending PC/SC OPEN request: %s\n",
2162 goto command_failed;
2164 /* Read the response. */
2165 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
2167 log_error ("error receiving PC/SC OPEN response: %s\n",
2168 i? strerror (errno) : "premature EOF");
2169 goto command_failed;
2171 len = buf32_to_size_t (msgbuf+1);
2172 if (msgbuf[0] != 0x81 || len < 4)
2174 log_error ("invalid response header from PC/SC received\n");
2175 goto command_failed;
2177 len -= 4; /* Already read the error code. */
2178 if (len > DIM (slotp->atr))
2180 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
2181 (unsigned long)len);
2182 goto command_failed;
2184 err = PCSC_ERR_MASK (buf32_to_ulong (msgbuf+5));
2187 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
2188 goto command_failed;
2191 slotp->last_status = 0;
2193 /* The open request may return a zero for the ATR length to
2194 indicate that no card is present. */
2198 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
2200 log_error ("error receiving PC/SC OPEN response: %s\n",
2201 i? strerror (errno) : "premature EOF");
2202 goto command_failed;
2204 /* If we got to here we know that a card is present
2205 and usable. Thus remember this. */
2206 slotp->last_status = ( APDU_CARD_USABLE
2208 | APDU_CARD_ACTIVE);
2210 slotp->atrlen = len;
2212 reader_table[slot].close_reader = close_pcsc_reader;
2213 reader_table[slot].reset_reader = reset_pcsc_reader;
2214 reader_table[slot].get_status_reader = pcsc_get_status;
2215 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
2216 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
2218 pcsc_vendor_specific_init (slot);
2220 /* Read the status so that IS_T0 will be set. */
2221 pcsc_get_status (slot, &dummy_status);
2223 dump_reader_status (slot);
2228 close (slotp->pcsc.req_fd);
2229 close (slotp->pcsc.rsp_fd);
2230 slotp->pcsc.req_fd = -1;
2231 slotp->pcsc.rsp_fd = -1;
2232 if (slotp->pcsc.pid != -1)
2233 kill (slotp->pcsc.pid, SIGTERM);
2234 slotp->pcsc.pid = (pid_t)(-1);
2237 /* There is no way to return SW. */
2241 #endif /*NEED_PCSC_WRAPPER*/
2245 open_pcsc_reader (const char *portstr)
2247 #ifdef NEED_PCSC_WRAPPER
2248 return open_pcsc_reader_wrapped (portstr);
2250 return open_pcsc_reader_direct (portstr);
2255 /* Check whether the reader supports the ISO command code COMMAND
2256 on the pinpad. Return 0 on success. */
2258 check_pcsc_pinpad (int slot, int command, pininfo_t *pininfo)
2262 if (reader_table[slot].pcsc.pinmin >= 0)
2263 pininfo->minlen = reader_table[slot].pcsc.pinmin;
2265 if (reader_table[slot].pcsc.pinmax >= 0)
2266 pininfo->maxlen = reader_table[slot].pcsc.pinmax;
2268 if (!pininfo->minlen)
2269 pininfo->minlen = 1;
2270 if (!pininfo->maxlen)
2271 pininfo->maxlen = 15;
2273 if ((command == ISO7816_VERIFY && reader_table[slot].pcsc.verify_ioctl != 0)
2274 || (command == ISO7816_CHANGE_REFERENCE_DATA
2275 && reader_table[slot].pcsc.modify_ioctl != 0))
2276 r = 0; /* Success */
2278 r = SW_NOT_SUPPORTED;
2281 log_debug ("check_pcsc_pinpad: command=%02X, r=%d\n",
2282 (unsigned int)command, r);
2284 if (reader_table[slot].pinpad_varlen_supported)
2285 pininfo->fixedlen = 0;
2290 #define PIN_VERIFY_STRUCTURE_SIZE 24
2292 pcsc_pinpad_verify (int slot, int class, int ins, int p0, int p1,
2296 unsigned char *pin_verify;
2297 int len = PIN_VERIFY_STRUCTURE_SIZE + pininfo->fixedlen;
2299 * The result buffer is only expected to have two-byte result on
2300 * return. However, some implementation uses this buffer for lower
2301 * layer too and it assumes that there is enough space for lower
2302 * layer communication. Such an implementation fails for TPDU
2303 * readers with "insufficient buffer", as it needs header and
2304 * trailer. Six is the number for header + result + trailer (TPDU).
2306 unsigned char result[6];
2307 pcsc_dword_t resultlen = 6;
2310 if (!reader_table[slot].atrlen
2311 && (sw = reset_pcsc_reader (slot)))
2314 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
2315 return SW_NOT_SUPPORTED;
2317 pin_verify = xtrymalloc (len);
2319 return SW_HOST_OUT_OF_CORE;
2321 no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
2323 pin_verify[0] = 0x00; /* bTimeOut */
2324 pin_verify[1] = 0x00; /* bTimeOut2 */
2325 pin_verify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2326 pin_verify[3] = pininfo->fixedlen; /* bmPINBlockString */
2327 pin_verify[4] = 0x00; /* bmPINLengthFormat */
2328 pin_verify[5] = pininfo->maxlen; /* wPINMaxExtraDigit */
2329 pin_verify[6] = pininfo->minlen; /* wPINMaxExtraDigit */
2330 pin_verify[7] = 0x02; /* bEntryValidationCondition: Validation key pressed */
2331 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
2332 pin_verify[7] |= 0x01; /* Max size reached. */
2333 pin_verify[8] = 0x01; /* bNumberMessage: One message */
2334 pin_verify[9] = 0x09; /* wLangId: 0x0409: US English */
2335 pin_verify[10] = 0x04; /* wLangId: 0x0409: US English */
2336 pin_verify[11] = 0x00; /* bMsgIndex */
2337 pin_verify[12] = 0x00; /* bTeoPrologue[0] */
2338 pin_verify[13] = 0x00; /* bTeoPrologue[1] */
2339 pin_verify[14] = pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
2340 pin_verify[15] = pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
2341 pin_verify[16] = 0x00; /* ulDataLength */
2342 pin_verify[17] = 0x00; /* ulDataLength */
2343 pin_verify[18] = 0x00; /* ulDataLength */
2344 pin_verify[19] = class; /* abData[0] */
2345 pin_verify[20] = ins; /* abData[1] */
2346 pin_verify[21] = p0; /* abData[2] */
2347 pin_verify[22] = p1; /* abData[3] */
2348 pin_verify[23] = pininfo->fixedlen; /* abData[4] */
2349 if (pininfo->fixedlen)
2350 memset (&pin_verify[24], 0xff, pininfo->fixedlen);
2355 log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
2356 class, ins, p0, p1, len, pininfo->maxlen);
2358 sw = control_pcsc (slot, reader_table[slot].pcsc.verify_ioctl,
2359 pin_verify, len, result, &resultlen);
2361 if (sw || resultlen < 2)
2363 log_error ("control_pcsc failed: %d\n", sw);
2364 return sw? sw: SW_HOST_INCOMPLETE_CARD_RESPONSE;
2366 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2368 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
2373 #define PIN_MODIFY_STRUCTURE_SIZE 29
2375 pcsc_pinpad_modify (int slot, int class, int ins, int p0, int p1,
2379 unsigned char *pin_modify;
2380 int len = PIN_MODIFY_STRUCTURE_SIZE + 2 * pininfo->fixedlen;
2381 unsigned char result[6]; /* See the comment at pinpad_verify. */
2382 pcsc_dword_t resultlen = 6;
2385 if (!reader_table[slot].atrlen
2386 && (sw = reset_pcsc_reader (slot)))
2389 if (pininfo->fixedlen < 0 || pininfo->fixedlen >= 16)
2390 return SW_NOT_SUPPORTED;
2392 pin_modify = xtrymalloc (len);
2394 return SW_HOST_OUT_OF_CORE;
2396 no_lc = (!pininfo->fixedlen && reader_table[slot].is_spr532);
2398 pin_modify[0] = 0x00; /* bTimeOut */
2399 pin_modify[1] = 0x00; /* bTimeOut2 */
2400 pin_modify[2] = 0x82; /* bmFormatString: Byte, pos=0, left, ASCII. */
2401 pin_modify[3] = pininfo->fixedlen; /* bmPINBlockString */
2402 pin_modify[4] = 0x00; /* bmPINLengthFormat */
2403 pin_modify[5] = 0x00; /* bInsertionOffsetOld */
2404 pin_modify[6] = pininfo->fixedlen; /* bInsertionOffsetNew */
2405 pin_modify[7] = pininfo->maxlen; /* wPINMaxExtraDigit */
2406 pin_modify[8] = pininfo->minlen; /* wPINMaxExtraDigit */
2407 pin_modify[9] = (p0 == 0 ? 0x03 : 0x01);
2409 * 0x00: new PIN once
2410 * 0x01: new PIN twice (confirmation)
2411 * 0x02: old PIN and new PIN once
2412 * 0x03: old PIN and new PIN twice (confirmation)
2414 pin_modify[10] = 0x02; /* bEntryValidationCondition: Validation key pressed */
2415 if (pininfo->minlen && pininfo->maxlen && pininfo->minlen == pininfo->maxlen)
2416 pin_modify[10] |= 0x01; /* Max size reached. */
2417 pin_modify[11] = 0x03; /* bNumberMessage: Three messages */
2418 pin_modify[12] = 0x09; /* wLangId: 0x0409: US English */
2419 pin_modify[13] = 0x04; /* wLangId: 0x0409: US English */
2420 pin_modify[14] = 0x00; /* bMsgIndex1 */
2421 pin_modify[15] = 0x01; /* bMsgIndex2 */
2422 pin_modify[16] = 0x02; /* bMsgIndex3 */
2423 pin_modify[17] = 0x00; /* bTeoPrologue[0] */
2424 pin_modify[18] = 0x00; /* bTeoPrologue[1] */
2425 pin_modify[19] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* bTeoPrologue[2] */
2426 pin_modify[20] = 2 * pininfo->fixedlen + 0x05 - no_lc; /* ulDataLength */
2427 pin_modify[21] = 0x00; /* ulDataLength */
2428 pin_modify[22] = 0x00; /* ulDataLength */
2429 pin_modify[23] = 0x00; /* ulDataLength */
2430 pin_modify[24] = class; /* abData[0] */
2431 pin_modify[25] = ins; /* abData[1] */
2432 pin_modify[26] = p0; /* abData[2] */
2433 pin_modify[27] = p1; /* abData[3] */
2434 pin_modify[28] = 2 * pininfo->fixedlen; /* abData[4] */
2435 if (pininfo->fixedlen)
2436 memset (&pin_modify[29], 0xff, 2 * pininfo->fixedlen);
2441 log_debug ("send secure: c=%02X i=%02X p1=%02X p2=%02X len=%d pinmax=%d\n",
2442 class, ins, p0, p1, len, (int)pininfo->maxlen);
2444 sw = control_pcsc (slot, reader_table[slot].pcsc.modify_ioctl,
2445 pin_modify, len, result, &resultlen);
2447 if (sw || resultlen < 2)
2449 log_error ("control_pcsc failed: %d\n", sw);
2450 return sw? sw : SW_HOST_INCOMPLETE_CARD_RESPONSE;
2452 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2454 log_debug (" response: sw=%04X datalen=%d\n", sw, (unsigned int)resultlen);
2460 Internal CCID driver interface.
2465 dump_ccid_reader_status (int slot)
2467 log_info ("reader slot %d: using ccid driver\n", slot);
2471 close_ccid_reader (int slot)
2473 ccid_close_reader (reader_table[slot].ccid.handle);
2474 reader_table[slot].rdrname = NULL;
2475 reader_table[slot].used = 0;
2481 reset_ccid_reader (int slot)
2484 reader_table_t slotp = reader_table + slot;
2485 unsigned char atr[33];
2488 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
2491 /* If the reset was successful, update the ATR. */
2492 assert (sizeof slotp->atr >= sizeof atr);
2493 slotp->atrlen = atrlen;
2494 memcpy (slotp->atr, atr, atrlen);
2495 dump_reader_status (slot);
2501 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
2503 reader_table_t slotp = reader_table + slot;
2505 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
2510 get_status_ccid (int slot, unsigned int *status)
2515 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
2520 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
2522 *status = APDU_CARD_PRESENT;
2530 /* Actually send the APDU of length APDULEN to SLOT and return a
2531 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2532 set to BUFLEN. Returns: Internal CCID driver error code. */
2534 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
2535 unsigned char *buffer, size_t *buflen,
2541 /* If we don't have an ATR, we need to reset the reader first. */
2542 if (!reader_table[slot].atrlen
2543 && (err = reset_ccid_reader (slot)))
2547 log_printhex (" raw apdu:", apdu, apdulen);
2549 maxbuflen = *buflen;
2551 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
2552 apdu, apdulen, pininfo,
2553 buffer, maxbuflen, buflen);
2555 err = ccid_transceive (reader_table[slot].ccid.handle,
2557 buffer, maxbuflen, buflen);
2559 log_error ("ccid_transceive failed: (0x%lx)\n",
2566 /* Check whether the CCID reader supports the ISO command code COMMAND
2567 on the pinpad. Return 0 on success. For a description of the pin
2568 parameters, see ccid-driver.c */
2570 check_ccid_pinpad (int slot, int command, pininfo_t *pininfo)
2572 unsigned char apdu[] = { 0, 0, 0, 0x81 };
2575 return ccid_transceive_secure (reader_table[slot].ccid.handle, apdu,
2576 sizeof apdu, pininfo, NULL, 0, NULL);
2581 ccid_pinpad_operation (int slot, int class, int ins, int p0, int p1,
2584 unsigned char apdu[4];
2586 unsigned char result[2];
2587 size_t resultlen = 2;
2593 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
2594 apdu, sizeof apdu, pininfo,
2595 result, 2, &resultlen);
2600 return SW_HOST_INCOMPLETE_CARD_RESPONSE;
2602 sw = (result[resultlen-2] << 8) | result[resultlen-1];
2607 /* Open the reader and try to read an ATR. */
2609 open_ccid_reader (const char *portstr)
2613 reader_table_t slotp;
2615 slot = new_reader_slot ();
2618 slotp = reader_table + slot;
2620 err = ccid_open_reader (&slotp->ccid.handle, portstr,
2621 (const char **)&slotp->rdrname);
2629 err = ccid_get_atr (slotp->ccid.handle,
2630 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
2638 /* If we got to here we know that a card is present
2639 and usable. Thus remember this. */
2640 reader_table[slot].last_status = (APDU_CARD_USABLE
2642 | APDU_CARD_ACTIVE);
2645 reader_table[slot].close_reader = close_ccid_reader;
2646 reader_table[slot].reset_reader = reset_ccid_reader;
2647 reader_table[slot].get_status_reader = get_status_ccid;
2648 reader_table[slot].send_apdu_reader = send_apdu_ccid;
2649 reader_table[slot].check_pinpad = check_ccid_pinpad;
2650 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
2651 reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
2652 reader_table[slot].pinpad_verify = ccid_pinpad_operation;
2653 reader_table[slot].pinpad_modify = ccid_pinpad_operation;
2654 /* Our CCID reader code does not support T=0 at all, thus reset the
2656 reader_table[slot].is_t0 = 0;
2658 dump_reader_status (slot);
2665 #endif /* HAVE_LIBUSB */
2669 #ifdef USE_G10CODE_RAPDU
2671 The Remote APDU Interface.
2673 This uses the Remote APDU protocol to contact a reader.
2675 The port number is actually an index into the list of ports as
2676 returned via the protocol.
2681 rapdu_status_to_sw (int status)
2687 case RAPDU_STATUS_SUCCESS: rc = 0; break;
2689 case RAPDU_STATUS_INVCMD:
2690 case RAPDU_STATUS_INVPROT:
2691 case RAPDU_STATUS_INVSEQ:
2692 case RAPDU_STATUS_INVCOOKIE:
2693 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
2695 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
2696 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
2697 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
2698 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
2699 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2700 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2702 default: rc = SW_HOST_GENERAL_ERROR; break;
2711 close_rapdu_reader (int slot)
2713 rapdu_release (reader_table[slot].rapdu.handle);
2714 reader_table[slot].used = 0;
2720 reset_rapdu_reader (int slot)
2723 reader_table_t slotp;
2724 rapdu_msg_t msg = NULL;
2726 slotp = reader_table + slot;
2728 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2731 log_error ("sending rapdu command RESET failed: %s\n",
2732 err < 0 ? strerror (errno): rapdu_strerror (err));
2733 rapdu_msg_release (msg);
2734 return rapdu_status_to_sw (err);
2736 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2739 log_error ("receiving rapdu message failed: %s\n",
2740 err < 0 ? strerror (errno): rapdu_strerror (err));
2741 rapdu_msg_release (msg);
2742 return rapdu_status_to_sw (err);
2744 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2746 int sw = rapdu_status_to_sw (msg->cmd);
2747 log_error ("rapdu command RESET failed: %s\n",
2748 rapdu_strerror (msg->cmd));
2749 rapdu_msg_release (msg);
2752 if (msg->datalen > DIM (slotp->atr))
2754 log_error ("ATR returned by the RAPDU layer is too large\n");
2755 rapdu_msg_release (msg);
2756 return SW_HOST_INV_VALUE;
2758 slotp->atrlen = msg->datalen;
2759 memcpy (slotp->atr, msg->data, msg->datalen);
2761 rapdu_msg_release (msg);
2767 my_rapdu_get_status (int slot, unsigned int *status)
2770 reader_table_t slotp;
2771 rapdu_msg_t msg = NULL;
2774 slotp = reader_table + slot;
2776 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2777 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2778 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2781 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2782 err < 0 ? strerror (errno): rapdu_strerror (err));
2783 return rapdu_status_to_sw (err);
2785 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2788 log_error ("receiving rapdu message failed: %s\n",
2789 err < 0 ? strerror (errno): rapdu_strerror (err));
2790 rapdu_msg_release (msg);
2791 return rapdu_status_to_sw (err);
2793 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2795 int sw = rapdu_status_to_sw (msg->cmd);
2796 log_error ("rapdu command GET_STATUS failed: %s\n",
2797 rapdu_strerror (msg->cmd));
2798 rapdu_msg_release (msg);
2801 *status = msg->data[0];
2803 rapdu_msg_release (msg);
2808 /* Actually send the APDU of length APDULEN to SLOT and return a
2809 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2810 set to BUFLEN. Returns: APDU error code. */
2812 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2813 unsigned char *buffer, size_t *buflen,
2817 reader_table_t slotp;
2818 rapdu_msg_t msg = NULL;
2819 size_t maxlen = *buflen;
2821 slotp = reader_table + slot;
2825 log_printhex (" APDU_data:", apdu, apdulen);
2829 log_error ("rapdu_send_apdu: APDU is too short\n");
2830 return SW_HOST_INV_VALUE;
2833 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2836 log_error ("sending rapdu command APDU failed: %s\n",
2837 err < 0 ? strerror (errno): rapdu_strerror (err));
2838 rapdu_msg_release (msg);
2839 return rapdu_status_to_sw (err);
2841 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2844 log_error ("receiving rapdu message failed: %s\n",
2845 err < 0 ? strerror (errno): rapdu_strerror (err));
2846 rapdu_msg_release (msg);
2847 return rapdu_status_to_sw (err);
2849 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2851 int sw = rapdu_status_to_sw (msg->cmd);
2852 log_error ("rapdu command APDU failed: %s\n",
2853 rapdu_strerror (msg->cmd));
2854 rapdu_msg_release (msg);
2858 if (msg->datalen > maxlen)
2860 log_error ("rapdu response apdu too large\n");
2861 rapdu_msg_release (msg);
2862 return SW_HOST_INV_VALUE;
2865 *buflen = msg->datalen;
2866 memcpy (buffer, msg->data, msg->datalen);
2868 rapdu_msg_release (msg);
2873 open_rapdu_reader (int portno,
2874 const unsigned char *cookie, size_t length,
2875 int (*readfnc) (void *opaque,
2876 void *buffer, size_t size),
2877 void *readfnc_value,
2878 int (*writefnc) (void *opaque,
2879 const void *buffer, size_t size),
2880 void *writefnc_value,
2881 void (*closefnc) (void *opaque),
2882 void *closefnc_value)
2886 reader_table_t slotp;
2887 rapdu_msg_t msg = NULL;
2889 slot = new_reader_slot ();
2892 slotp = reader_table + slot;
2894 slotp->rapdu.handle = rapdu_new ();
2895 if (!slotp->rapdu.handle)
2902 rapdu_set_reader (slotp->rapdu.handle, portno);
2904 rapdu_set_iofunc (slotp->rapdu.handle,
2905 readfnc, readfnc_value,
2906 writefnc, writefnc_value,
2907 closefnc, closefnc_value);
2908 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2910 /* First try to get the current ATR, but if the card is inactive
2911 issue a reset instead. */
2912 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2913 if (err == RAPDU_STATUS_NEEDRESET)
2914 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2917 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2918 err < 0 ? strerror (errno): rapdu_strerror (err));
2921 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2924 log_info ("receiving rapdu message failed: %s\n",
2925 err < 0 ? strerror (errno): rapdu_strerror (err));
2928 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2930 log_info ("rapdu command GET ATR failed: %s\n",
2931 rapdu_strerror (msg->cmd));
2934 if (msg->datalen > DIM (slotp->atr))
2936 log_error ("ATR returned by the RAPDU layer is too large\n");
2939 slotp->atrlen = msg->datalen;
2940 memcpy (slotp->atr, msg->data, msg->datalen);
2942 reader_table[slot].close_reader = close_rapdu_reader;
2943 reader_table[slot].reset_reader = reset_rapdu_reader;
2944 reader_table[slot].get_status_reader = my_rapdu_get_status;
2945 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2946 reader_table[slot].check_pinpad = NULL;
2947 reader_table[slot].dump_status_reader = NULL;
2948 reader_table[slot].pinpad_verify = NULL;
2949 reader_table[slot].pinpad_modify = NULL;
2951 dump_reader_status (slot);
2952 rapdu_msg_release (msg);
2957 rapdu_msg_release (msg);
2958 rapdu_release (slotp->rapdu.handle);
2964 #endif /*USE_G10CODE_RAPDU*/
2973 /* Open the reader and return an internal slot number or -1 on
2974 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2975 the first USB reader. For PC/SC the first listed reader). */
2977 apdu_open_reader (const char *portstr)
2979 static int pcsc_api_loaded, ct_api_loaded;
2983 log_debug ("enter: apdu_open_reader: portstr=%s\n", portstr);
2986 if (!opt.disable_ccid)
2988 static int once_available;
2992 slot = open_ccid_reader (portstr);
2997 log_debug ("leave: apdu_open_reader => slot=%d [ccid]\n", slot);
2998 return slot; /* got one */
3001 /* If we ever loaded successfully loaded a CCID reader we never
3002 want to fallback to another driver. This solves a problem
3003 where ccid was used, the card unplugged and then scdaemon
3004 tries to find a new reader and will eventually try PC/SC over
3005 and over again. To reset this flag "gpgconf --kill scdaemon"
3010 log_debug ("leave: apdu_open_reader => slot=-1 (once_avail)\n");
3014 /* If a CCID reader specification has been given, the user does
3015 not want a fallback to other drivers. */
3017 for (s=portstr, i=0; *s; s++)
3018 if (*s == ':' && (++i == 3))
3021 log_debug ("leave: apdu_open_reader => slot=-1 (no ccid)\n");
3026 #endif /* HAVE_LIBUSB */
3028 if (opt.ctapi_driver && *opt.ctapi_driver)
3030 int port = portstr? atoi (portstr) : 32768;
3036 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
3039 log_error ("apdu_open_reader: failed to open driver: %s\n",
3043 CT_init = dlsym (handle, "CT_init");
3044 CT_data = dlsym (handle, "CT_data");
3045 CT_close = dlsym (handle, "CT_close");
3046 if (!CT_init || !CT_data || !CT_close)
3048 log_error ("apdu_open_reader: invalid CT-API driver\n");
3054 return open_ct_reader (port);
3058 /* No ctAPI configured, so lets try the PC/SC API */
3059 if (!pcsc_api_loaded)
3061 #ifndef NEED_PCSC_WRAPPER
3064 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
3067 log_error ("apdu_open_reader: failed to open driver '%s': %s\n",
3068 opt.pcsc_driver, dlerror ());
3072 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
3073 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
3074 pcsc_list_readers = dlsym (handle, "SCardListReaders");
3075 #if defined(_WIN32) || defined(__CYGWIN__)
3076 if (!pcsc_list_readers)
3077 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
3079 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
3080 #if defined(_WIN32) || defined(__CYGWIN__)
3081 if (!pcsc_get_status_change)
3082 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
3084 pcsc_connect = dlsym (handle, "SCardConnect");
3085 #if defined(_WIN32) || defined(__CYGWIN__)
3087 pcsc_connect = dlsym (handle, "SCardConnectA");
3089 pcsc_reconnect = dlsym (handle, "SCardReconnect");
3090 #if defined(_WIN32) || defined(__CYGWIN__)
3091 if (!pcsc_reconnect)
3092 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
3094 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
3095 pcsc_status = dlsym (handle, "SCardStatus");
3096 #if defined(_WIN32) || defined(__CYGWIN__)
3098 pcsc_status = dlsym (handle, "SCardStatusA");
3100 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
3101 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
3102 pcsc_transmit = dlsym (handle, "SCardTransmit");
3103 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
3104 pcsc_control = dlsym (handle, "SCardControl");
3106 if (!pcsc_establish_context
3107 || !pcsc_release_context
3108 || !pcsc_list_readers
3109 || !pcsc_get_status_change
3114 || !pcsc_begin_transaction
3115 || !pcsc_end_transaction
3118 /* || !pcsc_set_timeout */)
3120 /* Note that set_timeout is currently not used and also not
3121 available under Windows. */
3122 log_error ("apdu_open_reader: invalid PC/SC driver "
3123 "(%d%d%d%d%d%d%d%d%d%d%d%d%d)\n",
3124 !!pcsc_establish_context,
3125 !!pcsc_release_context,
3126 !!pcsc_list_readers,
3127 !!pcsc_get_status_change,
3132 !!pcsc_begin_transaction,
3133 !!pcsc_end_transaction,
3140 #endif /*!NEED_PCSC_WRAPPER*/
3141 pcsc_api_loaded = 1;
3144 slot = open_pcsc_reader (portstr);
3147 log_debug ("leave: apdu_open_reader => slot=%d [pc/sc]\n", slot);
3152 /* Open an remote reader and return an internal slot number or -1 on
3153 error. This function is an alternative to apdu_open_reader and used
3154 with remote readers only. Note that the supplied CLOSEFNC will
3155 only be called once and the slot will not be valid afther this.
3157 If PORTSTR is NULL we default to the first available port.
3160 apdu_open_remote_reader (const char *portstr,
3161 const unsigned char *cookie, size_t length,
3162 int (*readfnc) (void *opaque,
3163 void *buffer, size_t size),
3164 void *readfnc_value,
3165 int (*writefnc) (void *opaque,
3166 const void *buffer, size_t size),
3167 void *writefnc_value,
3168 void (*closefnc) (void *opaque),
3169 void *closefnc_value)
3171 #ifdef USE_G10CODE_RAPDU
3172 return open_rapdu_reader (portstr? atoi (portstr) : 0,
3174 readfnc, readfnc_value,
3175 writefnc, writefnc_value,
3176 closefnc, closefnc_value);
3182 (void)readfnc_value;
3184 (void)writefnc_value;
3186 (void)closefnc_value;
3198 apdu_close_reader (int slot)
3203 log_debug ("enter: apdu_close_reader: slot=%d\n", slot);
3205 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3208 log_debug ("leave: apdu_close_reader => SW_HOST_NO_DRIVER\n");
3209 return SW_HOST_NO_DRIVER;
3211 sw = apdu_disconnect (slot);
3215 * When the reader/token was removed it might come here.
3216 * It should go through to call CLOSE_READER even if we got an error.
3219 log_debug ("apdu_close_reader => 0x%x (apdu_disconnect)\n", sw);
3221 if (reader_table[slot].close_reader)
3223 sw = reader_table[slot].close_reader (slot);
3225 log_debug ("leave: apdu_close_reader => 0x%x (close_reader)\n", sw);
3229 log_debug ("leave: apdu_close_reader => SW_HOST_NOT_SUPPORTED\n");
3230 return SW_HOST_NOT_SUPPORTED;
3234 /* Function suitable for a cleanup function to close all reader. It
3235 should not be used if the reader will be opened again. The reason
3236 for implementing this to properly close USB devices so that they
3237 will startup the next time without error. */
3239 apdu_prepare_exit (void)
3241 static int sentinel;
3247 for (slot = 0; slot < MAX_READER; slot++)
3248 if (reader_table[slot].used)
3250 apdu_disconnect (slot);
3251 if (reader_table[slot].close_reader)
3252 reader_table[slot].close_reader (slot);
3253 reader_table[slot].used = 0;
3260 /* Enumerate all readers and return information on whether this reader
3261 is in use. The caller should start with SLOT set to 0 and
3262 increment it with each call until an error is returned. */
3264 apdu_enum_reader (int slot, int *used)
3266 if (slot < 0 || slot >= MAX_READER)
3267 return SW_HOST_NO_DRIVER;
3268 *used = reader_table[slot].used;
3273 /* Connect a card. This is used to power up the card and make sure
3274 that an ATR is available. Depending on the reader backend it may
3275 return an error for an inactive card or if no card is
3278 apdu_connect (int slot)
3281 unsigned int status = 0;
3284 log_debug ("enter: apdu_connect: slot=%d\n", slot);
3286 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3289 log_debug ("leave: apdu_connect => SW_HOST_NO_DRIVER\n");
3290 return SW_HOST_NO_DRIVER;
3293 /* Only if the access method provides a connect function we use it.
3294 If not, we expect that the card has been implicitly connected by
3295 apdu_open_reader. */
3296 if (reader_table[slot].connect_card)
3298 sw = lock_slot (slot);
3301 sw = reader_table[slot].connect_card (slot);
3306 /* We need to call apdu_get_status_internal, so that the last-status
3307 machinery gets setup properly even if a card is inserted while
3308 scdaemon is fired up and apdu_get_status has not yet been called.
3309 Without that we would force a reset of the card with the next
3310 call to apdu_get_status. */
3312 sw = apdu_get_status_internal (slot, 1, 1, &status, NULL);
3316 else if (!(status & APDU_CARD_PRESENT))
3317 sw = SW_HOST_NO_CARD;
3318 else if ((status & APDU_CARD_PRESENT) && !(status & APDU_CARD_ACTIVE))
3319 sw = SW_HOST_CARD_INACTIVE;
3322 log_debug ("leave: apdu_connect => sw=0x%x\n", sw);
3329 apdu_disconnect (int slot)
3334 log_debug ("enter: apdu_disconnect: slot=%d\n", slot);
3336 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3339 log_debug ("leave: apdu_disconnect => SW_HOST_NO_DRIVER\n");
3340 return SW_HOST_NO_DRIVER;
3343 if (reader_table[slot].disconnect_card)
3345 sw = lock_slot (slot);
3348 sw = reader_table[slot].disconnect_card (slot);
3356 log_debug ("leave: apdu_disconnect => sw=0x%x\n", sw);
3361 /* Set the progress callback of SLOT to CB and its args to CB_ARG. If
3362 CB is NULL the progress callback is removed. */
3364 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
3368 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3369 return SW_HOST_NO_DRIVER;
3371 if (reader_table[slot].set_progress_cb)
3373 sw = lock_slot (slot);
3376 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
3386 /* Do a reset for the card in reader at SLOT. */
3388 apdu_reset (int slot)
3393 log_debug ("enter: apdu_reset: slot=%d\n", slot);
3395 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3398 log_debug ("leave: apdu_reset => SW_HOST_NO_DRIVER\n");
3399 return SW_HOST_NO_DRIVER;
3402 if ((sw = lock_slot (slot)))
3405 log_debug ("leave: apdu_reset => sw=0x%x (lock_slot)\n", sw);
3409 reader_table[slot].last_status = 0;
3410 if (reader_table[slot].reset_reader)
3411 sw = reader_table[slot].reset_reader (slot);
3415 /* If we got to here we know that a card is present
3416 and usable. Thus remember this. */
3417 reader_table[slot].last_status = (APDU_CARD_USABLE
3419 | APDU_CARD_ACTIVE);
3424 log_debug ("leave: apdu_reset => sw=0x%x\n", sw);
3429 /* Return the ATR or NULL if none is available. On success the length
3430 of the ATR is stored at ATRLEN. The caller must free the returned
3433 apdu_get_atr (int slot, size_t *atrlen)
3438 log_debug ("enter: apdu_get_atr: slot=%d\n", slot);
3440 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3443 log_debug ("leave: apdu_get_atr => NULL (bad slot)\n");
3446 if (!reader_table[slot].atrlen)
3449 log_debug ("leave: apdu_get_atr => NULL (no ATR)\n");
3453 buf = xtrymalloc (reader_table[slot].atrlen);
3457 log_debug ("leave: apdu_get_atr => NULL (out of core)\n");
3460 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
3461 *atrlen = reader_table[slot].atrlen;
3463 log_debug ("leave: apdu_get_atr => atrlen=%zu\n", *atrlen);
3469 /* Retrieve the status for SLOT. The function does only wait for the
3470 card to become available if HANG is set to true. On success the
3471 bits in STATUS will be set to
3473 APDU_CARD_USABLE (bit 0) = card present and usable
3474 APDU_CARD_PRESENT (bit 1) = card present
3475 APDU_CARD_ACTIVE (bit 2) = card active
3476 (bit 3) = card access locked [not yet implemented]
3478 For must applications, testing bit 0 is sufficient.
3480 CHANGED will receive the value of the counter tracking the number
3481 of card insertions. This value may be used to detect a card
3485 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
3486 unsigned int *status, unsigned int *changed)
3491 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3492 return SW_HOST_NO_DRIVER;
3494 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
3497 if (reader_table[slot].get_status_reader)
3498 sw = reader_table[slot].get_status_reader (slot, &s);
3504 reader_table[slot].last_status = 0;
3508 /* Keep track of changes. */
3509 if (s != reader_table[slot].last_status
3510 || !reader_table[slot].any_status )
3512 reader_table[slot].change_counter++;
3513 /* Make sure that the ATR is invalid so that a reset will be
3514 triggered by apdu_activate. */
3516 reader_table[slot].atrlen = 0;
3518 reader_table[slot].any_status = 1;
3519 reader_table[slot].last_status = s;
3524 *changed = reader_table[slot].change_counter;
3529 /* See above for a description. */
3531 apdu_get_status (int slot, int hang,
3532 unsigned int *status, unsigned int *changed)
3537 log_debug ("enter: apdu_get_status: slot=%d hang=%d\n", slot, hang);
3538 sw = apdu_get_status_internal (slot, hang, 0, status, changed);
3541 if (status && changed)
3542 log_debug ("leave: apdu_get_status => sw=0x%x status=%u changecnt=%u\n",
3543 sw, *status, *changed);
3545 log_debug ("leave: apdu_get_status => sw=0x%x status=%u\n",
3548 log_debug ("leave: apdu_get_status => sw=0x%x changed=%u\n",
3551 log_debug ("leave: apdu_get_status => sw=0x%x\n", sw);
3557 /* Check whether the reader supports the ISO command code COMMAND on
3558 the pinpad. Return 0 on success. For a description of the pin
3559 parameters, see ccid-driver.c */
3561 apdu_check_pinpad (int slot, int command, pininfo_t *pininfo)
3563 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3564 return SW_HOST_NO_DRIVER;
3566 if (opt.enable_pinpad_varlen)
3567 pininfo->fixedlen = 0;
3569 if (reader_table[slot].check_pinpad)
3573 if ((sw = lock_slot (slot)))
3576 sw = reader_table[slot].check_pinpad (slot, command, pininfo);
3581 return SW_HOST_NOT_SUPPORTED;
3586 apdu_pinpad_verify (int slot, int class, int ins, int p0, int p1,
3589 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3590 return SW_HOST_NO_DRIVER;
3592 if (reader_table[slot].pinpad_verify)
3596 if ((sw = lock_slot (slot)))
3599 sw = reader_table[slot].pinpad_verify (slot, class, ins, p0, p1,
3605 return SW_HOST_NOT_SUPPORTED;
3610 apdu_pinpad_modify (int slot, int class, int ins, int p0, int p1,
3613 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3614 return SW_HOST_NO_DRIVER;
3616 if (reader_table[slot].pinpad_modify)
3620 if ((sw = lock_slot (slot)))
3623 sw = reader_table[slot].pinpad_modify (slot, class, ins, p0, p1,
3629 return SW_HOST_NOT_SUPPORTED;
3633 /* Dispatcher for the actual send_apdu function. Note, that this
3634 function should be called in locked state. */
3636 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
3637 unsigned char *buffer, size_t *buflen, pininfo_t *pininfo)
3639 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3640 return SW_HOST_NO_DRIVER;
3642 if (reader_table[slot].send_apdu_reader)
3643 return reader_table[slot].send_apdu_reader (slot,
3648 return SW_HOST_NOT_SUPPORTED;
3652 /* Core APDU tranceiver function. Parameters are described at
3653 apdu_send_le with the exception of PININFO which indicates pinpad
3654 related operations if not NULL. If EXTENDED_MODE is not 0
3655 command chaining or extended length will be used according to these
3657 n < 0 := Use command chaining with the data part limited to -n
3658 in each chunk. If -1 is used a default value is used.
3659 n == 0 := No extended mode or command chaining.
3660 n == 1 := Use extended length for input and output without a
3662 n > 1 := Use extended length with up to N bytes.
3666 send_le (int slot, int class, int ins, int p0, int p1,
3667 int lc, const char *data, int le,
3668 unsigned char **retbuf, size_t *retbuflen,
3669 pininfo_t *pininfo, int extended_mode)
3671 #define SHORT_RESULT_BUFFER_SIZE 258
3672 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
3673 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3674 unsigned char *result_buffer = NULL;
3675 size_t result_buffer_size;
3676 unsigned char *result;
3678 unsigned char short_apdu_buffer[5+256+1];
3679 unsigned char *apdu_buffer = NULL;
3680 size_t apdu_buffer_size;
3681 unsigned char *apdu;
3684 long rc; /* We need a long here due to PC/SC. */
3685 int did_exact_length_hack = 0;
3686 int use_chaining = 0;
3687 int use_extended_length = 0;
3690 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3691 return SW_HOST_NO_DRIVER;
3694 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
3695 class, ins, p0, p1, lc, le, extended_mode);
3697 if (lc != -1 && (lc > 255 || lc < 0))
3699 /* Data does not fit into an APDU. What we do now depends on
3700 the EXTENDED_MODE parameter. */
3702 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
3703 else if (extended_mode > 0)
3704 use_extended_length = 1;
3705 else if (extended_mode < 0)
3707 /* Send APDU using chaining mode. */
3709 return SW_WRONG_LENGTH; /* Sanity check. */
3710 if ((class&0xf0) != 0)
3711 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
3712 use_chaining = extended_mode == -1? 255 : -extended_mode;
3713 use_chaining &= 0xff;
3716 return SW_HOST_INV_VALUE;
3718 else if (lc == -1 && extended_mode > 0)
3719 use_extended_length = 1;
3721 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
3723 /* Expected Data does not fit into an APDU. What we do now
3724 depends on the EXTENDED_MODE parameter. Note that a check
3725 for command chaining does not make sense because we are
3728 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
3729 else if (use_extended_length)
3730 ; /* We are already using extended length. */
3731 else if (extended_mode > 0)
3732 use_extended_length = 1;
3734 return SW_HOST_INV_VALUE;
3737 if ((!data && lc != -1) || (data && lc == -1))
3738 return SW_HOST_INV_VALUE;
3740 if (use_extended_length)
3742 if (reader_table[slot].is_t0)
3743 return SW_HOST_NOT_SUPPORTED;
3745 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
3746 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
3747 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
3749 return SW_HOST_OUT_OF_CORE;
3754 apdu_buffer_size = sizeof short_apdu_buffer;
3755 apdu = short_apdu_buffer;
3758 if (use_extended_length && (le > 256 || le < 0))
3760 /* Two more bytes are needed for status bytes. */
3761 result_buffer_size = le < 0? 4096 : (le + 2);
3762 result_buffer = xtrymalloc (result_buffer_size);
3765 xfree (apdu_buffer);
3766 return SW_HOST_OUT_OF_CORE;
3768 result = result_buffer;
3772 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3773 result = short_result_buffer;
3775 #undef SHORT_RESULT_BUFFER_SIZE
3777 if ((sw = lock_slot (slot)))
3779 xfree (apdu_buffer);
3780 xfree (result_buffer);
3786 if (use_extended_length)
3790 apdu[apdulen++] = class;
3791 apdu[apdulen++] = ins;
3792 apdu[apdulen++] = p0;
3793 apdu[apdulen++] = p1;
3796 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3797 apdu[apdulen++] = ((lc >> 8) & 0xff);
3798 apdu[apdulen++] = (lc & 0xff);
3799 memcpy (apdu+apdulen, data, lc);
3806 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3807 apdu[apdulen++] = ((le >> 8) & 0xff);
3808 apdu[apdulen++] = (le & 0xff);
3814 apdu[apdulen] = class;
3815 if (use_chaining && lc > 255)
3817 apdu[apdulen] |= 0x10;
3818 assert (use_chaining < 256);
3819 lc_chunk = use_chaining;
3828 apdu[apdulen++] = ins;
3829 apdu[apdulen++] = p0;
3830 apdu[apdulen++] = p1;
3833 apdu[apdulen++] = lc_chunk;
3834 memcpy (apdu+apdulen, data, lc_chunk);
3836 apdulen += lc_chunk;
3837 /* T=0 does not allow the use of Lc together with Le;
3838 thus disable Le in this case. */
3839 if (reader_table[slot].is_t0)
3842 if (le != -1 && !use_chaining)
3843 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3847 /* As a safeguard don't pass any garbage to the driver. */
3848 assert (apdulen <= apdu_buffer_size);
3849 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3850 resultlen = result_buffer_size;
3851 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3852 if (rc || resultlen < 2)
3854 log_info ("apdu_send_simple(%d) failed: %s\n",
3855 slot, apdu_strerror (rc));
3857 xfree (apdu_buffer);
3858 xfree (result_buffer);
3859 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3861 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3862 if (!use_extended_length
3863 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3865 apdu[apdulen-1] = (sw & 0x00ff);
3866 did_exact_length_hack = 1;
3867 goto exact_length_hack;
3870 while (use_chaining && sw == SW_SUCCESS);
3874 xfree (apdu_buffer);
3876 apdu_buffer_size = 0;
3879 /* Store away the returned data but strip the statusword. */
3883 log_debug (" response: sw=%04X datalen=%d\n",
3884 sw, (unsigned int)resultlen);
3885 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3886 log_printhex (" dump: ", result, resultlen);
3889 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3893 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3897 xfree (result_buffer);
3898 return SW_HOST_OUT_OF_CORE;
3900 *retbuflen = resultlen;
3901 memcpy (*retbuf, result, resultlen);
3904 else if ((sw & 0xff00) == SW_MORE_DATA)
3906 unsigned char *p = NULL, *tmp;
3907 size_t bufsize = 4096;
3909 /* It is likely that we need to return much more data, so we
3910 start off with a large buffer. */
3913 *retbuf = p = xtrymalloc (bufsize);
3917 xfree (result_buffer);
3918 return SW_HOST_OUT_OF_CORE;
3920 assert (resultlen < bufsize);
3921 memcpy (p, result, resultlen);
3927 int len = (sw & 0x00ff);
3930 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3932 apdu_buffer_size = sizeof short_apdu_buffer;
3933 apdu = short_apdu_buffer;
3935 apdu[apdulen++] = class;
3936 apdu[apdulen++] = 0xC0;
3937 apdu[apdulen++] = 0;
3938 apdu[apdulen++] = 0;
3939 apdu[apdulen++] = len;
3940 assert (apdulen <= apdu_buffer_size);
3941 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3942 resultlen = result_buffer_size;
3943 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3944 if (rc || resultlen < 2)
3946 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3947 slot, apdu_strerror (rc));
3949 xfree (result_buffer);
3950 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3952 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3956 log_debug (" more: sw=%04X datalen=%d\n",
3957 sw, (unsigned int)resultlen);
3958 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3959 log_printhex (" dump: ", result, resultlen);
3962 if ((sw & 0xff00) == SW_MORE_DATA
3964 || sw == SW_EOF_REACHED )
3966 if (retbuf && resultlen)
3968 if (p - *retbuf + resultlen > bufsize)
3970 bufsize += resultlen > 4096? resultlen: 4096;
3971 tmp = xtryrealloc (*retbuf, bufsize);
3975 xfree (result_buffer);
3976 return SW_HOST_OUT_OF_CORE;
3978 p = tmp + (p - *retbuf);
3981 memcpy (p, result, resultlen);
3986 log_info ("apdu_send_simple(%d) "
3987 "got unexpected status %04X from get response\n",
3990 while ((sw & 0xff00) == SW_MORE_DATA);
3994 *retbuflen = p - *retbuf;
3995 tmp = xtryrealloc (*retbuf, *retbuflen);
4002 xfree (result_buffer);
4004 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
4005 log_printhex (" dump: ", *retbuf, *retbuflen);
4010 /* Send an APDU to the card in SLOT. The APDU is created from all
4011 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
4012 for LC won't sent this field and the data field; in this case DATA
4013 must also be passed as NULL. If EXTENDED_MODE is not 0 command
4014 chaining or extended length will be used; see send_le for details.
4015 The return value is the status word or -1 for an invalid SLOT or
4016 other non card related error. If RETBUF is not NULL, it will
4017 receive an allocated buffer with the returned data. The length of
4018 that data will be put into *RETBUFLEN. The caller is responsible
4019 for releasing the buffer even in case of errors. */
4021 apdu_send_le(int slot, int extended_mode,
4022 int class, int ins, int p0, int p1,
4023 int lc, const char *data, int le,
4024 unsigned char **retbuf, size_t *retbuflen)
4026 return send_le (slot, class, ins, p0, p1,
4029 NULL, extended_mode);
4033 /* Send an APDU to the card in SLOT. The APDU is created from all
4034 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
4035 LC won't sent this field and the data field; in this case DATA must
4036 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
4037 or extended length will be used; see send_le for details. The
4038 return value is the status word or -1 for an invalid SLOT or other
4039 non card related error. If RETBUF is not NULL, it will receive an
4040 allocated buffer with the returned data. The length of that data
4041 will be put into *RETBUFLEN. The caller is responsible for
4042 releasing the buffer even in case of errors. */
4044 apdu_send (int slot, int extended_mode,
4045 int class, int ins, int p0, int p1,
4046 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
4048 return send_le (slot, class, ins, p0, p1, lc, data, 256,
4049 retbuf, retbuflen, NULL, extended_mode);
4052 /* Send an APDU to the card in SLOT. The APDU is created from all
4053 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
4054 LC won't sent this field and the data field; in this case DATA must
4055 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
4056 or extended length will be used; see send_le for details. The
4057 return value is the status word or -1 for an invalid SLOT or other
4058 non card related error. No data will be returned. */
4060 apdu_send_simple (int slot, int extended_mode,
4061 int class, int ins, int p0, int p1,
4062 int lc, const char *data)
4064 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
4069 /* This is a more generic version of the apdu sending routine. It
4070 takes an already formatted APDU in APDUDATA or length APDUDATALEN
4071 and returns with an APDU including the status word. With
4072 HANDLE_MORE set to true this function will handle the MORE DATA
4073 status and return all APDUs concatenated with one status word at
4074 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
4075 with a max. result data length of EXTENDED_LENGTH bytes. The
4076 function does not return a regular status word but 0 on success.
4077 If the slot is locked, the function returns immediately with an
4080 apdu_send_direct (int slot, size_t extended_length,
4081 const unsigned char *apdudata, size_t apdudatalen,
4083 unsigned char **retbuf, size_t *retbuflen)
4085 #define SHORT_RESULT_BUFFER_SIZE 258
4086 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
4087 unsigned char *result_buffer = NULL;
4088 size_t result_buffer_size;
4089 unsigned char *result;
4091 unsigned char short_apdu_buffer[5+256+10];
4092 unsigned char *apdu_buffer = NULL;
4093 unsigned char *apdu;
4096 long rc; /* we need a long here due to PC/SC. */
4099 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
4100 return SW_HOST_NO_DRIVER;
4102 if (apdudatalen > 65535)
4103 return SW_HOST_INV_VALUE;
4105 if (apdudatalen > sizeof short_apdu_buffer - 5)
4107 apdu_buffer = xtrymalloc (apdudatalen + 5);
4109 return SW_HOST_OUT_OF_CORE;
4114 apdu = short_apdu_buffer;
4116 apdulen = apdudatalen;
4117 memcpy (apdu, apdudata, apdudatalen);
4118 class = apdulen? *apdu : 0;
4120 if (extended_length >= 256 && extended_length <= 65536)
4122 result_buffer_size = extended_length;
4123 result_buffer = xtrymalloc (result_buffer_size + 10);
4126 xfree (apdu_buffer);
4127 return SW_HOST_OUT_OF_CORE;
4129 result = result_buffer;
4133 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
4134 result = short_result_buffer;
4136 #undef SHORT_RESULT_BUFFER_SIZE
4138 if ((sw = trylock_slot (slot)))
4140 xfree (apdu_buffer);
4141 xfree (result_buffer);
4145 resultlen = result_buffer_size;
4146 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
4147 xfree (apdu_buffer);
4149 if (rc || resultlen < 2)
4151 log_error ("apdu_send_direct(%d) failed: %s\n",
4152 slot, apdu_strerror (rc));
4154 xfree (result_buffer);
4155 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
4157 sw = (result[resultlen-2] << 8) | result[resultlen-1];
4158 /* Store away the returned data but strip the statusword. */
4162 log_debug (" response: sw=%04X datalen=%d\n",
4163 sw, (unsigned int)resultlen);
4164 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
4165 log_printhex (" dump: ", result, resultlen);
4168 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
4170 unsigned char *p = NULL, *tmp;
4171 size_t bufsize = 4096;
4173 /* It is likely that we need to return much more data, so we
4174 start off with a large buffer. */
4177 *retbuf = p = xtrymalloc (bufsize + 2);
4181 xfree (result_buffer);
4182 return SW_HOST_OUT_OF_CORE;
4184 assert (resultlen < bufsize);
4185 memcpy (p, result, resultlen);
4191 int len = (sw & 0x00ff);
4194 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
4196 apdu = short_apdu_buffer;
4198 apdu[apdulen++] = class;
4199 apdu[apdulen++] = 0xC0;
4200 apdu[apdulen++] = 0;
4201 apdu[apdulen++] = 0;
4202 apdu[apdulen++] = len;
4203 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
4204 resultlen = result_buffer_size;
4205 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
4206 if (rc || resultlen < 2)
4208 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
4209 slot, apdu_strerror (rc));
4211 xfree (result_buffer);
4212 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
4214 sw = (result[resultlen-2] << 8) | result[resultlen-1];
4218 log_debug (" more: sw=%04X datalen=%d\n",
4219 sw, (unsigned int)resultlen);
4220 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
4221 log_printhex (" dump: ", result, resultlen);
4224 if ((sw & 0xff00) == SW_MORE_DATA
4226 || sw == SW_EOF_REACHED )
4228 if (retbuf && resultlen)
4230 if (p - *retbuf + resultlen > bufsize)
4232 bufsize += resultlen > 4096? resultlen: 4096;
4233 tmp = xtryrealloc (*retbuf, bufsize + 2);
4237 xfree (result_buffer);
4238 return SW_HOST_OUT_OF_CORE;
4240 p = tmp + (p - *retbuf);
4243 memcpy (p, result, resultlen);
4248 log_info ("apdu_send_direct(%d) "
4249 "got unexpected status %04X from get response\n",
4252 while ((sw & 0xff00) == SW_MORE_DATA);
4256 *retbuflen = p - *retbuf;
4257 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
4266 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
4270 xfree (result_buffer);
4271 return SW_HOST_OUT_OF_CORE;
4273 *retbuflen = resultlen;
4274 memcpy (*retbuf, result, resultlen);
4279 xfree (result_buffer);
4281 /* Append the status word. Note that we reserved the two extra
4282 bytes while allocating the buffer. */
4285 (*retbuf)[(*retbuflen)++] = (sw >> 8);
4286 (*retbuf)[(*retbuflen)++] = sw;
4289 if (DBG_CARD_IO && retbuf)
4290 log_printhex (" dump: ", *retbuf, *retbuflen);
4297 apdu_get_reader_name (int slot)
4299 return reader_table[slot].rdrname;