Enable readline support in --card-edit.
[gnupg.git] / scd / apdu.c
blobd114b6eca7de8083b3cbe18dd5a16c4fbb98a00b
1 /* apdu.c - ISO 7816 APDU functions and low level I/O
2 * Copyright (C) 2003, 2004, 2008, 2009 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 * $Id$
22 /* NOTE: This module is also used by other software, thus the use of
23 the macro USE_GNU_PTH is mandatory. For GnuPG this macro is
24 guaranteed to be defined true. */
26 #include <config.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <signal.h>
33 #ifdef USE_GNU_PTH
34 # include <unistd.h>
35 # include <fcntl.h>
36 # include <pth.h>
37 #endif
40 /* If requested include the definitions for the remote APDU protocol
41 code. */
42 #ifdef USE_G10CODE_RAPDU
43 #include "rapdu.h"
44 #endif /*USE_G10CODE_RAPDU*/
46 #if defined(GNUPG_SCD_MAIN_HEADER)
47 #include GNUPG_SCD_MAIN_HEADER
48 #elif GNUPG_MAJOR_VERSION == 1
49 /* This is used with GnuPG version < 1.9. The code has been source
50 copied from the current GnuPG >= 1.9 and is maintained over
51 there. */
52 #include "options.h"
53 #include "errors.h"
54 #include "memory.h"
55 #include "util.h"
56 #include "i18n.h"
57 #include "dynload.h"
58 #include "cardglue.h"
59 #else /* GNUPG_MAJOR_VERSION != 1 */
60 #include "scdaemon.h"
61 #include "exechelp.h"
62 #endif /* GNUPG_MAJOR_VERSION != 1 */
64 #include "apdu.h"
65 #include "ccid-driver.h"
68 /* Due to conflicting use of threading libraries we usually can't link
69 against libpcsclite. Instead we use a wrapper program. */
70 #ifdef USE_GNU_PTH
71 #if !defined(HAVE_W32_SYSTEM) && !defined(__CYGWIN__)
72 #define NEED_PCSC_WRAPPER 1
73 #endif
74 #endif
77 #define MAX_READER 4 /* Number of readers we support concurrently. */
80 #if defined(_WIN32) || defined(__CYGWIN__)
81 #define DLSTDCALL __stdcall
82 #else
83 #define DLSTDCALL
84 #endif
87 /* Helper to pass parameters related to keypad based operations. */
88 struct pininfo_s
90 int mode;
91 int minlen;
92 int maxlen;
93 int padlen;
96 /* A structure to collect information pertaining to one reader
97 slot. */
98 struct reader_table_s {
99 int used; /* True if slot is used. */
100 unsigned short port; /* Port number: 0 = unused, 1 - dev/tty */
102 /* Function pointers intialized to the various backends. */
103 int (*connect_card)(int);
104 int (*disconnect_card)(int);
105 int (*close_reader)(int);
106 int (*shutdown_reader)(int);
107 int (*reset_reader)(int);
108 int (*get_status_reader)(int, unsigned int *);
109 int (*send_apdu_reader)(int,unsigned char *,size_t,
110 unsigned char *, size_t *, struct pininfo_s *);
111 int (*check_keypad)(int, int, int, int, int, int);
112 void (*dump_status_reader)(int);
113 int (*set_progress_cb)(int, gcry_handler_progress_t, void*);
115 struct {
116 ccid_driver_t handle;
117 } ccid;
118 struct {
119 unsigned long context;
120 unsigned long card;
121 unsigned long protocol;
122 #ifdef NEED_PCSC_WRAPPER
123 int req_fd;
124 int rsp_fd;
125 pid_t pid;
126 #endif /*NEED_PCSC_WRAPPER*/
127 } pcsc;
128 #ifdef USE_G10CODE_RAPDU
129 struct {
130 rapdu_t handle;
131 } rapdu;
132 #endif /*USE_G10CODE_RAPDU*/
133 char *rdrname; /* Name of the connected reader or NULL if unknown. */
134 int any_status; /* True if we have seen any status. */
135 int last_status;
136 int status;
137 int is_t0; /* True if we know that we are running T=0. */
138 unsigned char atr[33];
139 size_t atrlen; /* A zero length indicates that the ATR has
140 not yet been read; i.e. the card is not
141 ready for use. */
142 unsigned int change_counter;
143 #ifdef USE_GNU_PTH
144 int lock_initialized;
145 pth_mutex_t lock;
146 #endif
148 typedef struct reader_table_s *reader_table_t;
150 /* A global table to keep track of active readers. */
151 static struct reader_table_s reader_table[MAX_READER];
154 /* ct API function pointer. */
155 static char (* DLSTDCALL CT_init) (unsigned short ctn, unsigned short Pn);
156 static char (* DLSTDCALL CT_data) (unsigned short ctn, unsigned char *dad,
157 unsigned char *sad, unsigned short lc,
158 unsigned char *cmd, unsigned short *lr,
159 unsigned char *rsp);
160 static char (* DLSTDCALL CT_close) (unsigned short ctn);
162 /* PC/SC constants and function pointer. */
163 #define PCSC_SCOPE_USER 0
164 #define PCSC_SCOPE_TERMINAL 1
165 #define PCSC_SCOPE_SYSTEM 2
166 #define PCSC_SCOPE_GLOBAL 3
168 #define PCSC_PROTOCOL_T0 1
169 #define PCSC_PROTOCOL_T1 2
170 #define PCSC_PROTOCOL_RAW 4
172 #define PCSC_SHARE_EXCLUSIVE 1
173 #define PCSC_SHARE_SHARED 2
174 #define PCSC_SHARE_DIRECT 3
176 #define PCSC_LEAVE_CARD 0
177 #define PCSC_RESET_CARD 1
178 #define PCSC_UNPOWER_CARD 2
179 #define PCSC_EJECT_CARD 3
181 #define PCSC_UNKNOWN 0x0001
182 #define PCSC_ABSENT 0x0002 /* Card is absent. */
183 #define PCSC_PRESENT 0x0004 /* Card is present. */
184 #define PCSC_SWALLOWED 0x0008 /* Card is present and electrical connected. */
185 #define PCSC_POWERED 0x0010 /* Card is powered. */
186 #define PCSC_NEGOTIABLE 0x0020 /* Card is awaiting PTS. */
187 #define PCSC_SPECIFIC 0x0040 /* Card is ready for use. */
189 #define PCSC_STATE_UNAWARE 0x0000 /* Want status. */
190 #define PCSC_STATE_IGNORE 0x0001 /* Ignore this reader. */
191 #define PCSC_STATE_CHANGED 0x0002 /* State has changed. */
192 #define PCSC_STATE_UNKNOWN 0x0004 /* Reader unknown. */
193 #define PCSC_STATE_UNAVAILABLE 0x0008 /* Status unavailable. */
194 #define PCSC_STATE_EMPTY 0x0010 /* Card removed. */
195 #define PCSC_STATE_PRESENT 0x0020 /* Card inserted. */
196 #define PCSC_STATE_ATRMATCH 0x0040 /* ATR matches card. */
197 #define PCSC_STATE_EXCLUSIVE 0x0080 /* Exclusive Mode. */
198 #define PCSC_STATE_INUSE 0x0100 /* Shared mode. */
199 #define PCSC_STATE_MUTE 0x0200 /* Unresponsive card. */
201 /* Some PC/SC error codes. */
202 #define PCSC_E_CANCELLED 0x80100002
203 #define PCSC_E_CANT_DISPOSE 0x8010000E
204 #define PCSC_E_INSUFFICIENT_BUFFER 0x80100008
205 #define PCSC_E_INVALID_ATR 0x80100015
206 #define PCSC_E_INVALID_HANDLE 0x80100003
207 #define PCSC_E_INVALID_PARAMETER 0x80100004
208 #define PCSC_E_INVALID_TARGET 0x80100005
209 #define PCSC_E_INVALID_VALUE 0x80100011
210 #define PCSC_E_NO_MEMORY 0x80100006
211 #define PCSC_E_UNKNOWN_READER 0x80100009
212 #define PCSC_E_TIMEOUT 0x8010000A
213 #define PCSC_E_SHARING_VIOLATION 0x8010000B
214 #define PCSC_E_NO_SMARTCARD 0x8010000C
215 #define PCSC_E_UNKNOWN_CARD 0x8010000D
216 #define PCSC_E_PROTO_MISMATCH 0x8010000F
217 #define PCSC_E_NOT_READY 0x80100010
218 #define PCSC_E_SYSTEM_CANCELLED 0x80100012
219 #define PCSC_E_NOT_TRANSACTED 0x80100016
220 #define PCSC_E_READER_UNAVAILABLE 0x80100017
221 #define PCSC_W_REMOVED_CARD 0x80100069
223 /* The PC/SC error is defined as a long as per specs. Due to left
224 shifts bit 31 will get sign extended. We use this mask to fix
225 it. */
226 #define PCSC_ERR_MASK(a) ((a) & 0xffffffff)
229 struct pcsc_io_request_s
231 unsigned long protocol;
232 unsigned long pci_len;
235 typedef struct pcsc_io_request_s *pcsc_io_request_t;
237 struct pcsc_readerstate_s
239 const char *reader;
240 void *user_data;
241 unsigned long current_state;
242 unsigned long event_state;
243 unsigned long atrlen;
244 unsigned char atr[33];
247 typedef struct pcsc_readerstate_s *pcsc_readerstate_t;
249 long (* DLSTDCALL pcsc_establish_context) (unsigned long scope,
250 const void *reserved1,
251 const void *reserved2,
252 unsigned long *r_context);
253 long (* DLSTDCALL pcsc_release_context) (unsigned long context);
254 long (* DLSTDCALL pcsc_list_readers) (unsigned long context,
255 const char *groups,
256 char *readers, unsigned long*readerslen);
257 long (* DLSTDCALL pcsc_get_status_change) (unsigned long context,
258 unsigned long timeout,
259 pcsc_readerstate_t readerstates,
260 unsigned long nreaderstates);
261 long (* DLSTDCALL pcsc_connect) (unsigned long context,
262 const char *reader,
263 unsigned long share_mode,
264 unsigned long preferred_protocols,
265 unsigned long *r_card,
266 unsigned long *r_active_protocol);
267 long (* DLSTDCALL pcsc_reconnect) (unsigned long card,
268 unsigned long share_mode,
269 unsigned long preferred_protocols,
270 unsigned long initialization,
271 unsigned long *r_active_protocol);
272 long (* DLSTDCALL pcsc_disconnect) (unsigned long card,
273 unsigned long disposition);
274 long (* DLSTDCALL pcsc_status) (unsigned long card,
275 char *reader, unsigned long *readerlen,
276 unsigned long *r_state,
277 unsigned long *r_protocol,
278 unsigned char *atr, unsigned long *atrlen);
279 long (* DLSTDCALL pcsc_begin_transaction) (unsigned long card);
280 long (* DLSTDCALL pcsc_end_transaction) (unsigned long card,
281 unsigned long disposition);
282 long (* DLSTDCALL pcsc_transmit) (unsigned long card,
283 const pcsc_io_request_t send_pci,
284 const unsigned char *send_buffer,
285 unsigned long send_len,
286 pcsc_io_request_t recv_pci,
287 unsigned char *recv_buffer,
288 unsigned long *recv_len);
289 long (* DLSTDCALL pcsc_set_timeout) (unsigned long context,
290 unsigned long timeout);
293 /* Prototypes. */
294 static int pcsc_get_status (int slot, unsigned int *status);
295 static int reset_pcsc_reader (int slot);
296 static int apdu_get_status_internal (int slot, int hang, int no_atr_reset,
297 unsigned int *status,
298 unsigned int *changed);
303 Helper
307 /* Find an unused reader slot for PORTSTR and put it into the reader
308 table. Return -1 on error or the index into the reader table. */
309 static int
310 new_reader_slot (void)
312 int i, reader = -1;
314 for (i=0; i < MAX_READER; i++)
316 if (!reader_table[i].used && reader == -1)
317 reader = i;
319 if (reader == -1)
321 log_error ("new_reader_slot: out of slots\n");
322 return -1;
324 #ifdef USE_GNU_PTH
325 if (!reader_table[reader].lock_initialized)
327 if (!pth_mutex_init (&reader_table[reader].lock))
329 log_error ("error initializing mutex: %s\n", strerror (errno));
330 return -1;
332 reader_table[reader].lock_initialized = 1;
334 #endif /*USE_GNU_PTH*/
335 reader_table[reader].connect_card = NULL;
336 reader_table[reader].disconnect_card = NULL;
337 reader_table[reader].close_reader = NULL;
338 reader_table[reader].shutdown_reader = NULL;
339 reader_table[reader].reset_reader = NULL;
340 reader_table[reader].get_status_reader = NULL;
341 reader_table[reader].send_apdu_reader = NULL;
342 reader_table[reader].check_keypad = NULL;
343 reader_table[reader].dump_status_reader = NULL;
344 reader_table[reader].set_progress_cb = NULL;
346 reader_table[reader].used = 1;
347 reader_table[reader].any_status = 0;
348 reader_table[reader].last_status = 0;
349 reader_table[reader].is_t0 = 1;
350 #ifdef NEED_PCSC_WRAPPER
351 reader_table[reader].pcsc.req_fd = -1;
352 reader_table[reader].pcsc.rsp_fd = -1;
353 reader_table[reader].pcsc.pid = (pid_t)(-1);
354 #endif
356 return reader;
360 static void
361 dump_reader_status (int slot)
363 if (!opt.verbose)
364 return;
366 if (reader_table[slot].dump_status_reader)
367 reader_table[slot].dump_status_reader (slot);
369 if (reader_table[slot].status != -1
370 && reader_table[slot].atrlen)
372 log_info ("slot %d: ATR=", slot);
373 log_printhex ("", reader_table[slot].atr, reader_table[slot].atrlen);
379 static const char *
380 host_sw_string (long err)
382 switch (err)
384 case 0: return "okay";
385 case SW_HOST_OUT_OF_CORE: return "out of core";
386 case SW_HOST_INV_VALUE: return "invalid value";
387 case SW_HOST_NO_DRIVER: return "no driver";
388 case SW_HOST_NOT_SUPPORTED: return "not supported";
389 case SW_HOST_LOCKING_FAILED: return "locking failed";
390 case SW_HOST_BUSY: return "busy";
391 case SW_HOST_NO_CARD: return "no card";
392 case SW_HOST_CARD_INACTIVE: return "card inactive";
393 case SW_HOST_CARD_IO_ERROR: return "card I/O error";
394 case SW_HOST_GENERAL_ERROR: return "general error";
395 case SW_HOST_NO_READER: return "no reader";
396 case SW_HOST_ABORTED: return "aborted";
397 case SW_HOST_NO_KEYPAD: return "no keypad";
398 case SW_HOST_ALREADY_CONNECTED: return "already connected";
399 default: return "unknown host status error";
404 const char *
405 apdu_strerror (int rc)
407 switch (rc)
409 case SW_EOF_REACHED : return "eof reached";
410 case SW_EEPROM_FAILURE : return "eeprom failure";
411 case SW_WRONG_LENGTH : return "wrong length";
412 case SW_CHV_WRONG : return "CHV wrong";
413 case SW_CHV_BLOCKED : return "CHV blocked";
414 case SW_USE_CONDITIONS : return "use conditions not satisfied";
415 case SW_BAD_PARAMETER : return "bad parameter";
416 case SW_NOT_SUPPORTED : return "not supported";
417 case SW_FILE_NOT_FOUND : return "file not found";
418 case SW_RECORD_NOT_FOUND:return "record not found";
419 case SW_REF_NOT_FOUND : return "reference not found";
420 case SW_BAD_LC : return "bad Lc";
421 case SW_BAD_P0_P1 : return "bad P0 or P1";
422 case SW_INS_NOT_SUP : return "instruction not supported";
423 case SW_CLA_NOT_SUP : return "class not supported";
424 case SW_SUCCESS : return "success";
425 default:
426 if ((rc & ~0x00ff) == SW_MORE_DATA)
427 return "more data available";
428 if ( (rc & 0x10000) )
429 return host_sw_string (rc);
430 return "unknown status error";
437 ct API Interface
440 static const char *
441 ct_error_string (long err)
443 switch (err)
445 case 0: return "okay";
446 case -1: return "invalid data";
447 case -8: return "ct error";
448 case -10: return "transmission error";
449 case -11: return "memory allocation error";
450 case -128: return "HTSI error";
451 default: return "unknown CT-API error";
456 static void
457 ct_dump_reader_status (int slot)
459 log_info ("reader slot %d: %s\n", slot,
460 reader_table[slot].status == 1? "Processor ICC present" :
461 reader_table[slot].status == 0? "Memory ICC present" :
462 "ICC not present" );
466 /* Wait for the card in SLOT and activate it. Return a status word
467 error or 0 on success. */
468 static int
469 ct_activate_card (int slot)
471 int rc;
472 unsigned char dad[1], sad[1], cmd[11], buf[256];
473 unsigned short buflen;
475 /* Check whether card has been inserted. */
476 dad[0] = 1; /* Destination address: CT. */
477 sad[0] = 2; /* Source address: Host. */
479 cmd[0] = 0x20; /* Class byte. */
480 cmd[1] = 0x13; /* Request status. */
481 cmd[2] = 0x00; /* From kernel. */
482 cmd[3] = 0x80; /* Return card's DO. */
483 cmd[4] = 0x00;
485 buflen = DIM(buf);
487 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
488 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
490 log_error ("ct_activate_card: can't get status of reader %d: %s\n",
491 slot, ct_error_string (rc));
492 return SW_HOST_CARD_IO_ERROR;
495 /* Connected, now activate the card. */
496 dad[0] = 1; /* Destination address: CT. */
497 sad[0] = 2; /* Source address: Host. */
499 cmd[0] = 0x20; /* Class byte. */
500 cmd[1] = 0x12; /* Request ICC. */
501 cmd[2] = 0x01; /* From first interface. */
502 cmd[3] = 0x01; /* Return card's ATR. */
503 cmd[4] = 0x00;
505 buflen = DIM(buf);
507 rc = CT_data (slot, dad, sad, 5, cmd, &buflen, buf);
508 if (rc || buflen < 2 || buf[buflen-2] != 0x90)
510 log_error ("ct_activate_card(%d): activation failed: %s\n",
511 slot, ct_error_string (rc));
512 if (!rc)
513 log_printhex (" received data:", buf, buflen);
514 return SW_HOST_CARD_IO_ERROR;
517 /* Store the type and the ATR. */
518 if (buflen - 2 > DIM (reader_table[0].atr))
520 log_error ("ct_activate_card(%d): ATR too long\n", slot);
521 return SW_HOST_CARD_IO_ERROR;
524 reader_table[slot].status = buf[buflen - 1];
525 memcpy (reader_table[slot].atr, buf, buflen - 2);
526 reader_table[slot].atrlen = buflen - 2;
527 return 0;
531 static int
532 close_ct_reader (int slot)
534 CT_close (slot);
535 reader_table[slot].used = 0;
536 return 0;
539 static int
540 reset_ct_reader (int slot)
542 /* FIXME: Check is this is sufficient do do a reset. */
543 return ct_activate_card (slot);
547 static int
548 ct_get_status (int slot, unsigned int *status)
550 (void)slot;
551 /* The status we returned is wrong but we don't care becuase ctAPI
552 is not anymore required. */
553 *status = APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE;
554 return 0;
557 /* Actually send the APDU of length APDULEN to SLOT and return a
558 maximum of *BUFLEN data in BUFFER, the actual retruned size will be
559 set to BUFLEN. Returns: CT API error code. */
560 static int
561 ct_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
562 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
564 int rc;
565 unsigned char dad[1], sad[1];
566 unsigned short ctbuflen;
568 (void)pininfo;
570 /* If we don't have an ATR, we need to reset the reader first. */
571 if (!reader_table[slot].atrlen
572 && (rc = reset_ct_reader (slot)))
573 return rc;
575 dad[0] = 0; /* Destination address: Card. */
576 sad[0] = 2; /* Source address: Host. */
577 ctbuflen = *buflen;
578 if (DBG_CARD_IO)
579 log_printhex (" CT_data:", apdu, apdulen);
580 rc = CT_data (slot, dad, sad, apdulen, apdu, &ctbuflen, buffer);
581 *buflen = ctbuflen;
583 return rc? SW_HOST_CARD_IO_ERROR: 0;
588 /* Open a reader and return an internal handle for it. PORT is a
589 non-negative value with the port number of the reader. USB readers
590 do have port numbers starting at 32769. */
591 static int
592 open_ct_reader (int port)
594 int rc, reader;
596 if (port < 0 || port > 0xffff)
598 log_error ("open_ct_reader: invalid port %d requested\n", port);
599 return -1;
601 reader = new_reader_slot ();
602 if (reader == -1)
603 return reader;
604 reader_table[reader].port = port;
606 rc = CT_init (reader, (unsigned short)port);
607 if (rc)
609 log_error ("apdu_open_ct_reader failed on port %d: %s\n",
610 port, ct_error_string (rc));
611 reader_table[reader].used = 0;
612 return -1;
615 /* Only try to activate the card. */
616 rc = ct_activate_card (reader);
617 if (rc)
619 reader_table[reader].atrlen = 0;
620 rc = 0;
623 reader_table[reader].close_reader = close_ct_reader;
624 reader_table[reader].reset_reader = reset_ct_reader;
625 reader_table[reader].get_status_reader = ct_get_status;
626 reader_table[reader].send_apdu_reader = ct_send_apdu;
627 reader_table[reader].check_keypad = NULL;
628 reader_table[reader].dump_status_reader = ct_dump_reader_status;
630 dump_reader_status (reader);
631 return reader;
636 PC/SC Interface
639 #ifdef NEED_PCSC_WRAPPER
640 static int
641 writen (int fd, const void *buf, size_t nbytes)
643 size_t nleft = nbytes;
644 int nwritten;
646 /* log_printhex (" writen:", buf, nbytes); */
648 while (nleft > 0)
650 #ifdef USE_GNU_PTH
651 nwritten = pth_write (fd, buf, nleft);
652 #else
653 nwritten = write (fd, buf, nleft);
654 #endif
655 if (nwritten < 0 && errno == EINTR)
656 continue;
657 if (nwritten < 0)
658 return -1;
659 nleft -= nwritten;
660 buf = (const char*)buf + nwritten;
662 return 0;
665 /* Read up to BUFLEN bytes from FD and return the number of bytes
666 actually read in NREAD. Returns -1 on error or 0 on success. */
667 static int
668 readn (int fd, void *buf, size_t buflen, size_t *nread)
670 size_t nleft = buflen;
671 int n;
672 /* void *orig_buf = buf; */
674 while (nleft > 0)
676 #ifdef USE_GNU_PTH
677 # ifdef HAVE_W32_SYSTEM
678 # error Cannot use pth_read here because it expects a system HANDLE.
679 # endif
680 n = pth_read (fd, buf, nleft);
681 #else
682 n = read (fd, buf, nleft);
683 #endif
684 if (n < 0 && errno == EINTR)
685 continue;
686 if (n < 0)
687 return -1; /* read error. */
688 if (!n)
689 break; /* EOF */
690 nleft -= n;
691 buf = (char*)buf + n;
693 if (nread)
694 *nread = buflen - nleft;
696 /* log_printhex (" readn:", orig_buf, *nread); */
698 return 0;
700 #endif /*NEED_PCSC_WRAPPER*/
702 static const char *
703 pcsc_error_string (long err)
705 const char *s;
707 if (!err)
708 return "okay";
709 if ((err & 0x80100000) != 0x80100000)
710 return "invalid PC/SC error code";
711 err &= 0xffff;
712 switch (err)
714 case 0x0002: s = "cancelled"; break;
715 case 0x000e: s = "can't dispose"; break;
716 case 0x0008: s = "insufficient buffer"; break;
717 case 0x0015: s = "invalid ATR"; break;
718 case 0x0003: s = "invalid handle"; break;
719 case 0x0004: s = "invalid parameter"; break;
720 case 0x0005: s = "invalid target"; break;
721 case 0x0011: s = "invalid value"; break;
722 case 0x0006: s = "no memory"; break;
723 case 0x0013: s = "comm error"; break;
724 case 0x0001: s = "internal error"; break;
725 case 0x0014: s = "unknown error"; break;
726 case 0x0007: s = "waited too long"; break;
727 case 0x0009: s = "unknown reader"; break;
728 case 0x000a: s = "timeout"; break;
729 case 0x000b: s = "sharing violation"; break;
730 case 0x000c: s = "no smartcard"; break;
731 case 0x000d: s = "unknown card"; break;
732 case 0x000f: s = "proto mismatch"; break;
733 case 0x0010: s = "not ready"; break;
734 case 0x0012: s = "system cancelled"; break;
735 case 0x0016: s = "not transacted"; break;
736 case 0x0017: s = "reader unavailable"; break;
737 case 0x0065: s = "unsupported card"; break;
738 case 0x0066: s = "unresponsive card"; break;
739 case 0x0067: s = "unpowered card"; break;
740 case 0x0068: s = "reset card"; break;
741 case 0x0069: s = "removed card"; break;
742 case 0x006a: s = "inserted card"; break;
743 case 0x001f: s = "unsupported feature"; break;
744 case 0x0019: s = "PCI too small"; break;
745 case 0x001a: s = "reader unsupported"; break;
746 case 0x001b: s = "duplicate reader"; break;
747 case 0x001c: s = "card unsupported"; break;
748 case 0x001d: s = "no service"; break;
749 case 0x001e: s = "service stopped"; break;
750 default: s = "unknown PC/SC error code"; break;
752 return s;
755 /* Map PC/SC error codes to our special host status words. */
756 static int
757 pcsc_error_to_sw (long ec)
759 int rc;
761 switch ( PCSC_ERR_MASK (ec) )
763 case 0: rc = 0; break;
765 case PCSC_E_CANCELLED: rc = SW_HOST_ABORTED; break;
766 case PCSC_E_NO_MEMORY: rc = SW_HOST_OUT_OF_CORE; break;
767 case PCSC_E_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
768 case PCSC_E_SHARING_VIOLATION: rc = SW_HOST_LOCKING_FAILED; break;
769 case PCSC_E_NO_SMARTCARD: rc = SW_HOST_NO_CARD; break;
770 case PCSC_W_REMOVED_CARD: rc = SW_HOST_NO_CARD; break;
772 case PCSC_E_INVALID_TARGET:
773 case PCSC_E_INVALID_VALUE:
774 case PCSC_E_INVALID_HANDLE:
775 case PCSC_E_INVALID_PARAMETER:
776 case PCSC_E_INSUFFICIENT_BUFFER: rc = SW_HOST_INV_VALUE; break;
778 default: rc = SW_HOST_GENERAL_ERROR; break;
781 return rc;
784 static void
785 dump_pcsc_reader_status (int slot)
787 if (reader_table[slot].pcsc.card)
789 log_info ("reader slot %d: active protocol:", slot);
790 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T0))
791 log_printf (" T0");
792 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
793 log_printf (" T1");
794 else if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_RAW))
795 log_printf (" raw");
796 log_printf ("\n");
798 else
799 log_info ("reader slot %d: not connected\n", slot);
803 #ifndef NEED_PCSC_WRAPPER
804 static int
805 pcsc_get_status_direct (int slot, unsigned int *status)
807 long err;
808 struct pcsc_readerstate_s rdrstates[1];
810 memset (rdrstates, 0, sizeof *rdrstates);
811 rdrstates[0].reader = reader_table[slot].rdrname;
812 rdrstates[0].current_state = PCSC_STATE_UNAWARE;
813 err = pcsc_get_status_change (reader_table[slot].pcsc.context,
815 rdrstates, 1);
816 if (err == PCSC_E_TIMEOUT)
817 err = 0; /* Timeout is no error error here. */
818 if (err)
820 log_error ("pcsc_get_status_change failed: %s (0x%lx)\n",
821 pcsc_error_string (err), err);
822 return pcsc_error_to_sw (err);
825 /* log_debug */
826 /* ("pcsc_get_status_change: %s%s%s%s%s%s%s%s%s%s\n", */
827 /* (rdrstates[0].event_state & PCSC_STATE_IGNORE)? " ignore":"", */
828 /* (rdrstates[0].event_state & PCSC_STATE_CHANGED)? " changed":"", */
829 /* (rdrstates[0].event_state & PCSC_STATE_UNKNOWN)? " unknown":"", */
830 /* (rdrstates[0].event_state & PCSC_STATE_UNAVAILABLE)?" unavail":"", */
831 /* (rdrstates[0].event_state & PCSC_STATE_EMPTY)? " empty":"", */
832 /* (rdrstates[0].event_state & PCSC_STATE_PRESENT)? " present":"", */
833 /* (rdrstates[0].event_state & PCSC_STATE_ATRMATCH)? " atr":"", */
834 /* (rdrstates[0].event_state & PCSC_STATE_EXCLUSIVE)? " excl":"", */
835 /* (rdrstates[0].event_state & PCSC_STATE_INUSE)? " unuse":"", */
836 /* (rdrstates[0].event_state & PCSC_STATE_MUTE)? " mute":"" ); */
838 *status = 0;
839 if ( (rdrstates[0].event_state & PCSC_STATE_PRESENT) )
840 *status |= APDU_CARD_PRESENT;
841 if ( !(rdrstates[0].event_state & PCSC_STATE_MUTE) )
842 *status |= APDU_CARD_ACTIVE;
843 #ifndef HAVE_W32_SYSTEM
844 /* We indicate a useful card if it is not in use by another
845 application. This is because we only use exclusive access
846 mode. */
847 if ( (*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
848 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE)
849 && !(rdrstates[0].event_state & PCSC_STATE_INUSE) )
850 *status |= APDU_CARD_USABLE;
851 #else
852 /* Some winscard drivers may set EXCLUSIVE and INUSE at the same
853 time when we are the only user (SCM SCR335) under Windows. */
854 if ((*status & (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
855 == (APDU_CARD_PRESENT|APDU_CARD_ACTIVE))
856 *status |= APDU_CARD_USABLE;
857 #endif
859 return 0;
861 #endif /*!NEED_PCSC_WRAPPER*/
864 #ifdef NEED_PCSC_WRAPPER
865 static int
866 pcsc_get_status_wrapped (int slot, unsigned int *status)
868 long err;
869 reader_table_t slotp;
870 size_t len, full_len;
871 int i, n;
872 unsigned char msgbuf[9];
873 unsigned char buffer[16];
874 int sw = SW_HOST_CARD_IO_ERROR;
876 slotp = reader_table + slot;
878 if (slotp->pcsc.req_fd == -1
879 || slotp->pcsc.rsp_fd == -1
880 || slotp->pcsc.pid == (pid_t)(-1) )
882 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
883 return sw;
886 msgbuf[0] = 0x04; /* STATUS command. */
887 len = 0;
888 msgbuf[1] = (len >> 24);
889 msgbuf[2] = (len >> 16);
890 msgbuf[3] = (len >> 8);
891 msgbuf[4] = (len );
892 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
894 log_error ("error sending PC/SC STATUS request: %s\n",
895 strerror (errno));
896 goto command_failed;
899 /* Read the response. */
900 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
902 log_error ("error receiving PC/SC STATUS response: %s\n",
903 i? strerror (errno) : "premature EOF");
904 goto command_failed;
906 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
907 if (msgbuf[0] != 0x81 || len < 4)
909 log_error ("invalid response header from PC/SC received\n");
910 goto command_failed;
912 len -= 4; /* Already read the error code. */
913 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
914 | (msgbuf[7] << 8 ) | msgbuf[8]);
915 if (err)
917 log_error ("pcsc_status failed: %s (0x%lx)\n",
918 pcsc_error_string (err), err);
919 /* This is a proper error code, so return immediately. */
920 return pcsc_error_to_sw (err);
923 full_len = len;
925 /* The current version returns 3 words but we allow also for old
926 versions returning only 2 words. */
927 n = 12 < len ? 12 : len;
928 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len))
929 || (len != 8 && len != 12))
931 log_error ("error receiving PC/SC STATUS response: %s\n",
932 i? strerror (errno) : "premature EOF");
933 goto command_failed;
936 slotp->is_t0 = (len == 12 && !!(buffer[11] & PCSC_PROTOCOL_T0));
939 full_len -= len;
940 /* Newer versions of the wrapper might send more status bytes.
941 Read them. */
942 while (full_len)
944 unsigned char dummybuf[128];
946 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
947 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
949 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
950 i? strerror (errno) : "premature EOF");
951 goto command_failed;
953 full_len -= n;
956 /* We are lucky: The wrapper already returns the data in the
957 required format. */
958 *status = buffer[3];
959 return 0;
961 command_failed:
962 close (slotp->pcsc.req_fd);
963 close (slotp->pcsc.rsp_fd);
964 slotp->pcsc.req_fd = -1;
965 slotp->pcsc.rsp_fd = -1;
966 kill (slotp->pcsc.pid, SIGTERM);
967 slotp->pcsc.pid = (pid_t)(-1);
968 slotp->used = 0;
969 return sw;
971 #endif /*NEED_PCSC_WRAPPER*/
974 static int
975 pcsc_get_status (int slot, unsigned int *status)
977 #ifdef NEED_PCSC_WRAPPER
978 return pcsc_get_status_wrapped (slot, status);
979 #else
980 return pcsc_get_status_direct (slot, status);
981 #endif
985 #ifndef NEED_PCSC_WRAPPER
986 static int
987 pcsc_send_apdu_direct (int slot, unsigned char *apdu, size_t apdulen,
988 unsigned char *buffer, size_t *buflen,
989 struct pininfo_s *pininfo)
991 long err;
992 struct pcsc_io_request_s send_pci;
993 unsigned long recv_len;
995 if (!reader_table[slot].atrlen
996 && (err = reset_pcsc_reader (slot)))
997 return err;
999 if (DBG_CARD_IO)
1000 log_printhex (" PCSC_data:", apdu, apdulen);
1002 if ((reader_table[slot].pcsc.protocol & PCSC_PROTOCOL_T1))
1003 send_pci.protocol = PCSC_PROTOCOL_T1;
1004 else
1005 send_pci.protocol = PCSC_PROTOCOL_T0;
1006 send_pci.pci_len = sizeof send_pci;
1007 recv_len = *buflen;
1008 err = pcsc_transmit (reader_table[slot].pcsc.card,
1009 &send_pci, apdu, apdulen,
1010 NULL, buffer, &recv_len);
1011 *buflen = recv_len;
1012 if (err)
1013 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1014 pcsc_error_string (err), err);
1016 return pcsc_error_to_sw (err);
1018 #endif /*!NEED_PCSC_WRAPPER*/
1021 #ifdef NEED_PCSC_WRAPPER
1022 static int
1023 pcsc_send_apdu_wrapped (int slot, unsigned char *apdu, size_t apdulen,
1024 unsigned char *buffer, size_t *buflen,
1025 struct pininfo_s *pininfo)
1027 long err;
1028 reader_table_t slotp;
1029 size_t len, full_len;
1030 int i, n;
1031 unsigned char msgbuf[9];
1032 int sw = SW_HOST_CARD_IO_ERROR;
1034 (void)pininfo;
1036 if (!reader_table[slot].atrlen
1037 && (err = reset_pcsc_reader (slot)))
1038 return err;
1040 if (DBG_CARD_IO)
1041 log_printhex (" PCSC_data:", apdu, apdulen);
1043 slotp = reader_table + slot;
1045 if (slotp->pcsc.req_fd == -1
1046 || slotp->pcsc.rsp_fd == -1
1047 || slotp->pcsc.pid == (pid_t)(-1) )
1049 log_error ("pcsc_send_apdu: pcsc-wrapper not running\n");
1050 return sw;
1053 msgbuf[0] = 0x03; /* TRANSMIT command. */
1054 len = apdulen;
1055 msgbuf[1] = (len >> 24);
1056 msgbuf[2] = (len >> 16);
1057 msgbuf[3] = (len >> 8);
1058 msgbuf[4] = (len );
1059 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1060 || writen (slotp->pcsc.req_fd, apdu, len))
1062 log_error ("error sending PC/SC TRANSMIT request: %s\n",
1063 strerror (errno));
1064 goto command_failed;
1067 /* Read the response. */
1068 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1070 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1071 i? strerror (errno) : "premature EOF");
1072 goto command_failed;
1074 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1075 if (msgbuf[0] != 0x81 || len < 4)
1077 log_error ("invalid response header from PC/SC received\n");
1078 goto command_failed;
1080 len -= 4; /* Already read the error code. */
1081 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1082 | (msgbuf[7] << 8 ) | msgbuf[8]);
1083 if (err)
1085 log_error ("pcsc_transmit failed: %s (0x%lx)\n",
1086 pcsc_error_string (err), err);
1087 return pcsc_error_to_sw (err);
1090 full_len = len;
1092 n = *buflen < len ? *buflen : len;
1093 if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n)
1095 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1096 i? strerror (errno) : "premature EOF");
1097 goto command_failed;
1099 *buflen = n;
1101 full_len -= len;
1102 if (full_len)
1104 log_error ("pcsc_send_apdu: provided buffer too short - truncated\n");
1105 err = SW_HOST_INV_VALUE;
1107 /* We need to read any rest of the response, to keep the
1108 protocol running. */
1109 while (full_len)
1111 unsigned char dummybuf[128];
1113 n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf);
1114 if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n)
1116 log_error ("error receiving PC/SC TRANSMIT response: %s\n",
1117 i? strerror (errno) : "premature EOF");
1118 goto command_failed;
1120 full_len -= n;
1123 return err;
1125 command_failed:
1126 close (slotp->pcsc.req_fd);
1127 close (slotp->pcsc.rsp_fd);
1128 slotp->pcsc.req_fd = -1;
1129 slotp->pcsc.rsp_fd = -1;
1130 kill (slotp->pcsc.pid, SIGTERM);
1131 slotp->pcsc.pid = (pid_t)(-1);
1132 slotp->used = 0;
1133 return sw;
1135 #endif /*NEED_PCSC_WRAPPER*/
1138 /* Send the APDU of length APDULEN to SLOT and return a maximum of
1139 *BUFLEN data in BUFFER, the actual returned size will be stored at
1140 BUFLEN. Returns: A status word. */
1141 static int
1142 pcsc_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
1143 unsigned char *buffer, size_t *buflen,
1144 struct pininfo_s *pininfo)
1146 #ifdef NEED_PCSC_WRAPPER
1147 return pcsc_send_apdu_wrapped (slot, apdu, apdulen, buffer, buflen, pininfo);
1148 #else
1149 return pcsc_send_apdu_direct (slot, apdu, apdulen, buffer, buflen, pininfo);
1150 #endif
1154 #ifndef NEED_PCSC_WRAPPER
1155 static int
1156 close_pcsc_reader_direct (int slot)
1158 pcsc_release_context (reader_table[slot].pcsc.context);
1159 xfree (reader_table[slot].rdrname);
1160 reader_table[slot].rdrname = NULL;
1161 reader_table[slot].used = 0;
1162 return 0;
1164 #endif /*!NEED_PCSC_WRAPPER*/
1167 #ifdef NEED_PCSC_WRAPPER
1168 static int
1169 close_pcsc_reader_wrapped (int slot)
1171 long err;
1172 reader_table_t slotp;
1173 size_t len;
1174 int i;
1175 unsigned char msgbuf[9];
1177 slotp = reader_table + slot;
1179 if (slotp->pcsc.req_fd == -1
1180 || slotp->pcsc.rsp_fd == -1
1181 || slotp->pcsc.pid == (pid_t)(-1) )
1183 log_error ("close_pcsc_reader: pcsc-wrapper not running\n");
1184 return 0;
1187 msgbuf[0] = 0x02; /* CLOSE command. */
1188 len = 0;
1189 msgbuf[1] = (len >> 24);
1190 msgbuf[2] = (len >> 16);
1191 msgbuf[3] = (len >> 8);
1192 msgbuf[4] = (len );
1193 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1195 log_error ("error sending PC/SC CLOSE request: %s\n",
1196 strerror (errno));
1197 goto command_failed;
1200 /* Read the response. */
1201 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1203 log_error ("error receiving PC/SC CLOSE response: %s\n",
1204 i? strerror (errno) : "premature EOF");
1205 goto command_failed;
1207 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1208 if (msgbuf[0] != 0x81 || len < 4)
1210 log_error ("invalid response header from PC/SC received\n");
1211 goto command_failed;
1213 len -= 4; /* Already read the error code. */
1214 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1215 | (msgbuf[7] << 8 ) | msgbuf[8]);
1216 if (err)
1217 log_error ("pcsc_close failed: %s (0x%lx)\n",
1218 pcsc_error_string (err), err);
1220 /* We will close the wrapper in any case - errors are merely
1221 informational. */
1223 command_failed:
1224 close (slotp->pcsc.req_fd);
1225 close (slotp->pcsc.rsp_fd);
1226 slotp->pcsc.req_fd = -1;
1227 slotp->pcsc.rsp_fd = -1;
1228 kill (slotp->pcsc.pid, SIGTERM);
1229 slotp->pcsc.pid = (pid_t)(-1);
1230 slotp->used = 0;
1231 return 0;
1233 #endif /*NEED_PCSC_WRAPPER*/
1236 static int
1237 close_pcsc_reader (int slot)
1239 #ifdef NEED_PCSC_WRAPPER
1240 return close_pcsc_reader_wrapped (slot);
1241 #else
1242 return close_pcsc_reader_direct (slot);
1243 #endif
1247 /* Connect a PC/SC card. */
1248 #ifndef NEED_PCSC_WRAPPER
1249 static int
1250 connect_pcsc_card (int slot)
1252 long err;
1254 assert (slot >= 0 && slot < MAX_READER);
1256 if (reader_table[slot].pcsc.card)
1257 return SW_HOST_ALREADY_CONNECTED;
1259 reader_table[slot].atrlen = 0;
1260 reader_table[slot].last_status = 0;
1261 reader_table[slot].is_t0 = 0;
1263 err = pcsc_connect (reader_table[slot].pcsc.context,
1264 reader_table[slot].rdrname,
1265 PCSC_SHARE_EXCLUSIVE,
1266 PCSC_PROTOCOL_T0|PCSC_PROTOCOL_T1,
1267 &reader_table[slot].pcsc.card,
1268 &reader_table[slot].pcsc.protocol);
1269 if (err)
1271 reader_table[slot].pcsc.card = 0;
1272 if (err != PCSC_E_NO_SMARTCARD)
1273 log_error ("pcsc_connect failed: %s (0x%lx)\n",
1274 pcsc_error_string (err), err);
1276 else
1278 char reader[250];
1279 unsigned long readerlen, atrlen;
1280 unsigned long card_state, card_protocol;
1282 atrlen = DIM (reader_table[0].atr);
1283 readerlen = sizeof reader -1 ;
1284 err = pcsc_status (reader_table[slot].pcsc.card,
1285 reader, &readerlen,
1286 &card_state, &card_protocol,
1287 reader_table[slot].atr, &atrlen);
1288 if (err)
1289 log_error ("pcsc_status failed: %s (0x%lx) %lu\n",
1290 pcsc_error_string (err), err, readerlen);
1291 else
1293 if (atrlen > DIM (reader_table[0].atr))
1294 log_bug ("ATR returned by pcsc_status is too large\n");
1295 reader_table[slot].atrlen = atrlen;
1296 /* If we got to here we know that a card is present
1297 and usable. Remember this. */
1298 reader_table[slot].last_status = ( APDU_CARD_USABLE
1299 | APDU_CARD_PRESENT
1300 | APDU_CARD_ACTIVE);
1301 reader_table[slot].is_t0 = !!(card_protocol & PCSC_PROTOCOL_T0);
1305 dump_reader_status (slot);
1306 return pcsc_error_to_sw (err);
1308 #endif /*!NEED_PCSC_WRAPPER*/
1311 /* Disconnect a PC/SC card. Note that this succeeds even if the card
1312 is not connected. */
1313 #ifndef NEED_PCSC_WRAPPER
1314 static int
1315 disconnect_pcsc_card (int slot)
1317 long err;
1319 assert (slot >= 0 && slot < MAX_READER);
1321 if (!reader_table[slot].pcsc.card)
1322 return 0;
1324 err = pcsc_disconnect (reader_table[slot].pcsc.card, PCSC_LEAVE_CARD);
1325 if (err)
1327 log_error ("pcsc_disconnect failed: %s (0x%lx)\n",
1328 pcsc_error_string (err), err);
1329 return SW_HOST_CARD_IO_ERROR;
1331 reader_table[slot].pcsc.card = 0;
1332 return 0;
1334 #endif /*!NEED_PCSC_WRAPPER*/
1337 #ifndef NEED_PCSC_WRAPPER
1338 static int
1339 reset_pcsc_reader_direct (int slot)
1341 int sw;
1343 sw = disconnect_pcsc_card (slot);
1344 if (!sw)
1345 sw = connect_pcsc_card (slot);
1347 return sw;
1349 #endif /*NEED_PCSC_WRAPPER*/
1352 #ifdef NEED_PCSC_WRAPPER
1353 static int
1354 reset_pcsc_reader_wrapped (int slot)
1356 long err;
1357 reader_table_t slotp;
1358 size_t len;
1359 int i, n;
1360 unsigned char msgbuf[9];
1361 unsigned int dummy_status;
1362 int sw = SW_HOST_CARD_IO_ERROR;
1364 slotp = reader_table + slot;
1366 if (slotp->pcsc.req_fd == -1
1367 || slotp->pcsc.rsp_fd == -1
1368 || slotp->pcsc.pid == (pid_t)(-1) )
1370 log_error ("pcsc_get_status: pcsc-wrapper not running\n");
1371 return sw;
1374 msgbuf[0] = 0x05; /* RESET command. */
1375 len = 0;
1376 msgbuf[1] = (len >> 24);
1377 msgbuf[2] = (len >> 16);
1378 msgbuf[3] = (len >> 8);
1379 msgbuf[4] = (len );
1380 if ( writen (slotp->pcsc.req_fd, msgbuf, 5) )
1382 log_error ("error sending PC/SC RESET request: %s\n",
1383 strerror (errno));
1384 goto command_failed;
1387 /* Read the response. */
1388 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1390 log_error ("error receiving PC/SC RESET response: %s\n",
1391 i? strerror (errno) : "premature EOF");
1392 goto command_failed;
1394 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1395 if (msgbuf[0] != 0x81 || len < 4)
1397 log_error ("invalid response header from PC/SC received\n");
1398 goto command_failed;
1400 len -= 4; /* Already read the error code. */
1401 if (len > DIM (slotp->atr))
1403 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1404 (unsigned long)len);
1405 sw = SW_HOST_GENERAL_ERROR;
1406 goto command_failed;
1408 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1409 | (msgbuf[7] << 8 ) | msgbuf[8]);
1410 if (err)
1412 log_error ("PC/SC RESET failed: %s (0x%lx)\n",
1413 pcsc_error_string (err), err);
1414 /* If the error code is no smart card, we should not considere
1415 this a major error and close the wrapper. */
1416 sw = pcsc_error_to_sw (err);
1417 if (err == PCSC_E_NO_SMARTCARD)
1418 return sw;
1419 goto command_failed;
1422 /* The open function may return a zero for the ATR length to
1423 indicate that no card is present. */
1424 n = len;
1425 if (n)
1427 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1429 log_error ("error receiving PC/SC RESET response: %s\n",
1430 i? strerror (errno) : "premature EOF");
1431 goto command_failed;
1434 slotp->atrlen = len;
1436 /* Read the status so that IS_T0 will be set. */
1437 pcsc_get_status (slot, &dummy_status);
1439 return 0;
1441 command_failed:
1442 close (slotp->pcsc.req_fd);
1443 close (slotp->pcsc.rsp_fd);
1444 slotp->pcsc.req_fd = -1;
1445 slotp->pcsc.rsp_fd = -1;
1446 kill (slotp->pcsc.pid, SIGTERM);
1447 slotp->pcsc.pid = (pid_t)(-1);
1448 slotp->used = 0;
1449 return sw;
1451 #endif /* !NEED_PCSC_WRAPPER */
1454 /* Send an PC/SC reset command and return a status word on error or 0
1455 on success. */
1456 static int
1457 reset_pcsc_reader (int slot)
1459 #ifdef NEED_PCSC_WRAPPER
1460 return reset_pcsc_reader_wrapped (slot);
1461 #else
1462 return reset_pcsc_reader_direct (slot);
1463 #endif
1467 /* Open the PC/SC reader without using the wrapper. Returns -1 on
1468 error or a slot number for the reader. */
1469 #ifndef NEED_PCSC_WRAPPER
1470 static int
1471 open_pcsc_reader_direct (const char *portstr)
1473 long err;
1474 int slot;
1475 char *list = NULL;
1476 unsigned long nreader, listlen;
1477 char *p;
1479 slot = new_reader_slot ();
1480 if (slot == -1)
1481 return -1;
1483 /* Fixme: Allocating a context for each slot is not required. One
1484 global context should be sufficient. */
1485 err = pcsc_establish_context (PCSC_SCOPE_SYSTEM, NULL, NULL,
1486 &reader_table[slot].pcsc.context);
1487 if (err)
1489 log_error ("pcsc_establish_context failed: %s (0x%lx)\n",
1490 pcsc_error_string (err), err);
1491 reader_table[slot].used = 0;
1492 return -1;
1495 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1496 NULL, NULL, &nreader);
1497 if (!err)
1499 list = xtrymalloc (nreader+1); /* Better add 1 for safety reasons. */
1500 if (!list)
1502 log_error ("error allocating memory for reader list\n");
1503 pcsc_release_context (reader_table[slot].pcsc.context);
1504 reader_table[slot].used = 0;
1505 return -1 /*SW_HOST_OUT_OF_CORE*/;
1507 err = pcsc_list_readers (reader_table[slot].pcsc.context,
1508 NULL, list, &nreader);
1510 if (err)
1512 log_error ("pcsc_list_readers failed: %s (0x%lx)\n",
1513 pcsc_error_string (err), err);
1514 pcsc_release_context (reader_table[slot].pcsc.context);
1515 reader_table[slot].used = 0;
1516 xfree (list);
1517 return -1;
1520 listlen = nreader;
1521 p = list;
1522 while (nreader)
1524 if (!*p && !p[1])
1525 break;
1526 if (*p)
1527 log_info ("detected reader `%s'\n", p);
1528 if (nreader < (strlen (p)+1))
1530 log_error ("invalid response from pcsc_list_readers\n");
1531 break;
1533 nreader -= strlen (p)+1;
1534 p += strlen (p) + 1;
1537 reader_table[slot].rdrname = xtrymalloc (strlen (portstr? portstr : list)+1);
1538 if (!reader_table[slot].rdrname)
1540 log_error ("error allocating memory for reader name\n");
1541 pcsc_release_context (reader_table[slot].pcsc.context);
1542 reader_table[slot].used = 0;
1543 return -1;
1545 strcpy (reader_table[slot].rdrname, portstr? portstr : list);
1546 xfree (list);
1547 list = NULL;
1549 reader_table[slot].pcsc.card = 0;
1550 reader_table[slot].atrlen = 0;
1551 reader_table[slot].last_status = 0;
1553 reader_table[slot].connect_card = connect_pcsc_card;
1554 reader_table[slot].disconnect_card = disconnect_pcsc_card;
1555 reader_table[slot].close_reader = close_pcsc_reader;
1556 reader_table[slot].reset_reader = reset_pcsc_reader;
1557 reader_table[slot].get_status_reader = pcsc_get_status;
1558 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1559 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1561 dump_reader_status (slot);
1562 return slot;
1564 #endif /*!NEED_PCSC_WRAPPER */
1567 /* Open the PC/SC reader using the pcsc_wrapper program. This is
1568 needed to cope with different thread models and other peculiarities
1569 of libpcsclite. */
1570 #ifdef NEED_PCSC_WRAPPER
1571 static int
1572 open_pcsc_reader_wrapped (const char *portstr)
1574 int slot;
1575 reader_table_t slotp;
1576 int fd, rp[2], wp[2];
1577 int n, i;
1578 pid_t pid;
1579 size_t len;
1580 unsigned char msgbuf[9];
1581 int err;
1582 unsigned int dummy_status;
1583 int sw = SW_HOST_CARD_IO_ERROR;
1584 /* Note that we use the constant and not the fucntion because this
1585 code won't be be used under Windows. */
1586 const char *wrapperpgm = GNUPG_LIBEXECDIR "/gnupg-pcsc-wrapper";
1588 if (access (wrapperpgm, X_OK))
1590 log_error ("can't run PC/SC access module `%s': %s\n",
1591 wrapperpgm, strerror (errno));
1592 return -1;
1595 slot = new_reader_slot ();
1596 if (slot == -1)
1597 return -1;
1598 slotp = reader_table + slot;
1600 /* Fire up the PC/SCc wrapper. We don't use any fork/exec code from
1601 the common directy but implement it directly so that this file
1602 may still be source copied. */
1604 if (pipe (rp) == -1)
1606 log_error ("error creating a pipe: %s\n", strerror (errno));
1607 slotp->used = 0;
1608 return -1;
1610 if (pipe (wp) == -1)
1612 log_error ("error creating a pipe: %s\n", strerror (errno));
1613 close (rp[0]);
1614 close (rp[1]);
1615 slotp->used = 0;
1616 return -1;
1619 pid = fork ();
1620 if (pid == -1)
1622 log_error ("error forking process: %s\n", strerror (errno));
1623 close (rp[0]);
1624 close (rp[1]);
1625 close (wp[0]);
1626 close (wp[1]);
1627 slotp->used = 0;
1628 return -1;
1630 slotp->pcsc.pid = pid;
1632 if (!pid)
1633 { /*
1634 === Child ===
1637 /* Double fork. */
1638 pid = fork ();
1639 if (pid == -1)
1640 _exit (31);
1641 if (pid)
1642 _exit (0); /* Immediate exit this parent, so that the child
1643 gets cleaned up by the init process. */
1645 /* Connect our pipes. */
1646 if (wp[0] != 0 && dup2 (wp[0], 0) == -1)
1647 log_fatal ("dup2 stdin failed: %s\n", strerror (errno));
1648 if (rp[1] != 1 && dup2 (rp[1], 1) == -1)
1649 log_fatal ("dup2 stdout failed: %s\n", strerror (errno));
1651 /* Send stderr to the bit bucket. */
1652 fd = open ("/dev/null", O_WRONLY);
1653 if (fd == -1)
1654 log_fatal ("can't open `/dev/null': %s", strerror (errno));
1655 if (fd != 2 && dup2 (fd, 2) == -1)
1656 log_fatal ("dup2 stderr failed: %s\n", strerror (errno));
1658 /* Close all other files. */
1659 close_all_fds (3, NULL);
1661 execl (wrapperpgm,
1662 "pcsc-wrapper",
1663 "--",
1664 "1", /* API version */
1665 opt.pcsc_driver, /* Name of the PC/SC library. */
1666 NULL);
1667 _exit (31);
1671 === Parent ===
1673 close (wp[0]);
1674 close (rp[1]);
1675 slotp->pcsc.req_fd = wp[1];
1676 slotp->pcsc.rsp_fd = rp[0];
1678 /* Wait for the intermediate child to terminate. */
1679 #ifdef USE_GNU_PTH
1680 #define WAIT pth_waitpid
1681 #else
1682 #define WAIT waitpid
1683 #endif
1684 while ( (i=WAIT (pid, NULL, 0)) == -1 && errno == EINTR)
1686 #undef WAIT
1688 /* Now send the open request. */
1689 msgbuf[0] = 0x01; /* OPEN command. */
1690 len = portstr? strlen (portstr):0;
1691 msgbuf[1] = (len >> 24);
1692 msgbuf[2] = (len >> 16);
1693 msgbuf[3] = (len >> 8);
1694 msgbuf[4] = (len );
1695 if ( writen (slotp->pcsc.req_fd, msgbuf, 5)
1696 || (portstr && writen (slotp->pcsc.req_fd, portstr, len)))
1698 log_error ("error sending PC/SC OPEN request: %s\n",
1699 strerror (errno));
1700 goto command_failed;
1702 /* Read the response. */
1703 if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9)
1705 log_error ("error receiving PC/SC OPEN response: %s\n",
1706 i? strerror (errno) : "premature EOF");
1707 goto command_failed;
1709 len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4];
1710 if (msgbuf[0] != 0x81 || len < 4)
1712 log_error ("invalid response header from PC/SC received\n");
1713 goto command_failed;
1715 len -= 4; /* Already read the error code. */
1716 if (len > DIM (slotp->atr))
1718 log_error ("PC/SC returned a too large ATR (len=%lx)\n",
1719 (unsigned long)len);
1720 goto command_failed;
1722 err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16)
1723 | (msgbuf[7] << 8 ) | msgbuf[8]);
1724 if (err)
1726 log_error ("PC/SC OPEN failed: %s\n", pcsc_error_string (err));
1727 sw = pcsc_error_to_sw (err);
1728 goto command_failed;
1731 slotp->last_status = 0;
1733 /* The open request may return a zero for the ATR length to
1734 indicate that no card is present. */
1735 n = len;
1736 if (n)
1738 if ((i=readn (slotp->pcsc.rsp_fd, slotp->atr, n, &len)) || len != n)
1740 log_error ("error receiving PC/SC OPEN response: %s\n",
1741 i? strerror (errno) : "premature EOF");
1742 goto command_failed;
1744 /* If we got to here we know that a card is present
1745 and usable. Thus remember this. */
1746 slotp->last_status = ( APDU_CARD_USABLE
1747 | APDU_CARD_PRESENT
1748 | APDU_CARD_ACTIVE);
1750 slotp->atrlen = len;
1752 reader_table[slot].close_reader = close_pcsc_reader;
1753 reader_table[slot].reset_reader = reset_pcsc_reader;
1754 reader_table[slot].get_status_reader = pcsc_get_status;
1755 reader_table[slot].send_apdu_reader = pcsc_send_apdu;
1756 reader_table[slot].dump_status_reader = dump_pcsc_reader_status;
1758 /* Read the status so that IS_T0 will be set. */
1759 pcsc_get_status (slot, &dummy_status);
1761 dump_reader_status (slot);
1762 return slot;
1764 command_failed:
1765 close (slotp->pcsc.req_fd);
1766 close (slotp->pcsc.rsp_fd);
1767 slotp->pcsc.req_fd = -1;
1768 slotp->pcsc.rsp_fd = -1;
1769 kill (slotp->pcsc.pid, SIGTERM);
1770 slotp->pcsc.pid = (pid_t)(-1);
1771 slotp->used = 0;
1772 /* There is no way to return SW. */
1773 return -1;
1776 #endif /*NEED_PCSC_WRAPPER*/
1779 static int
1780 open_pcsc_reader (const char *portstr)
1782 #ifdef NEED_PCSC_WRAPPER
1783 return open_pcsc_reader_wrapped (portstr);
1784 #else
1785 return open_pcsc_reader_direct (portstr);
1786 #endif
1791 #ifdef HAVE_LIBUSB
1793 Internal CCID driver interface.
1797 static void
1798 dump_ccid_reader_status (int slot)
1800 log_info ("reader slot %d: using ccid driver\n", slot);
1803 static int
1804 close_ccid_reader (int slot)
1806 ccid_close_reader (reader_table[slot].ccid.handle);
1807 reader_table[slot].used = 0;
1808 return 0;
1812 static int
1813 shutdown_ccid_reader (int slot)
1815 ccid_shutdown_reader (reader_table[slot].ccid.handle);
1816 return 0;
1820 static int
1821 reset_ccid_reader (int slot)
1823 int err;
1824 reader_table_t slotp = reader_table + slot;
1825 unsigned char atr[33];
1826 size_t atrlen;
1828 err = ccid_get_atr (slotp->ccid.handle, atr, sizeof atr, &atrlen);
1829 if (err)
1830 return err;
1831 /* If the reset was successful, update the ATR. */
1832 assert (sizeof slotp->atr >= sizeof atr);
1833 slotp->atrlen = atrlen;
1834 memcpy (slotp->atr, atr, atrlen);
1835 dump_reader_status (slot);
1836 return 0;
1840 static int
1841 set_progress_cb_ccid_reader (int slot, gcry_handler_progress_t cb, void *cb_arg)
1843 reader_table_t slotp = reader_table + slot;
1845 return ccid_set_progress_cb (slotp->ccid.handle, cb, cb_arg);
1849 static int
1850 get_status_ccid (int slot, unsigned int *status)
1852 int rc;
1853 int bits;
1855 rc = ccid_slot_status (reader_table[slot].ccid.handle, &bits);
1856 if (rc)
1857 return rc;
1859 if (bits == 0)
1860 *status = (APDU_CARD_USABLE|APDU_CARD_PRESENT|APDU_CARD_ACTIVE);
1861 else if (bits == 1)
1862 *status = APDU_CARD_PRESENT;
1863 else
1864 *status = 0;
1866 return 0;
1870 /* Actually send the APDU of length APDULEN to SLOT and return a
1871 maximum of *BUFLEN data in BUFFER, the actual returned size will be
1872 set to BUFLEN. Returns: Internal CCID driver error code. */
1873 static int
1874 send_apdu_ccid (int slot, unsigned char *apdu, size_t apdulen,
1875 unsigned char *buffer, size_t *buflen,
1876 struct pininfo_s *pininfo)
1878 long err;
1879 size_t maxbuflen;
1881 /* If we don't have an ATR, we need to reset the reader first. */
1882 if (!reader_table[slot].atrlen
1883 && (err = reset_ccid_reader (slot)))
1884 return err;
1886 if (DBG_CARD_IO)
1887 log_printhex (" raw apdu:", apdu, apdulen);
1889 maxbuflen = *buflen;
1890 if (pininfo)
1891 err = ccid_transceive_secure (reader_table[slot].ccid.handle,
1892 apdu, apdulen,
1893 pininfo->mode,
1894 pininfo->minlen,
1895 pininfo->maxlen,
1896 pininfo->padlen,
1897 buffer, maxbuflen, buflen);
1898 else
1899 err = ccid_transceive (reader_table[slot].ccid.handle,
1900 apdu, apdulen,
1901 buffer, maxbuflen, buflen);
1902 if (err)
1903 log_error ("ccid_transceive failed: (0x%lx)\n",
1904 err);
1906 return err;
1910 /* Check whether the CCID reader supports the ISO command code COMMAND
1911 on the keypad. Return 0 on success. For a description of the pin
1912 parameters, see ccid-driver.c */
1913 static int
1914 check_ccid_keypad (int slot, int command, int pin_mode,
1915 int pinlen_min, int pinlen_max, int pin_padlen)
1917 unsigned char apdu[] = { 0, 0, 0, 0x81 };
1919 apdu[1] = command;
1920 return ccid_transceive_secure (reader_table[slot].ccid.handle,
1921 apdu, sizeof apdu,
1922 pin_mode, pinlen_min, pinlen_max, pin_padlen,
1923 NULL, 0, NULL);
1927 /* Open the reader and try to read an ATR. */
1928 static int
1929 open_ccid_reader (const char *portstr)
1931 int err;
1932 int slot;
1933 reader_table_t slotp;
1935 slot = new_reader_slot ();
1936 if (slot == -1)
1937 return -1;
1938 slotp = reader_table + slot;
1940 err = ccid_open_reader (&slotp->ccid.handle, portstr);
1941 if (err)
1943 slotp->used = 0;
1944 return -1;
1947 err = ccid_get_atr (slotp->ccid.handle,
1948 slotp->atr, sizeof slotp->atr, &slotp->atrlen);
1949 if (err)
1951 slotp->atrlen = 0;
1952 err = 0;
1954 else
1956 /* If we got to here we know that a card is present
1957 and usable. Thus remember this. */
1958 reader_table[slot].last_status = (APDU_CARD_USABLE
1959 | APDU_CARD_PRESENT
1960 | APDU_CARD_ACTIVE);
1963 reader_table[slot].close_reader = close_ccid_reader;
1964 reader_table[slot].shutdown_reader = shutdown_ccid_reader;
1965 reader_table[slot].reset_reader = reset_ccid_reader;
1966 reader_table[slot].get_status_reader = get_status_ccid;
1967 reader_table[slot].send_apdu_reader = send_apdu_ccid;
1968 reader_table[slot].check_keypad = check_ccid_keypad;
1969 reader_table[slot].dump_status_reader = dump_ccid_reader_status;
1970 reader_table[slot].set_progress_cb = set_progress_cb_ccid_reader;
1971 /* Our CCID reader code does not support T=0 at all, thus reset the
1972 flag. */
1973 reader_table[slot].is_t0 = 0;
1975 dump_reader_status (slot);
1976 return slot;
1981 #endif /* HAVE_LIBUSB */
1985 #ifdef USE_G10CODE_RAPDU
1987 The Remote APDU Interface.
1989 This uses the Remote APDU protocol to contact a reader.
1991 The port number is actually an index into the list of ports as
1992 returned via the protocol.
1996 static int
1997 rapdu_status_to_sw (int status)
1999 int rc;
2001 switch (status)
2003 case RAPDU_STATUS_SUCCESS: rc = 0; break;
2005 case RAPDU_STATUS_INVCMD:
2006 case RAPDU_STATUS_INVPROT:
2007 case RAPDU_STATUS_INVSEQ:
2008 case RAPDU_STATUS_INVCOOKIE:
2009 case RAPDU_STATUS_INVREADER: rc = SW_HOST_INV_VALUE; break;
2011 case RAPDU_STATUS_TIMEOUT: rc = SW_HOST_CARD_IO_ERROR; break;
2012 case RAPDU_STATUS_CARDIO: rc = SW_HOST_CARD_IO_ERROR; break;
2013 case RAPDU_STATUS_NOCARD: rc = SW_HOST_NO_CARD; break;
2014 case RAPDU_STATUS_CARDCHG: rc = SW_HOST_NO_CARD; break;
2015 case RAPDU_STATUS_BUSY: rc = SW_HOST_BUSY; break;
2016 case RAPDU_STATUS_NEEDRESET: rc = SW_HOST_CARD_INACTIVE; break;
2018 default: rc = SW_HOST_GENERAL_ERROR; break;
2021 return rc;
2026 static int
2027 close_rapdu_reader (int slot)
2029 rapdu_release (reader_table[slot].rapdu.handle);
2030 reader_table[slot].used = 0;
2031 return 0;
2035 static int
2036 reset_rapdu_reader (int slot)
2038 int err;
2039 reader_table_t slotp;
2040 rapdu_msg_t msg = NULL;
2042 slotp = reader_table + slot;
2044 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2045 if (err)
2047 log_error ("sending rapdu command RESET failed: %s\n",
2048 err < 0 ? strerror (errno): rapdu_strerror (err));
2049 rapdu_msg_release (msg);
2050 return rapdu_status_to_sw (err);
2052 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2053 if (err)
2055 log_error ("receiving rapdu message failed: %s\n",
2056 err < 0 ? strerror (errno): rapdu_strerror (err));
2057 rapdu_msg_release (msg);
2058 return rapdu_status_to_sw (err);
2060 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2062 int sw = rapdu_status_to_sw (msg->cmd);
2063 log_error ("rapdu command RESET failed: %s\n",
2064 rapdu_strerror (msg->cmd));
2065 rapdu_msg_release (msg);
2066 return sw;
2068 if (msg->datalen > DIM (slotp->atr))
2070 log_error ("ATR returned by the RAPDU layer is too large\n");
2071 rapdu_msg_release (msg);
2072 return SW_HOST_INV_VALUE;
2074 slotp->atrlen = msg->datalen;
2075 memcpy (slotp->atr, msg->data, msg->datalen);
2077 rapdu_msg_release (msg);
2078 return 0;
2082 static int
2083 my_rapdu_get_status (int slot, unsigned int *status)
2085 int err;
2086 reader_table_t slotp;
2087 rapdu_msg_t msg = NULL;
2088 int oldslot;
2090 slotp = reader_table + slot;
2092 oldslot = rapdu_set_reader (slotp->rapdu.handle, slot);
2093 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_STATUS);
2094 rapdu_set_reader (slotp->rapdu.handle, oldslot);
2095 if (err)
2097 log_error ("sending rapdu command GET_STATUS failed: %s\n",
2098 err < 0 ? strerror (errno): rapdu_strerror (err));
2099 return rapdu_status_to_sw (err);
2101 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2102 if (err)
2104 log_error ("receiving rapdu message failed: %s\n",
2105 err < 0 ? strerror (errno): rapdu_strerror (err));
2106 rapdu_msg_release (msg);
2107 return rapdu_status_to_sw (err);
2109 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2111 int sw = rapdu_status_to_sw (msg->cmd);
2112 log_error ("rapdu command GET_STATUS failed: %s\n",
2113 rapdu_strerror (msg->cmd));
2114 rapdu_msg_release (msg);
2115 return sw;
2117 *status = msg->data[0];
2119 rapdu_msg_release (msg);
2120 return 0;
2124 /* Actually send the APDU of length APDULEN to SLOT and return a
2125 maximum of *BUFLEN data in BUFFER, the actual returned size will be
2126 set to BUFLEN. Returns: APDU error code. */
2127 static int
2128 my_rapdu_send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2129 unsigned char *buffer, size_t *buflen,
2130 struct pininfo_s *pininfo)
2132 int err;
2133 reader_table_t slotp;
2134 rapdu_msg_t msg = NULL;
2135 size_t maxlen = *buflen;
2137 slotp = reader_table + slot;
2139 *buflen = 0;
2140 if (DBG_CARD_IO)
2141 log_printhex (" APDU_data:", apdu, apdulen);
2143 if (apdulen < 4)
2145 log_error ("rapdu_send_apdu: APDU is too short\n");
2146 return SW_HOST_INV_VALUE;
2149 err = rapdu_send_apdu (slotp->rapdu.handle, apdu, apdulen);
2150 if (err)
2152 log_error ("sending rapdu command APDU failed: %s\n",
2153 err < 0 ? strerror (errno): rapdu_strerror (err));
2154 rapdu_msg_release (msg);
2155 return rapdu_status_to_sw (err);
2157 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2158 if (err)
2160 log_error ("receiving rapdu message failed: %s\n",
2161 err < 0 ? strerror (errno): rapdu_strerror (err));
2162 rapdu_msg_release (msg);
2163 return rapdu_status_to_sw (err);
2165 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2167 int sw = rapdu_status_to_sw (msg->cmd);
2168 log_error ("rapdu command APDU failed: %s\n",
2169 rapdu_strerror (msg->cmd));
2170 rapdu_msg_release (msg);
2171 return sw;
2174 if (msg->datalen > maxlen)
2176 log_error ("rapdu response apdu too large\n");
2177 rapdu_msg_release (msg);
2178 return SW_HOST_INV_VALUE;
2181 *buflen = msg->datalen;
2182 memcpy (buffer, msg->data, msg->datalen);
2184 rapdu_msg_release (msg);
2185 return 0;
2188 static int
2189 open_rapdu_reader (int portno,
2190 const unsigned char *cookie, size_t length,
2191 int (*readfnc) (void *opaque,
2192 void *buffer, size_t size),
2193 void *readfnc_value,
2194 int (*writefnc) (void *opaque,
2195 const void *buffer, size_t size),
2196 void *writefnc_value,
2197 void (*closefnc) (void *opaque),
2198 void *closefnc_value)
2200 int err;
2201 int slot;
2202 reader_table_t slotp;
2203 rapdu_msg_t msg = NULL;
2205 slot = new_reader_slot ();
2206 if (slot == -1)
2207 return -1;
2208 slotp = reader_table + slot;
2210 slotp->rapdu.handle = rapdu_new ();
2211 if (!slotp->rapdu.handle)
2213 slotp->used = 0;
2214 return -1;
2217 rapdu_set_reader (slotp->rapdu.handle, portno);
2219 rapdu_set_iofunc (slotp->rapdu.handle,
2220 readfnc, readfnc_value,
2221 writefnc, writefnc_value,
2222 closefnc, closefnc_value);
2223 rapdu_set_cookie (slotp->rapdu.handle, cookie, length);
2225 /* First try to get the current ATR, but if the card is inactive
2226 issue a reset instead. */
2227 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_GET_ATR);
2228 if (err == RAPDU_STATUS_NEEDRESET)
2229 err = rapdu_send_cmd (slotp->rapdu.handle, RAPDU_CMD_RESET);
2230 if (err)
2232 log_info ("sending rapdu command GET_ATR/RESET failed: %s\n",
2233 err < 0 ? strerror (errno): rapdu_strerror (err));
2234 goto failure;
2236 err = rapdu_read_msg (slotp->rapdu.handle, &msg);
2237 if (err)
2239 log_info ("receiving rapdu message failed: %s\n",
2240 err < 0 ? strerror (errno): rapdu_strerror (err));
2241 goto failure;
2243 if (msg->cmd != RAPDU_STATUS_SUCCESS || !msg->datalen)
2245 log_info ("rapdu command GET ATR failed: %s\n",
2246 rapdu_strerror (msg->cmd));
2247 goto failure;
2249 if (msg->datalen > DIM (slotp->atr))
2251 log_error ("ATR returned by the RAPDU layer is too large\n");
2252 goto failure;
2254 slotp->atrlen = msg->datalen;
2255 memcpy (slotp->atr, msg->data, msg->datalen);
2257 reader_table[slot].close_reader = close_rapdu_reader;
2258 reader_table[slot].reset_reader = reset_rapdu_reader;
2259 reader_table[slot].get_status_reader = my_rapdu_get_status;
2260 reader_table[slot].send_apdu_reader = my_rapdu_send_apdu;
2261 reader_table[slot].check_keypad = NULL;
2262 reader_table[slot].dump_status_reader = NULL;
2264 dump_reader_status (slot);
2265 rapdu_msg_release (msg);
2266 return slot;
2268 failure:
2269 rapdu_msg_release (msg);
2270 rapdu_release (slotp->rapdu.handle);
2271 slotp->used = 0;
2272 return -1;
2275 #endif /*USE_G10CODE_RAPDU*/
2280 Driver Access
2284 static int
2285 lock_slot (int slot)
2287 #ifdef USE_GNU_PTH
2288 if (!pth_mutex_acquire (&reader_table[slot].lock, 0, NULL))
2290 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2291 return SW_HOST_LOCKING_FAILED;
2293 #endif /*USE_GNU_PTH*/
2294 return 0;
2297 static int
2298 trylock_slot (int slot)
2300 #ifdef USE_GNU_PTH
2301 if (!pth_mutex_acquire (&reader_table[slot].lock, TRUE, NULL))
2303 if (errno == EBUSY)
2304 return SW_HOST_BUSY;
2305 log_error ("failed to acquire apdu lock: %s\n", strerror (errno));
2306 return SW_HOST_LOCKING_FAILED;
2308 #endif /*USE_GNU_PTH*/
2309 return 0;
2312 static void
2313 unlock_slot (int slot)
2315 #ifdef USE_GNU_PTH
2316 if (!pth_mutex_release (&reader_table[slot].lock))
2317 log_error ("failed to release apdu lock: %s\n", strerror (errno));
2318 #endif /*USE_GNU_PTH*/
2322 /* Open the reader and return an internal slot number or -1 on
2323 error. If PORTSTR is NULL we default to a suitable port (for ctAPI:
2324 the first USB reader. For PC/SC the first listed reader). */
2326 apdu_open_reader (const char *portstr)
2328 static int pcsc_api_loaded, ct_api_loaded;
2330 #ifdef HAVE_LIBUSB
2331 if (!opt.disable_ccid)
2333 int slot, i;
2334 const char *s;
2336 slot = open_ccid_reader (portstr);
2337 if (slot != -1)
2338 return slot; /* got one */
2340 /* If a CCID reader specification has been given, the user does
2341 not want a fallback to other drivers. */
2342 if (portstr)
2343 for (s=portstr, i=0; *s; s++)
2344 if (*s == ':' && (++i == 3))
2345 return -1;
2348 #endif /* HAVE_LIBUSB */
2350 if (opt.ctapi_driver && *opt.ctapi_driver)
2352 int port = portstr? atoi (portstr) : 32768;
2354 if (!ct_api_loaded)
2356 void *handle;
2358 handle = dlopen (opt.ctapi_driver, RTLD_LAZY);
2359 if (!handle)
2361 log_error ("apdu_open_reader: failed to open driver: %s\n",
2362 dlerror ());
2363 return -1;
2365 CT_init = dlsym (handle, "CT_init");
2366 CT_data = dlsym (handle, "CT_data");
2367 CT_close = dlsym (handle, "CT_close");
2368 if (!CT_init || !CT_data || !CT_close)
2370 log_error ("apdu_open_reader: invalid CT-API driver\n");
2371 dlclose (handle);
2372 return -1;
2374 ct_api_loaded = 1;
2376 return open_ct_reader (port);
2380 /* No ctAPI configured, so lets try the PC/SC API */
2381 if (!pcsc_api_loaded)
2383 #ifndef NEED_PCSC_WRAPPER
2384 void *handle;
2386 handle = dlopen (opt.pcsc_driver, RTLD_LAZY);
2387 if (!handle)
2389 log_error ("apdu_open_reader: failed to open driver `%s': %s\n",
2390 opt.pcsc_driver, dlerror ());
2391 return -1;
2394 pcsc_establish_context = dlsym (handle, "SCardEstablishContext");
2395 pcsc_release_context = dlsym (handle, "SCardReleaseContext");
2396 pcsc_list_readers = dlsym (handle, "SCardListReaders");
2397 #if defined(_WIN32) || defined(__CYGWIN__)
2398 if (!pcsc_list_readers)
2399 pcsc_list_readers = dlsym (handle, "SCardListReadersA");
2400 #endif
2401 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChange");
2402 #if defined(_WIN32) || defined(__CYGWIN__)
2403 if (!pcsc_get_status_change)
2404 pcsc_get_status_change = dlsym (handle, "SCardGetStatusChangeA");
2405 #endif
2406 pcsc_connect = dlsym (handle, "SCardConnect");
2407 #if defined(_WIN32) || defined(__CYGWIN__)
2408 if (!pcsc_connect)
2409 pcsc_connect = dlsym (handle, "SCardConnectA");
2410 #endif
2411 pcsc_reconnect = dlsym (handle, "SCardReconnect");
2412 #if defined(_WIN32) || defined(__CYGWIN__)
2413 if (!pcsc_reconnect)
2414 pcsc_reconnect = dlsym (handle, "SCardReconnectA");
2415 #endif
2416 pcsc_disconnect = dlsym (handle, "SCardDisconnect");
2417 pcsc_status = dlsym (handle, "SCardStatus");
2418 #if defined(_WIN32) || defined(__CYGWIN__)
2419 if (!pcsc_status)
2420 pcsc_status = dlsym (handle, "SCardStatusA");
2421 #endif
2422 pcsc_begin_transaction = dlsym (handle, "SCardBeginTransaction");
2423 pcsc_end_transaction = dlsym (handle, "SCardEndTransaction");
2424 pcsc_transmit = dlsym (handle, "SCardTransmit");
2425 pcsc_set_timeout = dlsym (handle, "SCardSetTimeout");
2427 if (!pcsc_establish_context
2428 || !pcsc_release_context
2429 || !pcsc_list_readers
2430 || !pcsc_get_status_change
2431 || !pcsc_connect
2432 || !pcsc_reconnect
2433 || !pcsc_disconnect
2434 || !pcsc_status
2435 || !pcsc_begin_transaction
2436 || !pcsc_end_transaction
2437 || !pcsc_transmit
2438 /* || !pcsc_set_timeout */)
2440 /* Note that set_timeout is currently not used and also not
2441 available under Windows. */
2442 log_error ("apdu_open_reader: invalid PC/SC driver "
2443 "(%d%d%d%d%d%d%d%d%d%d%d%d)\n",
2444 !!pcsc_establish_context,
2445 !!pcsc_release_context,
2446 !!pcsc_list_readers,
2447 !!pcsc_get_status_change,
2448 !!pcsc_connect,
2449 !!pcsc_reconnect,
2450 !!pcsc_disconnect,
2451 !!pcsc_status,
2452 !!pcsc_begin_transaction,
2453 !!pcsc_end_transaction,
2454 !!pcsc_transmit,
2455 !!pcsc_set_timeout );
2456 dlclose (handle);
2457 return -1;
2459 #endif /*!NEED_PCSC_WRAPPER*/
2460 pcsc_api_loaded = 1;
2463 return open_pcsc_reader (portstr);
2467 /* Open an remote reader and return an internal slot number or -1 on
2468 error. This function is an alternative to apdu_open_reader and used
2469 with remote readers only. Note that the supplied CLOSEFNC will
2470 only be called once and the slot will not be valid afther this.
2472 If PORTSTR is NULL we default to the first availabe port.
2475 apdu_open_remote_reader (const char *portstr,
2476 const unsigned char *cookie, size_t length,
2477 int (*readfnc) (void *opaque,
2478 void *buffer, size_t size),
2479 void *readfnc_value,
2480 int (*writefnc) (void *opaque,
2481 const void *buffer, size_t size),
2482 void *writefnc_value,
2483 void (*closefnc) (void *opaque),
2484 void *closefnc_value)
2486 #ifdef USE_G10CODE_RAPDU
2487 return open_rapdu_reader (portstr? atoi (portstr) : 0,
2488 cookie, length,
2489 readfnc, readfnc_value,
2490 writefnc, writefnc_value,
2491 closefnc, closefnc_value);
2492 #else
2493 (void)portstr;
2494 (void)cookie;
2495 (void)length;
2496 (void)readfnc;
2497 (void)readfnc_value;
2498 (void)writefnc;
2499 (void)writefnc_value;
2500 (void)closefnc;
2501 (void)closefnc_value;
2502 #ifdef _WIN32
2503 errno = ENOENT;
2504 #else
2505 errno = ENOSYS;
2506 #endif
2507 return -1;
2508 #endif
2513 apdu_close_reader (int slot)
2515 int sw;
2517 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2518 return SW_HOST_NO_DRIVER;
2519 sw = apdu_disconnect (slot);
2520 if (sw)
2521 return sw;
2522 if (reader_table[slot].close_reader)
2523 return reader_table[slot].close_reader (slot);
2524 return SW_HOST_NOT_SUPPORTED;
2528 /* Function suitable for a cleanup function to close all reader. It
2529 should not be used if the reader will be opened again. The reason
2530 for implementing this to properly close USB devices so that they
2531 will startup the next time without error. */
2532 void
2533 apdu_prepare_exit (void)
2535 static int sentinel;
2536 int slot;
2538 if (!sentinel)
2540 sentinel = 1;
2541 for (slot = 0; slot < MAX_READER; slot++)
2542 if (reader_table[slot].used)
2544 apdu_disconnect (slot);
2545 if (reader_table[slot].close_reader)
2546 reader_table[slot].close_reader (slot);
2547 reader_table[slot].used = 0;
2549 sentinel = 0;
2554 /* Shutdown a reader; that is basically the same as a close but keeps
2555 the handle ready for later use. A apdu_reset_reader or apdu_connect
2556 should be used to get it active again. */
2558 apdu_shutdown_reader (int slot)
2560 int sw;
2562 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2563 return SW_HOST_NO_DRIVER;
2564 sw = apdu_disconnect (slot);
2565 if (sw)
2566 return sw;
2567 if (reader_table[slot].shutdown_reader)
2568 return reader_table[slot].shutdown_reader (slot);
2569 return SW_HOST_NOT_SUPPORTED;
2572 /* Enumerate all readers and return information on whether this reader
2573 is in use. The caller should start with SLOT set to 0 and
2574 increment it with each call until an error is returned. */
2576 apdu_enum_reader (int slot, int *used)
2578 if (slot < 0 || slot >= MAX_READER)
2579 return SW_HOST_NO_DRIVER;
2580 *used = reader_table[slot].used;
2581 return 0;
2585 /* Connect a card. This is used to power up the card and make sure
2586 that an ATR is available. */
2588 apdu_connect (int slot)
2590 int sw;
2592 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2593 return SW_HOST_NO_DRIVER;
2595 /* Only if the access method provides a connect function we use it.
2596 If not, we expect that the card has been implicitly connected by
2597 apdu_open_reader. */
2598 if (reader_table[slot].connect_card)
2600 sw = lock_slot (slot);
2601 if (!sw)
2603 sw = reader_table[slot].connect_card (slot);
2604 unlock_slot (slot);
2607 else
2608 sw = 0;
2610 /* We need to call apdu_get_status_internal, so that the last-status
2611 machinery gets setup properly even if a card is inserted while
2612 scdaemon is fired up and apdu_get_status has not yet been called.
2613 Without that we would force a reset of the card with the next
2614 call to apdu_get_status. */
2615 apdu_get_status_internal (slot, 1, 1, NULL, NULL);
2617 return sw;
2622 apdu_disconnect (int slot)
2624 int sw;
2626 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2627 return SW_HOST_NO_DRIVER;
2629 if (reader_table[slot].disconnect_card)
2631 sw = lock_slot (slot);
2632 if (!sw)
2634 sw = reader_table[slot].disconnect_card (slot);
2635 unlock_slot (slot);
2638 else
2639 sw = 0;
2640 return sw;
2644 /* Set the progress callback of SLOT to CB and its args to CB_ARG. If
2645 CB is NULL the progress callback is removed. */
2647 apdu_set_progress_cb (int slot, gcry_handler_progress_t cb, void *cb_arg)
2649 int sw;
2651 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2652 return SW_HOST_NO_DRIVER;
2654 if (reader_table[slot].set_progress_cb)
2656 sw = lock_slot (slot);
2657 if (!sw)
2659 sw = reader_table[slot].set_progress_cb (slot, cb, cb_arg);
2660 unlock_slot (slot);
2663 else
2664 sw = 0;
2665 return sw;
2669 /* Do a reset for the card in reader at SLOT. */
2671 apdu_reset (int slot)
2673 int sw;
2675 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2676 return SW_HOST_NO_DRIVER;
2678 if ((sw = lock_slot (slot)))
2679 return sw;
2681 reader_table[slot].last_status = 0;
2682 if (reader_table[slot].reset_reader)
2683 sw = reader_table[slot].reset_reader (slot);
2685 if (!sw)
2687 /* If we got to here we know that a card is present
2688 and usable. Thus remember this. */
2689 reader_table[slot].last_status = (APDU_CARD_USABLE
2690 | APDU_CARD_PRESENT
2691 | APDU_CARD_ACTIVE);
2694 unlock_slot (slot);
2695 return sw;
2699 /* Activate a card if it has not yet been done. This is a kind of
2700 reset-if-required. It is useful to test for presence of a card
2701 before issuing a bunch of apdu commands. It does not wait on a
2702 locked card. */
2704 apdu_activate (int slot)
2706 int sw;
2707 unsigned int s;
2709 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2710 return SW_HOST_NO_DRIVER;
2712 if ((sw = trylock_slot (slot)))
2713 return sw;
2715 if (reader_table[slot].get_status_reader)
2716 sw = reader_table[slot].get_status_reader (slot, &s);
2718 if (!sw)
2720 if (!(s & 2)) /* Card not present. */
2721 sw = SW_HOST_NO_CARD;
2722 else if ( ((s & 2) && !(s & 4))
2723 || !reader_table[slot].atrlen )
2725 /* We don't have an ATR or a card is present though inactive:
2726 do a reset now. */
2727 if (reader_table[slot].reset_reader)
2729 reader_table[slot].last_status = 0;
2730 sw = reader_table[slot].reset_reader (slot);
2731 if (!sw)
2733 /* If we got to here we know that a card is present
2734 and usable. Thus remember this. */
2735 reader_table[slot].last_status = (APDU_CARD_USABLE
2736 | APDU_CARD_PRESENT
2737 | APDU_CARD_ACTIVE);
2743 unlock_slot (slot);
2744 return sw;
2748 unsigned char *
2749 apdu_get_atr (int slot, size_t *atrlen)
2751 unsigned char *buf;
2753 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2754 return NULL;
2755 if (!reader_table[slot].atrlen)
2756 return NULL;
2757 buf = xtrymalloc (reader_table[slot].atrlen);
2758 if (!buf)
2759 return NULL;
2760 memcpy (buf, reader_table[slot].atr, reader_table[slot].atrlen);
2761 *atrlen = reader_table[slot].atrlen;
2762 return buf;
2767 /* Retrieve the status for SLOT. The function does only wait for the
2768 card to become available if HANG is set to true. On success the
2769 bits in STATUS will be set to
2771 APDU_CARD_USABLE (bit 0) = card present and usable
2772 APDU_CARD_PRESENT (bit 1) = card present
2773 APDU_CARD_ACTIVE (bit 2) = card active
2774 (bit 3) = card access locked [not yet implemented]
2776 For must applications, testing bit 0 is sufficient.
2778 CHANGED will receive the value of the counter tracking the number
2779 of card insertions. This value may be used to detect a card
2780 change.
2782 static int
2783 apdu_get_status_internal (int slot, int hang, int no_atr_reset,
2784 unsigned int *status, unsigned int *changed)
2786 int sw;
2787 unsigned int s;
2789 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2790 return SW_HOST_NO_DRIVER;
2792 if ((sw = hang? lock_slot (slot) : trylock_slot (slot)))
2793 return sw;
2795 if (reader_table[slot].get_status_reader)
2796 sw = reader_table[slot].get_status_reader (slot, &s);
2798 unlock_slot (slot);
2800 if (sw)
2802 reader_table[slot].last_status = 0;
2803 return sw;
2806 /* Keep track of changes. */
2807 if (s != reader_table[slot].last_status
2808 || !reader_table[slot].any_status )
2810 reader_table[slot].change_counter++;
2811 /* Make sure that the ATR is invalid so that a reset will be
2812 triggered by apdu_activate. */
2813 if (!no_atr_reset)
2814 reader_table[slot].atrlen = 0;
2816 reader_table[slot].any_status = 1;
2817 reader_table[slot].last_status = s;
2819 if (status)
2820 *status = s;
2821 if (changed)
2822 *changed = reader_table[slot].change_counter;
2823 return 0;
2827 /* See above for a description. */
2829 apdu_get_status (int slot, int hang,
2830 unsigned int *status, unsigned int *changed)
2832 return apdu_get_status_internal (slot, hang, 0, status, changed);
2836 /* Check whether the reader supports the ISO command code COMMAND on
2837 the keypad. Return 0 on success. For a description of the pin
2838 parameters, see ccid-driver.c */
2840 apdu_check_keypad (int slot, int command, int pin_mode,
2841 int pinlen_min, int pinlen_max, int pin_padlen)
2843 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2844 return SW_HOST_NO_DRIVER;
2846 if (reader_table[slot].check_keypad)
2847 return reader_table[slot].check_keypad (slot, command,
2848 pin_mode, pinlen_min, pinlen_max,
2849 pin_padlen);
2850 else
2851 return SW_HOST_NOT_SUPPORTED;
2855 /* Dispatcher for the actual send_apdu function. Note, that this
2856 function should be called in locked state. */
2857 static int
2858 send_apdu (int slot, unsigned char *apdu, size_t apdulen,
2859 unsigned char *buffer, size_t *buflen, struct pininfo_s *pininfo)
2861 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2862 return SW_HOST_NO_DRIVER;
2864 if (reader_table[slot].send_apdu_reader)
2865 return reader_table[slot].send_apdu_reader (slot,
2866 apdu, apdulen,
2867 buffer, buflen,
2868 pininfo);
2869 else
2870 return SW_HOST_NOT_SUPPORTED;
2874 /* Core APDU tranceiver function. Parameters are described at
2875 apdu_send_le with the exception of PININFO which indicates keypad
2876 related operations if not NULL. If EXTENDED_MODE is not 0
2877 command chaining or extended length will be used according to these
2878 values:
2879 n < 0 := Use command chaining with the data part limited to -n
2880 in each chunk. If -1 is used a default value is used.
2881 n == 0 := No extended mode or command chaining.
2882 n == 1 := Use extended length for input and output without a
2883 length limit.
2884 n > 1 := Use extended length with up to N bytes.
2887 static int
2888 send_le (int slot, int class, int ins, int p0, int p1,
2889 int lc, const char *data, int le,
2890 unsigned char **retbuf, size_t *retbuflen,
2891 struct pininfo_s *pininfo, int extended_mode)
2893 #define SHORT_RESULT_BUFFER_SIZE 258
2894 /* We allocate 8 extra bytes as a safety margin towards a driver bug. */
2895 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
2896 unsigned char *result_buffer = NULL;
2897 size_t result_buffer_size;
2898 unsigned char *result;
2899 size_t resultlen;
2900 unsigned char short_apdu_buffer[5+256+1];
2901 unsigned char *apdu_buffer = NULL;
2902 size_t apdu_buffer_size;
2903 unsigned char *apdu;
2904 size_t apdulen;
2905 int sw;
2906 long rc; /* We need a long here due to PC/SC. */
2907 int did_exact_length_hack = 0;
2908 int use_chaining = 0;
2909 int use_extended_length = 0;
2910 int lc_chunk;
2912 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
2913 return SW_HOST_NO_DRIVER;
2915 if (DBG_CARD_IO)
2916 log_debug ("send apdu: c=%02X i=%02X p1=%02X p2=%02X lc=%d le=%d em=%d\n",
2917 class, ins, p0, p1, lc, le, extended_mode);
2919 if (lc != -1 && (lc > 255 || lc < 0))
2921 /* Data does not fit into an APDU. What we do now depends on
2922 the EXTENDED_MODE parameter. */
2923 if (!extended_mode)
2924 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2925 else if (extended_mode > 0)
2926 use_extended_length = 1;
2927 else if (extended_mode < 0)
2929 /* Send APDU using chaining mode. */
2930 if (lc > 16384)
2931 return SW_WRONG_LENGTH; /* Sanity check. */
2932 if ((class&0xf0) != 0)
2933 return SW_HOST_INV_VALUE; /* Upper 4 bits need to be 0. */
2934 use_chaining = extended_mode == -1? 255 : -extended_mode;
2935 use_chaining &= 0xff;
2937 else
2938 return SW_HOST_INV_VALUE;
2940 else if (lc == -1 && extended_mode > 0)
2941 use_extended_length = 1;
2943 if (le != -1 && (le > (extended_mode > 0? 255:256) || le < 0))
2945 /* Expected Data does not fit into an APDU. What we do now
2946 depends on the EXTENDED_MODE parameter. Note that a check
2947 for command chaining does not make sense because we are
2948 looking at Le. */
2949 if (!extended_mode)
2950 return SW_WRONG_LENGTH; /* No way to send such an APDU. */
2951 else if (use_extended_length)
2952 ; /* We are already using extended length. */
2953 else if (extended_mode > 0)
2954 use_extended_length = 1;
2955 else
2956 return SW_HOST_INV_VALUE;
2959 if ((!data && lc != -1) || (data && lc == -1))
2960 return SW_HOST_INV_VALUE;
2962 if (use_extended_length)
2964 if (reader_table[slot].is_t0)
2965 return SW_HOST_NOT_SUPPORTED;
2967 /* Space for: cls/ins/p1/p2+Z+2_byte_Lc+Lc+2_byte_Le. */
2968 apdu_buffer_size = 4 + 1 + (lc >= 0? (2+lc):0) + 2;
2969 apdu_buffer = xtrymalloc (apdu_buffer_size + 10);
2970 if (!apdu_buffer)
2971 return SW_HOST_OUT_OF_CORE;
2972 apdu = apdu_buffer;
2974 else
2976 apdu_buffer_size = sizeof short_apdu_buffer;
2977 apdu = short_apdu_buffer;
2980 if (use_extended_length && (le > 256 || le < 0))
2982 result_buffer_size = le < 0? 4096 : le;
2983 result_buffer = xtrymalloc (result_buffer_size + 10);
2984 if (!result_buffer)
2986 xfree (apdu_buffer);
2987 return SW_HOST_OUT_OF_CORE;
2989 result = result_buffer;
2991 else
2993 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
2994 result = short_result_buffer;
2996 #undef SHORT_RESULT_BUFFER_SIZE
2998 if ((sw = lock_slot (slot)))
3000 xfree (apdu_buffer);
3001 xfree (result_buffer);
3002 return sw;
3007 if (use_extended_length)
3009 use_chaining = 0;
3010 apdulen = 0;
3011 apdu[apdulen++] = class;
3012 apdu[apdulen++] = ins;
3013 apdu[apdulen++] = p0;
3014 apdu[apdulen++] = p1;
3015 apdu[apdulen++] = 0; /* Z byte: Extended length marker. */
3016 if (lc >= 0)
3018 apdu[apdulen++] = ((lc >> 8) & 0xff);
3019 apdu[apdulen++] = (lc & 0xff);
3020 memcpy (apdu+apdulen, data, lc);
3021 data += lc;
3022 apdulen += lc;
3024 if (le != -1)
3026 apdu[apdulen++] = ((le >> 8) & 0xff);
3027 apdu[apdulen++] = (le & 0xff);
3030 else
3032 apdulen = 0;
3033 apdu[apdulen] = class;
3034 if (use_chaining && lc > 255)
3036 apdu[apdulen] |= 0x10;
3037 assert (use_chaining < 256);
3038 lc_chunk = use_chaining;
3039 lc -= use_chaining;
3041 else
3043 use_chaining = 0;
3044 lc_chunk = lc;
3046 apdulen++;
3047 apdu[apdulen++] = ins;
3048 apdu[apdulen++] = p0;
3049 apdu[apdulen++] = p1;
3050 if (lc_chunk != -1)
3052 apdu[apdulen++] = lc_chunk;
3053 memcpy (apdu+apdulen, data, lc_chunk);
3054 data += lc_chunk;
3055 apdulen += lc_chunk;
3056 /* T=0 does not allow the use of Lc together with Le;
3057 thus disable Le in this case. */
3058 if (reader_table[slot].is_t0)
3059 le = -1;
3061 if (le != -1 && !use_chaining)
3062 apdu[apdulen++] = le; /* Truncation is okay (0 means 256). */
3065 exact_length_hack:
3066 /* As a safeguard don't pass any garbage to the driver. */
3067 assert (apdulen <= apdu_buffer_size);
3068 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3069 resultlen = result_buffer_size;
3070 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, pininfo);
3071 if (rc || resultlen < 2)
3073 log_info ("apdu_send_simple(%d) failed: %s\n",
3074 slot, apdu_strerror (rc));
3075 unlock_slot (slot);
3076 xfree (apdu_buffer);
3077 xfree (result_buffer);
3078 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3080 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3081 if (!use_extended_length
3082 && !did_exact_length_hack && SW_EXACT_LENGTH_P (sw))
3084 apdu[apdulen-1] = (sw & 0x00ff);
3085 did_exact_length_hack = 1;
3086 goto exact_length_hack;
3089 while (use_chaining && sw == SW_SUCCESS);
3091 if (apdu_buffer)
3093 xfree (apdu_buffer);
3094 apdu_buffer = NULL;
3095 apdu_buffer_size = 0;
3098 /* Store away the returned data but strip the statusword. */
3099 resultlen -= 2;
3100 if (DBG_CARD_IO)
3102 log_debug (" response: sw=%04X datalen=%d\n",
3103 sw, (unsigned int)resultlen);
3104 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3105 log_printhex (" dump: ", result, resultlen);
3108 if (sw == SW_SUCCESS || sw == SW_EOF_REACHED)
3110 if (retbuf)
3112 *retbuf = xtrymalloc (resultlen? resultlen : 1);
3113 if (!*retbuf)
3115 unlock_slot (slot);
3116 xfree (result_buffer);
3117 return SW_HOST_OUT_OF_CORE;
3119 *retbuflen = resultlen;
3120 memcpy (*retbuf, result, resultlen);
3123 else if ((sw & 0xff00) == SW_MORE_DATA)
3125 unsigned char *p = NULL, *tmp;
3126 size_t bufsize = 4096;
3128 /* It is likely that we need to return much more data, so we
3129 start off with a large buffer. */
3130 if (retbuf)
3132 *retbuf = p = xtrymalloc (bufsize);
3133 if (!*retbuf)
3135 unlock_slot (slot);
3136 xfree (result_buffer);
3137 return SW_HOST_OUT_OF_CORE;
3139 assert (resultlen < bufsize);
3140 memcpy (p, result, resultlen);
3141 p += resultlen;
3146 int len = (sw & 0x00ff);
3148 if (DBG_CARD_IO)
3149 log_debug ("apdu_send_simple(%d): %d more bytes available\n",
3150 slot, len);
3151 apdu_buffer_size = sizeof short_apdu_buffer;
3152 apdu = short_apdu_buffer;
3153 apdulen = 0;
3154 apdu[apdulen++] = class;
3155 apdu[apdulen++] = 0xC0;
3156 apdu[apdulen++] = 0;
3157 apdu[apdulen++] = 0;
3158 apdu[apdulen++] = len;
3159 assert (apdulen <= apdu_buffer_size);
3160 memset (apdu+apdulen, 0, apdu_buffer_size - apdulen);
3161 resultlen = result_buffer_size;
3162 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3163 if (rc || resultlen < 2)
3165 log_error ("apdu_send_simple(%d) for get response failed: %s\n",
3166 slot, apdu_strerror (rc));
3167 unlock_slot (slot);
3168 xfree (result_buffer);
3169 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3171 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3172 resultlen -= 2;
3173 if (DBG_CARD_IO)
3175 log_debug (" more: sw=%04X datalen=%d\n",
3176 sw, (unsigned int)resultlen);
3177 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3178 log_printhex (" dump: ", result, resultlen);
3181 if ((sw & 0xff00) == SW_MORE_DATA
3182 || sw == SW_SUCCESS
3183 || sw == SW_EOF_REACHED )
3185 if (retbuf && resultlen)
3187 if (p - *retbuf + resultlen > bufsize)
3189 bufsize += resultlen > 4096? resultlen: 4096;
3190 tmp = xtryrealloc (*retbuf, bufsize);
3191 if (!tmp)
3193 unlock_slot (slot);
3194 xfree (result_buffer);
3195 return SW_HOST_OUT_OF_CORE;
3197 p = tmp + (p - *retbuf);
3198 *retbuf = tmp;
3200 memcpy (p, result, resultlen);
3201 p += resultlen;
3204 else
3205 log_info ("apdu_send_simple(%d) "
3206 "got unexpected status %04X from get response\n",
3207 slot, sw);
3209 while ((sw & 0xff00) == SW_MORE_DATA);
3211 if (retbuf)
3213 *retbuflen = p - *retbuf;
3214 tmp = xtryrealloc (*retbuf, *retbuflen);
3215 if (tmp)
3216 *retbuf = tmp;
3220 unlock_slot (slot);
3221 xfree (result_buffer);
3223 if (DBG_CARD_IO && retbuf && sw == SW_SUCCESS)
3224 log_printhex (" dump: ", *retbuf, *retbuflen);
3226 return sw;
3229 /* Send an APDU to the card in SLOT. The APDU is created from all
3230 given parameters: CLASS, INS, P0, P1, LC, DATA, LE. A value of -1
3231 for LC won't sent this field and the data field; in this case DATA
3232 must also be passed as NULL. If EXTENDED_MODE is not 0 command
3233 chaining or extended length will be used; see send_le for details.
3234 The return value is the status word or -1 for an invalid SLOT or
3235 other non card related error. If RETBUF is not NULL, it will
3236 receive an allocated buffer with the returned data. The length of
3237 that data will be put into *RETBUFLEN. The caller is reponsible
3238 for releasing the buffer even in case of errors. */
3240 apdu_send_le(int slot, int extended_mode,
3241 int class, int ins, int p0, int p1,
3242 int lc, const char *data, int le,
3243 unsigned char **retbuf, size_t *retbuflen)
3245 return send_le (slot, class, ins, p0, p1,
3246 lc, data, le,
3247 retbuf, retbuflen,
3248 NULL, extended_mode);
3252 /* Send an APDU to the card in SLOT. The APDU is created from all
3253 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3254 LC won't sent this field and the data field; in this case DATA must
3255 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3256 or extended length will be used; see send_le for details. The
3257 return value is the status word or -1 for an invalid SLOT or other
3258 non card related error. If RETBUF is not NULL, it will receive an
3259 allocated buffer with the returned data. The length of that data
3260 will be put into *RETBUFLEN. The caller is reponsible for
3261 releasing the buffer even in case of errors. */
3263 apdu_send (int slot, int extended_mode,
3264 int class, int ins, int p0, int p1,
3265 int lc, const char *data, unsigned char **retbuf, size_t *retbuflen)
3267 return send_le (slot, class, ins, p0, p1, lc, data, 256,
3268 retbuf, retbuflen, NULL, extended_mode);
3271 /* Send an APDU to the card in SLOT. The APDU is created from all
3272 given parameters: CLASS, INS, P0, P1, LC, DATA. A value of -1 for
3273 LC won't sent this field and the data field; in this case DATA must
3274 also be passed as NULL. If EXTENDED_MODE is not 0 command chaining
3275 or extended length will be used; see send_le for details. The
3276 return value is the status word or -1 for an invalid SLOT or other
3277 non card related error. No data will be returned. */
3279 apdu_send_simple (int slot, int extended_mode,
3280 int class, int ins, int p0, int p1,
3281 int lc, const char *data)
3283 return send_le (slot, class, ins, p0, p1, lc, data, -1, NULL, NULL, NULL,
3284 extended_mode);
3288 /* Same as apdu_send_simple but uses the keypad of the reader. */
3290 apdu_send_simple_kp (int slot, int class, int ins, int p0, int p1,
3291 int lc, const char *data,
3292 int pin_mode,
3293 int pinlen_min, int pinlen_max, int pin_padlen)
3295 struct pininfo_s pininfo;
3297 pininfo.mode = pin_mode;
3298 pininfo.minlen = pinlen_min;
3299 pininfo.maxlen = pinlen_max;
3300 pininfo.padlen = pin_padlen;
3301 return send_le (slot, class, ins, p0, p1, lc, data, -1,
3302 NULL, NULL, &pininfo, 0);
3306 /* This is a more generic version of the apdu sending routine. It
3307 takes an already formatted APDU in APDUDATA or length APDUDATALEN
3308 and returns with an APDU including the status word. With
3309 HANDLE_MORE set to true this function will handle the MORE DATA
3310 status and return all APDUs concatenated with one status word at
3311 the end. If EXTENDED_LENGTH is != 0 extended lengths are allowed
3312 with a max. result data length of EXTENDED_LENGTH bytes. The
3313 function does not return a regular status word but 0 on success.
3314 If the slot is locked, the function returns immediately with an
3315 error. */
3317 apdu_send_direct (int slot, size_t extended_length,
3318 const unsigned char *apdudata, size_t apdudatalen,
3319 int handle_more,
3320 unsigned char **retbuf, size_t *retbuflen)
3322 #define SHORT_RESULT_BUFFER_SIZE 258
3323 unsigned char short_result_buffer[SHORT_RESULT_BUFFER_SIZE+10];
3324 unsigned char *result_buffer = NULL;
3325 size_t result_buffer_size;
3326 unsigned char *result;
3327 size_t resultlen;
3328 unsigned char short_apdu_buffer[5+256+10];
3329 unsigned char *apdu_buffer = NULL;
3330 unsigned char *apdu;
3331 size_t apdulen;
3332 int sw;
3333 long rc; /* we need a long here due to PC/SC. */
3334 int class;
3336 if (slot < 0 || slot >= MAX_READER || !reader_table[slot].used )
3337 return SW_HOST_NO_DRIVER;
3339 if (apdudatalen > 65535)
3340 return SW_HOST_INV_VALUE;
3342 if (apdudatalen > sizeof short_apdu_buffer - 5)
3344 apdu_buffer = xtrymalloc (apdudatalen + 5);
3345 if (!apdu_buffer)
3346 return SW_HOST_OUT_OF_CORE;
3347 apdu = apdu_buffer;
3349 else
3351 apdu = short_apdu_buffer;
3353 apdulen = apdudatalen;
3354 memcpy (apdu, apdudata, apdudatalen);
3355 class = apdulen? *apdu : 0;
3357 if (extended_length >= 256 && extended_length <= 65536)
3359 result_buffer_size = extended_length;
3360 result_buffer = xtrymalloc (result_buffer_size + 10);
3361 if (!result_buffer)
3363 xfree (apdu_buffer);
3364 return SW_HOST_OUT_OF_CORE;
3366 result = result_buffer;
3368 else
3370 result_buffer_size = SHORT_RESULT_BUFFER_SIZE;
3371 result = short_result_buffer;
3373 #undef SHORT_RESULT_BUFFER_SIZE
3375 if ((sw = trylock_slot (slot)))
3377 xfree (apdu_buffer);
3378 xfree (result_buffer);
3379 return sw;
3382 resultlen = result_buffer_size;
3383 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3384 xfree (apdu_buffer);
3385 apdu_buffer = NULL;
3386 if (rc || resultlen < 2)
3388 log_error ("apdu_send_direct(%d) failed: %s\n",
3389 slot, apdu_strerror (rc));
3390 unlock_slot (slot);
3391 xfree (result_buffer);
3392 return rc? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3394 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3395 /* Store away the returned data but strip the statusword. */
3396 resultlen -= 2;
3397 if (DBG_CARD_IO)
3399 log_debug (" response: sw=%04X datalen=%d\n",
3400 sw, (unsigned int)resultlen);
3401 if ( !retbuf && (sw == SW_SUCCESS || (sw & 0xff00) == SW_MORE_DATA))
3402 log_printhex (" dump: ", result, resultlen);
3405 if (handle_more && (sw & 0xff00) == SW_MORE_DATA)
3407 unsigned char *p = NULL, *tmp;
3408 size_t bufsize = 4096;
3410 /* It is likely that we need to return much more data, so we
3411 start off with a large buffer. */
3412 if (retbuf)
3414 *retbuf = p = xtrymalloc (bufsize + 2);
3415 if (!*retbuf)
3417 unlock_slot (slot);
3418 xfree (result_buffer);
3419 return SW_HOST_OUT_OF_CORE;
3421 assert (resultlen < bufsize);
3422 memcpy (p, result, resultlen);
3423 p += resultlen;
3428 int len = (sw & 0x00ff);
3430 if (DBG_CARD_IO)
3431 log_debug ("apdu_send_direct(%d): %d more bytes available\n",
3432 slot, len);
3433 apdu = short_apdu_buffer;
3434 apdulen = 0;
3435 apdu[apdulen++] = class;
3436 apdu[apdulen++] = 0xC0;
3437 apdu[apdulen++] = 0;
3438 apdu[apdulen++] = 0;
3439 apdu[apdulen++] = len;
3440 memset (apdu+apdulen, 0, sizeof (short_apdu_buffer) - apdulen);
3441 resultlen = result_buffer_size;
3442 rc = send_apdu (slot, apdu, apdulen, result, &resultlen, NULL);
3443 if (rc || resultlen < 2)
3445 log_error ("apdu_send_direct(%d) for get response failed: %s\n",
3446 slot, apdu_strerror (rc));
3447 unlock_slot (slot);
3448 xfree (result_buffer);
3449 return rc ? rc : SW_HOST_INCOMPLETE_CARD_RESPONSE;
3451 sw = (result[resultlen-2] << 8) | result[resultlen-1];
3452 resultlen -= 2;
3453 if (DBG_CARD_IO)
3455 log_debug (" more: sw=%04X datalen=%d\n",
3456 sw, (unsigned int)resultlen);
3457 if (!retbuf && (sw==SW_SUCCESS || (sw&0xff00)==SW_MORE_DATA))
3458 log_printhex (" dump: ", result, resultlen);
3461 if ((sw & 0xff00) == SW_MORE_DATA
3462 || sw == SW_SUCCESS
3463 || sw == SW_EOF_REACHED )
3465 if (retbuf && resultlen)
3467 if (p - *retbuf + resultlen > bufsize)
3469 bufsize += resultlen > 4096? resultlen: 4096;
3470 tmp = xtryrealloc (*retbuf, bufsize + 2);
3471 if (!tmp)
3473 unlock_slot (slot);
3474 xfree (result_buffer);
3475 return SW_HOST_OUT_OF_CORE;
3477 p = tmp + (p - *retbuf);
3478 *retbuf = tmp;
3480 memcpy (p, result, resultlen);
3481 p += resultlen;
3484 else
3485 log_info ("apdu_send_direct(%d) "
3486 "got unexpected status %04X from get response\n",
3487 slot, sw);
3489 while ((sw & 0xff00) == SW_MORE_DATA);
3491 if (retbuf)
3493 *retbuflen = p - *retbuf;
3494 tmp = xtryrealloc (*retbuf, *retbuflen + 2);
3495 if (tmp)
3496 *retbuf = tmp;
3499 else
3501 if (retbuf)
3503 *retbuf = xtrymalloc ((resultlen? resultlen : 1)+2);
3504 if (!*retbuf)
3506 unlock_slot (slot);
3507 xfree (result_buffer);
3508 return SW_HOST_OUT_OF_CORE;
3510 *retbuflen = resultlen;
3511 memcpy (*retbuf, result, resultlen);
3515 unlock_slot (slot);
3516 xfree (result_buffer);
3518 /* Append the status word. Note that we reserved the two extra
3519 bytes while allocating the buffer. */
3520 if (retbuf)
3522 (*retbuf)[(*retbuflen)++] = (sw >> 8);
3523 (*retbuf)[(*retbuflen)++] = sw;
3526 if (DBG_CARD_IO && retbuf)
3527 log_printhex (" dump: ", *retbuf, *retbuflen);
3529 return 0;